Changesets · Branches · Tags · Compare
| Changeset | e270a4c41fc9c0b230570e7594de5cbe5741d0570cf33ba194d536881ef11476 |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-08-09 13:51 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-08-09 13:51 +02:00 |
| Parents | 03aa3c89ee64 |
4 files changed
modified README.md +8 −0
| @@ -85,4 +85,12 @@ | ||
| 85 | 85 | ### Referencias |
| 86 | 86 | BM25 — Robertson, Walker, Jones, Hancock-Beaulieu & Gatford, *Okapi at TREC-3*, 1994; formulación moderna en Robertson & Zaragoza, FnTIR 3(4), 2009 · IDF — Spärck Jones, *Journal of Documentation* 28(1), 1972 · RRF — Cormack, Clarke & Buettcher, SIGIR 2009 · MMR — Carbonell & Goldstein, SIGIR 1998 · sumideros de atención — Xiao, Tian, Chen, Han & Lewis, ICLR 2024 · tiempo de validez — Snodgrass & Ahn, SIGMOD 1985. |
| 87 | 87 | |
| 88 | +**Estos números son reproducibles con una orden**, sobre el propio código de este repositorio: | |
| 89 | + | |
| 90 | +```bash | |
| 91 | +node bench/run.mjs --root core --ext .js --seeds 8 | |
| 92 | +``` | |
| 93 | + | |
| 94 | +El banco está en [`bench/`](bench/) y no usa ningún modelo para juzgar — es una comprobación de presencia determinista. El porqué de esa decisión, y la condición `tail` que hay que batir, están explicados ahí. | |
| 95 | + | |
| 88 | 96 | La historia completa, incluido lo que salió mal: **<https://bitacora.utopiaia.com/posts/16-beaten-by-doing-nothing.html>** |
added bench/README.md +73 −0
| @@ -0,0 +1,73 @@ | ||
| 1 | +# Banco de recuerdo de hechos | |
| 2 | + | |
| 3 | +Mide un empaquetador de contexto contestando a **una sola pregunta**, sin ningún modelo de por medio: | |
| 4 | + | |
| 5 | +> El agente leyó una definición a mitad de sesión. Al final se la piden. | |
| 6 | +> **¿Sigue esa definición dentro del contexto empaquetado?** | |
| 7 | + | |
| 8 | +## Por qué no hay un modelo juzgando | |
| 9 | + | |
| 10 | +Porque un banco cuyo resultado depende de qué juez elijas **no sirve para decidir entre dos empaquetadores**. | |
| 11 | + | |
| 12 | +Puntuando exactamente las mismas respuestas, con las mismas preguntas, tres jueces distintos nos dieron: | |
| 13 | + | |
| 14 | +| juez | resultado | | |
| 15 | +|---|---| | |
| 16 | +| un modelo de razonamiento de 11 GB | **WRONG a todo** — razonaba bien, pero escribía en otro campo | | |
| 17 | +| un 7B con el prompt permisivo | **CORRECT a todo**, incluido *"enfermera"* contra la referencia *"maestra"* | | |
| 18 | +| el mismo 7B con el prompt endurecido | 8/8 en el control | | |
| 19 | + | |
| 20 | +Los dos primeros no eran modelos malos: uno estaba razonando correctamente y el otro contestaba por inercia. **La diferencia entre el segundo y el tercero fue solo el prompt.** Un número que se mueve así no puede arbitrar una decisión de ingeniería. | |
| 21 | + | |
| 22 | +Este banco no tiene ese problema: es una comprobación de presencia, determinista, y da el mismo resultado dos veces seguidas. | |
| 23 | + | |
| 24 | +## Cómo se generan las sesiones | |
| 25 | + | |
| 26 | +**No son sintéticas.** Se abre un proyecto real y se ejecutan herramientas de verdad sobre él —listar el árbol, leer ficheros paginados, buscar—, y cada resultado que entra en el historial es la salida auténtica de esa herramienta, con su formato real: sus miles de líneas de ruido, sus rutas, sus números de línea. | |
| 27 | + | |
| 28 | +Eso importa porque el fallo que se busca solo aparece con material real. Un resultado de herramienta es mayoritariamente ruido con dos líneas útiles dentro; con texto sintético uniforme, cualquier empaquetador parece bueno. | |
| 29 | + | |
| 30 | +Lo único guionizado es **qué herramienta llama el agente a continuación** —la parte que decidiría un modelo—, sacado de un generador con semilla para tener muchas sesiones distintas y poder reportar media entre semillas en vez de una tirada afortunada. | |
| 31 | + | |
| 32 | +## Uso | |
| 33 | + | |
| 34 | +```bash | |
| 35 | +node run.mjs --root <ruta-de-un-repo> | |
| 36 | +``` | |
| 37 | + | |
| 38 | +Opciones: `--ext .js` · `--budget 3000` · `--seeds 8` · `--packer <fichero.js>` | |
| 39 | + | |
| 40 | +`--packer` debe exportar `packHistory(history, budgetTokens)`. Por defecto usa el core de este mismo repositorio, así que los números de abajo se reproducen sin configurar nada. | |
| 41 | + | |
| 42 | +## Las tres condiciones | |
| 43 | + | |
| 44 | +Todas reciben **el mismo presupuesto de tokens**. Lo único que cambia es la política de selección. | |
| 45 | + | |
| 46 | +| | qué hace | | |
| 47 | +|---|---| | |
| 48 | +| `full` | el historial entero, sin comprimir — el techo, y no respeta el presupuesto | | |
| 49 | +| `tail` | los últimos mensajes hasta llenar el presupuesto, tirar el resto | | |
| 50 | +| `packer` | el empaquetador que se está midiendo | | |
| 51 | + | |
| 52 | +**`tail` es el listón que hay que batir, y es el motivo de que este banco exista.** Cuatro generaciones de nuestro empaquetador se midieron cada una contra la anterior, todas ganando, y ninguna contra `tail`. Cuando por fin se puso, resultó que una de esas versiones **puntuaba por debajo**: comprimir con ella era peor que no comprimir. Si tu empaquetador no le gana a *"quédate lo último y tira el resto"*, nada más de lo que midas de él significa nada. | |
| 53 | + | |
| 54 | +## Resultado sobre este mismo repositorio | |
| 55 | + | |
| 56 | +``` | |
| 57 | +node run.mjs --root ../core --ext .js --seeds 8 | |
| 58 | +``` | |
| 59 | + | |
| 60 | +| presupuesto | `tail` | **`packer`** | `full` (techo) | | |
| 61 | +|---|---|---|---| | |
| 62 | +| 3.000 | 45,3 % | **92,2 %** · 2.073 tok | 100 % · 29.462 tok | | |
| 63 | +| 8.000 | 68,8 % | **95,3 %** · 5.253 tok | 100 % · 29.462 tok | | |
| 64 | + | |
| 65 | +8 sesiones, 64 sondas. El corpus es el propio `core/` de este repositorio, así que cualquiera reproduce estas cifras clonando y ejecutando una orden. | |
| 66 | + | |
| 67 | +## Qué NO mide | |
| 68 | + | |
| 69 | +- **Que el modelo use bien lo que recibe.** Presencia es condición necesaria, no suficiente: tener la evidencia delante no garantiza acertar. Para eso hace falta un banco con un modelo respondiendo, con todos los problemas de arbitraje descritos arriba. | |
| 70 | +- **Preguntas cuya respuesta no está en ninguna línea.** *"¿Cuántos ficheros has tocado?"* está repartida en cuarenta mensajes y ninguna selección top-k la alcanza por construcción. | |
| 71 | +- **Conversación.** Está hecho sobre sesiones de agente con herramientas. Un empaquetador ajustado aquí puede perder en diálogo: nos pasó, y la causa resultó ser el partidor de palabras, no la política de empaquetado. | |
| 72 | + | |
| 73 | +Apache-2.0, como el resto del repositorio. |
added bench/run.mjs +111 −0
| @@ -0,0 +1,111 @@ | ||
| 1 | +#!/usr/bin/env node | |
| 2 | +/** | |
| 3 | + * Banco de recuerdo de hechos para empaquetadores de contexto. | |
| 4 | + * | |
| 5 | + * QUÉ MIDE, y por qué está hecho así: | |
| 6 | + * | |
| 7 | + * Se generan sesiones de agente sobre un proyecto REAL — cada resultado de | |
| 8 | + * herramienta es la salida auténtica de leer, listar o buscar en ficheros de | |
| 9 | + * verdad, no texto sintético. A mitad de sesión el agente leyó una definición. | |
| 10 | + * Al final se le pregunta por ella. La única pregunta del banco es: | |
| 11 | + * | |
| 12 | + * ¿sigue esa definición dentro del contexto empaquetado? | |
| 13 | + * | |
| 14 | + * NO hay modelo juzgando. Es una comprobación de presencia, determinista y | |
| 15 | + * reproducible. Eso importa más de lo que parece: puntuando las MISMAS | |
| 16 | + * respuestas, tres jueces distintos nos dieron 0 %, ~100 % y algo medible, | |
| 17 | + * según el modelo y el prompt. Un banco cuyo resultado depende de qué juez | |
| 18 | + * elijas no sirve para decidir entre dos empaquetadores. | |
| 19 | + * | |
| 20 | + * Todas las condiciones reciben el MISMO presupuesto de tokens. Lo que cambia | |
| 21 | + * es únicamente la política de selección. | |
| 22 | + * | |
| 23 | + * USO | |
| 24 | + * node run.mjs --root <ruta-de-un-repo> [--ext .js] [--budget 3000] | |
| 25 | + * [--seeds 8] [--packer <fichero.js>] | |
| 26 | + * | |
| 27 | + * --packer debe exportar `packHistory(history, budgetTokens)`. Por defecto usa | |
| 28 | + * el core de este mismo repositorio, así que los números del README se | |
| 29 | + * reproducen sin configurar nada. | |
| 30 | + */ | |
| 31 | +import { createRequire } from 'module'; | |
| 32 | +import path from 'path'; | |
| 33 | +import { fileURLToPath } from 'url'; | |
| 34 | +const require = createRequire(import.meta.url); | |
| 35 | +const HERE = path.dirname(fileURLToPath(import.meta.url)); | |
| 36 | +const SG = require(path.join(HERE, 'sessiongen.js')); | |
| 37 | + | |
| 38 | +const argv = process.argv.slice(2); | |
| 39 | +const arg = (k, d) => { const i = argv.indexOf('--' + k); return i >= 0 ? argv[i + 1] : d; }; | |
| 40 | +const ROOT = arg('root'); | |
| 41 | +const EXT = arg('ext', '.js'); | |
| 42 | +const BUDGET = parseInt(arg('budget', '3000'), 10); | |
| 43 | +const SEEDS = parseInt(arg('seeds', '8'), 10); | |
| 44 | +const PACKER = path.resolve(arg('packer', path.join(HERE, '..', 'core', 'context.js'))); | |
| 45 | + | |
| 46 | +if (!ROOT) { | |
| 47 | + console.error('falta --root <ruta-de-un-repo>. Ej: node run.mjs --root ../core --ext .js'); | |
| 48 | + process.exit(2); | |
| 49 | +} | |
| 50 | + | |
| 51 | +// El core lee banderas de localStorage, que en Node no existe. Se le da un | |
| 52 | +// sustituto vacío: así el banco mide el comportamiento POR DEFECTO, que es lo | |
| 53 | +// que hay que medir — no una configuración que alguien dejó puesta. | |
| 54 | +if (typeof globalThis.localStorage === 'undefined') { | |
| 55 | + const mem = new Map(); | |
| 56 | + globalThis.localStorage = { | |
| 57 | + getItem: k => (mem.has(k) ? mem.get(k) : null), | |
| 58 | + setItem: (k, v) => mem.set(k, String(v)), | |
| 59 | + removeItem: k => mem.delete(k), | |
| 60 | + }; | |
| 61 | +} | |
| 62 | + | |
| 63 | +const { packHistory } = await import('file://' + PACKER); | |
| 64 | +const estTok = s => Math.ceil((s || '').length / 4) + 4; | |
| 65 | + | |
| 66 | +// CONDICIONES. `tail` es el listón que hay que batir: quedarse los últimos | |
| 67 | +// mensajes hasta llenar el presupuesto y tirar el resto. Si un empaquetador no | |
| 68 | +// le gana a esto, todo lo demás que midas de él da igual. | |
| 69 | +const tail = (history, budget) => { | |
| 70 | + const out = []; let used = 0; | |
| 71 | + for (let i = history.length - 1; i >= 0; i--) { | |
| 72 | + const t = estTok(history[i].content); | |
| 73 | + if (used + t > budget) break; | |
| 74 | + out.unshift(history[i]); used += t; | |
| 75 | + } | |
| 76 | + return out.length ? out : [history[history.length - 1]]; | |
| 77 | +}; | |
| 78 | + | |
| 79 | +const CONDS = { | |
| 80 | + full: h => h, | |
| 81 | + tail: h => tail(h, BUDGET), | |
| 82 | + packer: h => packHistory(h, BUDGET), | |
| 83 | +}; | |
| 84 | + | |
| 85 | +const acc = {}; for (const c of Object.keys(CONDS)) acc[c] = { hit: 0, n: 0, tok: 0 }; | |
| 86 | +let sessions = 0; | |
| 87 | + | |
| 88 | +for (let seed = 1; seed <= SEEDS; seed++) { | |
| 89 | + const s = SG.buildSession({ root: ROOT, seed: seed * 7919, steps: 26, exts: [EXT] }); | |
| 90 | + const probes = SG.selectProbes(s, SG.mulberry32(seed * 104729), 8, 'old', 'ident'); | |
| 91 | + if (probes.length < 3) continue; | |
| 92 | + sessions++; | |
| 93 | + for (const p of probes) { | |
| 94 | + const h = [...s.history, { role: 'user', content: p.query }]; | |
| 95 | + for (const [name, fn] of Object.entries(CONDS)) { | |
| 96 | + const out = await fn(h, BUDGET); | |
| 97 | + const txt = out.map(m => m.content).join('\n'); | |
| 98 | + acc[name].n++; | |
| 99 | + acc[name].tok += out.reduce((a, m) => a + estTok(m.content), 0); | |
| 100 | + if (txt.includes(p.ident) && txt.includes(p.value)) acc[name].hit++; | |
| 101 | + } | |
| 102 | + } | |
| 103 | +} | |
| 104 | + | |
| 105 | +console.log(`\n ${ROOT} · ${sessions} sesiones · presupuesto ${BUDGET} tokens\n`); | |
| 106 | +console.log(` ${'condición'.padEnd(12)}${'recuerdo'.padStart(10)}${'tokens'.padStart(10)}`); | |
| 107 | +for (const [name, a] of Object.entries(acc)) { | |
| 108 | + if (!a.n) continue; | |
| 109 | + console.log(` ${name.padEnd(12)}${(100 * a.hit / a.n).toFixed(1).padStart(9)}%${Math.round(a.tok / a.n).toString().padStart(10)}`); | |
| 110 | +} | |
| 111 | +console.log(`\n n = ${acc.packer.n} sondas\n`); |
added bench/sessiongen.js +229 −0
| @@ -0,0 +1,229 @@ | ||
| 1 | +'use strict'; | |
| 2 | +/** | |
| 3 | + * REAL agentic-session generator for Elffuss Code / Elffuss Claw. | |
| 4 | + * | |
| 5 | + * Not synthetic: every tool result is the REAL output of the REAL tool over a REAL project | |
| 6 | + * on disk, formatted byte-for-byte the way elffuss-code/web/js/tools/{index,code}.js and | |
| 7 | + * agent.js emit it ("[resultado <tool>]\n<output>", 100-line numbered pages, the | |
| 8 | + * "no existe «x»" error text, ...). What is scripted is only the *policy* (which tool the | |
| 9 | + * agent calls next) — the part a model would choose — drawn from a seeded RNG so we get many | |
| 10 | + * DIFFERENT real sessions and can report mean±sd instead of one lucky run. | |
| 11 | + */ | |
| 12 | +const fs = require('fs'); | |
| 13 | +const path = require('path'); | |
| 14 | +const { execSync } = require('child_process'); | |
| 15 | + | |
| 16 | +function mulberry32(a) { | |
| 17 | + return function () { | |
| 18 | + a |= 0; a = (a + 0x6D2B79F5) | 0; | |
| 19 | + let t = Math.imul(a ^ (a >>> 15), 1 | a); | |
| 20 | + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; | |
| 21 | + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; | |
| 22 | + }; | |
| 23 | +} | |
| 24 | +const pick = (rng, arr) => arr[Math.floor(rng() * arr.length)]; | |
| 25 | + | |
| 26 | +const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'target', | |
| 27 | + '.venv', '__pycache__', '.DS_Store']); | |
| 28 | + | |
| 29 | +function listFiles(root, exts) { | |
| 30 | + const out = []; | |
| 31 | + (function walk(dir) { | |
| 32 | + let ents; | |
| 33 | + try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } | |
| 34 | + ents.sort((a, b) => (a.isDirectory() !== b.isDirectory()) | |
| 35 | + ? (a.isDirectory() ? -1 : 1) : a.name.localeCompare(b.name)); | |
| 36 | + for (const e of ents) { | |
| 37 | + if (IGNORE.has(e.name)) continue; | |
| 38 | + const p = path.join(dir, e.name); | |
| 39 | + if (e.isDirectory()) walk(p); | |
| 40 | + else if (!exts || exts.some(x => e.name.endsWith(x))) out.push(path.relative(root, p)); | |
| 41 | + } | |
| 42 | + })(root); | |
| 43 | + return out; | |
| 44 | +} | |
| 45 | + | |
| 46 | +function toolTree(root, depth = 2) { // = code.tree | |
| 47 | + const out = []; let count = 0; | |
| 48 | + (function walk(dir, prefix, d) { | |
| 49 | + if (d > depth || count > 350) return; | |
| 50 | + let ents; | |
| 51 | + try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } | |
| 52 | + ents.sort((a, b) => (a.isDirectory() !== b.isDirectory()) | |
| 53 | + ? (a.isDirectory() ? -1 : 1) : a.name.localeCompare(b.name)); | |
| 54 | + for (const e of ents) { | |
| 55 | + if (IGNORE.has(e.name)) continue; | |
| 56 | + if (++count > 350) { out.push(prefix + '…'); return; } | |
| 57 | + out.push(prefix + (e.isDirectory() ? '📁 ' : '') + e.name); | |
| 58 | + if (e.isDirectory()) walk(path.join(dir, e.name), prefix + ' ', d + 1); | |
| 59 | + } | |
| 60 | + })(root, '', 1); | |
| 61 | + return out.join('\n') || '(vacío)'; | |
| 62 | +} | |
| 63 | + | |
| 64 | +const MAX_READ = 120000, PAGE_SIZE = 100; | |
| 65 | +function toolRead(root, rel, { offset, limit, around } = {}) { // = code.read | |
| 66 | + const abs = path.join(root, rel); | |
| 67 | + let full; | |
| 68 | + try { full = fs.readFileSync(abs, 'utf8'); } | |
| 69 | + catch { | |
| 70 | + const base = path.basename(rel); | |
| 71 | + const hits = listFiles(root).filter(f => path.basename(f) === base).slice(0, 3); | |
| 72 | + return { err: true, text: `ERROR: no existe «${rel}» en este proyecto.` + | |
| 73 | + (hits.length ? ` ¿Quizá: ${hits.join(' · ')}?` : '') + | |
| 74 | + ' Consulta el árbol (code.tree) o busca (code.search) antes de leer.' }; | |
| 75 | + } | |
| 76 | + if (offset == null && limit == null && around == null) { | |
| 77 | + const size = fs.statSync(abs).size; | |
| 78 | + return { text: full.length > MAX_READ ? full.slice(0, MAX_READ) + `\n… (recortado, ${size} bytes)` : full, | |
| 79 | + lines: full.split('\n'), start: 1 }; | |
| 80 | + } | |
| 81 | + const lines = full.split('\n'); | |
| 82 | + const totalLines = lines.length; | |
| 83 | + const size = Math.max(1, Math.min(Math.round(limit) || PAGE_SIZE, 500)); | |
| 84 | + const start = around != null ? Math.max(1, Math.round(around) - Math.floor(size / 2)) | |
| 85 | + : Math.max(1, Math.round(offset) || 1); | |
| 86 | + const startIdx = start - 1; | |
| 87 | + const slice = lines.slice(startIdx, startIdx + size); | |
| 88 | + const endLine = startIdx + slice.length; | |
| 89 | + const numbered = slice.map((l, i) => `${start + i}→${l}`).join('\n'); | |
| 90 | + const more = endLine < totalLines | |
| 91 | + ? `\n… quedan líneas ${endLine + 1}-${totalLines} — pide code.read con offset:${endLine + 1} para seguir` : ''; | |
| 92 | + return { text: numbered + more, lines: slice, start, numbered: true }; | |
| 93 | +} | |
| 94 | + | |
| 95 | +function toolSearch(root, query, ext = '') { // = code.search | |
| 96 | + const results = []; const q = query.toLowerCase(); | |
| 97 | + for (const rel of listFiles(root, ext ? [ext] : null)) { | |
| 98 | + if (results.length > 80) break; | |
| 99 | + let body; try { body = fs.readFileSync(path.join(root, rel), 'utf8'); } catch { continue; } | |
| 100 | + if (body.length > 200000) continue; | |
| 101 | + body.split('\n').forEach((l, i) => { | |
| 102 | + if (results.length <= 80 && l.toLowerCase().includes(q)) | |
| 103 | + results.push(`${rel}:${i + 1}: ${l.trim().slice(0, 140)}`); | |
| 104 | + }); | |
| 105 | + } | |
| 106 | + return results.length ? results.join('\n') : `Sin resultados para «${query}»`; | |
| 107 | +} | |
| 108 | + | |
| 109 | +function toolShell(root, cmd) { // = terminal.run (REAL exec) | |
| 110 | + try { | |
| 111 | + return execSync(cmd, { cwd: root, encoding: 'utf8', timeout: 15000, | |
| 112 | + maxBuffer: 8 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }).trimEnd() || '(sin salida)'; | |
| 113 | + } catch (e) { | |
| 114 | + return `ERROR (exit ${e.status}): ${(e.stderr || e.stdout || e.message).toString().trim().slice(0, 500)}`; | |
| 115 | + } | |
| 116 | +} | |
| 117 | + | |
| 118 | +// ── gold facts: definition lines a later turn will ask for again ──────────── | |
| 119 | +const DEF_RE = [ | |
| 120 | + /^\s*(?:pub\s+)?const\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?::[^=]+)?=\s*(.+?);?\s*$/, | |
| 121 | + /^\s*(?:export\s+)?const\s+([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+?);?\s*$/, | |
| 122 | + /^\s*(?:static)\s+([A-Z_][A-Z0-9_]*)\s*:[^=]+=\s*(.+?);?\s*$/, | |
| 123 | +]; | |
| 124 | +function extractGolds(rawLines, file) { | |
| 125 | + const golds = []; | |
| 126 | + for (const raw of rawLines) { | |
| 127 | + const line = raw.replace(/^\d+→/, ''); | |
| 128 | + for (const re of DEF_RE) { | |
| 129 | + const m = line.match(re); | |
| 130 | + if (!m) continue; | |
| 131 | + const ident = m[1]; | |
| 132 | + const val = m[2].trim().replace(/\s*\/\/.*$/, '').trim(); | |
| 133 | + if (val.length < 1 || val.length > 60) break; | |
| 134 | + const tok = (val.match(/\d[\d_.]*|"[^"]{2,30}"|'[^']{2,30}'/) || [])[0]; | |
| 135 | + if (!tok || ident.length < 4) break; | |
| 136 | + golds.push({ ident, value: tok.replace(/^['"]|['"]$/g, ''), file, line }); | |
| 137 | + break; | |
| 138 | + } | |
| 139 | + } | |
| 140 | + return golds; | |
| 141 | +} | |
| 142 | + | |
| 143 | +const TASKS = [ | |
| 144 | + 'Revisa este proyecto y dime cómo está organizado el manejo de contexto/estado; luego prepara un cambio pequeño y seguro.', | |
| 145 | + 'Quiero refactorizar la configuración: localiza todas las constantes por defecto y déjalas documentadas en un solo sitio.', | |
| 146 | + 'Hay un bug: algunos valores por defecto no coinciden con la documentación. Audita el código y propón el arreglo.', | |
| 147 | + 'Añade un flag para poder desactivar la funcionalidad principal en caliente, sin romper el comportamiento actual.', | |
| 148 | + 'Necesito entender el flujo de ejecución de punta a punta para poder tocarlo sin romper nada.', | |
| 149 | +]; | |
| 150 | + | |
| 151 | +function buildSession({ root, seed, steps = 26, exts }) { | |
| 152 | + const rng = mulberry32(seed); | |
| 153 | + const files = listFiles(root, exts); | |
| 154 | + if (!files.length) throw new Error('no files in ' + root); | |
| 155 | + const history = [], golds = [], meta = { root, seed, tools: [] }; | |
| 156 | + const task = pick(rng, TASKS); | |
| 157 | + history.push({ role: 'user', content: task }); | |
| 158 | + | |
| 159 | + const searchTerms = ['const', 'fn ', 'export', 'error', 'config', 'default', 'async', 'return', 'let mut', 'import']; | |
| 160 | + const shellCmds = ['ls -la', 'wc -l *', 'git status --short', 'git log --oneline -5', | |
| 161 | + 'find . -name "*.rs" -o -name "*.js" | head -20', 'du -sh .']; | |
| 162 | + let readIdx = 0; | |
| 163 | + const readOrder = [...files].sort(() => rng() - 0.5); | |
| 164 | + | |
| 165 | + for (let s = 0; s < steps; s++) { | |
| 166 | + let tool, args, out, rawLines = null, srcFile = null; | |
| 167 | + const r = rng(); | |
| 168 | + if (s === 0) { tool = 'code.tree'; args = { depth: 2 }; out = toolTree(root, 2); } | |
| 169 | + else if (s === 1) { const t = pick(rng, searchTerms); tool = 'code.search'; args = { query: t }; out = toolSearch(root, t); } | |
| 170 | + else if (r < 0.60) { | |
| 171 | + const rel = readOrder[readIdx++ % readOrder.length]; | |
| 172 | + const useOffset = rng() < 0.5; | |
| 173 | + const res = useOffset ? toolRead(root, rel, { offset: 1 + Math.floor(rng() * 3) * 100 }) : toolRead(root, rel); | |
| 174 | + tool = 'code.read'; args = useOffset ? { path: rel, offset: 1 } : { path: rel }; | |
| 175 | + out = res.text; rawLines = res.lines || null; srcFile = rel; | |
| 176 | + } else if (r < 0.72) { const t = pick(rng, searchTerms); tool = 'code.search'; args = { query: t }; out = toolSearch(root, t); } | |
| 177 | + else if (r < 0.84) { const c = pick(rng, shellCmds); tool = 'terminal.run'; args = { command: c }; out = toolShell(root, c); } | |
| 178 | + else if (r < 0.92) { tool = 'code.tree'; args = { depth: 2 }; out = toolTree(root, 2); } // agents DO re-list | |
| 179 | + else { | |
| 180 | + const rel = pick(rng, files).replace(/\.(rs|js|ts|py)$/, '_v2.$1'); | |
| 181 | + tool = 'code.read'; args = { path: rel }; out = toolRead(root, rel).text; | |
| 182 | + } | |
| 183 | + history.push({ role: 'assistant', content: | |
| 184 | + `Voy a mirar esto.\n\`\`\`json\n{"tool":"${tool}","args":${JSON.stringify(args)}}\n\`\`\`` }); | |
| 185 | + history.push({ role: 'user', content: `[resultado ${tool}]\n${out}` }); | |
| 186 | + meta.tools.push(tool); | |
| 187 | + if (rawLines && srcFile) for (const g of extractGolds(rawLines, srcFile)) { g.turn = history.length - 1; golds.push(g); } | |
| 188 | + } | |
| 189 | + return { history, golds, meta, task }; | |
| 190 | +} | |
| 191 | + | |
| 192 | +// Probes = the follow-up questions. `qmode` controls how the question refers to the fact: | |
| 193 | +// 'ident' the question names the identifier (an agent going back to a symbol it saw) | |
| 194 | +// 'file' the question names only the FILE (harder: no lexical hook on the gold line) | |
| 195 | +function selectProbes(session, rng, maxProbes = 12, mode = 'old', qmode = 'ident') { | |
| 196 | + const byIdent = new Map(); | |
| 197 | + for (const g of session.golds) { | |
| 198 | + if (!byIdent.has(g.ident)) byIdent.set(g.ident, new Set()); | |
| 199 | + byIdent.get(g.ident).add(g.line.trim()); | |
| 200 | + } | |
| 201 | + const uniq = session.golds.filter(g => byIdent.get(g.ident).size === 1 | |
| 202 | + && !session.task.includes(g.ident) && !session.task.includes(g.value)); | |
| 203 | + const seen = new Set(); const cand = []; | |
| 204 | + for (const g of uniq) { if (seen.has(g.ident)) continue; seen.add(g.ident); cand.push(g); } | |
| 205 | + const oldest = cand.filter(g => g.turn < session.history.length - 14); | |
| 206 | + const pool = mode === 'all' ? cand : (oldest.length >= 4 ? oldest : cand); | |
| 207 | + const perTurn = new Map(), perFile = new Map(); const chosen = []; | |
| 208 | + for (const g of [...pool].sort(() => rng() - 0.5)) { | |
| 209 | + const t = perTurn.get(g.turn) || 0, f = perFile.get(g.file) || 0; | |
| 210 | + if (t >= 2 || f >= 3) continue; | |
| 211 | + perTurn.set(g.turn, t + 1); perFile.set(g.file, f + 1); | |
| 212 | + chosen.push(g); | |
| 213 | + if (chosen.length >= maxProbes) break; | |
| 214 | + } | |
| 215 | + const Q_IDENT = [ | |
| 216 | + (g) => `Vuelve a ${g.ident}: ¿qué valor por defecto tenía y en qué fichero está definido? Lo necesito para el cambio.`, | |
| 217 | + (g) => `Necesito editar ${g.ident}. Dime su valor actual exacto y el fichero, no lo adivines.`, | |
| 218 | + (g) => `¿Cuál era el valor de ${g.ident}? Cítame la línea del fichero donde se define.`, | |
| 219 | + ]; | |
| 220 | + const Q_FILE = [ | |
| 221 | + (g) => `Del fichero ${g.file}: enumérame las constantes que definía con su valor exacto.`, | |
| 222 | + (g) => `Vuelve a ${g.file}. ¿Qué valores por defecto declaraba? Cítalos tal cual.`, | |
| 223 | + (g) => `Necesito los valores por defecto que vimos en ${g.file}, literales.`, | |
| 224 | + ]; | |
| 225 | + const Q = qmode === 'file' ? Q_FILE : Q_IDENT; | |
| 226 | + return chosen.map((g, i) => ({ ...g, query: Q[i % Q.length](g) })); | |
| 227 | +} | |
| 228 | + | |
| 229 | +module.exports = { buildSession, selectProbes, listFiles, toolTree, toolRead, toolSearch, mulberry32 }; |