Elffuss BraidHub

utopia-ia/elffuss public

main · 11.0 KiBRawPermalink
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 */
12const fs = require('fs');
13const path = require('path');
14const { execSync } = require('child_process');
15
16function 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}
24const pick = (rng, arr) => arr[Math.floor(rng() * arr.length)];
25
26const IGNORE = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'target',
27 '.venv', '__pycache__', '.DS_Store']);
28
29function 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
46function 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
64const MAX_READ = 120000, PAGE_SIZE = 100;
65function 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
95function 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
109function 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 ────────────
119const 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];
124function 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
143const 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
151function 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)
195function 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
229module.exports = { buildSession, selectProbes, listFiles, toolTree, toolRead, toolSearch, mulberry32 };