Changesets · Branches · Tags · Compare
| Changeset | 7668ad741842d8dde7c9924cfb7e491bd81a50348cb7af3fa115353e6c265b01 |
|---|---|
| Author | KikoCis <kikocisneros@gmail.com> · 2026-08-09 14:21 +02:00 |
| Committer | KikoCis <kikocisneros@gmail.com> · 2026-08-09 14:21 +02:00 |
| Parents | e270a4c41fc9 |
13 files changed
modified README.md +101 −70
| @@ -1,96 +1,127 @@ | ||
| 1 | 1 | # ✳ Elffuss — core |
| 2 | 2 | |
| 3 | -Núcleo compartido de la familia **Elffuss**: un runtime de agente que vive | |
| 4 | -**entero en el navegador**, sin build ni backend obligatorio. Los productos que | |
| 5 | -lo usan: | |
| 3 | +Elffuss is an agent runtime that lives **entirely in the browser**: no build step, no backend, no install — ES modules served exactly as they are written. This repository is the shared core behind two real products, and its centrepiece is the part that decides what an agent still remembers once the history stops fitting. | |
| 6 | 4 | |
| 7 | -- **[Elffuss Claw](https://elffuss-claw.utopiaia.com)** — un SO web agéntico: el | |
| 8 | - chat es la interfaz, las apps se crean como HTML al vuelo. | |
| 9 | -- **[Elffuss Code](https://elffuss-code.utopiaia.com)** — un IDE web tipo VS Code | |
| 10 | - con la elfa de agente de código. | |
| 5 | +**Every number below is reproducible with one command**, against this repository's own source: | |
| 11 | 6 | |
| 12 | -## Qué hay en el core (`core/`) | |
| 7 | +```bash | |
| 8 | +node bench/run.mjs --root core --ext .js --seeds 8 | |
| 9 | +``` | |
| 13 | 10 | |
| 14 | -ES modules vanilla, sin dependencias, sin build: | |
| 11 | +No API key, no model, no network, nothing to configure. That is the whole difference between this and a README full of figures nobody can check. | |
| 15 | 12 | |
| 16 | -| Módulo | Qué hace | | |
| 17 | -|---|---| | |
| 18 | -| `context.js` | **Selección de contexto por relevancia** frente a la pregunta viva: BM25 real (saturación + normalización por longitud) con **IDF endógena** —sin lista de parada, funciona en cualquier idioma—, granularidad de línea, control de redundancia y presupuesto de tokens garantizado. Las perillas salen de la presión de compresión medida, no de constantes. Opcionalmente fusiona una segunda opinión semántica por rangos. Medido: recall de hechos **15,1 % → 65,3 %** con el mismo gasto. | | |
| 19 | -| `skills.js` | **Skills de Claude Code**: instala SKILL.md desde `anthropics/skills`, `claude-plugins-official` o cualquier repo público; se inyectan al system prompt. | | |
| 20 | -| `md.js` | Renderizador de markdown seguro (escape total) para el chat, estilo plugin de Claude Code. | | |
| 21 | -| `splash-gl.js` | Galaxia de partículas WebGL (GL_POINTS + blending aditivo, todo en el vertex shader) para las pantallas de bienvenida. | | |
| 22 | -| `providers/api.js` | Proveedor genérico para APIs externas: OpenAI-compatible (OpenAI, Ollama, llama.cpp) y Anthropic Messages, con streaming SSE y llamadas directas desde el navegador. | | |
| 13 | +--- | |
| 23 | 14 | |
| 24 | -## Filosofía | |
| 15 | +## The context manager | |
| 25 | 16 | |
| 26 | -- **Todo en el navegador.** Los modelos corren en local (WebGPU vía transformers.js | |
| 27 | - / LiteRT-LM); los proveedores externos son opt-in y sus claves nunca salen del | |
| 28 | - navegador del usuario. | |
| 29 | -- **Sin build.** ES modules que se sirven tal cual. Clonar y abrir. | |
| 17 | +[`core/context.js`](core/context.js) selects the history by **relevance to the live question** rather than by recency: | |
| 30 | 18 | |
| 31 | -## Uso | |
| 19 | +- **BM25 with endogenous IDF.** The rarity of a term is computed from the conversation itself, so there is no hand-written stoplist and nothing to localise — it works in whatever language the session happens to be in, including a session that mixes two. | |
| 20 | +- **Line granularity.** A tool result is mostly noise with two useful lines inside it. Keeping it whole or dropping it whole wastes the budget in both directions. | |
| 21 | +- **Redundancy control (MMR)**, with the penalty derived from the material's *measured* redundancy instead of a constant. | |
| 22 | +- **A token budget that is actually honoured.** The emitted size is measured and lines are handed back until the output genuinely fits. | |
| 23 | +- **Staleness and absolute dates, resolved at write time.** A file read on turn 3 and edited on turn 20 has two versions in the history, and the stale one scores just as well. That is not inefficiency, it is incorrectness — and neither is "we deployed it yesterday", written on turn 3 and read on turn 40. | |
| 32 | 24 | |
| 33 | -Los productos **vendorizan** el core en `web/js/` (mismos nombres de archivo) y | |
| 34 | -lo sincronizan con su `sync-core.sh`. Así cada repo es autocontenido y se puede | |
| 35 | -clonar y abrir sin instalar nada. | |
| 25 | +Optionally, a **semantic second opinion fused by rank** ([`core/embed.js`](core/embed.js)). | |
| 36 | 26 | |
| 37 | -## Licencia | |
| 27 | +### Agent sessions — fact recall, no LLM judge | |
| 38 | 28 | |
| 39 | -Apache License 2.0 — ver [LICENSE](LICENSE). | |
| 29 | +The agent read a definition halfway through a real session; at the end it is asked for it. The benchmark asks one question: is that definition still in the packed context? Every condition gets the same token budget. | |
| 40 | 30 | |
| 41 | -## Cómo se mide el gestor de contexto | |
| 31 | +| budget | `tail` | **`packer`** | `full` (ceiling) | | |
| 32 | +|---|---|---|---| | |
| 33 | +| 3,000 | 48.4% | **93.8%** · 1,596 tok | 100% · 29,732 tok | | |
| 34 | +| 8,000 | 70.3% | **95.3%** · 2,965 tok | 100% · 29,732 tok | | |
| 42 | 35 | |
| 43 | -No se elige por intuición. Todo a **igual presupuesto de tokens**. | |
| 36 | +`tail` — keep the last messages until the budget is full, throw away the rest — is the bar that has to be cleared. It is there because four generations of this packer were each measured against the previous one, all of them winning, and none of them against `tail`. When `tail` was finally put in, one of those versions turned out to score *below* it. | |
| 44 | 37 | |
| 45 | -**Sesiones reales de agente** — 25 sesiones sobre proyectos reales, 174 sondas, recuerdo de hechos, sin juez LLM: | |
| 38 | +### Long-term dialogue — F1, with a real model answering, at ~8% of the context | |
| 46 | 39 | |
| 47 | -| | recuerdo | | |
| 40 | +| | F1 | | |
| 48 | 41 | |---|---| |
| 49 | -| truncar por la cola | 7,0 % | | |
| 50 | -| versión anterior | 15,1 % | | |
| 51 | -| **esta** | **65,3 % ± 8,5** | | |
| 42 | +| **the full context, uncompressed** | **22.56** | | |
| 43 | +| tail truncation | 6.62 | | |
| 44 | +| hand-written heuristics | 6.07 | | |
| 45 | +| BM25 without IDF | 20.34 | | |
| 46 | +| BM25 | 23.59 | | |
| 47 | +| embeddings | 23.95 | | |
| 48 | +| **rank fusion** | **28.09** | | |
| 52 | 49 | |
| 53 | -Y con el presupuesto barrido, porque una sola cifra engaña: | |
| 50 | +**Retrieving well beats sending everything**: 28.09 against 22.56, using 8% of the tokens. What is irrelevant is not neutral ballast — it distracts. That result is also why the packer stops when the evidence runs out instead of when the tokens run out: filling right up to the edge puts back by hand exactly what the compression came to remove. | |
| 54 | 51 | |
| 55 | -| contexto ÷ presupuesto | truncar | versión anterior | esta | | |
| 56 | -|---|---|---|---| | |
| 57 | -| 15,8× *(agobio)* | 8,2 % | 13,2 % | **70,7 %** | | |
| 58 | -| 5,9× | 15,7 % | 13,2 % | **73,2 %** | | |
| 59 | -| 3,0× | 31,8 % | 13,2 % | **83,6 %** | | |
| 60 | -| 1,5× *(casi cabe)* | 72,5 % | 13,2 % | **94,6 %** | | |
| 52 | +--- | |
| 61 | 53 | |
| 62 | -La columna del medio no es un error: la versión anterior recuperaba **lo mismo con diez veces más sitio**, porque tiraba material antes de puntuarlo. | |
| 54 | +## What was measured, and not assumed | |
| 63 | 55 | |
| 64 | -**Memoria a largo plazo** — 200 preguntas, F1 del propio repo del banco, modelo real respondiendo, ~8 % del contexto: | |
| 56 | +- **Turning the hand-written heuristics on cost −3.02 F1.** It was not that they added nothing — they subtracted. | |
| 57 | +- **Removing the IDF costs −3.25 F1.** Endogenous rarity does real work, and it replaces any hand-written stoplist, in any language. | |
| 58 | +- **The word splitter tuned for code cost 12.8 points on its own benchmark.** It required tokens to start with a letter, so `3pm`, `2nd` and `5` vanished whole, and it kept `src/utils.js` as a single token, so asking about `utils` matched nothing. Fixing only that, with everything else held equal, moved fact recall from 82.1% to 94.9%. It was never the packing policy. | |
| 59 | +- **Lexical and semantic tie overall but cover different gaps.** When the question does not literally name what it is looking for, embeddings win (24.28 vs 18.60); when it does, BM25 wins (29.33 vs 23.58). Fusing by rank takes essentially the better of the two columns — it matches the semantic side where the semantic side wins (24.05 vs 24.28, i.e. it gives up 0.23) and clears the lexical side where the lexical side wins (32.73 vs 29.33, +3.40). So it is not free in both directions, but the trade is heavily in its favour. The semantic side does not replace the lexical one — it covers its blind spot. | |
| 65 | 60 | |
| 66 | -| | F1 | | |
| 61 | +--- | |
| 62 | + | |
| 63 | +## What is honest about this | |
| 64 | + | |
| 65 | +- **The dialogue benchmark is CC BY-NC.** It is something we measure against, not something shipped here. The benchmark in [`bench/`](bench/) is the one in this repository, and it runs on your own code. | |
| 66 | +- **The semantic side is off by default.** The gain is real (+4.50 F1), but it costs a sizeable model download the first time, and without WebGPU it makes every turn more expensive. It is wired up and tested, and it turns on by request. With the flag off, `embed.js` — and with it transformers.js and the model — is not even imported. | |
| 67 | +- **The engine is tuned for agent sessions.** In dialogue it went as far as losing to a bare BM25 until the word splitter was fixed. A packer tuned on one shape of history can lose on another, and this one was. | |
| 68 | + | |
| 69 | +--- | |
| 70 | + | |
| 71 | +## What is in `core/` | |
| 72 | + | |
| 73 | +Vanilla ES modules, no dependencies, no build: | |
| 74 | + | |
| 75 | +| Module | What it does | | |
| 67 | 76 | |---|---| |
| 68 | -| **el contexto COMPLETO, sin comprimir** | **22,56** | | |
| 69 | -| truncar por la cola | 6,62 | | |
| 70 | -| heurísticas escritas a mano | 6,07 | | |
| 71 | -| BM25 sin IDF | 20,34 | | |
| 72 | -| BM25 | 23,59 | | |
| 73 | -| embeddings | 23,95 | | |
| 74 | -| **fusión por rangos** | **28,09** | | |
| 75 | - | |
| 76 | -**Recuperar bien bate a tenerlo todo**: 28,09 contra 22,56 con el 8 % de los tokens. Lo irrelevante no es lastre neutro, distrae. | |
| 77 | - | |
| 78 | -### Lo que se midió y no se supuso | |
| 79 | -- Activar las heurísticas costaba **−3,02 F1**. No es que no aportaran: restaban. | |
| 80 | -- Quitar la IDF cuesta **−3,25 F1**. La rareza endógena hace trabajo real, y sustituye a cualquier lista de parada escrita a mano — en cualquier idioma. | |
| 81 | -- Lo semántico **no sustituye** al léxico, le cubre el punto ciego: sin solape de vocabulario entre pregunta y respuesta ganan los embeddings (24,28 vs 18,60); con solape gana BM25 (29,33 vs 23,58); la fusión se queda con los dos. | |
| 82 | -- El encargo original pasa de perderse **siempre** a conservarse **siempre** con una reserva de cabecera del 5 %. | |
| 83 | -- Contenido obsoleto: sin control de caducidad, la versión **falsa** de un fichero editado sobrevivía **8/8**; con él, **0/8**. | |
| 84 | - | |
| 85 | -### Referencias | |
| 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 | - | |
| 88 | -**Estos números son reproducibles con una orden**, sobre el propio código de este repositorio: | |
| 77 | +| `context.js` | The context manager described above: BM25 with endogenous IDF, line granularity, redundancy control, a guaranteed token budget, staleness and date resolution at write time, and optional rank fusion with a semantic ranker. | | |
| 78 | +| `embed.js` | The semantic side: a small multilingual embedding model in the browser, loaded lazily and only behind the flag, with a per-content session cache. | | |
| 79 | +| `ceo.js` | Autonomous "CEO brain": when the user is idle, several profiles think in parallel over the workspace and leave improvement proposals. It never modifies existing files, and it stops the moment the user comes back. | | |
| 80 | +| `mind.js` | The Mind view: the brain's thinking rendered as a 3D world, with the project's real city underneath and a beam dropping onto each file as it is touched. | | |
| 81 | +| `skills.js` | Claude Code skills: installs `SKILL.md` from `anthropics/skills`, the official plugins, or any public repo, and injects them into the system prompt. | | |
| 82 | +| `md.js` | Safe markdown renderer for the chat — all HTML escaped first, then a bounded set of transformations. | | |
| 83 | +| `humanize.js` | Turns a tool call into a human sentence, so the user is never shown raw JSON — including mid-stream, before the JSON has closed. | | |
| 84 | +| `splash-gl.js` | WebGL particle galaxy for the splash screen: GL_POINTS and additive blending, computed entirely in the vertex shader. | | |
| 85 | +| `telemetry.js` | Opt-in error/feedback mailbox, off by default. Code and project content are never sent. | | |
| 86 | +| `providers/api.js` | Generic provider for external APIs: OpenAI-compatible and Anthropic Messages, with SSE streaming, called directly from the user's browser so the key never passes through a server of ours. | | |
| 89 | 87 | |
| 90 | -```bash | |
| 91 | -node bench/run.mjs --root core --ext .js --seeds 8 | |
| 92 | -``` | |
| 88 | +--- | |
| 89 | + | |
| 90 | +## Design rules | |
| 91 | + | |
| 92 | +- **Everything in the browser.** Models run locally; external providers are opt-in and their keys never leave the user's browser. | |
| 93 | +- **No build.** ES modules served as they are. Clone and open. | |
| 94 | +- **Nothing is chosen by intuition.** Every knob in the context manager either comes out of a measurement or comes out of the measured compression pressure at run time. | |
| 95 | + | |
| 96 | +## Using it | |
| 97 | + | |
| 98 | +The products **vendor** the core into `web/js/` (same file names) and keep it in sync with their own `sync-core.sh`, so each repository stays self-contained and can be cloned and opened with nothing installed. | |
| 99 | + | |
| 100 | +## The products | |
| 101 | + | |
| 102 | +- **[Elffuss Claw](https://elffuss-claw.utopiaia.com)** — an agentic web OS: the chat is the interface, and apps are created as HTML on the fly. | |
| 103 | +- **[Elffuss Code](https://elffuss-code.utopiaia.com)** — a VS Code-style web IDE with the coding agent built in. | |
| 104 | + | |
| 105 | +The full story, including what went wrong: **<https://bitacora.utopiaia.com/posts/16-beaten-by-doing-nothing.html>** | |
| 106 | + | |
| 107 | +## Licence | |
| 108 | + | |
| 109 | +Apache License 2.0 — see [LICENSE](LICENSE). | |
| 110 | + | |
| 111 | +--- | |
| 112 | + | |
| 113 | +## References | |
| 114 | + | |
| 115 | +Robertson, S. E., Walker, S., Jones, S., Hancock-Beaulieu, M. M., & Gatford, M. (1994). *Okapi at TREC-3.* TREC-3. | |
| 116 | + | |
| 117 | +Robertson, S. E., & Zaragoza, H. (2009). *The Probabilistic Relevance Framework: BM25 and Beyond.* Foundations and Trends in Information Retrieval, 3(4). <https://doi.org/10.1561/1500000019> | |
| 118 | + | |
| 119 | +Spärck Jones, K. (1972). *A Statistical Interpretation of Term Specificity and Its Application in Retrieval.* Journal of Documentation, 28(1). | |
| 120 | + | |
| 121 | +Carbonell, J., & Goldstein, J. (1998). *The Use of MMR, Diversity-Based Reranking for Reordering Documents and Producing Summaries.* SIGIR 1998. | |
| 122 | + | |
| 123 | +Cormack, G. V., Clarke, C. L. A., & Buettcher, S. (2009). *Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods.* SIGIR 2009. <https://doi.org/10.1145/1571941.1572114> | |
| 93 | 124 | |
| 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í. | |
| 125 | +Xiao, G., Tian, Y., Chen, B., Han, S., & Lewis, M. (2024). *Efficient Streaming Language Models with Attention Sinks.* ICLR 2024. <https://arxiv.org/abs/2309.17453> | |
| 95 | 126 | |
| 96 | -La historia completa, incluido lo que salió mal: **<https://bitacora.utopiaia.com/posts/16-beaten-by-doing-nothing.html>** | |
| 127 | +Snodgrass, R., & Ahn, I. (1985). *A Taxonomy of Time in Databases.* SIGMOD 1985. |
modified bench/README.md +44 −38
| @@ -1,73 +1,79 @@ | ||
| 1 | -# Banco de recuerdo de hechos | |
| 1 | +# Fact-recall benchmark | |
| 2 | 2 | |
| 3 | -Mide un empaquetador de contexto contestando a **una sola pregunta**, sin ningún modelo de por medio: | |
| 3 | +It measures a context packer by answering **one single question**, with no model anywhere in the loop: | |
| 4 | 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?** | |
| 5 | +> The agent read a definition halfway through the session. At the end it is asked for it. | |
| 6 | +> **Is that definition still inside the packed context?** | |
| 7 | 7 | |
| 8 | -## Por qué no hay un modelo juzgando | |
| 8 | +## Why there is no model judging | |
| 9 | 9 | |
| 10 | -Porque un banco cuyo resultado depende de qué juez elijas **no sirve para decidir entre dos empaquetadores**. | |
| 10 | +Because a benchmark whose result depends on which judge you pick **is no use for deciding between two packers**. | |
| 11 | 11 | |
| 12 | -Puntuando exactamente las mismas respuestas, con las mismas preguntas, tres jueces distintos nos dieron: | |
| 12 | +Scoring exactly the same answers, with the same questions, three different judges gave us: | |
| 13 | 13 | |
| 14 | -| juez | resultado | | |
| 14 | +| judge | result | | |
| 15 | 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 | | |
| 16 | +| an 11 GB reasoning model | **WRONG on everything** — it reasoned correctly, but wrote into another field | | |
| 17 | +| a 7B with the permissive prompt | **CORRECT on everything**, including *"nurse"* against the reference *"teacher"* | | |
| 18 | +| the same 7B with the hardened prompt | 8/8 on the control | | |
| 19 | 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. | |
| 20 | +The first two were not bad models: one was reasoning correctly and the other was answering out of inertia. **The only difference between the second and the third was the prompt.** A number that moves like that cannot arbitrate an engineering decision. | |
| 21 | 21 | |
| 22 | -Este banco no tiene ese problema: es una comprobación de presencia, determinista, y da el mismo resultado dos veces seguidas. | |
| 22 | +This benchmark does not have that problem: it is a presence check, deterministic, and it gives the same result twice in a row. | |
| 23 | 23 | |
| 24 | -## Cómo se generan las sesiones | |
| 24 | +## How the sessions are generated | |
| 25 | 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. | |
| 26 | +**They are not synthetic.** A real project is opened and real tools are run over it — list the tree, read paginated files, search — and every result that enters the history is the genuine output of that tool, in its real format: its thousands of lines of noise, its paths, its line numbers. | |
| 27 | 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. | |
| 28 | +That matters because the failure being hunted only shows up with real material. A tool result is mostly noise with two useful lines inside it; with uniform synthetic text, any packer looks good. | |
| 29 | 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. | |
| 30 | +The only scripted part is **which tool the agent calls next** — the part a model would decide — drawn from a seeded generator so there are many different sessions and a mean across seeds can be reported instead of one lucky run. | |
| 31 | 31 | |
| 32 | -## Uso | |
| 32 | +## Usage | |
| 33 | 33 | |
| 34 | 34 | ```bash |
| 35 | -node run.mjs --root <ruta-de-un-repo> | |
| 35 | +node run.mjs --root <path-to-a-repo> | |
| 36 | 36 | ``` |
| 37 | 37 | |
| 38 | -Opciones: `--ext .js` · `--budget 3000` · `--seeds 8` · `--packer <fichero.js>` | |
| 38 | +Options: `--ext .js` · `--budget 3000` · `--seeds 8` · `--packer <file.js>` | |
| 39 | 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. | |
| 40 | +`--packer` must export `packHistory(history, budgetTokens)`. By default it uses this repository's own core, so the numbers below reproduce with nothing to configure. | |
| 41 | 41 | |
| 42 | -## Las tres condiciones | |
| 42 | +## The three conditions | |
| 43 | 43 | |
| 44 | -Todas reciben **el mismo presupuesto de tokens**. Lo único que cambia es la política de selección. | |
| 44 | +All of them get **the same token budget**. The only thing that changes is the selection policy. | |
| 45 | 45 | |
| 46 | -| | qué hace | | |
| 46 | +| | what it does | | |
| 47 | 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 | | |
| 48 | +| `full` | the entire history, uncompressed — the ceiling, and it does not respect the budget | | |
| 49 | +| `tail` | the last messages until the budget is full, throw away the rest | | |
| 50 | +| `packer` | the packer being measured | | |
| 51 | 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. | |
| 52 | +**`tail` is the bar that has to be cleared, and it is the reason this benchmark exists.** Four generations of our packer were each measured against the previous one, all of them winning, and none of them against `tail`. When `tail` was finally put in, it turned out that one of those versions **scored below it**: compressing with it was worse than not compressing at all. If your packer does not beat *"keep the last bit and throw away the rest"*, nothing else you measure about it means anything. | |
| 53 | 53 | |
| 54 | -## Resultado sobre este mismo repositorio | |
| 54 | +## Result over this very repository | |
| 55 | 55 | |
| 56 | 56 | ``` |
| 57 | 57 | node run.mjs --root ../core --ext .js --seeds 8 |
| 58 | 58 | ``` |
| 59 | 59 | |
| 60 | -| presupuesto | `tail` | **`packer`** | `full` (techo) | | |
| 60 | +| budget | `tail` | **`packer`** | `full` (ceiling) | | |
| 61 | 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 | | |
| 62 | +| 3,000 | 48.4% | **93.8%** · 1,596 tok | 100% · 29,732 tok | | |
| 63 | +| 8,000 | 70.3% | **95.3%** · 2,965 tok | 100% · 29,732 tok | | |
| 64 | 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. | |
| 65 | +Note the token column: at a 8,000 budget the packer spends 2,965 — it stops when it runs out of *relevant material*, not when it runs out of room. The budget is a ceiling, not a quota. | |
| 66 | 66 | |
| 67 | -## Qué NO mide | |
| 67 | +8 sessions, 64 probes. | |
| 68 | 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. | |
| 69 | +⚠️ **These figures are a reference point, not a constant, and it is worth knowing why.** The corpus is this repository's own `core/`, and the sessions embed the genuine output of `git status`, `git log` and `ls -la` on the working tree. That is the whole point — real tool output, with its real noise — but it also means the numbers move when the tree moves. They are deterministic for a fixed state (run it twice, get the same thing) and they shifted by a couple of points when the comments in `core/` were translated to English, because translating the corpus *is* changing the corpus. | |
| 72 | 70 | |
| 73 | -Apache-2.0, como el resto del repositorio. | |
| 71 | +So: reproduce the ordering, not the third decimal. If `packer` is not far above `tail` on your tree, that is the signal — not whether it lands on 93.8. | |
| 72 | + | |
| 73 | +## What it does NOT measure | |
| 74 | + | |
| 75 | +- **That the model uses well what it receives.** Presence is a necessary condition, not a sufficient one: having the evidence in front of you does not guarantee getting it right. For that you need a benchmark with a model answering, with all the arbitration problems described above. | |
| 76 | +- **Questions whose answer is in no single line.** *"How many files have you touched?"* is spread across forty messages and no top-k selection reaches it, by construction. | |
| 77 | +- **Conversation.** This is built on agent sessions with tools. A packer tuned here can lose in dialogue: it happened to us, and the cause turned out to be the word splitter, not the packing policy. | |
| 78 | + | |
| 79 | +Apache-2.0, like the rest of the repository. |
modified bench/run.mjs +31 −30
| @@ -1,32 +1,32 @@ | ||
| 1 | 1 | #!/usr/bin/env node |
| 2 | 2 | /** |
| 3 | - * Banco de recuerdo de hechos para empaquetadores de contexto. | |
| 3 | + * Fact-recall benchmark for context packers. | |
| 4 | 4 | * |
| 5 | - * QUÉ MIDE, y por qué está hecho así: | |
| 5 | + * WHAT IT MEASURES, and why it is built this way: | |
| 6 | 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: | |
| 7 | + * Agent sessions are generated over a REAL project — every tool result is the | |
| 8 | + * genuine output of reading, listing or searching real files, not synthetic | |
| 9 | + * text. Halfway through the session the agent read a definition. At the end it | |
| 10 | + * is asked about it. The benchmark's only question is: | |
| 11 | 11 | * |
| 12 | - * ¿sigue esa definición dentro del contexto empaquetado? | |
| 12 | + * is that definition still inside the packed context? | |
| 13 | 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. | |
| 14 | + * There is NO model judging. It is a presence check: deterministic and | |
| 15 | + * reproducible. That matters more than it looks: scoring the SAME answers, | |
| 16 | + * three different judges gave us 0%, ~100% and something measurable, depending | |
| 17 | + * on the model and the prompt. A benchmark whose result depends on which judge | |
| 18 | + * you pick is no use for deciding between two packers. | |
| 19 | 19 | * |
| 20 | - * Todas las condiciones reciben el MISMO presupuesto de tokens. Lo que cambia | |
| 21 | - * es únicamente la política de selección. | |
| 20 | + * Every condition gets the SAME token budget. The only thing that changes is | |
| 21 | + * the selection policy. | |
| 22 | 22 | * |
| 23 | - * USO | |
| 24 | - * node run.mjs --root <ruta-de-un-repo> [--ext .js] [--budget 3000] | |
| 25 | - * [--seeds 8] [--packer <fichero.js>] | |
| 23 | + * USAGE | |
| 24 | + * node run.mjs --root <path-to-a-repo> [--ext .js] [--budget 3000] | |
| 25 | + * [--seeds 8] [--packer <file.js>] | |
| 26 | 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. | |
| 27 | + * --packer must export `packHistory(history, budgetTokens)`. By default it uses | |
| 28 | + * this repository's own core, so the README numbers reproduce with nothing to | |
| 29 | + * configure. | |
| 30 | 30 | */ |
| 31 | 31 | import { createRequire } from 'module'; |
| 32 | 32 | import path from 'path'; |
| @@ -44,13 +44,14 @@ | ||
| 44 | 44 | const PACKER = path.resolve(arg('packer', path.join(HERE, '..', 'core', 'context.js'))); |
| 45 | 45 | |
| 46 | 46 | if (!ROOT) { |
| 47 | - console.error('falta --root <ruta-de-un-repo>. Ej: node run.mjs --root ../core --ext .js'); | |
| 47 | + console.error('missing --root <path-to-a-repo>. E.g.: node run.mjs --root ../core --ext .js'); | |
| 48 | 48 | process.exit(2); |
| 49 | 49 | } |
| 50 | 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. | |
| 51 | +// The core reads flags from localStorage, which does not exist in Node. It is | |
| 52 | +// given an empty stand-in: that way the benchmark measures the DEFAULT | |
| 53 | +// behaviour, which is what has to be measured — not some configuration | |
| 54 | +// somebody left switched on. | |
| 54 | 55 | if (typeof globalThis.localStorage === 'undefined') { |
| 55 | 56 | const mem = new Map(); |
| 56 | 57 | globalThis.localStorage = { |
| @@ -63,9 +64,9 @@ | ||
| 63 | 64 | const { packHistory } = await import('file://' + PACKER); |
| 64 | 65 | const estTok = s => Math.ceil((s || '').length / 4) + 4; |
| 65 | 66 | |
| 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. | |
| 67 | +// CONDITIONS. `tail` is the bar that has to be cleared: keep the last messages | |
| 68 | +// until the budget is full and throw away the rest. If a packer does not beat | |
| 69 | +// this, everything else you measure about it is beside the point. | |
| 69 | 70 | const tail = (history, budget) => { |
| 70 | 71 | const out = []; let used = 0; |
| 71 | 72 | for (let i = history.length - 1; i >= 0; i--) { |
| @@ -102,10 +103,10 @@ | ||
| 102 | 103 | } |
| 103 | 104 | } |
| 104 | 105 | |
| 105 | -console.log(`\n ${ROOT} · ${sessions} sesiones · presupuesto ${BUDGET} tokens\n`); | |
| 106 | -console.log(` ${'condición'.padEnd(12)}${'recuerdo'.padStart(10)}${'tokens'.padStart(10)}`); | |
| 106 | +console.log(`\n ${ROOT} · ${sessions} sessions · budget ${BUDGET} tokens\n`); | |
| 107 | +console.log(` ${'condition'.padEnd(12)}${'recall'.padStart(10)}${'tokens'.padStart(10)}`); | |
| 107 | 108 | for (const [name, a] of Object.entries(acc)) { |
| 108 | 109 | if (!a.n) continue; |
| 109 | 110 | 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 | } |
| 111 | -console.log(`\n n = ${acc.packer.n} sondas\n`); | |
| 112 | +console.log(`\n n = ${acc.packer.n} probes\n`); |
modified core/ceo.js +49 −48
| @@ -1,28 +1,29 @@ | ||
| 1 | -// Cerebro CEO autónomo (compartido por Elffuss Code y Elffuss Claw): cuando el | |
| 2 | -// usuario NO está pidiendo nada (ocioso) y hay un modelo local cargado, la elfa | |
| 3 | -// «trabaja por su cuenta» — revisa el espacio de trabajo, reparte el trabajo en | |
| 4 | -// varios perfiles que piensan EN PARALELO (cada uno una línea de pensamiento en | |
| 5 | -// la vista Mente) y sintetiza propuestas de mejora. | |
| 1 | +// Autonomous CEO brain (shared by Elffuss Code and Elffuss Claw): when the user | |
| 2 | +// is NOT asking for anything (idle) and a local model is loaded, the elf "works | |
| 3 | +// on her own" — she surveys the workspace, splits the work across several | |
| 4 | +// profiles that think IN PARALLEL (each one a line of thought in the Mind view) | |
| 5 | +// and synthesises improvement proposals. | |
| 6 | 6 | // |
| 7 | -// Agnóstico de herramientas a propósito: cada app inyecta su propio adaptador | |
| 8 | -// de workspace (`init({ workspace, ... })`) — Code usa code.js (proyecto de | |
| 9 | -// código), Claw usa fs.js (carpetas con permiso). El core no sabe ni le importa | |
| 10 | -// cuál es. | |
| 7 | +// Deliberately tool-agnostic: each app injects its own workspace adapter | |
| 8 | +// (`init({ workspace, ... })`) — Code uses code.js (a code project), Claw uses | |
| 9 | +// fs.js (folders with permission). The core neither knows nor cares which. | |
| 11 | 10 | // |
| 12 | -// Seguridad: NO modifica tus ficheros. Deja las propuestas en una carpeta | |
| 13 | -// aditiva (nunca toca lo existente) y las hace «flotar» en la Mente. Se PARA en | |
| 14 | -// cuanto detecta actividad del usuario y reanuda al volver a estar ocioso. | |
| 11 | +// Safety: it does NOT modify your files. It leaves the proposals in an additive | |
| 12 | +// folder (it never touches what already exists) and makes them "float" in the | |
| 13 | +// Mind. It STOPS the moment it detects user activity and resumes once things | |
| 14 | +// are idle again. | |
| 15 | 15 | import { Agent } from './agent.js'; |
| 16 | 16 | import { humanizeTool } from './humanize.js'; |
| 17 | 17 | |
| 18 | -const IDLE_MS = 18000; // 18 s sin actividad → el CEO se pone a trabajar | |
| 19 | -const TICK_MS = 3000; // frecuencia de comprobación | |
| 20 | -// 5 min entre ciclos automáticos: con 45s, una tarde ociosa generaba MILES de | |
| 21 | -// ficheros. «Pensar ahora» (forceCycle) sigue disponible sin esperar esto. | |
| 18 | +const IDLE_MS = 18000; // no activity for this long → the CEO starts working | |
| 19 | +const TICK_MS = 3000; // how often we check | |
| 20 | +// Five minutes between automatic cycles: on a much shorter cooldown, one idle | |
| 21 | +// afternoon generated THOUSANDS of files. "Think now" (forceCycle) is still | |
| 22 | +// available without waiting for this. | |
| 22 | 23 | const COOLDOWN_MS = 300000; |
| 23 | -const SOUL_CAP = 25; // ficheros sueltos antes de consolidar en archivo.md | |
| 24 | +const SOUL_CAP = 25; // loose files before consolidating into archivo.md | |
| 24 | 25 | |
| 25 | -// perfil por defecto si la app anfitriona no da los suyos | |
| 26 | +// default profile if the host app does not supply its own | |
| 26 | 27 | const GENERIC_PROFILES = [ |
| 27 | 28 | { id: 'p1', name: 'Revisión', focus: 'qué mejorar de forma concreta y accionable', color: '#7c5cff' }, |
| 28 | 29 | { id: 'p2', name: 'Calidad', focus: 'errores, casos borde, cosas que podrían fallar', color: '#49e8ff' }, |
| @@ -31,11 +32,11 @@ | ||
| 31 | 32 | const slug = s => String(s).toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '') |
| 32 | 33 | .replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '').slice(0, 24) || 'perfil'; |
| 33 | 34 | |
| 34 | -// ── namespace (localStorage) y adaptador de workspace: los da la app anfitriona ── | |
| 35 | -let NS = 'elffuss'; // prefijo de las claves de localStorage | |
| 35 | +// ── namespace (localStorage) and workspace adapter: supplied by the host app ── | |
| 36 | +let NS = 'elffuss'; // prefix for the localStorage keys | |
| 36 | 37 | let ws = null; // { isReady, tree, write, read, list, remove } |
| 37 | 38 | let getProvider = () => null; |
| 38 | -let isBusy = () => false; // ¿el usuario tiene trabajo en cola/procesándose? → prioridad | |
| 39 | +let isBusy = () => false; // does the user have work queued/in flight? → priority | |
| 39 | 40 | let defaultProfiles = GENERIC_PROFILES; |
| 40 | 41 | const K = suffix => NS + '.' + suffix; |
| 41 | 42 | |
| @@ -61,8 +62,8 @@ | ||
| 61 | 62 | |
| 62 | 63 | let enabled = false, running = false, lastActivity = Date.now(), timer = null, lastCycleEnd = 0, cycleN = 0; |
| 63 | 64 | |
| 64 | -// MISIÓN reprogramable: el usuario puede reorientar el cerebro desde la Mente | |
| 65 | -// («céntrate en seguridad», «optimiza mis Excel», «documenta todo»…). | |
| 65 | +// Reprogrammable MISSION: the user can re-aim the brain from the Mind view | |
| 66 | +// ("focus on security", "optimise my spreadsheets", "document everything"…). | |
| 66 | 67 | let DEFAULT_MISSION = 'Revisar el espacio de trabajo y proponer mejoras concretas y accionables.'; |
| 67 | 68 | let mission = null; |
| 68 | 69 | function ensureMission() { if (mission == null) { try { mission = localStorage.getItem(K('ceoMission')) || DEFAULT_MISSION; } catch { mission = DEFAULT_MISSION; } } } |
| @@ -71,11 +72,11 @@ | ||
| 71 | 72 | mission = (text || '').trim() || DEFAULT_MISSION; |
| 72 | 73 | try { localStorage.setItem(K('ceoMission'), mission); } catch { /* */ } |
| 73 | 74 | emit('ceo', { type: 'reprogram', text: 'Nueva misión recibida: ' + mission }); |
| 74 | - lastCycleEnd = 0; lastActivity = Date.now() - IDLE_MS; // que arranque un ciclo pronto con la nueva misión | |
| 75 | + lastCycleEnd = 0; lastActivity = Date.now() - IDLE_MS; // start a cycle soon with the new mission | |
| 75 | 76 | return mission; |
| 76 | 77 | } |
| 77 | 78 | |
| 78 | -// Carpeta-«alma» donde el cerebro crea y guarda TODO (configurable). | |
| 79 | +// "Soul" folder where the brain creates and stores EVERYTHING (configurable). | |
| 79 | 80 | let DEFAULT_SOUL = '.elffuss/soul'; |
| 80 | 81 | let soulDir = null; |
| 81 | 82 | function ensureSoulDir() { if (soulDir == null) { try { soulDir = localStorage.getItem(K('ceoDir')) || DEFAULT_SOUL; } catch { soulDir = DEFAULT_SOUL; } } } |
| @@ -87,10 +88,10 @@ | ||
| 87 | 88 | return soulDir; |
| 88 | 89 | } |
| 89 | 90 | |
| 90 | -// ── semáforo cross-pestaña: UN SOLO cerebro ejecuta, TODAS visualizan ─────── | |
| 91 | -// El líder tiene un Web Lock exclusivo (se libera solo al cerrar la pestaña); | |
| 92 | -// difunde sus pensamientos por BroadcastChannel para que el resto los vea. | |
| 93 | -// (Aislado por origen por el propio navegador: Code y Claw nunca se cruzan.) | |
| 91 | +// ── cross-tab semaphore: ONE brain runs, ALL tabs display ────────────────── | |
| 92 | +// The leader holds an exclusive Web Lock (released on its own when the tab is | |
| 93 | +// closed); it broadcasts its thoughts over BroadcastChannel so the rest can see | |
| 94 | +// them. (Isolated per origin by the browser itself: Code and Claw never cross.) | |
| 94 | 95 | let isLeader = false, bc = null, realEmit = () => {}, crossTabWired = false; |
| 95 | 96 | function initCrossTab() { |
| 96 | 97 | if (crossTabWired) return; |
| @@ -98,7 +99,7 @@ | ||
| 98 | 99 | try { |
| 99 | 100 | bc = new BroadcastChannel(NS + '-ceo'); |
| 100 | 101 | bc.onmessage = e => { if (e.data && e.data.kind === 'thought') realEmit(e.data.channel, e.data.ev); }; |
| 101 | - } catch { /* sin BroadcastChannel */ } | |
| 102 | + } catch { /* no BroadcastChannel */ } | |
| 102 | 103 | if (navigator.locks && navigator.locks.request) { |
| 103 | 104 | navigator.locks.request(NS + '-ceo-leader', { mode: 'exclusive' }, () => new Promise(() => { isLeader = true; })) |
| 104 | 105 | .catch(() => { isLeader = true; }); |
| @@ -106,7 +107,7 @@ | ||
| 106 | 107 | } |
| 107 | 108 | function emit(channel, ev) { |
| 108 | 109 | realEmit(channel, ev); |
| 109 | - try { bc && bc.postMessage({ kind: 'thought', channel, ev }); } catch { /* ev no serializable */ } | |
| 110 | + try { bc && bc.postMessage({ kind: 'thought', channel, ev }); } catch { /* ev not serialisable */ } | |
| 110 | 111 | } |
| 111 | 112 | |
| 112 | 113 | // init({ workspace, provider, onEvent, isBusy, namespace, defaultProfiles, defaultMission, defaultSoulDir }) |
| @@ -125,12 +126,12 @@ | ||
| 125 | 126 | export function noteActivity() { lastActivity = Date.now(); if (running) running = 'interrupt'; } |
| 126 | 127 | export function isEnabled() { return enabled; } |
| 127 | 128 | export function isRunning() { return !!running; } |
| 128 | -// Play/stop: persistido AQUÍ (fuente única) — cualquier botón que lo toque | |
| 129 | -// queda sincronizado, y la elección sobrevive a recargar la página. | |
| 129 | +// Play/stop: persisted HERE (single source) — any button that touches it stays | |
| 130 | +// in sync, and the choice survives a page reload. | |
| 130 | 131 | export function wasEnabledLastSession() { try { return localStorage.getItem(K('ceoEnabled')) === '1'; } catch { return false; } } |
| 131 | -// ¿el usuario llegó a decidir alguna vez (play o stop)? Distingue «nunca lo | |
| 132 | -// tocó» de «lo pausó a propósito» — solo lo primero debe auto-activarse al | |
| 133 | -// abrir la Mente; lo segundo hay que RESPETARLO, no pisarlo. | |
| 132 | +// did the user ever actually decide (play or stop)? This tells "never touched | |
| 133 | +// it" apart from "paused it on purpose" — only the first should auto-enable | |
| 134 | +// when the Mind is opened; the second must be RESPECTED, not overridden. | |
| 134 | 135 | export function hasDecided() { try { return localStorage.getItem(K('ceoEnabled')) != null; } catch { return false; } } |
| 135 | 136 | export function enable() { |
| 136 | 137 | if (enabled) return; |
| @@ -146,12 +147,12 @@ | ||
| 146 | 147 | |
| 147 | 148 | function schedule() { if (timer) clearTimeout(timer); timer = setTimeout(tick, TICK_MS); } |
| 148 | 149 | |
| 149 | -// «Pensar ahora» — salta la espera de ociosidad. Sigue respetando el | |
| 150 | -// semáforo: si otra pestaña es la líder, no compite por la GPU. | |
| 150 | +// "Think now" — skips the idle wait. It still respects the semaphore: if | |
| 151 | +// another tab is the leader, it does not compete for the accelerator. | |
| 151 | 152 | export async function forceCycle() { |
| 152 | 153 | if (!isLeader) { emit('ceo', { type: 'paused', text: 'Otra pestaña lleva el cerebro — ábrela ahí para forzar un ciclo.' }); return false; } |
| 153 | 154 | if (running) return false; |
| 154 | - // isReady() puede ser síncrona (Code: handle en memoria) o async (Claw: consulta IndexedDB) — se espera siempre. | |
| 155 | + // isReady() may be sync (Code: handle in memory) or async (Claw: queries IndexedDB) — always awaited. | |
| 155 | 156 | if (!(await ws?.isReady()) || !getProvider()) { emit('ceo', { type: 'paused', text: 'Necesito un espacio de trabajo abierto y un modelo cargado.' }); return false; } |
| 156 | 157 | try { await runCycle(); } finally { lastCycleEnd = Date.now(); } |
| 157 | 158 | return true; |
| @@ -163,15 +164,15 @@ | ||
| 163 | 164 | const rested = Date.now() - lastCycleEnd > COOLDOWN_MS; |
| 164 | 165 | const mightRun = isLeader && !running && !isBusy() && idle >= IDLE_MS && rested && getProvider(); |
| 165 | 166 | if (mightRun && await ws?.isReady()) { |
| 166 | - try { await runCycle(); } catch { /* siguiente ciclo */ } | |
| 167 | + try { await runCycle(); } catch { /* next cycle */ } | |
| 167 | 168 | lastCycleEnd = Date.now(); |
| 168 | 169 | } |
| 169 | 170 | schedule(); |
| 170 | 171 | } |
| 171 | 172 | |
| 172 | -// helper: corre el agente con el proveedor actual sobre un prompt, emitiendo | |
| 173 | -// tokens/herramientas a un canal. Devuelve el texto final. Las tool-calls pasan | |
| 174 | -// SIEMPRE por el mismo runTool que usa el chat normal (Agent.handle real). | |
| 173 | +// helper: runs the agent with the current provider over a prompt, emitting | |
| 174 | +// tokens/tools to a channel. Returns the final text. Tool calls ALWAYS go | |
| 175 | +// through the same runTool the normal chat uses (the real Agent.handle). | |
| 175 | 176 | async function think(channel, task) { |
| 176 | 177 | const prov = getProvider(); |
| 177 | 178 | if (!prov) return ''; |
| @@ -193,7 +194,7 @@ | ||
| 193 | 194 | emit('ceo', { type: 'cycle', n: cycleN, text: 'Nuevo ciclo: reviso el espacio de trabajo y reparto el trabajo…' }); |
| 194 | 195 | |
| 195 | 196 | let tree = ''; |
| 196 | - try { tree = await ws.tree({ depth: 2 }); } catch { /* sin workspace */ } | |
| 197 | + try { tree = await ws.tree({ depth: 2 }); } catch { /* no workspace */ } | |
| 197 | 198 | emit('ceo', { type: 'survey', text: 'Panorama captado (' + tree.split('\n').length + ' entradas). Delegando…' }); |
| 198 | 199 | |
| 199 | 200 | const brief = (d) => `MISIÓN del equipo (fijada por el usuario): ${getMission()}\n` + |
| @@ -225,14 +226,14 @@ | ||
| 225 | 226 | running = false; |
| 226 | 227 | } |
| 227 | 228 | |
| 228 | -// Rotación: si hay demasiados ficheros sueltos, los MÁS ANTIGUOS se consolidan | |
| 229 | -// (recopilan) en un único archivo.md y se borran — para no acabar con miles. | |
| 229 | +// Rotation: if there are too many loose files, the OLDEST ones are consolidated | |
| 230 | +// into a single archivo.md and deleted — so we do not end up with thousands. | |
| 230 | 231 | async function rotateSoul() { |
| 231 | 232 | try { |
| 232 | 233 | const soul = getSoulDir(); |
| 233 | 234 | const names = (await ws.list(soul)).filter(n => n.endsWith('.md') && n !== 'archivo.md'); |
| 234 | 235 | if (names.length < SOUL_CAP) return; |
| 235 | - names.sort(); // el nombre empieza por fecha → orden cronológico | |
| 236 | + names.sort(); // the name starts with the date → chronological order | |
| 236 | 237 | const excess = names.slice(0, names.length - SOUL_CAP + 1); |
| 237 | 238 | let archive = ''; try { archive = await ws.read({ path: `${soul}/archivo.md` }); } catch { archive = '# Archivo histórico del cerebro\n'; } |
| 238 | 239 | for (const name of excess) { |
| @@ -241,5 +242,5 @@ | ||
| 241 | 242 | await ws.write({ path: `${soul}/archivo.md`, content: archive.slice(-80000) }); |
| 242 | 243 | for (const name of excess) { try { await ws.remove(soul, name); } catch { /* */ } } |
| 243 | 244 | emit('ceo', { type: 'reprogram', text: `Consolidé ${excess.length} propuestas antiguas en archivo.md` }); |
| 244 | - } catch { /* soulDir aún sin crear o sin permiso: nada que rotar */ } | |
| 245 | + } catch { /* soulDir not created yet, or no permission: nothing to rotate */ } | |
| 245 | 246 | } |
modified core/context.js +311 −293
| @@ -1,82 +1,85 @@ | ||
| 1 | -// Gestor de contexto: selección del historial por RELEVANCIA frente a la | |
| 2 | -// pregunta viva. BM25 con IDF endógena + control de redundancia (MMR), y de | |
| 3 | -// forma opcional una segunda opinión semántica fusionada por rangos. | |
| 1 | +// Context manager: selecting the history by RELEVANCE against the live | |
| 2 | +// question. BM25 with endogenous IDF + redundancy control (MMR), and optionally | |
| 3 | +// a second, semantic opinion fused by rank. | |
| 4 | 4 | // |
| 5 | -// ── qué cambió respecto de la versión anterior, y por qué ──────────────────── | |
| 5 | +// ── what changed from the previous version, and why ───────────────────────── | |
| 6 | 6 | // |
| 7 | -// 1. FUERA la lista de parada escrita a mano. Antes había un STOP con ~90 | |
| 8 | -// palabras castellanas. La IDF ya se calcula sobre el propio historial, así | |
| 9 | -// que lo ubicuo recibe peso casi nulo por construcción — sin diccionario y | |
| 10 | -// sin saber en qué idioma estamos. Una lista a mano solo sabía castellano: | |
| 11 | -// en una sesión de código en inglés no filtraba nada, y en cualquier idioma | |
| 12 | -// envejecía. La IDF endógena se adapta a cada conversación. | |
| 7 | +// 1. OUT goes the hand-written stoplist. There used to be a STOP list of ~90 | |
| 8 | +// Spanish words. IDF is already computed over the history itself, so | |
| 9 | +// whatever is ubiquitous gets near-zero weight by construction — with no | |
| 10 | +// dictionary and without knowing what language we are in. A hand-written | |
| 11 | +// list only knew Spanish: in an English coding session it filtered nothing, | |
| 12 | +// and in any language it aged. Endogenous IDF adapts to every conversation. | |
| 13 | 13 | // |
| 14 | -// 2. FUERA el recorte ciego de resultados antiguos. Antes se truncaban a 600 | |
| 15 | -// caracteres los `[resultado …]` viejos ANTES de puntuarlos. No se puede | |
| 16 | -// recuperar lo que se tiró antes de medir si importaba: si la respuesta | |
| 17 | -// estaba en el carácter 900, ya no había forma de encontrarla. Ahora se | |
| 18 | -// puntúa primero y se recorta después, y por línea. | |
| 14 | +// 2. OUT goes the blind trimming of old results. Old `[resultado …]` messages | |
| 15 | +// used to be truncated to 600 characters BEFORE being scored. You cannot | |
| 16 | +// retrieve what you threw away before measuring whether it mattered: if the | |
| 17 | +// answer was at character 900, there was no longer any way to find it. Now | |
| 18 | +// it is scored first and trimmed afterwards, and per line. | |
| 19 | 19 | // |
| 20 | -// 3. Granularidad de LÍNEA, no de mensaje. Un resultado de herramienta es | |
| 21 | -// mayoritariamente ruido con dos líneas útiles; quedárselo o tirarlo entero | |
| 22 | -// desperdicia presupuesto en ambos sentidos. | |
| 20 | +// 3. LINE granularity, not message granularity. A tool result is mostly noise | |
| 21 | +// with two useful lines in it; keeping it whole or dropping it whole wastes | |
| 22 | +// budget in both directions. | |
| 23 | 23 | // |
| 24 | -// 4. Control de REDUNDANCIA (MMR). Es lo único que suma por encima de BM25, y | |
| 25 | -// poco: +2,4 puntos a escala completa. (Un smoke de 3 semillas decía +8,9; | |
| 26 | -// era ruido de semilla. BM25 con IDF endógena hace casi todo el trabajo.) | |
| 24 | +// 4. REDUNDANCY control (MMR). It is the only thing that adds anything on top | |
| 25 | +// of BM25, and not much: +2.4 points at full scale. (A 3-seed smoke test | |
| 26 | +// said +8.9; that was seed noise. BM25 with endogenous IDF does almost all | |
| 27 | +// of the work.) | |
| 27 | 28 | // |
| 28 | -// 5. Las perillas salen de la PRESIÓN medida, no de constantes — ver prepare(). | |
| 29 | +// 5. The knobs come from the measured PRESSURE, not from constants — see prepare(). | |
| 29 | 30 | // |
| 30 | -// 6. FECHAS ABSOLUTAS al escribir. «ayer» dicho en el turno 3 es mentira en el | |
| 31 | -// turno 40, y eso NO es un fallo de recuperación: la línea se recupera bien y | |
| 32 | -// lo que lleva es falso. Se anota la fecha del turno junto al original — ver | |
| 33 | -// annotateDates. Sonda propia (el banco de hechos no puede verlo): la fecha | |
| 34 | -// pasa de estar el 0 % de las veces a estar el 100 %, por +7 tokens. | |
| 31 | +// 6. ABSOLUTE DATES at write time. "yesterday", said on turn 3, is a lie on | |
| 32 | +// turn 40, and that is NOT a retrieval failure: the line is retrieved just | |
| 33 | +// fine and what it carries is false. The turn's date is annotated next to | |
| 34 | +// the original — see annotateDates. Our own probe (the fact benchmark cannot | |
| 35 | +// see this): the date goes from being present 0% of the time to 100% of the | |
| 36 | +// time, for +7 tokens. | |
| 35 | 37 | // |
| 36 | -// 7. TARJETA DE RECUENTO, tras bandera. «¿cuántos ficheros has tocado?» no está | |
| 37 | -// en ninguna línea; ningún top-k la encuentra por construcción. Se cuenta al | |
| 38 | -// escribir — ver buildLedger. Cuesta −0,7 puntos de recall a presupuesto | |
| 39 | -// 3.000 y nada a 16.000, así que va apagada por defecto. | |
| 38 | +// 7. TALLY CARD, behind a flag. "how many files have you touched?" is in no | |
| 39 | +// line at all; no top-k finds it, by construction. It is counted at write | |
| 40 | +// time — see buildLedger. It costs −0.7 points of recall at budget 3,000 and | |
| 41 | +// nothing at 16,000, so it is off by default. | |
| 40 | 42 | // |
| 41 | -// Medido a igual presupuesto de tokens (recall de hechos, sin juez LLM; | |
| 42 | -// 25 sesiones, 174 sondas): | |
| 43 | -// truncar por la cola ......... 7,0 % | |
| 44 | -// empaquetador anterior ....... 15,1 % | |
| 45 | -// este ........................ 65,3 % ± 8,5 | |
| 43 | +// Measured at equal token budget (fact recall, no LLM judge; 25 sessions, | |
| 44 | +// 174 probes): | |
| 45 | +// tail truncation ............. 7.0% | |
| 46 | +// previous packer ............. 15.1% | |
| 47 | +// this one .................... 65.3% ± 8.5 | |
| 46 | 48 | // |
| 47 | -// El presupuesto es en tokens (~4 chars/token). Los últimos RECENT mensajes se | |
| 48 | -// conservan literales mientras quepan en su reserva; el resto compite. | |
| 49 | +// The budget is in tokens (~4 chars/token). The last RECENT messages are kept | |
| 50 | +// verbatim as long as they fit in their reserve; everything else competes. | |
| 49 | 51 | |
| 50 | 52 | const RECENT = 6; |
| 51 | -// La reserva de recientes ya no es constante: sale de la presión medida (ver | |
| 52 | -// prepare). Sin tope, un solo resultado enorme se come el presupuesto entero. | |
| 53 | +// The recent-messages reserve is no longer a constant: it comes out of the | |
| 54 | +// measured pressure (see prepare). Without a cap, one huge result eats the | |
| 55 | +// entire budget. | |
| 53 | 56 | const MAX_MSG_CHARS = 12000; |
| 54 | -// λ y nº de candidatos NO son constantes: ver measureRedundancy() y | |
| 55 | -// selectAndEmit(). Un λ fijo destruye información buena cuando el material no | |
| 56 | -// es redundante, y 600 candidatos fijos dejan sin mirar la mayor parte del | |
| 57 | -// historial en cuanto el presupuesto es grande — que es el caso real. | |
| 57 | +// λ and the number of candidates are NOT constants: see measureRedundancy() and | |
| 58 | +// selectAndEmit(). A fixed λ destroys good information when the material is not | |
| 59 | +// redundant, and a fixed 600 candidates leaves most of the history unlooked-at | |
| 60 | +// as soon as the budget is large — which is the real case. | |
| 58 | 61 | const RRF_K = 60; |
| 59 | 62 | |
| 60 | -// Sin lista de parada: de eso se encarga la IDF. Se admiten tokens de 2 | |
| 61 | -// caracteres porque en código los identificadores cortos a veces son justo | |
| 62 | -// lo que se busca (`fs`, `db`, `id`). | |
| 63 | -// Emite el token COMPUESTO y además sus PARTES. | |
| 63 | +// No stoplist: IDF takes care of that. Two-character tokens are allowed | |
| 64 | +// because in code the short identifiers are sometimes exactly what is being | |
| 65 | +// looked for (`fs`, `db`, `id`). | |
| 66 | +// It emits the COMPOUND token and also its PARTS. | |
| 64 | 67 | // |
| 65 | -// El partidor anterior estaba afinado para código y en diálogo perdía: exigía | |
| 66 | -// empezar por letra —así que «3pm», «2nd» o «5» desaparecían enteros, y en | |
| 67 | -// conversación eso son horas, ordinales y fechas— y mantenía `src/utils.js` | |
| 68 | -// como UN token, de modo que preguntar por «utils» no casaba con la línea que | |
| 69 | -// lo contiene. | |
| 68 | +// The previous tokeniser was tuned for code and lost in dialogue: it required | |
| 69 | +// starting with a letter — so "3pm", "2nd" or "5" disappeared entirely, and in | |
| 70 | +// conversation those are times, ordinals and dates — and it kept | |
| 71 | +// `src/utils.js` as ONE token, so asking about "utils" did not match the line | |
| 72 | +// that contains it. | |
| 70 | 73 | // |
| 71 | -// Medido: cambiar SOLO esto, con todo lo demás igual, explicaba 3,5 de los 4,8 | |
| 72 | -// puntos que nos separaban de un BM25 con otro partidor en un banco de diálogo. | |
| 73 | -// Y en el banco de sesiones de agente subió el recuerdo de hechos del 82,1 % al | |
| 74 | -// 94,9 % (presupuesto 3.000) y del 85,9 % al 100 % (16.000). No era la política | |
| 75 | -// de empaquetado: era el partidor de palabras. | |
| 74 | +// Measured: changing ONLY this, with everything else equal, explained 3.5 of | |
| 75 | +// the 4.8 points that separated us from a BM25 with a different tokeniser on a | |
| 76 | +// dialogue benchmark. And on the agent-session benchmark it raised fact recall | |
| 77 | +// from 82.1% to 94.9% (budget 3,000) and from 85.9% to 100% (16,000). It was | |
| 78 | +// not the packing policy: it was the word splitter. | |
| 76 | 79 | // |
| 77 | -// La forma compuesta se conserva porque en código ES el identificador y casa | |
| 78 | -// exacto; las partes se añaden para el emparejamiento parcial. Se pagan más | |
| 79 | -// términos por línea, y de eso ya se encarga la normalización por longitud. | |
| 80 | +// The compound form is kept because in code it IS the identifier and it matches | |
| 81 | +// exactly; the parts are added for partial matching. You pay for more terms per | |
| 82 | +// line, and length normalisation already takes care of that. | |
| 80 | 83 | const tokens = s => { |
| 81 | 84 | const out = [], seen = new Set(); |
| 82 | 85 | const push = t => { if (t.length >= 2 && !seen.has(t)) { seen.add(t); out.push(t); } }; |
| @@ -86,11 +89,11 @@ | ||
| 86 | 89 | } |
| 87 | 90 | return out; |
| 88 | 91 | }; |
| 89 | -// Estimador de tokens. `longitud/4` sirve para prosa pero SUBESTIMA mucho el | |
| 90 | -// código: la puntuación densa (`{`, `=>`, `.`, `(`) son tokens de un carácter. | |
| 91 | -// Medido, contar solo por longitud hacía que el empaquetador creyera que cabía | |
| 92 | -// y se pasara ~1,5× del presupuesto — es decir, el «Too many tokens» que este | |
| 93 | -// fichero existe para evitar. Se toma el MAYOR de las dos estimaciones. | |
| 92 | +// Token estimator. `length/4` works for prose but badly UNDERESTIMATES code: | |
| 93 | +// dense punctuation (`{`, `=>`, `.`, `(`) are one-character tokens. Measured, | |
| 94 | +// counting by length alone made the packer believe things fitted and overshoot | |
| 95 | +// the budget by ~1.5× — that is, the "Too many tokens" this file exists to | |
| 96 | +// prevent. The LARGER of the two estimates is taken. | |
| 94 | 97 | const estTok = s => { |
| 95 | 98 | if (!s) return 0; |
| 96 | 99 | const pieces = (s.match(/\w+|[^\w\s]/g) || []).length; |
| @@ -106,15 +109,15 @@ | ||
| 106 | 109 | return { ...m, content: c.slice(0, head) + `\n… [recortado ${c.length - MAX_MSG_CHARS} caracteres] …\n` + c.slice(-tail) }; |
| 107 | 110 | } |
| 108 | 111 | |
| 109 | -// BM25 con saturación (k1) y normalización por longitud (b). La IDF sale del | |
| 110 | -// propio corpus que se le pasa — ahí está la gracia. | |
| 112 | +// BM25 with saturation (k1) and length normalisation (b). The IDF comes out of | |
| 113 | +// the very corpus it is handed — that is the whole point. | |
| 111 | 114 | // |
| 112 | -// Okapi BM25: Robertson, Walker, Jones, Hancock-Beaulieu & Gatford, «Okapi at | |
| 113 | -// TREC-3», TREC-3, 1994. Formulación moderna y justificación de k1/b: | |
| 114 | -// Robertson & Zaragoza, «The Probabilistic Relevance Framework: BM25 and | |
| 115 | -// Beyond», FnTIR 3(4), 2009 — https://doi.org/10.1561/1500000019 | |
| 116 | -// La IDF viene de Sparck Jones, Journal of Documentation 28(1), 1972: la idea | |
| 117 | -// de que lo raro informa, que es sobre la que se sostiene todo esto. | |
| 115 | +// Okapi BM25: Robertson, Walker, Jones, Hancock-Beaulieu & Gatford, "Okapi at | |
| 116 | +// TREC-3", TREC-3, 1994. Modern formulation and justification of k1/b: | |
| 117 | +// Robertson & Zaragoza, "The Probabilistic Relevance Framework: BM25 and | |
| 118 | +// Beyond", FnTIR 3(4), 2009 — https://doi.org/10.1561/1500000019 | |
| 119 | +// The IDF comes from Sparck Jones, Journal of Documentation 28(1), 1972: the | |
| 120 | +// idea that what is rare is what informs, which is what all of this rests on. | |
| 118 | 121 | function buildBM25(docs, k1 = 1.2, b = 0.75) { |
| 119 | 122 | const N = docs.length || 1; |
| 120 | 123 | const df = new Map(), tfs = []; |
| @@ -143,9 +146,9 @@ | ||
| 143 | 146 | |
| 144 | 147 | const simTokens = s => new Set(((s || '').toLowerCase().match(/[a-z0-9_./-]{2,}/g) || [])); |
| 145 | 148 | |
| 146 | -// Redundancia REAL del material, muestreada. Un historial de resultados de | |
| 147 | -// herramienta casi idénticos pide penalizar fuerte; una conversación donde cada | |
| 148 | -// línea es distinta, casi nada — y ahí un λ alto solo tira información buena. | |
| 149 | +// The material's REAL redundancy, sampled. A history of near-identical tool | |
| 150 | +// results calls for a hard penalty; a conversation where every line is | |
| 151 | +// different, almost none — and there a high λ only throws good information away. | |
| 149 | 152 | function measureRedundancy(items, sample = 240) { |
| 150 | 153 | if (items.length < 4) return 0; |
| 151 | 154 | const step = Math.max(1, Math.floor(items.length / sample)); |
| @@ -169,10 +172,10 @@ | ||
| 169 | 172 | return (na && nb) ? d / Math.sqrt(na * nb) : 0; |
| 170 | 173 | } |
| 171 | 174 | |
| 172 | -// Fusión por rangos recíprocos (RRF — Cormack, Clarke & Buettcher, SIGIR 2009, | |
| 173 | -// https://doi.org/10.1145/1571941.1572114): se mezclan POSICIONES, no | |
| 174 | -// puntuaciones, así no hay que calibrar escalas entre un BM25 sin acotar y un | |
| 175 | -// coseno en [-1,1]. | |
| 175 | +// Reciprocal rank fusion (RRF — Cormack, Clarke & Buettcher, SIGIR 2009, | |
| 176 | +// https://doi.org/10.1145/1571941.1572114): POSITIONS are mixed, not scores, so | |
| 177 | +// there is no need to calibrate scales between an unbounded BM25 and a cosine | |
| 178 | +// in [-1,1]. | |
| 176 | 179 | function rrf(lists, k = RRF_K) { |
| 177 | 180 | const out = new Map(); |
| 178 | 181 | for (const list of lists) list.forEach((id, r) => out.set(id, (out.get(id) || 0) + 1 / (k + r + 1))); |
| @@ -180,24 +183,25 @@ | ||
| 180 | 183 | } |
| 181 | 184 | |
| 182 | 185 | /** |
| 183 | - * CADUCIDAD — el mismo problema que ya resolvimos en el vigilante de carpetas, | |
| 184 | - * un piso más arriba. | |
| 186 | + * STALENESS — the same problem we already solved in the folder watcher, one | |
| 187 | + * floor up. | |
| 185 | 188 | * |
| 186 | - * El agente lee un fichero en el turno 3 y lo EDITA en el 20. BM25 recupera las | |
| 187 | - * dos versiones y la vieja puntúa igual de alto, porque comparte todo el | |
| 188 | - * vocabulario con la nueva. El modelo ve contenido obsoleto sin ninguna señal | |
| 189 | - * de que lo es — y eso no es ineficiencia, es INCORRECCIÓN: ninguna cantidad de | |
| 190 | - * relevancia arregla que el dato sea falso. Medido con una sonda leer→editar→ | |
| 191 | - * releer (8 semillas): la versión FALSA sobrevivía 8/8; con esto, 0/8, y la | |
| 192 | - * verdadera sigue 8/8, sin coste en recall. | |
| 189 | + * The agent reads a file on turn 3 and EDITS it on turn 20. BM25 retrieves both | |
| 190 | + * versions and the old one scores just as high, because it shares all of its | |
| 191 | + * vocabulary with the new one. The model sees stale content with no signal that | |
| 192 | + * it is stale — and that is not inefficiency, it is INCORRECTNESS: no amount of | |
| 193 | + * relevance fixes the fact that the datum is false. Measured with a | |
| 194 | + * read→edit→re-read probe (8 seeds): the FALSE version survived 8/8; with this, | |
| 195 | + * 0/8, and the true one still survives 8/8, at no cost in recall. | |
| 193 | 196 | * |
| 194 | - * El objetivo NO viene en el resultado: sale de la llamada del asistente | |
| 195 | - * anterior. Se DEGRADA, no se borra — con una salvedad medida: preguntando | |
| 196 | - * EXPRESAMENTE por el valor anterior, la vieja vuelve 0 de 8 veces. Está en el | |
| 197 | - * conjunto y no se recupera, porque compite entre cientos de líneas de | |
| 198 | - * puntuación cero y quién vuelve lo decide la diversidad, no la pregunta. | |
| 199 | - * ALCANZABLE NO ES RECUPERABLE: la diferencia entre «ya no es cierto» y «nunca | |
| 200 | - * existió» es real en la estructura y aún no en el comportamiento. | |
| 197 | + * The target does NOT come in the result: it comes from the preceding | |
| 198 | + * assistant call. It is DEMOTED, not deleted — with one measured caveat: asking | |
| 199 | + * EXPRESSLY for the previous value, the old one comes back 0 times out of 8. It | |
| 200 | + * is in the set and it does not get retrieved, because it competes among | |
| 201 | + * hundreds of zero-scoring lines and what comes back is decided by diversity, | |
| 202 | + * not by the question. REACHABLE IS NOT RETRIEVABLE: the difference between "it | |
| 203 | + * is no longer true" and "it never existed" is real in the structure and not | |
| 204 | + * yet in the behaviour. | |
| 201 | 205 | */ |
| 202 | 206 | function markSuperseded(msgs) { |
| 203 | 207 | const lastFor = new Map(), targetOf = new Map(); |
| @@ -215,31 +219,33 @@ | ||
| 215 | 219 | } |
| 216 | 220 | |
| 217 | 221 | /** |
| 218 | - * FECHAS ABSOLUTAS AL ESCRIBIR — la otra cara de markSuperseded. | |
| 222 | + * ABSOLUTE DATES AT WRITE TIME — the other face of markSuperseded. | |
| 219 | 223 | * |
| 220 | - * «lo desplegamos ayer», escrito en el turno 3, es una MENTIRA en el turno 40. | |
| 221 | - * Y esto no lo arregla ninguna perilla de BM25, porque no es un fallo de | |
| 222 | - * recuperación: la línea se recupera perfectamente y el dato que lleva es falso. | |
| 223 | - * Igual que la caducidad — relevancia perfecta, contenido incorrecto — solo que | |
| 224 | - * aquí lo que caduca es la palabra, no el fichero. | |
| 224 | + * "we deployed it yesterday", written on turn 3, is a LIE on turn 40. And no | |
| 225 | + * BM25 knob fixes this, because it is not a retrieval failure: the line is | |
| 226 | + * retrieved perfectly and the datum it carries is false. Same as staleness — | |
| 227 | + * perfect relevance, incorrect content — except that here what goes stale is | |
| 228 | + * the word, not the file. | |
| 225 | 229 | * |
| 226 | - * Por eso se resuelve al ESCRIBIR: al indexar todavía se sabe cuándo se dijo. | |
| 227 | - * Un turno después, ya no. | |
| 230 | + * That is why it is resolved at WRITE time: while indexing, we still know when | |
| 231 | + * it was said. One turn later, we no longer do. | |
| 228 | 232 | * |
| 229 | - * · Se ANOTA junto al original, no se sustituye: «ayer (2026-08-07)». Si la | |
| 230 | - * resolución se equivoca, el modelo sigue viendo la frase de verdad. | |
| 231 | - * · La referencia es la marca DEL TURNO (`m.ts`/time/timestamp/date). Sin | |
| 232 | - * marca y sin `now` explícito NO SE ANOTA: inventar una fecha es justo el | |
| 233 | - * fallo que esto viene a quitar. | |
| 234 | - * · Precisión honesta: lo que el idioma dice con precisión de día lleva un | |
| 235 | - * día; lo de semana o mes lleva el rango de la semana o el mes. | |
| 236 | - * · ⚠️ No se tocan vallas de código ni resultados de herramienta: un | |
| 237 | - * `2026-08-07` dentro de un diff no es una referencia temporal. | |
| 233 | + * · It is ANNOTATED next to the original, not substituted: "ayer | |
| 234 | + * (2026-08-07)". If the resolution gets it wrong, the model still sees the | |
| 235 | + * real sentence. | |
| 236 | + * · The reference is the TURN's stamp (`m.ts`/time/timestamp/date). With no | |
| 237 | + * stamp and no explicit `now`, NOTHING IS ANNOTATED: making up a date is | |
| 238 | + * precisely the failure this came to remove. | |
| 239 | + * · Honest precision: what the language states with day precision gets a day; | |
| 240 | + * what it states by week or month gets the range of that week or month. | |
| 241 | + * · ⚠️ Code fences and tool results are left alone: a `2026-08-07` inside a | |
| 242 | + * diff is not a temporal reference. | |
| 238 | 243 | * |
| 239 | - * Medido con sonda propia (el banco de hechos no puede ver esto: pregunta por | |
| 240 | - * identificadores), 32 sesiones reales, la frase en cuatro posiciones distintas: | |
| 241 | - * la línea se recupera 100 % · la FECHA está sin anotar 0 % · anotada 100 % · | |
| 242 | - * fecha falsa (si se usara «ahora») 0 %. Coste +7 tokens sobre 2.223. | |
| 244 | + * Measured with our own probe (the fact benchmark cannot see this: it asks | |
| 245 | + * about identifiers), 32 real sessions, the sentence in four different | |
| 246 | + * positions: the line is retrieved 100% · the DATE is there unannotated 0% · | |
| 247 | + * annotated 100% · false date (had "now" been used) 0%. Cost: +7 tokens on | |
| 248 | + * top of 2,223. | |
| 243 | 249 | */ |
| 244 | 250 | const DAY = 86400000; |
| 245 | 251 | const isoDay = d => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; |
| @@ -252,7 +258,7 @@ | ||
| 252 | 258 | const WORD_N = { un: 1, una: 1, uno: 1, dos: 2, tres: 3, cuatro: 4, cinco: 5, seis: 6, siete: 7, ocho: 8, nueve: 9, diez: 10, |
| 253 | 259 | a: 1, an: 1, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10 }; |
| 254 | 260 | const asNum = s => (/^\d+$/.test(s) ? parseInt(s, 10) : (WORD_N[s.toLowerCase()] || null)); |
| 255 | -// Precisión honesta: día → día, semana → rango de la semana, mes → mes. | |
| 261 | +// Honest precision: day → day, week → range of the week, month → month. | |
| 256 | 262 | function shiftBy(ref, n, unit, sign) { |
| 257 | 263 | if (n == null || n > 500) return null; |
| 258 | 264 | const u = unit.toLowerCase()[0]; |
| @@ -262,10 +268,11 @@ | ||
| 262 | 268 | if (u === 'a' || u === 'y') return String(plusMonths(ref, sign * 12 * n).getFullYear()); |
| 263 | 269 | return null; |
| 264 | 270 | } |
| 265 | -// dir<0 la anterior estricta · dir>0 la siguiente · dir=0 la más reciente | |
| 266 | -// contando hoy. El día suelto («el lunes») es AMBIGUO en los dos idiomas: se | |
| 267 | -// resuelve como retrospectivo porque en una bitácora de trabajo casi siempre lo | |
| 268 | -// es. Es la única regla de aquí que puede fallar, y por eso el original se queda. | |
| 271 | +// dir<0 the strictly previous one · dir>0 the next one · dir=0 the most recent | |
| 272 | +// one, counting today. A bare weekday ("el lunes") is AMBIGUOUS in both | |
| 273 | +// languages: it resolves as backward-looking because in a work log it almost | |
| 274 | +// always is. It is the only rule here that can be wrong, and that is why the | |
| 275 | +// original stays. | |
| 269 | 276 | function nearestDow(ref, target, dir) { |
| 270 | 277 | const cur = ref.getDay(); |
| 271 | 278 | if (dir > 0) { const f = (target - cur + 7) % 7; return plusDays(ref, f || 7); } |
| @@ -276,10 +283,10 @@ | ||
| 276 | 283 | const UNIT_P = 'd[ií]as?|semanas?|mes(?:es)?|años?|anos?|days?|weeks?|months?|years?'; |
| 277 | 284 | const DOW_ES = 'lunes|martes|mi[ée]rcoles|jueves|viernes|s[áa]bado|domingo'; |
| 278 | 285 | const DOW_EN = 'monday|tuesday|wednesday|thursday|friday|saturday|sunday'; |
| 279 | -// Orden = precedencia: la alternancia se queda con la PRIMERA que encaja. | |
| 286 | +// Order = precedence: the alternation keeps the FIRST one that fits. | |
| 280 | 287 | const WHEN = [ |
| 281 | - // «por la mañana» no es «mañana»: se reconoce para NO anotarla y para que la | |
| 282 | - // regla corta no llegue a verla. | |
| 288 | + // "por la mañana" (in the morning) is not "mañana" (tomorrow): it is matched | |
| 289 | + // so that it is NOT annotated, and so the short rule never gets to see it. | |
| 283 | 290 | ['\\b(?:por|de|a|en|desde|hasta)\\s+la\\s+mañana\\b|\\b(?:esta|una|cada|toda\\s+la|la)\\s+mañana\\b', () => null], |
| 284 | 291 | ['\\bantes\\s+de\\s+ayer\\b|\\banteayer\\b|\\bthe\\s+day\\s+before\\s+yesterday\\b', (m, r) => isoDay(plusDays(r, -2))], |
| 285 | 292 | ['\\bpasado\\s+mañana\\b|\\bthe\\s+day\\s+after\\s+tomorrow\\b', (m, r) => isoDay(plusDays(r, 2))], |
| @@ -297,8 +304,8 @@ | ||
| 297 | 304 | (m, r) => isoDay(nearestDow(r, DOW[m[1].toLowerCase()], /pasado/i.test(m[2]) ? -1 : 1))], |
| 298 | 305 | [`\\b(last|next|this)\\s+(${DOW_EN})\\b`, |
| 299 | 306 | (m, r) => isoDay(nearestDow(r, DOW[m[2].toLowerCase()], /last/i.test(m[1]) ? -1 : (/next/i.test(m[1]) ? 1 : 0)))], |
| 300 | - // Sin modificador hace falta artículo o preposición: un «Monday» suelto puede | |
| 301 | - // ser un nombre propio o un fichero. | |
| 307 | + // With no modifier, an article or preposition is required: a bare "Monday" | |
| 308 | + // may be a proper name or a file. | |
| 302 | 309 | [`\\bel\\s+(${DOW_ES})\\b`, (m, r) => isoDay(nearestDow(r, DOW[m[1].toLowerCase()], 0))], |
| 303 | 310 | [`\\bon\\s+(${DOW_EN})\\b`, (m, r) => isoDay(nearestDow(r, DOW[m[1].toLowerCase()], 0))], |
| 304 | 311 | ['\\banoche\\b|\\blast\\s+night\\b', (m, r) => isoDay(plusDays(r, -1))], |
| @@ -308,13 +315,13 @@ | ||
| 308 | 315 | ]; |
| 309 | 316 | const WHEN_RE = new RegExp(WHEN.map(w => `(?:${w[0]})`).join('|'), 'gi'); |
| 310 | 317 | const WHEN_ONE = WHEN.map(w => new RegExp(`^(?:${w[0]})$`, 'i')); |
| 311 | -// Vallas, acentos graves y valla sin cerrar (mensaje a medio llegar). | |
| 318 | +// Fences, backticks, and an unclosed fence (a message still arriving). | |
| 312 | 319 | const FENCE = /```[\s\S]*?```|```[\s\S]*$|~~~[\s\S]*?~~~|`[^`\n]+`/g; |
| 313 | 320 | |
| 314 | 321 | export function annotateDates(text, refMs) { |
| 315 | 322 | if (!text) return text; |
| 316 | 323 | WHEN_RE.lastIndex = 0; |
| 317 | - if (!WHEN_RE.test(text)) return text; // barrido único: el caso normal sale por aquí | |
| 324 | + if (!WHEN_RE.test(text)) return text; // single sweep: the normal case leaves here | |
| 318 | 325 | const ref = new Date(refMs); |
| 319 | 326 | if (isNaN(ref.getTime())) return text; |
| 320 | 327 | const parts = []; let last = 0, f; |
| @@ -326,10 +333,11 @@ | ||
| 326 | 333 | parts.push([text.slice(last), false]); |
| 327 | 334 | return parts.map(([s, isCode]) => isCode ? s : s.replace(WHEN_RE, (hit, ...rest) => { |
| 328 | 335 | const whole = rest[rest.length - 1], at = rest[rest.length - 2]; |
| 329 | - if (/^\s*\(\d{4}-\d{2}/.test(whole.slice(at + hit.length))) return hit; // idempotente | |
| 330 | - // `today()`, `memory::today`, `hoy_str` o `ayer.js` son CÓDIGO aunque lleguen | |
| 331 | - // sin valla: una tool-call sin valla lleva rutas, y anotar dentro de una ruta | |
| 332 | - // la rompe. Un punto de final de frase («lo hicimos ayer.») sí se anota. | |
| 336 | + if (/^\s*\(\d{4}-\d{2}/.test(whole.slice(at + hit.length))) return hit; // idempotent | |
| 337 | + // `today()`, `memory::today`, `hoy_str` or `ayer.js` are CODE even when they | |
| 338 | + // arrive without a fence: an unfenced tool call carries paths, and | |
| 339 | + // annotating inside a path breaks it. A sentence-final full stop ("lo | |
| 340 | + // hicimos ayer.") does get annotated. | |
| 333 | 341 | if (/[.:_/\\]$/.test(whole.slice(0, at)) || /^[(_]|^\.\w/.test(whole.slice(at + hit.length))) return hit; |
| 334 | 342 | for (let i = 0; i < WHEN.length; i++) { |
| 335 | 343 | const g = WHEN_ONE[i].exec(hit); |
| @@ -349,15 +357,15 @@ | ||
| 349 | 357 | return Number.isFinite(t) ? t : null; |
| 350 | 358 | }; |
| 351 | 359 | |
| 352 | -// Historial con las referencias temporales resueltas. Devuelve el MISMO array si | |
| 353 | -// no hubo nada que anotar, para no pagar copias en el caso normal. | |
| 360 | +// History with the temporal references resolved. Returns the SAME array if | |
| 361 | +// there was nothing to annotate, so the normal case pays for no copies. | |
| 354 | 362 | function datedHistory(history, now) { |
| 355 | 363 | let touched = false; |
| 356 | 364 | const out = history.map(m => { |
| 357 | 365 | const c = m.content || ''; |
| 358 | - if (!c || c.startsWith('[resultado')) return m; // salida de herramienta: intocable | |
| 366 | + if (!c || c.startsWith('[resultado')) return m; // tool output: untouchable | |
| 359 | 367 | const ref = asTime(m.ts ?? m.time ?? m.timestamp ?? m.date ?? m.createdAt) ?? asTime(now); |
| 360 | - if (ref == null) return m; // sin fecha conocida NO se inventa | |
| 368 | + if (ref == null) return m; // no known date → nothing is invented | |
| 361 | 369 | const a = annotateDates(c, ref); |
| 362 | 370 | if (a === c) return m; |
| 363 | 371 | touched = true; |
| @@ -367,19 +375,20 @@ | ||
| 367 | 375 | } |
| 368 | 376 | |
| 369 | 377 | /** |
| 370 | - * AGREGACIÓN — lo que no está en ninguna línea. | |
| 378 | + * AGGREGATION — what is in no line at all. | |
| 371 | 379 | * |
| 372 | - * «¿Cuántos ficheros has tocado?» no está repartido entre cuarenta líneas: es | |
| 373 | - * que NO EXISTE la línea que buscar. Ningún top-k la encuentra, y no por | |
| 374 | - * puntuar mal, sino por construcción. Como las fechas, se resuelve al ESCRIBIR: | |
| 375 | - * contando según pasan los resultados. Contador y nada más — sin modelo, sin | |
| 376 | - * resumen generado, sin juicio: es un recuento, y se lee como se lee `wc -l`. | |
| 380 | + * "How many files have you touched?" is not spread across forty lines: it is | |
| 381 | + * that the line to look for DOES NOT EXIST. No top-k finds it, and not because | |
| 382 | + * it scores badly, but by construction. Like the dates, it is resolved at WRITE | |
| 383 | + * time: counting as the results go past. A counter and nothing else — no model, | |
| 384 | + * no generated summary, no judgement: it is a tally, and it reads the way | |
| 385 | + * `wc -l` reads. | |
| 377 | 386 | * |
| 378 | - * El objetivo de cada llamada sale de la llamada del ASISTENTE (el resultado no | |
| 379 | - * lo lleva), igual que en markSuperseded, y la familia se decide por el VERBO | |
| 380 | - * del nombre de la herramienta: los productos que comparten este diseño tienen | |
| 381 | - * herramientas distintas (`code.read` / `fs.read`) y una lista cerrada de | |
| 382 | - * nombres envejecería con el primer producto nuevo. | |
| 387 | + * The target of each call comes from the ASSISTANT's call (the result does not | |
| 388 | + * carry it), same as in markSuperseded, and the family is decided by the VERB | |
| 389 | + * in the tool's name: the products that share this design have different tools | |
| 390 | + * (`code.read` / `fs.read`) and a closed list of names would go stale with the | |
| 391 | + * first new product. | |
| 383 | 392 | */ |
| 384 | 393 | const V_EDIT = /^(?:write|edit|create|save|patch|append|delete|remove|rm|move|rename|copy)$/; |
| 385 | 394 | const V_READ = /^(?:read|view|open|cat|show)$/; |
| @@ -396,7 +405,7 @@ | ||
| 396 | 405 | for (const line of c.split('\n')) { |
| 397 | 406 | if (!ERR.test(line)) continue; |
| 398 | 407 | errN++; errs.set(line.trim().slice(0, 90), i); |
| 399 | - break; // se cuentan RESULTADOS que fallaron, no líneas de traza | |
| 408 | + break; // we count failed RESULTS, not traceback lines | |
| 400 | 409 | } |
| 401 | 410 | return; |
| 402 | 411 | } |
| @@ -411,40 +420,41 @@ | ||
| 411 | 420 | else if (V_RUN.test(verb)) ran.set(m[2], i); |
| 412 | 421 | } |
| 413 | 422 | }); |
| 414 | - // Un fichero editado no vuelve a contarse como leído: «cuántos has tocado» no | |
| 415 | - // puede contar dos veces el mismo fichero. | |
| 423 | + // An edited file is not counted as read as well: "how many have you touched" | |
| 424 | + // cannot count the same file twice. | |
| 416 | 425 | for (const k of edited.keys()) read.delete(k); |
| 417 | 426 | return { read, edited, ran, errs, errN }; |
| 418 | 427 | } |
| 419 | 428 | |
| 420 | 429 | /** |
| 421 | - * La tarjeta, acotada. Tres reglas, y las tres salen de medir: | |
| 430 | + * The card, bounded. Three rules, and all three come from measuring: | |
| 422 | 431 | * |
| 423 | - * 1. El RECUENTO va siempre y es el total de verdad; la enumeración se recorta. | |
| 424 | - * Un recuento truncado que PARECE completo («8 ficheros» cuando fueron 200) | |
| 425 | - * es peor que no dar ninguno, así que el número va aparte y la lista dice | |
| 426 | - * «+N más». Cuando no cabe ni una entrada, la fila se queda en el número. | |
| 427 | - * 2. El techo sale del PRESUPUESTO, no de una constante. | |
| 428 | - * 3. Se le quita sitio a la fila que más TOKENS gasta, no a la que más entradas | |
| 429 | - * tiene: dos rutas de error largas cuestan más que ocho nombres cortos. | |
| 430 | - * Medido (32 sesiones, presupuesto 3.000, cobertura de los ficheros | |
| 431 | - * realmente editados, a igual coste ~148 tokens): recortar por número de | |
| 432 | - * entradas 67,7 % · recortar por coste 90,6 %. Sin tarjeta, 58,9 %. | |
| 433 | - * Y con el techo al 3 % baja a 57,3 %: una tarjeta demasiado apretada da el | |
| 434 | - * recuento gratis pero su enumeración ESTORBA. | |
| 432 | + * 1. The TALLY always goes in and is the true total; the enumeration is what | |
| 433 | + * gets trimmed. A truncated tally that LOOKS complete ("8 files" when there | |
| 434 | + * were 200) is worse than giving none at all, so the number goes separately | |
| 435 | + * and the list says "+N más". When not even one entry fits, the row is left | |
| 436 | + * as just the number. | |
| 437 | + * 2. The ceiling comes from the BUDGET, not from a constant. | |
| 438 | + * 3. Room is taken from the row that spends the most TOKENS, not from the one | |
| 439 | + * with the most entries: two long error paths cost more than eight short | |
| 440 | + * names. Measured (32 sessions, budget 3,000, coverage of the files | |
| 441 | + * actually edited, at equal cost of ~148 tokens): trimming by number of | |
| 442 | + * entries 67.7% · trimming by cost 90.6%. With no card, 58.9%. | |
| 443 | + * And with the ceiling at 3% it drops to 57.3%: a card squeezed too tight | |
| 444 | + * gives the tally for free but its enumeration GETS IN THE WAY. | |
| 435 | 445 | * |
| 436 | - * ⚠️ La tarjeta NO es gratis: en el banco de hechos de siempre (32 sesiones | |
| 437 | - * reales) cuesta −0,7 puntos a presupuesto 3.000 (65,7 % → 65,0 %) y ±0,0 a | |
| 438 | - * 16.000. Por eso va tras bandera y apagada: quien pregunte «cuántos ficheros» | |
| 439 | - * la quiere; quien no, está pagando por nada. | |
| 446 | + * ⚠️ The card is NOT free: on the usual fact benchmark (32 real sessions) it | |
| 447 | + * costs −0.7 points at budget 3,000 (65.7% → 65.0%) and ±0.0 at 16,000. That is | |
| 448 | + * why it sits behind a flag and off: whoever asks "how many files" wants it; | |
| 449 | + * whoever does not is paying for nothing. | |
| 440 | 450 | */ |
| 441 | 451 | function summaryCard(L, maxTok) { |
| 442 | 452 | const rows = [['ficheros leídos', L.read], ['ficheros editados', L.edited], |
| 443 | 453 | ['comandos', L.ran], ['errores', L.errs]]; |
| 444 | 454 | const totals = [L.read.size, L.edited.size, L.ran.size, L.errN]; |
| 445 | 455 | if (!totals.some(Boolean)) return null; |
| 446 | - // Las MÁS RECIENTES primero: si hay que recortar, lo que se acaba de tocar es | |
| 447 | - // lo que más probablemente van a preguntar. | |
| 456 | + // MOST RECENT first: if trimming is needed, whatever was just touched is what | |
| 457 | + // they are most likely to ask about. | |
| 448 | 458 | const listed = rows.map(([, m]) => [...m.entries()].sort((a, b) => b[1] - a[1]).map(e => e[0])); |
| 449 | 459 | const caps = rows.map(() => 8); |
| 450 | 460 | const line = i => { |
| @@ -470,46 +480,49 @@ | ||
| 470 | 480 | return { role: 'user', content: text }; |
| 471 | 481 | } |
| 472 | 482 | |
| 473 | -// Prepara el estado común: reserva de recientes, pregunta viva, líneas y BM25. | |
| 483 | +// Prepares the shared state: recent reserve, live question, lines and BM25. | |
| 474 | 484 | function prepare(history, budgetTokens, opts = {}) { |
| 475 | - // Lo que se resuelve al ESCRIBIR va antes que nada, porque cambia el material | |
| 476 | - // que se va a puntuar y lo que va a caber: las fechas se anotan sobre el | |
| 477 | - // historial, y la tarjeta se cobra del presupuesto ANTES de repartirlo — que | |
| 478 | - // es lo que la hace incondicional sin romper el contrato de tokens. | |
| 485 | + // Whatever is resolved at WRITE time goes before anything else, because it | |
| 486 | + // changes the material that is about to be scored and what is going to fit: | |
| 487 | + // the dates are annotated over the history, and the card is charged against | |
| 488 | + // the budget BEFORE it is shared out — which is what makes it unconditional | |
| 489 | + // without breaking the token contract. | |
| 479 | 490 | if (opts.dates !== false) history = datedHistory(history, opts.now); |
| 480 | 491 | const card = opts.summary ? summaryCard(buildLedger(history), |
| 481 | 492 | Math.max(24, Math.floor(budgetTokens * (opts.summaryFrac || 0.05)))) : null; |
| 482 | 493 | const cardTok = card ? estTok(card.content) + 4 : 0; |
| 483 | 494 | budgetTokens = Math.max(1, budgetTokens - cardTok); |
| 484 | 495 | |
| 485 | - // PRESIÓN de compresión: qué fracción del historial cabe. Todas las perillas | |
| 486 | - // que dependen del régimen salen de aquí, no de constantes — con 200k de | |
| 487 | - // historial contra 32k de presupuesto no manda lo mismo que con 5k contra 3k. | |
| 496 | + // Compression PRESSURE: what fraction of the history fits. Every knob that | |
| 497 | + // depends on the regime comes from here, not from constants — 200k of history | |
| 498 | + // against a 32k budget is not ruled by the same thing as 5k against 3k. | |
| 488 | 499 | const historyTok = history.reduce((s, m) => s + tokEstimate(m), 0); |
| 489 | 500 | const pressure = Math.max(0, Math.min(1, budgetTokens / (historyTok || 1))); |
| 490 | - // Con holgura conservar los últimos turnos sale barato; con agobio hay que | |
| 491 | - // dejarle sitio a la BÚSQUEDA, que es lo que trae la línea de hace 30 turnos. | |
| 501 | + // With room to spare, keeping the last turns is cheap; under strain you have | |
| 502 | + // to leave room for the SEARCH, which is what brings back the line from 30 | |
| 503 | + // turns ago. | |
| 492 | 504 | const recentFrac = 0.35 + 0.45 * pressure; |
| 493 | - // La recencia solo desempata BAJO PRESIÓN. Medido en un barrido: con agobio | |
| 494 | - // (16× de contexto sobre presupuesto) suma +11 puntos, porque casi ninguna | |
| 495 | - // línea tiene relevancia y lo nuevo es la única apuesta que queda. Con | |
| 496 | - // holgura RESTA −8: ahí gana el orden del documento, que mantiene juntos los | |
| 497 | - // tramos, y un fragmento contiguo vale más que líneas nuevas sueltas. | |
| 505 | + // Recency only breaks ties UNDER PRESSURE. Measured in a sweep: under strain | |
| 506 | + // (16× as much context as budget) it adds +11 points, because almost no line | |
| 507 | + // has any relevance and what is new is the only bet left. With room to spare | |
| 508 | + // it SUBTRACTS −8: there document order wins, because it keeps the stretches | |
| 509 | + // together, and one contiguous fragment is worth more than scattered new lines. | |
| 498 | 510 | const recTie = pressure < 0.25; |
| 499 | - // La cabecera va SIEMPRE, sin puerta: con la ventana elástica dejó de ser | |
| 500 | - // cierto que "con holgura el encargo sobrevive solo" — sobrevivía porque | |
| 501 | - // rellenábamos hasta el borde. Medido, al dejar de rellenar caía del 100 % al | |
| 502 | - // 0 % a presupuesto 16.000. Era un accidente del relleno, no tener sitio. | |
| 503 | - | |
| 504 | - // ── RESERVA DE COLA — es un SUELO, no solo un techo ──────────────────────── | |
| 505 | - // Parar en el primer mensaje que no cabe convierte la reserva en un tope y no | |
| 506 | - // en una garantía: medido, con presupuesto 3.000 la cola se quedaba con el | |
| 507 | - // 3-5 % en vez del ~38 % reservado, porque UN resultado de herramienta grande | |
| 508 | - // en la penúltima posición bloqueaba todo lo anterior. Los últimos turnos son | |
| 509 | - // lo que el modelo necesita sí o sí para saber dónde está, y eso no puede | |
| 510 | - // depender de que el turno de antes fuera voluminoso. | |
| 511 | - // Mientras no se alcance el suelo (10 %), el mensaje que no cabe se TRUNCA | |
| 512 | - // por el medio en vez de descartarse. Por encima, comportamiento de siempre. | |
| 511 | + // The head goes in ALWAYS, with no gate: with the elastic window it stopped | |
| 512 | + // being true that "with room to spare the brief survives on its own" — it | |
| 513 | + // survived because we were filling right up to the edge. Measured, once we | |
| 514 | + // stopped filling it fell from 100% to 0% at budget 16,000. It was an | |
| 515 | + // accident of the padding, not of having room. | |
| 516 | + | |
| 517 | + // ── TAIL RESERVE — it is a FLOOR, not just a ceiling ─────────────────────── | |
| 518 | + // Stopping at the first message that does not fit turns the reserve into a cap | |
| 519 | + // rather than a guarantee: measured, at budget 3,000 the tail was getting | |
| 520 | + // 3-5% instead of the ~38% reserved, because ONE big tool result in the | |
| 521 | + // second-to-last position blocked everything before it. The last turns are | |
| 522 | + // what the model absolutely needs in order to know where it is, and that | |
| 523 | + // cannot depend on the preceding turn having been bulky. | |
| 524 | + // Until the floor (10%) is reached, a message that does not fit is TRUNCATED | |
| 525 | + // through the middle instead of discarded. Above it, the usual behaviour. | |
| 513 | 526 | const reserve = Math.floor(budgetTokens * recentFrac); |
| 514 | 527 | const floorTok = Math.floor(budgetTokens * 0.05); |
| 515 | 528 | const recent = []; let used = 0; |
| @@ -529,32 +542,32 @@ | ||
| 529 | 542 | let old = history.slice(0, history.length - recent.length); |
| 530 | 543 | if (!old.length || used >= budgetTokens) return { done: true, recent, used, head: [], card, budget: budgetTokens }; |
| 531 | 544 | |
| 532 | - // ── RESERVA DE CABECERA ──────────────────────────────────────────────────── | |
| 533 | - // Los PRIMEROS mensajes se conservan literales y SIN puntuar, igual que los | |
| 534 | - // últimos, y solo bajo presión (misma puerta que la recencia, misma razón). | |
| 545 | + // ── HEAD RESERVE ─────────────────────────────────────────────────────────── | |
| 546 | + // The FIRST messages are kept verbatim and UNSCORED, just like the last ones, | |
| 547 | + // and only under pressure (same gate as recency, same reason). | |
| 535 | 548 | // |
| 536 | - // El arranque lleva el ENCARGO: qué hay que hacer, con qué restricciones. El | |
| 537 | - // resto de la sesión lo da por sabido, así que nadie lo repite — y sin | |
| 538 | - // repeticiones no hay solape léxico con la pregunta de ahora, o sea que BM25 | |
| 539 | - // no puede rescatarlo por mucho que importe. Es el único contenido que el | |
| 540 | - // agente NO puede reconstruir mirando el código. | |
| 549 | + // The opening carries the BRIEF: what has to be done, under what constraints. | |
| 550 | + // The rest of the session takes it as given, so nobody repeats it — and with | |
| 551 | + // no repetitions there is no lexical overlap with the current question, which | |
| 552 | + // means BM25 cannot rescue it no matter how much it matters. It is the only | |
| 553 | + // content the agent CANNOT reconstruct by looking at the code. | |
| 541 | 554 | // |
| 542 | - // Respaldo externo: es el resultado central de StreamingLLM (Xiao, Tian, Chen, | |
| 543 | - // Han & Lewis, ICLR 2024, https://arxiv.org/abs/2309.17453) — los primeros | |
| 544 | - // tokens actúan de SUMIDERO de atención y absorben el 45-55 % de la masa. | |
| 545 | - // Un recuperador puro no puede ver eso: no es una propiedad del texto, sino | |
| 546 | - // de cómo el modelo lo usa. | |
| 555 | + // External backing: it is the central result of StreamingLLM (Xiao, Tian, | |
| 556 | + // Chen, Han & Lewis, ICLR 2024, https://arxiv.org/abs/2309.17453) — the first | |
| 557 | + // tokens act as attention SINKS and absorb 45-55% of the mass. A pure | |
| 558 | + // retriever cannot see that: it is not a property of the text, but of how the | |
| 559 | + // model uses it. | |
| 547 | 560 | // |
| 548 | - // Medido (A/B mismo código, 8 semillas, sonda que pregunta por el encargo a | |
| 549 | - // mitad de sesión): | |
| 550 | - // presupuesto 3.000: el encargo sobrevive 0 % → 100 % | |
| 551 | - // presupuesto 16.000: el encargo sobrevive 100 % → 100 % | |
| 552 | - // hechos de media sesión: 85,7 % → 85,7 % · 91,1 % → 91,1 % | |
| 553 | - // O sea: rescata el encargo de nunca a siempre y NO cuesta nada. | |
| 554 | - // Cabecera DESACTIVADA: ayudaba en sesiones de agente (el encargo original | |
| 555 | - // pasaba de 0/5 a 5/5) pero en diálogo no hay encargo que proteger y la | |
| 556 | - // reserva cobra sin dar nada — en LoCoMo baja el recall de evidencia del | |
| 557 | - // 62,5 % al 56,2 % con los mismos tokens. Poner 0.05 para reactivarla. | |
| 561 | + // Measured (A/B on the same code, 8 seeds, a probe asking about the brief | |
| 562 | + // halfway through the session): | |
| 563 | + // budget 3,000: the brief survives 0% → 100% | |
| 564 | + // budget 16,000: the brief survives 100% → 100% | |
| 565 | + // mid-session facts: 85.7% → 85.7% · 91.1% → 91.1% | |
| 566 | + // That is: it rescues the brief from never to always and costs NOTHING. | |
| 567 | + // Head reserve DISABLED: it helped in agent sessions (the original brief went | |
| 568 | + // from 0/5 to 5/5) but in dialogue there is no brief to protect and the | |
| 569 | + // reserve charges without giving anything back — on LoCoMo it drops evidence | |
| 570 | + // recall from 62.5% to 56.2% at the same token count. Set 0.05 to re-enable. | |
| 558 | 571 | const headReserve = 0; |
| 559 | 572 | const head = []; let headUsed = 0; |
| 560 | 573 | for (let i = 0; i < old.length; i++) { |
| @@ -566,9 +579,9 @@ | ||
| 566 | 579 | used += headUsed; |
| 567 | 580 | if (!old.length || used >= budgetTokens) return { done: true, recent, used, head, card, budget: budgetTokens }; |
| 568 | 581 | |
| 569 | - // La pregunta VIVA: el último turno de usuario que no sea un resultado de | |
| 570 | - // herramienta. Es contra esto que se puntúa, no contra la tarea inicial — | |
| 571 | - // lo relevante cambia en cada turno. | |
| 582 | + // The LIVE question: the last user turn that is not a tool result. This is | |
| 583 | + // what everything is scored against, not the initial task — what is relevant | |
| 584 | + // changes on every turn. | |
| 572 | 585 | const query = [...history].reverse().find(m => |
| 573 | 586 | m.role === 'user' && !(m.content || '').startsWith('[resultado'))?.content || ''; |
| 574 | 587 | |
| @@ -584,8 +597,8 @@ | ||
| 584 | 597 | return { done: false, recent, old, used, items, query, recTie, pressure, head, card, budget: budgetTokens }; |
| 585 | 598 | } |
| 586 | 599 | |
| 587 | -// Selección bajo un único presupuesto global, con MMR, y emisión con marcas de | |
| 588 | -// omisión para que el modelo sepa que falta algo. | |
| 600 | +// Selection under a single global budget, with MMR, and emission with omission | |
| 601 | +// markers so that the model knows something is missing. | |
| 589 | 602 | function selectAndEmit(ctx, budgetTokens) { |
| 590 | 603 | const { recent, old, items } = ctx; |
| 591 | 604 | const head = ctx.head || []; |
| @@ -597,8 +610,10 @@ | ||
| 597 | 610 | const pool = [...items].sort((a, b) => b.score - a.score); |
| 598 | 611 | const keep = new Set(); |
| 599 | 612 | |
| 600 | - // MMR: al elegir, penalizar el parecido con lo ya elegido. Es lo único que | |
| 601 | - // mide por encima de BM25 a secas (+8,9 puntos). | |
| 613 | + // MMR: when choosing, penalise similarity to what has already been chosen. It | |
| 614 | + // is the only thing that measures above plain BM25 — and not by much: | |
| 615 | + // +2.4 points at full scale. A 3-seed smoke test said +8.9 and that was | |
| 616 | + // seed noise; the header carries the honest figure. | |
| 602 | 617 | const lambda = Math.max(0.15, Math.min(0.8, 2 * measureRedundancy(pool))); |
| 603 | 618 | const nCand = Math.max(400, Math.min(8000, Math.round(budgetTokens / 6))); |
| 604 | 619 | const cand = pool.slice(0, nCand); |
| @@ -614,38 +629,38 @@ | ||
| 614 | 629 | } |
| 615 | 630 | remaining.delete(best); |
| 616 | 631 | const it = byId.get(best), c = cost(it); |
| 617 | - if (it.score < 10) continue; // el MMR diversifica DENTRO de lo relevante | |
| 632 | + if (it.score < 10) continue; // MMR diversifies WITHIN what is relevant | |
| 618 | 633 | if (used + c > budgetTokens) continue; |
| 619 | 634 | keep.add(best); used += c; |
| 620 | 635 | const bs = tok.get(best); |
| 621 | 636 | for (const id of remaining) maxSim.set(id, Math.max(maxSim.get(id), jaccard(tok.get(id), bs))); |
| 622 | 637 | } |
| 623 | - // VENTANA ELÁSTICA: el presupuesto es un TECHO, no una cuota que agotar. Sin | |
| 624 | - // esto, el 38 % del presupuesto a 3.000 y el 56 % a 16.000 se iba en líneas | |
| 625 | - // sin una sola palabra en común con la pregunta. Y lo irrelevante no es | |
| 626 | - // lastre neutro: recuperar bien BATE al contexto completo (F1 28,09 vs | |
| 627 | - // 22,56), o sea que rellenar hasta el borde reintroduce a mano lo que la | |
| 628 | - // compresión venía a quitar. La ventana se para cuando se acaba la evidencia | |
| 629 | - // (estrato ≥ 10), no cuando se acaban los tokens. | |
| 630 | - // ⚠️ Es un INTERCAMBIO: gratis con presupuesto apretado (el de los | |
| 631 | - // productos), pero a 32.000 ahorra el 60 % de tokens a costa de 8,9 puntos de | |
| 632 | - // presencia del dato. Que eso compense depende de si menos ruido mejora la | |
| 633 | - // respuesta, y este banco mide presencia, no calidad. | |
| 638 | + // ELASTIC WINDOW: the budget is a CEILING, not a quota to be used up. Without | |
| 639 | + // this, 38% of the budget at 3,000 and 56% at 16,000 went on lines without a | |
| 640 | + // single word in common with the question. And what is irrelevant is not | |
| 641 | + // neutral ballast: retrieving well BEATS the full context (F1 28.09 vs | |
| 642 | + // 22.56), which means filling right up to the edge puts back by hand exactly | |
| 643 | + // what the compression came to remove. The window stops when the evidence | |
| 644 | + // runs out (stratum ≥ 10), not when the tokens run out. | |
| 645 | + // ⚠️ It is a TRADE-OFF: free with a tight budget (the products' case), but at | |
| 646 | + // 32,000 it saves 60% of the tokens at the cost of 8.9 points of the datum | |
| 647 | + // being present. Whether that pays off depends on whether less noise improves | |
| 648 | + // the answer, and this benchmark measures presence, not quality. | |
| 634 | 649 | for (const it of pool) { |
| 635 | 650 | const id = idOf(it); if (keep.has(id)) continue; |
| 636 | - if (it.score < 10) break; // se acabó lo relevante | |
| 651 | + if (it.score < 10) break; // the relevant material has run out | |
| 637 | 652 | const c = cost(it); |
| 638 | 653 | if (used + c > budgetTokens) continue; |
| 639 | 654 | keep.add(id); used += c; |
| 640 | 655 | } |
| 641 | 656 | |
| 642 | - // ── CONTRATO DE PRESUPUESTO ──────────────────────────────────────────────── | |
| 643 | - // El coste por línea ignora la sobrecarga por mensaje y las marcas de omisión, | |
| 644 | - // así que la suma de costes NO es lo que se emite. Sin esta corrección el | |
| 645 | - // empaquetador se pasa ~1,6-1,8× de lo que se le pide — medido — y eso es | |
| 646 | - // precisamente el «Too many tokens» que este fichero existe para evitar. | |
| 647 | - // Se mide el tamaño REAL emitido y se devuelven las líneas peor puntuadas | |
| 648 | - // hasta que la salida cabe de verdad. | |
| 657 | + // ── BUDGET CONTRACT ──────────────────────────────────────────────────────── | |
| 658 | + // The per-line cost ignores the per-message overhead and the omission | |
| 659 | + // markers, so the sum of the costs is NOT what gets emitted. Without this | |
| 660 | + // correction the packer overshoots what it was asked for by ~1.6-1.8× — | |
| 661 | + // measured — and that is precisely the "Too many tokens" this file exists to | |
| 662 | + // prevent. The REAL emitted size is measured and the worst-scoring lines are | |
| 663 | + // handed back until the output genuinely fits. | |
| 649 | 664 | const emit = () => { |
| 650 | 665 | let t = recent.reduce((s, m) => s + tokEstimate(m), 0) + head.reduce((s, m) => s + tokEstimate(m), 0); |
| 651 | 666 | let open = 0; |
| @@ -692,17 +707,17 @@ | ||
| 692 | 707 | packed.push({ role: m.role, content: out.join('\n') }); |
| 693 | 708 | }); |
| 694 | 709 | if (droppedMsgs) packed.push({ role: 'user', content: `[…${droppedMsgs} mensajes antiguos omitidos…]` }); |
| 695 | - // La tarjeta va PROTEGIDA, como la cabecera y la cola, y por su mismo motivo: | |
| 696 | - // no compite por relevancia porque no puede ganar — es un recuento, no | |
| 697 | - // comparte vocabulario con nada y BM25 la tiraría siempre, que es justo el | |
| 698 | - // fallo que viene a tapar. Va pegada a los últimos turnos, con la pregunta | |
| 699 | - // viva, no al principio. | |
| 710 | + // The card is PROTECTED, like the head and the tail, and for the very same | |
| 711 | + // reason: it does not compete on relevance because it cannot win — it is a | |
| 712 | + // tally, it shares vocabulary with nothing, and BM25 would drop it every | |
| 713 | + // time, which is exactly the failure it came to cover. It sits right next to | |
| 714 | + // the last turns, with the live question, not at the beginning. | |
| 700 | 715 | return [...head, ...packed, ...(ctx.card ? [ctx.card] : []), ...recent]; |
| 701 | 716 | } |
| 702 | 717 | |
| 703 | 718 | /** |
| 704 | - * Empaqueta el historial en `budgetTokens` — vía léxica, síncrona. | |
| 705 | - * Es la que se usa por defecto: no necesita modelo, ni red, ni nada. | |
| 719 | + * Packs the history into `budgetTokens` — lexical path, synchronous. | |
| 720 | + * This is the one used by default: it needs no model, no network, nothing. | |
| 706 | 721 | */ |
| 707 | 722 | export function packHistory(history, budgetTokens = 2200, opts = {}) { |
| 708 | 723 | if (!history.length) return history; |
| @@ -710,52 +725,55 @@ | ||
| 710 | 725 | if (ctx.done) return [...(ctx.head || []), ...(ctx.card ? [ctx.card] : []), ...ctx.recent]; |
| 711 | 726 | const max = ctx.items.reduce((m, it) => Math.max(m, it.bm), 0) || 1; |
| 712 | 727 | for (const it of ctx.items) { |
| 713 | - // Dos estratos separados por 10 — más de lo que la penalización MMR (≤0.5) | |
| 714 | - // puede recorrer, así que una línea sin relevancia NUNCA adelanta a una que | |
| 715 | - // sí la tiene. Dentro de cada estrato: BM25 arriba, desempate abajo. | |
| 728 | + // Two strata separated by 10 — more than the MMR penalty (≤0.5) can span, | |
| 729 | + // so a line with no relevance NEVER overtakes one that has some. Within | |
| 730 | + // each stratum: BM25 on top, tie-break underneath. | |
| 716 | 731 | it.score = (it.bm > 0 && !it.stale) ? 10 + it.bm / max : (ctx.recTie ? it.rec : 0); |
| 717 | - if (it.first) it.score = Math.max(it.score, 0.5); // cabecera de procedencia | |
| 732 | + if (it.first) it.score = Math.max(it.score, 0.5); // provenance header | |
| 718 | 733 | } |
| 719 | 734 | return selectAndEmit(ctx, ctx.budget); |
| 720 | 735 | } |
| 721 | 736 | |
| 722 | 737 | /** |
| 723 | - * Igual, más una segunda opinión SEMÁNTICA fusionada por rangos. | |
| 738 | + * The same, plus a second SEMANTIC opinion fused by rank. | |
| 724 | 739 | * |
| 725 | - * `embed(textos) -> vectores`. Se codifica por bloques de líneas, no línea a | |
| 726 | - * línea, porque codificar cada línea es prohibitivo y la señal sobrevive al | |
| 727 | - * troceado. | |
| 740 | + * `embed(texts) -> vectors`. Encoding happens per block of lines, not line by | |
| 741 | + * line, because encoding every line is prohibitive and the signal survives the | |
| 742 | + * chunking. | |
| 728 | 743 | * |
| 729 | - * ★ El tamaño de bloque es FIJO a propósito, y es lo que hace que la caché | |
| 730 | - * sirva. Con bloques fijos las fronteras no se mueven al crecer el historial | |
| 731 | - * (0-4, 5-9, …), así que el texto de un bloque ya codificado NO cambia nunca y | |
| 732 | - * un turno sólo paga lo NUEVO. Si el tamaño se DERIVA del número de líneas, | |
| 733 | - * cada vez que ese número cruza un umbral cambian TODOS los bloques y la caché | |
| 734 | - * falla entera — medido, el turno pasa a encarecerse según avanza la sesión en | |
| 735 | - * vez de abaratarse. Es el «indexar al escribir» del que depende todo esto. Si no se pasa `embed`, o si falla, cae limpiamente a la vía léxica. | |
| 744 | + * ★ The block size is FIXED on purpose, and that is what makes the cache worth | |
| 745 | + * anything. With fixed blocks the boundaries do not move as the history grows | |
| 746 | + * (0-4, 5-9, …), so the text of an already-encoded block NEVER changes and a | |
| 747 | + * turn only pays for what is NEW. If the size is DERIVED from the number of | |
| 748 | + * lines, then every time that number crosses a threshold ALL the blocks change | |
| 749 | + * and the cache misses entirely — measured, the turn starts getting more | |
| 750 | + * expensive as the session advances instead of cheaper. It is the "index at | |
| 751 | + * write time" that all of this depends on. If no `embed` is passed, or if it | |
| 752 | + * fails, it falls back cleanly to the lexical path. | |
| 736 | 753 | * |
| 737 | - * Por qué fusionar y no sustituir: medido, BM25 y los embeddings EMPATAN | |
| 738 | - * en global, pero NO hacen el mismo trabajo. Partiendo las preguntas por solape | |
| 739 | - * de vocabulario con la respuesta: sin solape, embeddings 24,28 > BM25 18,60; | |
| 740 | - * con solape, BM25 29,33 > embeddings 23,58. La fusión por rangos se queda con | |
| 741 | - * los DOS (24,05 / 32,73). Lo semántico no sustituye al léxico: le cubre el | |
| 742 | - * punto ciego. | |
| 754 | + * Why fuse instead of replace: measured, BM25 and the embeddings TIE overall, | |
| 755 | + * but they do NOT do the same job. Splitting the questions by vocabulary | |
| 756 | + * overlap with the answer: with no overlap, embeddings 24.28 > BM25 18.60; with | |
| 757 | + * overlap, BM25 29.33 > embeddings 23.58. Rank fusion keeps BOTH (24.05 / | |
| 758 | + * 32.73). The semantic side does not replace the lexical one: it covers its | |
| 759 | + * blind spot. | |
| 743 | 760 | */ |
| 744 | -// El lado semántico va tras bandera y APAGADO por defecto. La ganancia es real | |
| 745 | -// (+4,50 F1) pero el precio no es despreciable y depende del equipo de quien lo | |
| 746 | -// usa: son ~235 MB la primera vez, y sin WebGPU el turno se encarece siempre. | |
| 747 | -// Cableado, probado, y se enciende a petición. Con la bandera apagada embed.js | |
| 748 | -// —y con él transformers.js y el modelo— NI SE IMPORTA: coste exactamente cero. | |
| 761 | +// The semantic side sits behind a flag and is OFF by default. The gain is real | |
| 762 | +// (+4.50 F1) but the price is not negligible and it depends on whoever is | |
| 763 | +// running it: ~235 MB the first time, and without WebGPU every turn gets more | |
| 764 | +// expensive, always. Wired up, tested, and switched on on request. With the | |
| 765 | +// flag off, embed.js — and with it transformers.js and the model — IS NOT EVEN | |
| 766 | +// IMPORTED: exactly zero cost. | |
| 749 | 767 | // localStorage.setItem('elffuss.semantic', 'on') |
| 750 | 768 | function semanticoOn() { |
| 751 | 769 | try { return localStorage.getItem('elffuss.semantic') === 'on'; } catch { return false; } |
| 752 | 770 | } |
| 753 | 771 | |
| 754 | -// La TARJETA DE RECUENTO también va tras bandera, y por lo mismo: cuesta ~150 | |
| 755 | -// tokens del presupuesto y −0,7 puntos de recall a presupuesto 3.000 (nada a | |
| 756 | -// 16.000). A cambio el recuento pasa del 0 % al 100 % y la enumeración de lo | |
| 757 | -// editado del 58,9 % al 90,6 %. Compensa en la sesión que acaba con «hazme la | |
| 758 | -// lista de lo que tocaste»; en las demás se paga por nada. | |
| 772 | +// The TALLY CARD is also behind a flag, and for the same reason: it costs ~150 | |
| 773 | +// tokens of the budget and −0.7 points of recall at budget 3,000 (nothing at | |
| 774 | +// 16,000). In exchange the tally goes from 0% to 100% and the enumeration of | |
| 775 | +// what was edited from 58.9% to 90.6%. It pays off in the session that ends | |
| 776 | +// with "give me the list of what you touched"; in the rest you pay for nothing. | |
| 759 | 777 | // localStorage.setItem('elffuss.resumen', 'on') |
| 760 | 778 | function resumenOn() { |
| 761 | 779 | try { return localStorage.getItem('elffuss.resumen') === 'on'; } catch { return false; } |
| @@ -764,12 +782,12 @@ | ||
| 764 | 782 | export async function packHistoryAsync(history, budgetTokens = 2200, opts = {}) { |
| 765 | 783 | let { embed, block = 5, cache } = opts; |
| 766 | 784 | if (!history.length) return history; |
| 767 | - // Sin `embed` explícito, se resuelve por bandera con import DINÁMICO. | |
| 785 | + // With no explicit `embed`, it is resolved by flag with a DYNAMIC import. | |
| 768 | 786 | if (!embed && semanticoOn()) { |
| 769 | 787 | try { |
| 770 | 788 | const m = await import('./embed.js'); |
| 771 | 789 | embed = m.embed; cache = cache || m.embedCache(); |
| 772 | - } catch { /* sin modelo → vía léxica, la app NO deja de funcionar */ } | |
| 790 | + } catch { /* no model → lexical path, the app does NOT stop working */ } | |
| 773 | 791 | } |
| 774 | 792 | if (!embed) return packHistory(history, budgetTokens, opts); |
| 775 | 793 | const ctx = prepare(history, budgetTokens, { summary: resumenOn(), ...opts }); |
| @@ -800,13 +818,13 @@ | ||
| 800 | 818 | } |
| 801 | 819 | return selectAndEmit(ctx, ctx.budget); |
| 802 | 820 | } catch { |
| 803 | - return packHistory(history, budgetTokens, opts); // sin modelo, sin red, sin cuota → léxico | |
| 821 | + return packHistory(history, budgetTokens, opts); // no model, no network, no quota → lexical | |
| 804 | 822 | } |
| 805 | 823 | } |
| 806 | 824 | |
| 807 | 825 | /** |
| 808 | - * Caché de embeddings por contenido — "pensar al escribir": un texto se | |
| 809 | - * codifica UNA vez por sesión aunque reaparezca veinte turnos después. | |
| 826 | + * Embedding cache keyed by content — "think at write time": a text is encoded | |
| 827 | + * ONCE per session even if it reappears twenty turns later. | |
| 810 | 828 | */ |
| 811 | 829 | export function createEmbedCache(embed, max = 4000) { |
| 812 | 830 | const store = new Map(); |
modified core/embed.js +112 −105
| @@ -1,131 +1,135 @@ | ||
| 1 | -// Lado SEMÁNTICO del motor de contexto (el compañero de acer-core.js). | |
| 1 | +// SEMANTIC side of the context engine (the companion to context.js). | |
| 2 | 2 | // |
| 3 | 3 | // ───────────────────────────────────────────────────────────────────────────── |
| 4 | -// POR QUÉ EXISTE | |
| 4 | +// WHY IT EXISTS | |
| 5 | 5 | // |
| 6 | -// acer-core.js ya trae la vía híbrida completa (`packHistoryACERHybrid`): BM25 y | |
| 7 | -// embeddings fusionados por rangos. Lo que le faltaba era una función `embed`, | |
| 8 | -// así que degradaba a la vía léxica y en producción sólo corría BM25. | |
| 6 | +// `context.js` already ships the complete hybrid path (`packHistoryAsync`): | |
| 7 | +// BM25 and embeddings fused by rank. What it was missing was an `embed` | |
| 8 | +// function, so it fell back to the lexical path and in production only BM25 ran. | |
| 9 | 9 | // |
| 10 | -// Medido en LoCoMo (200 preguntas, F1 del propio repo, modelo real respondiendo, | |
| 11 | -// mismo presupuesto de tokens): | |
| 10 | +// Measured on LoCoMo (200 questions, the benchmark repo's own F1, a real model | |
| 11 | +// answering, same token budget): | |
| 12 | 12 | // |
| 13 | -// contexto COMPLETO sin comprimir ..... 22,56 | |
| 14 | -// BM25 (lo que corría hasta ahora) .... 23,59 | |
| 15 | -// embeddings solos .................... 23,95 | |
| 16 | -// fusión de RANGOS (esto) ............. 28,09 ← +4,50 sobre BM25 | |
| 13 | +// FULL context, uncompressed .......... 22.56 | |
| 14 | +// BM25 (what ran until now) ........... 23.59 | |
| 15 | +// embeddings alone .................... 23.95 | |
| 16 | +// RANK fusion (this) .................. 28.09 ← +4.50 over BM25 | |
| 17 | 17 | // |
| 18 | -// El motivo de que sume no es que lo semántico sea «mejor»: en global EMPATAN | |
| 19 | -// (23,59 vs 23,95). Hacen trabajos DISTINTOS. Partiendo las mismas preguntas por | |
| 20 | -// solape de vocabulario entre la pregunta y la respuesta: | |
| 18 | +// The reason it adds anything is not that the semantic side is "better": overall | |
| 19 | +// they TIE (23.59 vs 23.95). They do DIFFERENT jobs. Splitting the same | |
| 20 | +// questions by vocabulary overlap between question and answer: | |
| 21 | 21 | // |
| 22 | -// sin solape (n=107) con solape (n=93) | |
| 23 | -// BM25 ...................... 18,60 29,33 | |
| 24 | -// embeddings ................ 24,28 23,58 | |
| 25 | -// fusión de rangos .......... 24,05 32,73 | |
| 22 | +// no overlap (n=107) overlap (n=93) | |
| 23 | +// BM25 ...................... 18.60 29.33 | |
| 24 | +// embeddings ................ 24.28 23.58 | |
| 25 | +// rank fusion ............... 24.05 32.73 | |
| 26 | 26 | // |
| 27 | -// Cuando la pregunta NO nombra literalmente lo que busca, BM25 se hunde (18,60) | |
| 28 | -// y lo semántico aguanta (24,28). Cuando sí lo nombra, manda BM25 (29,33). La | |
| 29 | -// fusión se queda con los dos. Lo semántico no sustituye al léxico: le cubre el | |
| 30 | -// punto ciego. Eso —y no una ganancia global— es lo que se está cableando aquí. | |
| 27 | +// When the question does NOT literally name what it is looking for, BM25 sinks | |
| 28 | +// (18.60) and the semantic side holds up (24.28). When it does name it, BM25 | |
| 29 | +// wins (29.33). The fusion keeps both. The semantic side does not replace the | |
| 30 | +// lexical one: it covers its blind spot. That — and not an overall gain — is | |
| 31 | +// what is being wired up here. | |
| 31 | 32 | // |
| 32 | 33 | // ───────────────────────────────────────────────────────────────────────────── |
| 33 | -// MODELO ELEGIDO — Xenova/multilingual-e5-small, dtype q8 (118 MB) | |
| 34 | +// MODEL CHOSEN — Xenova/multilingual-e5-small, dtype q8 (118 MB) | |
| 34 | 35 | // |
| 35 | -// Requisitos duros y cómo los cumple: | |
| 36 | -// · transformers.js: es la conversión ONNX oficial del mantenedor de la | |
| 37 | -// librería → carga con el MISMO `pipeline()` que ya usa providers/onnx.js. | |
| 38 | -// · pequeño: 118 MB en q8. Es la variante más liviana del repo (el q4 pesa | |
| 39 | -// MÁS —398 MB— porque la matriz de embeddings de un vocabulario de 250k no | |
| 40 | -// se cuantiza igual de bien; aquí «menos bits» no significa menos disco). | |
| 41 | -// · multilingüe: tokenizador XLM-R, 100 idiomas. Los prompts van en castellano | |
| 42 | -// y el código en inglés, y ese cruce es exactamente el punto ciego léxico. | |
| 43 | -// · licencia: MIT (intfloat/multilingual-e5-small aguas arriba). | |
| 44 | -// · ventana de 512 tokens, que es la que necesitan los bloques que arma | |
| 45 | -// acer-core; no es un modelo de frases sueltas. | |
| 36 | +// Hard requirements and how it meets them: | |
| 37 | +// · transformers.js: it is the official ONNX conversion by the library's own | |
| 38 | +// maintainer → it loads with the SAME `pipeline()` providers/onnx.js uses. | |
| 39 | +// · small: 118 MB at q8. It is the lightest variant in the repo (q4 weighs | |
| 40 | +// MORE — 398 MB — because the embedding matrix of a 250k vocabulary does not | |
| 41 | +// quantise as well; here "fewer bits" does not mean less disk). | |
| 42 | +// · multilingual: XLM-R tokeniser, 100 languages. The prompts are in Spanish | |
| 43 | +// and the code is in English, and that crossing is exactly the lexical | |
| 44 | +// blind spot. | |
| 45 | +// · licence: MIT (intfloat/multilingual-e5-small upstream). | |
| 46 | +// · a 512-token window, which is what the blocks the packer assembles need; | |
| 47 | +// this is not a single-sentence model. | |
| 46 | 48 | // |
| 47 | -// Descartados, y por qué: | |
| 48 | -// · Xenova/all-MiniLM-L6-v2 (23 MB, Apache-2.0) — 5× más barato, pero SÓLO | |
| 49 | -// inglés. Justo el caso que venimos a cubrir es el castellano. | |
| 50 | -// · Xenova/paraphrase-multilingual-MiniLM-L12-v2 (118 MB, Apache-2.0) — mismo | |
| 51 | -// peso, pero está afinado para paráfrasis de FRASES con ventana de 128 | |
| 52 | -// tokens: trocearía los bloques por la mitad. | |
| 53 | -// · onnx-community/embeddinggemma-300m-ONNX (175 MB en q4f16 + pesos externos) | |
| 54 | -// — mejor calidad, pero 1,5× de descarga y licencia Gemma (uso comercial | |
| 55 | -// permitido pero con política de uso y obligaciones de redistribución), no | |
| 56 | -// una licencia comercial limpia. | |
| 57 | -// · ibm-granite/granite-embedding-107m-multilingual (Apache-2.0) — sólo | |
| 58 | -// publica ONNX en fp32: 428 MB, 3,6× la descarga. | |
| 59 | -// · minishlab/potion-multilingual-128M (MIT) — estático y rapidísimo, pero su | |
| 60 | -// único ONNX pesa 512 MB y transformers.js no lo soporta de serie. | |
| 49 | +// Rejected, and why: | |
| 50 | +// · Xenova/all-MiniLM-L6-v2 (23 MB, Apache-2.0) — 5× cheaper, but English | |
| 51 | +// ONLY. Spanish is precisely the case we came here to cover. | |
| 52 | +// · Xenova/paraphrase-multilingual-MiniLM-L12-v2 (118 MB, Apache-2.0) — same | |
| 53 | +// weight, but it is tuned for SENTENCE paraphrase with a 128-token window: | |
| 54 | +// it would cut the blocks in half. | |
| 55 | +// · onnx-community/embeddinggemma-300m-ONNX (175 MB at q4f16 + external | |
| 56 | +// weights) — better quality, but 1.5× the download and a Gemma licence | |
| 57 | +// (commercial use permitted, but with a use policy and redistribution | |
| 58 | +// obligations), not a clean commercial licence. | |
| 59 | +// · ibm-granite/granite-embedding-107m-multilingual (Apache-2.0) — only | |
| 60 | +// publishes ONNX in fp32: 428 MB, 3.6× the download. | |
| 61 | +// · minishlab/potion-multilingual-128M (MIT) — static and extremely fast, but | |
| 62 | +// its only ONNX weighs 512 MB and transformers.js does not support it | |
| 63 | +// out of the box. | |
| 61 | 64 | // |
| 62 | -// DTYPE SEGÚN EL DISPOSITIVO — medido, no supuesto. Mismo modelo, mismo lote de | |
| 63 | -// bloques, sólo cambiando dtype y dispositivo (coste relativo, 1,0 = el mejor): | |
| 65 | +// DTYPE BY DEVICE — measured, not assumed. Same model, same batch of blocks, | |
| 66 | +// changing only dtype and device (relative cost, 1.0 = the best): | |
| 64 | 67 | // |
| 65 | -// fp16 / WebGPU .... 1,0× (235 MB) ← el elegido cuando hay adaptador | |
| 66 | -// q4f16/ WebGPU .... 0,6× (205 MB) con bloques medianos; ver punto 2 | |
| 67 | -// q8 / wasm ...... 8,9× (118 MB) ← la red de seguridad | |
| 68 | -// fp32 / wasm ...... 11,0× (470 MB) | |
| 69 | -// q8 / WebGPU .... 14,1× (118 MB) ← PEOR que en CPU | |
| 68 | +// fp16 / WebGPU .... 1.0× (235 MB) ← the pick when there is an adapter | |
| 69 | +// q4f16/ WebGPU .... 0.6× (205 MB) with medium blocks; see point 2 | |
| 70 | +// q8 / wasm ...... 8.9× (118 MB) ← the safety net | |
| 71 | +// fp32 / wasm ...... 11.0× (470 MB) | |
| 72 | +// q8 / WebGPU .... 14.1× (118 MB) ← WORSE than on CPU | |
| 70 | 73 | // |
| 71 | -// Dos cosas que contradicen la intuición y por eso van escritas: | |
| 72 | -// 1. Los enteros de 8 bits NO se aceleran en WebGPU: ORT-web no tiene kernels | |
| 73 | -// para esos operadores y acaba yendo y viniendo de la CPU. El fichero más | |
| 74 | -// pequeño resulta ser el MÁS LENTO en la GPU. Elegir dtype por tamaño de | |
| 75 | -// descarga, sin medir, habría dado la peor combinación posible. | |
| 76 | -// 2. Con textos CORTOS —que es nuestro caso, ver SEM_BUDGET en context.js— el | |
| 77 | -// 4-bit se da la vuelta y pierde contra fp16 (2,6× más lento en líneas | |
| 78 | -// sueltas): a esas longitudes se paga más por deshacer la cuantización que | |
| 79 | -// lo que se ahorra en ancho de banda. Por eso fp16 y no q4f16, aunque en | |
| 80 | -// bloques grandes q4f16 gane. | |
| 74 | +// Two things that contradict intuition, which is why they are written down: | |
| 75 | +// 1. 8-bit integers are NOT accelerated on WebGPU: ORT-web has no kernels for | |
| 76 | +// those operators and ends up bouncing back and forth to the CPU. The | |
| 77 | +// smallest file turns out to be the SLOWEST on the GPU. Picking a dtype by | |
| 78 | +// download size, without measuring, would have given the worst possible | |
| 79 | +// combination. | |
| 80 | +// 2. With SHORT texts — which is our case, see the block sizing in context.js — | |
| 81 | +// 4-bit flips around and loses to fp16 (2.6× slower on single lines): at | |
| 82 | +// those lengths you pay more to undo the quantisation than you save in | |
| 83 | +// bandwidth. Hence fp16 and not q4f16, even though q4f16 wins on large | |
| 84 | +// blocks. | |
| 81 | 85 | // |
| 82 | -// De ahí la regla: fp16 si hay adaptador WebGPU de verdad, y q8/wasm como red de | |
| 83 | -// seguridad. La red de seguridad FUNCIONA pero es ~9× más lenta, hasta el punto | |
| 84 | -// de notarse en cada turno, y ése es uno de los motivos de que el lado semántico | |
| 85 | -// vaya apagado por defecto (ver context.js). | |
| 86 | +// Hence the rule: fp16 if there is a real WebGPU adapter, and q8/wasm as the | |
| 87 | +// safety net. The safety net WORKS but it is ~9× slower, to the point of being | |
| 88 | +// noticeable on every turn, and that is one of the reasons the semantic side is | |
| 89 | +// off by default (see context.js). | |
| 86 | 90 | // ───────────────────────────────────────────────────────────────────────────── |
| 87 | 91 | |
| 88 | -import { createEmbedCache } from './acer-core.js'; | |
| 92 | +import { createEmbedCache } from './context.js'; | |
| 89 | 93 | |
| 90 | 94 | export const EMBED_MODEL = { |
| 91 | 95 | id: 'Xenova/multilingual-e5-small', |
| 92 | 96 | dims: 384, |
| 93 | 97 | label: 'multilingual-e5-small', |
| 94 | - // dtype → fichero → descarga | |
| 98 | + // dtype → file → download | |
| 95 | 99 | webgpu: { dtype: 'fp16', sizeMB: 235 }, |
| 96 | 100 | wasm: { dtype: 'q8', sizeMB: 118 }, |
| 97 | 101 | }; |
| 98 | 102 | |
| 99 | -// La ventana del modelo son 512 tokens; recortar antes de tokenizar evita pagar | |
| 100 | -// el troceado de texto que el propio modelo va a descartar. | |
| 103 | +// The model's window is 512 tokens; trimming before tokenising avoids paying to | |
| 104 | +// split text the model itself is going to discard. | |
| 101 | 105 | const MAX_CHARS = 2000; |
| 102 | 106 | |
| 103 | -// Lotes pequeños: transformers.js rellena cada lote hasta el más largo, así que | |
| 104 | -// un lote gigante hace pagar la longitud del peor elemento por todos. | |
| 107 | +// Small batches: transformers.js pads every batch up to its longest item, so a | |
| 108 | +// giant batch makes everyone pay the length of the worst element. | |
| 105 | 109 | const BATCH = 16; |
| 106 | 110 | |
| 107 | -// e5 se entrenó SIEMPRE con prefijo ('query: ' / 'passage: '), nunca con texto | |
| 108 | -// pelado. acer-core llama a la misma `embed` para la pregunta y para los | |
| 109 | -// bloques, y no hay forma de distinguirlos sin tocar el núcleo; los autores del | |
| 110 | -// modelo documentan usar 'query: ' en AMBOS lados para uso simétrico. Quitarlo | |
| 111 | -// del todo sería peor: el modelo nunca vio esa distribución. | |
| 111 | +// e5 was ALWAYS trained with a prefix ('query: ' / 'passage: '), never with bare | |
| 112 | +// text. the packer calls the same `embed` for the question and for the blocks, | |
| 113 | +// and there is no way to tell them apart without touching the core; the model's | |
| 114 | +// authors document using 'query: ' on BOTH sides for symmetric use. Dropping it | |
| 115 | +// altogether would be worse: the model never saw that distribution. | |
| 112 | 116 | const PREFIX = 'query: '; |
| 113 | 117 | |
| 114 | 118 | let pipePromise = null; |
| 115 | -export let backend = null; // {device, dtype, sizeMB} una vez resuelto | |
| 119 | +export let backend = null; // {device, dtype, sizeMB} once resolved | |
| 116 | 120 | |
| 117 | 121 | /** |
| 118 | - * Carga PEREZOSA: nada de esto se toca en el arranque. El módulo entero se | |
| 119 | - * importa dinámicamente desde context.js sólo cuando la bandera está encendida, | |
| 120 | - * y el modelo no se descarga hasta la primera petición que de verdad lo use. | |
| 122 | + * LAZY loading: none of this is touched at startup. The whole module is | |
| 123 | + * dynamically imported from context.js only when the flag is on, and the model | |
| 124 | + * is not downloaded until the first request that genuinely uses it. | |
| 121 | 125 | */ |
| 122 | 126 | function getPipe(onProgress) { |
| 123 | 127 | if (!pipePromise) { |
| 124 | 128 | pipePromise = (async () => { |
| 125 | 129 | const tf = await import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@4'); |
| 126 | - // navigator.gpu puede EXISTIR sin adaptador real (mismo cuidado que en | |
| 127 | - // providers/onnx.js): comprobar el adaptador, no el objeto. Elegir mal | |
| 128 | - // aquí significa descargar 235 MB para acabar corriendo en CPU. | |
| 130 | + // navigator.gpu can EXIST without a real adapter (same care as in | |
| 131 | + // providers/onnx.js): check the adapter, not the object. Choosing wrong | |
| 132 | + // here means downloading 235 MB only to end up running on the CPU. | |
| 129 | 133 | let device = 'wasm'; |
| 130 | 134 | if (navigator.gpu) { |
| 131 | 135 | try { device = (await navigator.gpu.requestAdapter()) ? 'webgpu' : 'wasm'; } |
| @@ -137,10 +141,10 @@ | ||
| 137 | 141 | dtype: cfg.dtype, |
| 138 | 142 | progress_callback: onProgress, |
| 139 | 143 | }); |
| 140 | - backend = cfg; // sólo cuando de verdad está listo: isReady() no miente | |
| 144 | + backend = cfg; // only once it is genuinely ready: isReady() does not lie | |
| 141 | 145 | return pipe; |
| 142 | 146 | })().catch(e => { |
| 143 | - pipePromise = null; // que un fallo de red no deje el módulo muerto | |
| 147 | + pipePromise = null; // do not let a network failure leave the module dead | |
| 144 | 148 | backend = null; |
| 145 | 149 | throw e; |
| 146 | 150 | }); |
| @@ -148,16 +152,16 @@ | ||
| 148 | 152 | return pipePromise; |
| 149 | 153 | } |
| 150 | 154 | |
| 151 | -/** Precarga opcional (p.ej. desde Ajustes) sin bloquear ningún turno. */ | |
| 155 | +/** Optional preload (e.g. from Settings) without blocking any turn. */ | |
| 152 | 156 | export function warmup(onProgress) { return getPipe(onProgress); } |
| 153 | 157 | |
| 154 | -/** ¿Está ya cargado? Sirve para decidir si un turno va a pagar la descarga. */ | |
| 158 | +/** Already loaded? Useful to decide whether a turn will pay for the download. */ | |
| 155 | 159 | export function isReady() { return backend !== null; } |
| 156 | 160 | |
| 157 | 161 | /** |
| 158 | - * embed(textos) → vectores normalizados de 384 dimensiones. | |
| 159 | - * Contrato exacto que espera `packHistoryACERHybrid`: si esto lanza, acer-core | |
| 160 | - * se va por la vía léxica sin romperse ni avisar. | |
| 162 | + * embed(texts) → normalised 384-dimension vectors. | |
| 163 | + * The exact contract `packHistoryAsync` expects: if this throws, the packer | |
| 164 | + * takes the lexical path without breaking and without complaining. | |
| 161 | 165 | */ |
| 162 | 166 | export async function embed(texts) { |
| 163 | 167 | if (!texts || !texts.length) return []; |
| @@ -172,20 +176,23 @@ | ||
| 172 | 176 | return out; |
| 173 | 177 | } |
| 174 | 178 | |
| 175 | -// Caché de sesión POR CONTENIDO. No es una optimización: es lo que hace viable | |
| 176 | -// la idea. acer-core rearma los bloques desde el principio del historial en cada | |
| 177 | -// turno, así que sin caché un texto que ya se codificó en el turno 3 se volvería | |
| 178 | -// a codificar en el 4, el 5 y el 20 — el coste crecería con el CUADRADO de los | |
| 179 | -// turnos. Con caché, cada bloque se codifica una vez por sesión y un turno sólo | |
| 180 | -// paga los bloques nuevos. | |
| 181 | -// El tope es holgado a propósito: acer-core trocea el historial ENTERO en cada | |
| 182 | -// turno, así que si la caché desaloja entradas que el turno siguiente vuelve a | |
| 183 | -// pedir, se recodifica gratis. Son vectores de 384 flotantes: ~12 MB llenos. | |
| 179 | +// Session cache BY CONTENT. This is not an optimisation: it is what makes the | |
| 180 | +// idea viable at all. the packer reassembles the blocks from the start of the | |
| 181 | +// history on every turn, so without a cache a text already encoded on turn 3 | |
| 182 | +// would be re-encoded on turn 4, on turn 5 and on turn 20 — the cost would grow | |
| 183 | +// with the SQUARE of the number of turns. With a cache, each block is encoded | |
| 184 | +// once per session and a turn only pays for the new blocks. | |
| 185 | +// The ceiling is deliberately generous: the packer chunks the ENTIRE history on | |
| 186 | +// every turn, so if the cache evicts entries the next turn asks for again, they | |
| 187 | +// get re-encoded for nothing. These are 384-float vectors: ~12 MB when full. | |
| 184 | 188 | let cache = null; |
| 185 | 189 | export function embedCache() { |
| 186 | - if (!cache) cache = createEmbedCache(embed, { max: 8000 }); | |
| 190 | + // The signature is createEmbedCache(embed, max) with a NUMBER. Passing an | |
| 191 | + // object here meant `store.size > max` compared a number against an object, | |
| 192 | + // which is always false: the cache grew without bound and never evicted. | |
| 193 | + if (!cache) cache = createEmbedCache(embed, 8000); | |
| 187 | 194 | return cache; |
| 188 | 195 | } |
| 189 | 196 | |
| 190 | -/** Para diagnóstico/ajustes: cuántos textos lleva cacheados la sesión. */ | |
| 197 | +/** For diagnostics/settings: how many texts the session has cached so far. */ | |
| 191 | 198 | export function embedCacheSize() { return cache ? cache.size() : 0; } |
modified core/humanize.js +13 −13
| @@ -1,9 +1,10 @@ | ||
| 1 | -// Frase legible por humano para una tool-call («leyendo app.js…»). Compartido | |
| 2 | -// por el cerebro CEO (ceo.js) y el streaming en vivo del chat — así nunca se | |
| 3 | -// le enseña JSON crudo al usuario, siempre la misma redacción. Cubre los | |
| 4 | -// nombres de herramienta de Elffuss Code (code.*, terminal.*) y de Elffuss | |
| 5 | -// Claw (fs.*, app.*, web.*, skill.*, memory.*, tasks.*) — un tool desconocido | |
| 6 | -// cae al genérico «nombre argumento» sin romper nada. | |
| 1 | +// Human-readable phrase for a tool call ("leyendo app.js…"). Shared by the CEO | |
| 2 | +// brain (ceo.js) and by the live chat streaming — so the user is never shown | |
| 3 | +// raw JSON, and always the same wording. Covers the tool names of Elffuss Code | |
| 4 | +// (code.*, terminal.*) and Elffuss Claw (fs.*, app.*, web.*, skill.*, memory.*, | |
| 5 | +// tasks.*) — an unknown tool falls back to a generic "name argument" without | |
| 6 | +// breaking anything. | |
| 7 | +// NOTE: the returned strings are user-facing product copy and stay in Spanish. | |
| 7 | 8 | export function humanizeTool(name, args) { |
| 8 | 9 | const p = args?.path, q = args?.query, c = args?.command, n = args?.name; |
| 9 | 10 | switch (name) { |
| @@ -28,11 +29,10 @@ | ||
| 28 | 29 | } |
| 29 | 30 | } |
| 30 | 31 | |
| 31 | -// Detecta si el buffer que va llegando EN STREAMING ha entrado en un bloque de | |
| 32 | -// tool-call (```tool { … }) y, si es así, devuelve una frase humana en vez del | |
| 33 | -// JSON crudo — «preparando una acción…» hasta que el nombre de la tool sea | |
| 34 | -// legible, luego «leyendo app.js…» tan pronto como el campo aparezca, aunque | |
| 35 | -// el JSON todavía no haya cerrado. | |
| 32 | +// Detects whether the buffer arriving IN STREAM has entered a tool-call block | |
| 33 | +// (```tool { … }) and, if so, returns a human phrase instead of the raw JSON — | |
| 34 | +// "preparando una acción…" until the tool name is legible, then "leyendo | |
| 35 | +// app.js…" as soon as the field shows up, even if the JSON has not closed yet. | |
| 36 | 36 | export function humanizeStreamPreview(buf) { |
| 37 | 37 | if (buf.search(/```/) === -1 && !/^\s*\{\s*"tool"/.test(buf)) return null; |
| 38 | 38 | const toolM = buf.match(/"tool"\s*:\s*"([\w.]+)"/); |
| @@ -42,7 +42,7 @@ | ||
| 42 | 42 | const cmdM = buf.match(/"command"\s*:\s*"((?:[^"\\]|\\.)*)"/); |
| 43 | 43 | const nameM = buf.match(/"name"\s*:\s*"((?:[^"\\]|\\.)*)"/); |
| 44 | 44 | const out = humanizeTool(toolM[1], { path: pathM?.[1], query: queryM?.[1], command: cmdM?.[1], name: nameM?.[1] }); |
| 45 | - // el nombre de la tool ya se ve pero su campo (path/query/…) aún no llegó: | |
| 46 | - // mejor el genérico que un «leyendo undefined…» a medio streamear | |
| 45 | + // the tool name is already visible but its field (path/query/…) has not | |
| 46 | + // arrived yet: better the generic one than a half-streamed "leyendo undefined…" | |
| 47 | 47 | return /undefined/.test(out) ? 'preparando una acción…' : out; |
| 48 | 48 | } |
modified core/md.js +0 −0
Binary content is not shown. View the file.
modified core/mind.js +59 −59
| @@ -1,13 +1,13 @@ | ||
| 1 | -// Vista «Mente de Elffuss» — el pensamiento subyacente del cerebro CEO en un | |
| 2 | -// mundo 3D de fantasía psicodélica trance, con la CIUDAD real del proyecto | |
| 3 | -// (motor VibeCodeViewer) flotando por debajo. | |
| 4 | -// · cada línea/tool-call que llega nace como una ESTRELLA de texto (color por | |
| 5 | -// PERFIL, tamaño/tipografía según lo que ocurre) que se desvanece sola. | |
| 6 | -// · los perfiles (nombre, foco, color) se editan desde ⚙ — el usuario los crea | |
| 7 | -// a su gusto. | |
| 8 | -// · «≡ historial»: panel con TODO lo que ha llegado, sin recortar. | |
| 9 | -// · cuando lee/escribe un fichero real, un haz baja hasta él en la ciudad. | |
| 10 | -// · overlay PERSISTENTE (música/animación no reinician al salir y volver). | |
| 1 | +// "Elffuss Mind" view — the CEO brain's underlying thinking rendered as a | |
| 2 | +// psychedelic-trance 3D fantasy world, with the project's real CITY | |
| 3 | +// (VibeCodeViewer engine) floating underneath. | |
| 4 | +// · every line/tool-call that arrives is born as a text STAR (colour by | |
| 5 | +// PROFILE, size/typeface according to what is happening) that fades on its own. | |
| 6 | +// · the profiles (name, focus, colour) are edited from ⚙ — the user creates | |
| 7 | +// them to taste. | |
| 8 | +// · "≡ historial": a panel with EVERYTHING that has arrived, untruncated. | |
| 9 | +// · when it reads/writes a real file, a beam drops onto it in the city. | |
| 10 | +// · PERSISTENT overlay (music/animation do not restart on leaving and returning). | |
| 11 | 11 | import * as THREE from 'three'; |
| 12 | 12 | import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; |
| 13 | 13 | import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js'; |
| @@ -23,22 +23,22 @@ | ||
| 23 | 23 | |
| 24 | 24 | let open = false, built = false, raf = null; |
| 25 | 25 | let overlay, S, widget, onOpenFile = () => {}, onExecute = () => {}; |
| 26 | -// Ciudad de fondo (vista real del workspace) y semilla de pensamientos previos: | |
| 27 | -// AMBOS opcionales e inyectados por la app anfitriona — Code tiene un motor | |
| 28 | -// VibeCodeViewer sobre su proyecto único; Claw (v1) no lo ofrece y la Mente | |
| 29 | -// funciona igual de bien sin ciudad de fondo. | |
| 26 | +// Background city (the real view of the workspace) and the seed of previous | |
| 27 | +// thoughts: BOTH optional and injected by the host app — Code has a | |
| 28 | +// VibeCodeViewer engine over its single project; Claw (v1) does not offer one | |
| 29 | +// and the Mind works just as well without a background city. | |
| 30 | 30 | let loadThoughts = async () => []; // () => [{path, md}] |
| 31 | 31 | let buildCityFn = null; // (scene) => {cityWrap, cityCity, cityModel} | null |
| 32 | 32 | export function init({ loadThoughts: lt, buildCity: bc } = {}) { |
| 33 | 33 | if (lt) loadThoughts = lt; |
| 34 | 34 | if (bc) buildCityFn = bc; |
| 35 | 35 | } |
| 36 | -let anchorMap = new Map(); // id de perfil (+ 'ceo') → Vector3 (anclas del mundo) | |
| 37 | -const anchors = []; // { el, pos } — solo etiquetas de propuestas forjadas | |
| 36 | +let anchorMap = new Map(); // profile id (+ 'ceo') → Vector3 (world anchors) | |
| 37 | +const anchors = []; // { el, pos } — labels of forged proposals only | |
| 38 | 38 | let nodesGroup, thoughtNodes = []; |
| 39 | -let starGroup, stars = []; // estrellas de pensamiento efímeras | |
| 40 | -const lineBuf = new Map(); // canal → texto acumulado hasta la línea completa | |
| 41 | -const streamed = new Map(); // canal → ¿llegaron tokens? (evita duplicar el texto final) | |
| 39 | +let starGroup, stars = []; // ephemeral thought stars | |
| 40 | +const lineBuf = new Map(); // channel → text accumulated until the line is complete | |
| 41 | +const streamed = new Map(); // channel → did tokens arrive? (avoids duplicating the final text) | |
| 42 | 42 | let cityWrap = null, cityCity = null, cityModel = null; |
| 43 | 43 | let beams = [], fileActivity = []; |
| 44 | 44 | |
| @@ -51,7 +51,7 @@ | ||
| 51 | 51 | ? { id: 'ceo', name: 'CEO', color: CEO_COLOR } |
| 52 | 52 | : ceo.getProfiles().find(p => p.id === channel) || { id: channel, name: channel, color: '#7c5cff' }; |
| 53 | 53 | |
| 54 | -// ── música con Widget API (persistente: pausa al salir, reanuda al volver) ── | |
| 54 | +// ── music via the Widget API (persistent: pauses on leaving, resumes on return) ── | |
| 55 | 55 | function mountMusic(root) { |
| 56 | 56 | const wrap = document.createElement('div'); |
| 57 | 57 | wrap.className = 'mind-music'; |
| @@ -61,12 +61,12 @@ | ||
| 61 | 61 | '<div class="mind-music-cap">▶ Dekel · Baoba Festival — modo trance</div>'; |
| 62 | 62 | root.appendChild(wrap); |
| 63 | 63 | const iframe = wrap.querySelector('#mind-sc'); |
| 64 | - const initWidget = () => { try { widget = window.SC.Widget(iframe); } catch { /* aún no */ } }; | |
| 64 | + const initWidget = () => { try { widget = window.SC.Widget(iframe); } catch { /* not yet */ } }; | |
| 65 | 65 | if (window.SC && window.SC.Widget) initWidget(); |
| 66 | 66 | else { const s = document.createElement('script'); s.src = 'https://w.soundcloud.com/player/api.js'; s.onload = initWidget; document.head.appendChild(s); } |
| 67 | 67 | } |
| 68 | 68 | |
| 69 | -// ══ ESTRELLAS de pensamiento: cada línea/tool-call nace, brilla y se apaga ══ | |
| 69 | +// ══ thought STARS: every line/tool-call is born, shines and burns out ══ | |
| 70 | 70 | function makeTextSprite(text, color, { fontSize = 16, bold = false, glow = 10 } = {}) { |
| 71 | 71 | const pad = 8; |
| 72 | 72 | const probe = document.createElement('canvas').getContext('2d'); |
| @@ -88,7 +88,7 @@ | ||
| 88 | 88 | return sprite; |
| 89 | 89 | } |
| 90 | 90 | |
| 91 | -// kind: 'line' (charla normal) · 'tool' (tool-call) · 'event' (ciclo/estado) · 'built' (propuesta forjada) | |
| 91 | +// kind: 'line' (normal talk) · 'tool' (tool-call) · 'event' (cycle/status) · 'built' (forged proposal) | |
| 92 | 92 | const KIND_STYLE = { |
| 93 | 93 | line: { fontSize: 13, bold: false, glow: 8, life: 6, jitter: 15 }, |
| 94 | 94 | tool: { fontSize: 17, bold: true, glow: 16, life: 9, jitter: 9 }, |
| @@ -110,10 +110,10 @@ | ||
| 110 | 110 | if (stars.length > 160) { const old = stars.shift(); starGroup.remove(old.obj); old.obj.material.map.dispose(); old.obj.material.dispose(); } |
| 111 | 111 | } |
| 112 | 112 | |
| 113 | -// ── historial COMPLETO (todo lo que llega, sin recortar) — PERSISTENTE: antes | |
| 114 | -// vivía solo en el DOM/memoria y una recarga de página lo borraba entero. | |
| 113 | +// ── FULL history (everything that arrives, untruncated) — PERSISTENT: it used | |
| 114 | +// to live only in the DOM/memory and a page reload wiped it entirely. | |
| 115 | 115 | const LOG_CAP = 500; |
| 116 | -let logHistory = []; // [{channel, text}] — se guarda en IndexedDB | |
| 116 | +let logHistory = []; // [{channel, text}] — stored in IndexedDB | |
| 117 | 117 | let logSaveTimer = null; |
| 118 | 118 | function saveLogSoon() { |
| 119 | 119 | clearTimeout(logSaveTimer); |
| @@ -142,7 +142,7 @@ | ||
| 142 | 142 | if (!Array.isArray(saved) || !saved.length) return; |
| 143 | 143 | logHistory = saved; |
| 144 | 144 | for (const { channel, text } of saved) renderLogRow(channel, text); |
| 145 | - } catch { /* aún no hay historial guardado */ } | |
| 145 | + } catch { /* no saved history yet */ } | |
| 146 | 146 | } |
| 147 | 147 | |
| 148 | 148 | function flushLine(channel, force = false) { |
| @@ -152,7 +152,7 @@ | ||
| 152 | 152 | lineBuf.set(channel, ''); |
| 153 | 153 | } |
| 154 | 154 | |
| 155 | -// alimenta estrellas + historial + haces sobre la ciudad (ceo.js → aquí) | |
| 155 | +// feeds stars + history + beams over the city (ceo.js → here) | |
| 156 | 156 | export function pushThought(channel, ev) { |
| 157 | 157 | if (!open) return; |
| 158 | 158 | if (channel === 'sys') { logLine('ceo', ev.text); return; } |
| @@ -177,24 +177,24 @@ | ||
| 177 | 177 | logLine(channel, '⟐ ' + ev.text); |
| 178 | 178 | if (ev.path) fileBeam(ev.path, /escrib/i.test(ev.text) ? 'write' : 'read'); |
| 179 | 179 | } else if (ev.type === 'tool_result') { |
| 180 | - // el RESULTADO real de la tool (lo que de verdad se leyó/escribió/ejecutó), | |
| 181 | - // enlazado justo debajo de su tool-call — no solo el nombre de la acción. | |
| 180 | + // the tool's real RESULT (what was actually read/written/executed), linked | |
| 181 | + // right under its tool call — not just the name of the action. | |
| 182 | 182 | const t = '→ ' + (ev.text || '(sin salida)'); |
| 183 | 183 | spawnStar(channel, t, 'line'); |
| 184 | 184 | logLine(channel, t); |
| 185 | 185 | } else if (ev.type === 'done') { |
| 186 | 186 | flushLine(channel, true); |
| 187 | - // el proveedor puede devolver el texto final SIN pasar por tokens (sin | |
| 188 | - // streaming) → si no vimos ningún token, esto es lo único que lo muestra. | |
| 187 | + // the provider may return the final text WITHOUT going through tokens (no | |
| 188 | + // streaming) → if we saw no token at all, this is the only thing that shows it. | |
| 189 | 189 | if (ev.text && !streamed.get(channel)) { spawnStar(channel, ev.text, 'line'); logLine(channel, ev.text); } |
| 190 | 190 | } |
| 191 | 191 | } |
| 192 | 192 | |
| 193 | -// ── nodos de pensamiento clicables (cada .md forjado = un punto brillante) ── | |
| 193 | +// ── clickable thought nodes (each forged .md = one shining point) ── | |
| 194 | 194 | function addThoughtNode({ path, md, text }) { |
| 195 | 195 | if (!nodesGroup) return; |
| 196 | 196 | const i = thoughtNodes.length; |
| 197 | - const a = i * 2.399963; // ángulo áureo | |
| 197 | + const a = i * 2.399963; // golden angle | |
| 198 | 198 | const r = 30 + i * 5; |
| 199 | 199 | const mesh = new THREE.Mesh( |
| 200 | 200 | new THREE.IcosahedronGeometry(3.2, 0), |
| @@ -206,8 +206,8 @@ | ||
| 206 | 206 | const lab = document.createElement('div'); |
| 207 | 207 | lab.className = 'mind-node-label'; |
| 208 | 208 | lab.textContent = (path || 'pensamiento').split('/').pop(); |
| 209 | - // clicable ella misma — antes SOLO el raycast contra la diminuta malla 3D | |
| 210 | - // abría el panel, fácil de fallar; la etiqueta es el blanco visible real. | |
| 209 | + // clickable itself — before, ONLY the raycast against the tiny 3D mesh opened | |
| 210 | + // the panel, easy to miss; the label is the real visible target. | |
| 211 | 211 | lab.addEventListener('click', () => selectThoughtNode(mesh)); |
| 212 | 212 | document.getElementById('mind-anchors').appendChild(lab); |
| 213 | 213 | anchors.push({ el: lab, pos: mesh.position }); |
| @@ -215,10 +215,10 @@ | ||
| 215 | 215 | } |
| 216 | 216 | |
| 217 | 217 | async function loadExistingThoughts() { |
| 218 | - try { for (const it of await loadThoughts()) addThoughtNode(it); } catch { /* aún no hay */ } | |
| 218 | + try { for (const it of await loadThoughts()) addThoughtNode(it); } catch { /* none yet */ } | |
| 219 | 219 | } |
| 220 | 220 | |
| 221 | -// selección de un nodo de propuesta — desde la malla 3D (raycast) o su etiqueta | |
| 221 | +// selecting a proposal node — from the 3D mesh (raycast) or from its label | |
| 222 | 222 | function selectThoughtNode(mesh) { showThoughtPanel(mesh); focusOn(mesh.position, 26); } |
| 223 | 223 | |
| 224 | 224 | function showThoughtPanel(node) { |
| @@ -238,7 +238,7 @@ | ||
| 238 | 238 | if (openBtn) openBtn.onclick = () => { onOpenFile(node.userData.path); root.classList.remove('show'); }; |
| 239 | 239 | } |
| 240 | 240 | |
| 241 | -// ══ perfiles: anclas 3D + leyenda (recalculadas al abrir o al reprogramar) ══ | |
| 241 | +// ══ profiles: 3D anchors + legend (recomputed on open or on reprogramming) ══ | |
| 242 | 242 | function computeAnchors() { |
| 243 | 243 | const map = new Map(); |
| 244 | 244 | map.set('ceo', new THREE.Vector3(0, 46, 0)); |
| @@ -260,7 +260,7 @@ | ||
| 260 | 260 | row.onclick = () => { const pos = anchorMap.get(row.dataset.id); if (pos) focusOn(pos, 46); }; |
| 261 | 261 | }); |
| 262 | 262 | } |
| 263 | -// vuelo suave de la cámara hacia un punto — así «clic en algo → la cámara se centra» | |
| 263 | +// smooth camera flight towards a point — so that "click something → the camera centres on it" | |
| 264 | 264 | let flyTo = null; |
| 265 | 265 | function focusOn(pos, distance = 40) { |
| 266 | 266 | if (!S) return; |
| @@ -272,7 +272,7 @@ | ||
| 272 | 272 | const easeInOut = k => k < 0.5 ? 2 * k * k : 1 - Math.pow(-2 * k + 2, 2) / 2; |
| 273 | 273 | function rebuildWorld() { anchorMap = computeAnchors(); renderLegend(); } |
| 274 | 274 | |
| 275 | -// ── panel ⚙: reprograma misión, carpeta-alma y PERFILES (editables) ────── | |
| 275 | +// ── ⚙ panel: reprograms mission, soul folder and PROFILES (editable) ────── | |
| 276 | 276 | function wireConfig(root) { |
| 277 | 277 | const btn = root.querySelector('#mind-config'); |
| 278 | 278 | const cfg = root.querySelector('#mind-cfg'); |
| @@ -309,8 +309,8 @@ | ||
| 309 | 309 | }; |
| 310 | 310 | cfg.querySelector('#cfg-think-now').onclick = () => { ceo.forceCycle(); cfg.classList.remove('show'); }; |
| 311 | 311 | cfg.querySelector('#cfg-save').onclick = () => { |
| 312 | - // preserva el id original de cada perfil (si no, cada guardado los | |
| 313 | - // regeneraría desde el nombre y los ciclos en curso perderían el hilo) | |
| 312 | + // preserves each profile's original id (otherwise every save would | |
| 313 | + // regenerate them from the name and running cycles would lose the thread) | |
| 314 | 314 | const rows = [...cfg.querySelectorAll('.cfg-prof')].map(r => ({ |
| 315 | 315 | id: r.dataset.id || undefined, |
| 316 | 316 | color: r.querySelector('.cp-color').value, |
| @@ -334,8 +334,8 @@ | ||
| 334 | 334 | panel.querySelector('#ml-x').onclick = () => panel.classList.remove('show'); |
| 335 | 335 | } |
| 336 | 336 | |
| 337 | -// play/stop del cerebro, visible dentro de la Mente. La elección la persiste | |
| 338 | -// ceo.js (misma clave que usa el clic en la elfa) → sobrevive a recargar. | |
| 337 | +// brain play/stop, visible inside the Mind. The choice is persisted by ceo.js | |
| 338 | +// (the same key the click on the elf uses) → it survives a reload. | |
| 339 | 339 | function wirePlayStop(root) { |
| 340 | 340 | const btn = root.querySelector('#mind-playstop'); |
| 341 | 341 | const paint = () => { |
| @@ -347,16 +347,16 @@ | ||
| 347 | 347 | paint(); |
| 348 | 348 | } |
| 349 | 349 | |
| 350 | -// ══ ciudad de fondo (motor de la app anfitriona, por debajo del mundo) ══════ | |
| 350 | +// ══ background city (host app's engine, underneath the world) ══════ | |
| 351 | 351 | async function buildBackgroundCity(scene) { |
| 352 | 352 | if (!buildCityFn) return; |
| 353 | 353 | try { |
| 354 | 354 | const city = await buildCityFn(scene); |
| 355 | 355 | if (!city) return; |
| 356 | 356 | cityWrap = city.cityWrap; cityCity = city.cityCity; cityModel = city.cityModel; |
| 357 | - } catch { /* sigue sin ciudad de fondo */ } | |
| 357 | + } catch { /* carries on with no background city */ } | |
| 358 | 358 | } |
| 359 | -// haz de luz que baja hasta el fichero real en la ciudad + resalta su celda | |
| 359 | +// beam of light dropping onto the real file in the city + highlights its cell | |
| 360 | 360 | function fileBeam(path, kind) { |
| 361 | 361 | if (!cityModel || !cityCity || !S) return; |
| 362 | 362 | const rel = String(path).replace(/^\.?\//, ''); |
| @@ -373,7 +373,7 @@ | ||
| 373 | 373 | fileActivity.push({ id: f.id, born: elapsed, life: 2.2 }); |
| 374 | 374 | } |
| 375 | 375 | |
| 376 | -// ── mundo psicodélico ─────────────────────────────────────────────────────── | |
| 376 | +// ── psychedelic world ─────────────────────────────────────────────────────── | |
| 377 | 377 | function buildScene(canvas, W, H) { |
| 378 | 378 | const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true }); |
| 379 | 379 | renderer.setPixelRatio(Math.min(devicePixelRatio, 2)); |
| @@ -468,7 +468,7 @@ | ||
| 468 | 468 | S = buildScene(canvas, window.innerWidth, window.innerHeight); |
| 469 | 469 | buildBackgroundCity(S.scene); |
| 470 | 470 | await loadExistingThoughts(); |
| 471 | - await loadPersistedLog(); // el historial de «≡ historial» sobrevive a recargas | |
| 471 | + await loadPersistedLog(); // the "≡ historial" log survives reloads | |
| 472 | 472 | |
| 473 | 473 | const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(); |
| 474 | 474 | let downXY = null; |
| @@ -495,20 +495,20 @@ | ||
| 495 | 495 | startLoop(); |
| 496 | 496 | } |
| 497 | 497 | |
| 498 | -// Etiquetas de propuestas: se proyectan del mundo 3D a la pantalla, así que | |
| 499 | -// con muchas acumuladas acaban solapándose ilegibles según el ángulo de | |
| 500 | -// cámara. Aquí: cap a las más cercanas y reparto anti-solape (empuja hacia | |
| 501 | -// abajo la que choca con otra ya colocada), para que se apilen separadas. | |
| 498 | +// Proposal labels: they are projected from the 3D world onto the screen, so | |
| 499 | +// once many have piled up they end up overlapping illegibly depending on the | |
| 500 | +// camera angle. Here: cap to the nearest ones plus an anti-overlap pass (pushes | |
| 501 | +// down whichever collides with one already placed), so they stack apart. | |
| 502 | 502 | const MAX_LABELS = 14, LABEL_W = 90, LABEL_H = 20; |
| 503 | 503 | function projectAnchors() { |
| 504 | 504 | const w = window.innerWidth, h = window.innerHeight, v = new THREE.Vector3(); |
| 505 | 505 | const projected = []; |
| 506 | 506 | for (const a of anchors) { |
| 507 | 507 | v.copy(a.pos).project(S.camera); |
| 508 | - if (v.z > 1) { a.el.style.display = 'none'; continue; } // detrás de la cámara | |
| 508 | + if (v.z > 1) { a.el.style.display = 'none'; continue; } // behind the camera | |
| 509 | 509 | projected.push({ a, x: (v.x * 0.5 + 0.5) * w, y: (-v.y * 0.5 + 0.5) * h, depth: v.z }); |
| 510 | 510 | } |
| 511 | - projected.sort((p1, p2) => p1.depth - p2.depth); // las más cercanas a la cámara, prioridad | |
| 511 | + projected.sort((p1, p2) => p1.depth - p2.depth); // nearest to the camera get priority | |
| 512 | 512 | projected.forEach((p, i) => { p.a.el.style.display = i < MAX_LABELS ? '' : 'none'; }); |
| 513 | 513 | const visible = projected.slice(0, MAX_LABELS).sort((p1, p2) => p1.x - p2.x || p1.y - p2.y); |
| 514 | 514 | const placed = []; |
| @@ -556,7 +556,7 @@ | ||
| 556 | 556 | r.material.color.setHSL((t * 0.05 + r.userData.i * 0.03) % 1, 0.85, 0.6); |
| 557 | 557 | } |
| 558 | 558 | for (let i = 0; i < thoughtNodes.length; i++) { const n = thoughtNodes[i]; n.rotation.y = t + i; n.scale.setScalar(1 + Math.sin(t * 2 + i) * 0.14); } |
| 559 | - // estrellas: nacen (fade-in), viven, se apagan solas y se reciclan | |
| 559 | + // stars: they are born (fade-in), live, burn out on their own and get recycled | |
| 560 | 560 | for (let i = stars.length - 1; i >= 0; i--) { |
| 561 | 561 | const st = stars[i], age = t - st.born; |
| 562 | 562 | if (age > st.life) { starGroup.remove(st.obj); st.obj.material.map.dispose(); st.obj.material.dispose(); stars.splice(i, 1); continue; } |
| @@ -565,7 +565,7 @@ | ||
| 565 | 565 | st.obj.position.y += st.up * dt; |
| 566 | 566 | st.obj.position.x += Math.sin(t * 0.6 + st.seed) * 0.3 * dt; |
| 567 | 567 | } |
| 568 | - // haces sobre la ciudad + celdas de fichero resaltadas por actividad | |
| 568 | + // beams over the city + file cells highlighted by activity | |
| 569 | 569 | for (let i = beams.length - 1; i >= 0; i--) { |
| 570 | 570 | const b = beams[i], age = t - b.born; |
| 571 | 571 | if (age > b.life) { S.scene.remove(b.obj); b.obj.geometry.dispose(); b.obj.material.dispose(); beams.splice(i, 1); continue; } |
| @@ -597,7 +597,7 @@ | ||
| 597 | 597 | if (overlay) overlay.style.display = 'none'; |
| 598 | 598 | } |
| 599 | 599 | |
| 600 | -// para tests/depuración | |
| 600 | +// for tests/debugging | |
| 601 | 601 | export function _debug() { |
| 602 | 602 | return { |
| 603 | 603 | starCount: stars.length, hasCity: !!cityCity, profileCount: ceo.getProfiles().length, |
modified core/providers/api.js +6 −6
| @@ -1,8 +1,8 @@ | ||
| 1 | -// Proveedor genérico para APIs externas (configuración avanzada): | |
| 1 | +// Generic provider for external APIs (advanced configuration): | |
| 2 | 2 | // - kind 'openai' → /chat/completions (OpenAI, Ollama, llama-server…) |
| 3 | 3 | // - kind 'anthropic' → /v1/messages (Claude) |
| 4 | -// Las llamadas salen DIRECTAS del navegador del usuario al proveedor; la clave | |
| 5 | -// no pasa por ningún servidor nuestro. Streaming SSE en ambos dialectos. | |
| 4 | +// Calls go DIRECTLY from the user's browser to the provider; the key never | |
| 5 | +// passes through any server of ours. SSE streaming in both dialects. | |
| 6 | 6 | import { packHistoryAsync } from '../context.js'; |
| 7 | 7 | |
| 8 | 8 | let cfg = null; |
| @@ -81,7 +81,7 @@ | ||
| 81 | 81 | return out.trim(); |
| 82 | 82 | } |
| 83 | 83 | |
| 84 | -// Anthropic exige roles alternos empezando por user; fusiona consecutivos. | |
| 84 | +// Anthropic requires alternating roles starting with user; merge consecutive ones. | |
| 85 | 85 | function forAnthropic(msgs) { |
| 86 | 86 | const merged = []; |
| 87 | 87 | for (const m of msgs) { |
| @@ -94,7 +94,7 @@ | ||
| 94 | 94 | return merged; |
| 95 | 95 | } |
| 96 | 96 | |
| 97 | -// Lector SSE común: invoca fn con el texto tras cada 'data:'. | |
| 97 | +// Shared SSE reader: calls fn with the text after each 'data:'. | |
| 98 | 98 | async function readSSE(stream, fn) { |
| 99 | 99 | const reader = stream.getReader(); |
| 100 | 100 | const dec = new TextDecoder(); |
| @@ -110,7 +110,7 @@ | ||
| 110 | 110 | if (!line.startsWith('data:')) continue; |
| 111 | 111 | const payload = line.slice(5).trim(); |
| 112 | 112 | if (!payload) continue; |
| 113 | - try { fn(payload); } catch { /* chunk parcial */ } | |
| 113 | + try { fn(payload); } catch { /* partial chunk */ } | |
| 114 | 114 | } |
| 115 | 115 | } |
| 116 | 116 | } |
modified core/skills.js +23 −21
| @@ -1,14 +1,14 @@ | ||
| 1 | -// Skills de Elffuss Code: instrucciones en markdown (formato SKILL.md de | |
| 2 | -// Claude Code) que el modelo sigue cuando aplican. Se instalan desde el | |
| 3 | -// catálogo grande OFICIAL (github.com/anthropics/skills), desde los plugins | |
| 4 | -// oficiales, o desde CUALQUIER repo público (marketplaces de la comunidad | |
| 5 | -// tipo OpenClaude/openclaw). Todo transparente: se ve el repo, la lista y el | |
| 6 | -// SKILL.md que se inyecta. Se guardan en IndexedDB (nada sale del navegador). | |
| 1 | +// Elffuss Code skills: markdown instructions (Claude Code's SKILL.md format) | |
| 2 | +// that the model follows when they apply. They install from the big OFFICIAL | |
| 3 | +// catalogue (github.com/anthropics/skills), from the official plugins, or from | |
| 4 | +// ANY public repo (community marketplaces such as OpenClaude/openclaw). | |
| 5 | +// Everything is transparent: you see the repo, the list, and the SKILL.md that | |
| 6 | +// gets injected. They are stored in IndexedDB (nothing leaves the browser). | |
| 7 | 7 | import * as db from './db.js'; |
| 8 | 8 | |
| 9 | -const KEY = 'skills'; // skills instaladas | |
| 10 | -const SRC_KEY = 'skills.sources'; // repos personalizados añadidos por el usuario | |
| 11 | -const MAX_SKILL = 12_000; // caracteres del cuerpo que se inyectan al modelo | |
| 9 | +const KEY = 'skills'; // installed skills | |
| 10 | +const SRC_KEY = 'skills.sources'; // custom repos added by the user | |
| 11 | +const MAX_SKILL = 12_000; // characters of the body injected into the model | |
| 12 | 12 | |
| 13 | 13 | export const CATALOG_REPO = 'anthropics/skills'; |
| 14 | 14 | export const DEFAULT_SOURCES = [ |
| @@ -17,7 +17,7 @@ | ||
| 17 | 17 | { repo: 'anthropics/claude-plugins-official', label: 'Anthropic · Claude Code Plugins (oficial)', official: true }, |
| 18 | 18 | ]; |
| 19 | 19 | |
| 20 | -let cache = []; // instaladas, en memoria (para que el systemPrompt sea síncrono) | |
| 20 | +let cache = []; // installed, in memory (so that systemPrompt can be synchronous) | |
| 21 | 21 | |
| 22 | 22 | export async function initSkills() { |
| 23 | 23 | cache = (await db.get('kv', KEY).catch(() => null)) || []; |
| @@ -33,10 +33,11 @@ | ||
| 33 | 33 | const entry = { ...skill, content: (skill.content || '').slice(0, MAX_SKILL) }; |
| 34 | 34 | cache.push(entry); |
| 35 | 35 | await db.set('kv', KEY, cache); |
| 36 | - return entry; // devuelve la skill completa (name, description…) | |
| 36 | + return entry; // returns the full skill (name, description…) | |
| 37 | 37 | } |
| 38 | 38 | |
| 39 | -// Mensaje «cómo usarla» tras instalar: qué hace + un ejemplo de qué pedir. | |
| 39 | +// "How to use it" message after installing: what it does + an example of what | |
| 40 | +// to ask for. The returned copy is user-facing and stays in Spanish. | |
| 40 | 41 | export function usageMessage(skill) { |
| 41 | 42 | const desc = (skill.description || '').trim(); |
| 42 | 43 | const ejemplo = firstExample(skill) || `algo relacionado con «${skill.name}»`; |
| @@ -45,7 +46,7 @@ | ||
| 45 | 46 | `Ya la sigo en cada conversación. Para usarla, pídeme por ejemplo:\n\n> ${ejemplo}`; |
| 46 | 47 | } |
| 47 | 48 | |
| 48 | -// Intenta sacar un ejemplo de uso del cuerpo del SKILL.md (líneas de ejemplo/uso). | |
| 49 | +// Tries to pull a usage example out of the SKILL.md body (example/usage lines). | |
| 49 | 50 | function firstExample(skill) { |
| 50 | 51 | const body = skill.content || ''; |
| 51 | 52 | const m = body.match(/(?:ejemplo|example|uso|usage|prueba|try)[^\n:]*[::]\s*["“]?([^\n"”]{6,90})/i) |
| @@ -62,7 +63,7 @@ | ||
| 62 | 63 | return cache.find(s => s.name.toLowerCase() === String(name).toLowerCase()) || null; |
| 63 | 64 | } |
| 64 | 65 | |
| 65 | -// ---- fuentes (repos) ---- | |
| 66 | +// ---- sources (repos) ---- | |
| 66 | 67 | export async function sources() { |
| 67 | 68 | const custom = (await db.get('kv', SRC_KEY).catch(() => null)) || []; |
| 68 | 69 | return [...DEFAULT_SOURCES, ...custom]; |
| @@ -81,8 +82,8 @@ | ||
| 81 | 82 | await db.set('kv', SRC_KEY, custom.filter(s => s.repo !== repo)); |
| 82 | 83 | } |
| 83 | 84 | |
| 84 | -// ---- catálogo desde GitHub ---- | |
| 85 | -// Una sola llamada al árbol git del repo → todos los SKILL.md. | |
| 85 | +// ---- catalogue from GitHub ---- | |
| 86 | +// A single call to the repo's git tree → every SKILL.md. | |
| 86 | 87 | export async function listFromRepo(repo) { |
| 87 | 88 | let tree, branch; |
| 88 | 89 | for (const b of ['main', 'master']) { |
| @@ -97,7 +98,7 @@ | ||
| 97 | 98 | .sort((a, b) => a.dir.localeCompare(b.dir)); |
| 98 | 99 | } |
| 99 | 100 | |
| 100 | -// Descarga el SKILL.md y lo instala (frontmatter YAML simple). | |
| 101 | +// Downloads the SKILL.md and installs it (simple YAML frontmatter). | |
| 101 | 102 | export async function installFromRepo(entry) { |
| 102 | 103 | let md = null; |
| 103 | 104 | for (const b of [entry.branch, 'main', 'master'].filter(Boolean)) { |
| @@ -119,9 +120,9 @@ | ||
| 119 | 120 | return { name, description, content }; |
| 120 | 121 | } |
| 121 | 122 | |
| 122 | -// Creador de skills: Elffuss fabrica una skill propia (SKILL.md) a partir de | |
| 123 | -// lo que el usuario quiere, y la instala al instante. Aparece en la pestaña | |
| 124 | -// Skills y se inyecta en el prompt de los siguientes turnos. | |
| 123 | +// Skill maker: Elffuss builds a skill of its own (SKILL.md) out of whatever the | |
| 124 | +// user wants, and installs it instantly. It shows up in the Skills tab and is | |
| 125 | +// injected into the prompt of the following turns. | |
| 125 | 126 | export async function createSkill({ name, description, instructions } = {}) { |
| 126 | 127 | if (!name || !instructions) throw new Error('Faltan name o instructions'); |
| 127 | 128 | const skill = { |
| @@ -135,7 +136,8 @@ | ||
| 135 | 136 | return `Skill «${skill.name}» creada e instalada. Ya la sigo en cada conversación (mírala en la pestaña Skills).`; |
| 136 | 137 | } |
| 137 | 138 | |
| 138 | -// Bloque para el systemPrompt (síncrono, desde la caché). | |
| 139 | +// Block for the systemPrompt (synchronous, straight from the cache). The | |
| 140 | +// injected wording is prompt content, not documentation: it stays in Spanish. | |
| 139 | 141 | export function skillsPromptBlock() { |
| 140 | 142 | if (!cache.length) return ''; |
| 141 | 143 | const parts = cache.map(s => |
modified core/splash-gl.js +8 −8
| @@ -1,14 +1,14 @@ | ||
| 1 | -// Galaxia de partículas WebGL para el splash — sin librerías, autocontenida. | |
| 2 | -// Técnica: GL_POINTS + blending aditivo + rotación diferencial calculada por | |
| 3 | -// completo en el vertex shader desde una semilla (la CPU no toca nada por | |
| 4 | -// frame). ~24k partículas en espiral rosa→violeta con motas doradas, parallax | |
| 5 | -// de ratón y explosión al pulsar Entrar. | |
| 1 | +// WebGL particle galaxy for the splash screen — no libraries, self-contained. | |
| 2 | +// Technique: GL_POINTS + additive blending + differential rotation computed | |
| 3 | +// entirely in the vertex shader from a seed (nothing is touched per frame on | |
| 4 | +// the CPU side). ~24k particles in a pink→violet spiral with golden specks, | |
| 5 | +// pointer parallax, and a burst when Enter is pressed. | |
| 6 | 6 | export function startGalaxy(container) { |
| 7 | 7 | const canvas = document.createElement('canvas'); |
| 8 | 8 | canvas.className = 'gl'; |
| 9 | 9 | container.prepend(canvas); |
| 10 | 10 | const gl = canvas.getContext('webgl', { alpha: true, antialias: false, depth: false }); |
| 11 | - if (!gl) { canvas.remove(); return null; } // fallback: se queda el gradiente CSS | |
| 11 | + if (!gl) { canvas.remove(); return null; } // fallback: the CSS gradient stays | |
| 12 | 12 | |
| 13 | 13 | const N = 24000; |
| 14 | 14 | const seeds = new Float32Array(N * 2); |
| @@ -65,7 +65,7 @@ | ||
| 65 | 65 | |
| 66 | 66 | const buf = gl.createBuffer(); |
| 67 | 67 | gl.bindBuffer(gl.ARRAY_BUFFER, buf); |
| 68 | - gl.bufferData(gl.ARRAY_BUFFER, seeds, gl.STATIC_DRAW); // una vez; la GPU manda | |
| 68 | + gl.bufferData(gl.ARRAY_BUFFER, seeds, gl.STATIC_DRAW); // once; the shader drives it | |
| 69 | 69 | const loc = gl.getAttribLocation(prog, 'seed'); |
| 70 | 70 | gl.enableVertexAttribArray(loc); |
| 71 | 71 | gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0); |
| @@ -74,7 +74,7 @@ | ||
| 74 | 74 | const uT = U('t'), uAspect = U('aspect'), uBurst = U('burst'), uPar = U('par'), uDpr = U('dpr'); |
| 75 | 75 | |
| 76 | 76 | gl.enable(gl.BLEND); |
| 77 | - gl.blendFunc(gl.SRC_ALPHA, gl.ONE); // aditivo = brillo | |
| 77 | + gl.blendFunc(gl.SRC_ALPHA, gl.ONE); // additive = glow | |
| 78 | 78 | gl.clearColor(0, 0, 0, 0); |
| 79 | 79 | |
| 80 | 80 | let burstAt = 0, alive = true; |
modified core/telemetry.js +15 −15
| @@ -1,14 +1,14 @@ | ||
| 1 | -// Buzón opt-in de errores/feedback. Apagado por defecto — la promesa de | |
| 2 | -// «nada sale de tu máquina» sigue siendo cierta salvo que el usuario decida | |
| 3 | -// lo contrario en Ajustes. Cuando está activo: | |
| 4 | -// - errores no capturados (window.onerror / unhandledrejection) y los | |
| 5 | -// puntos concretos del código que llaman a reportError() se mandan a | |
| 6 | -// /proxy/report (mismo origen, vía el proxy compartido de Elffuss) | |
| 7 | -// - sendFeedback() manda texto libre que el usuario escriba a propósito | |
| 8 | -// Nunca se manda código ni contenido del proyecto — solo el mensaje técnico, | |
| 9 | -// la pila, la URL y el user-agent. Sin cola ni reintentos: si el envío | |
| 10 | -// falla, se descarta sin más (evita que un fallo de red se convierta en | |
| 11 | -// almacenamiento sin límite). | |
| 1 | +// Opt-in error/feedback mailbox. Off by default — the promise that "nothing | |
| 2 | +// leaves your machine" stays true unless the user decides otherwise in | |
| 3 | +// Settings. When it is on: | |
| 4 | +// - uncaught errors (window.onerror / unhandledrejection) and the specific | |
| 5 | +// places in the code that call reportError() are sent to /proxy/report | |
| 6 | +// (same origin, through the shared Elffuss proxy) | |
| 7 | +// - sendFeedback() sends free text the user deliberately wrote | |
| 8 | +// Code and project content are NEVER sent — only the technical message, the | |
| 9 | +// stack, the URL and the user agent. No queue and no retries: if the send | |
| 10 | +// fails it is simply dropped (this keeps a network failure from turning into | |
| 11 | +// unbounded storage). | |
| 12 | 12 | let appName = 'elffuss'; |
| 13 | 13 | let enabled = false; |
| 14 | 14 | let hooked = false; |
| @@ -19,7 +19,7 @@ | ||
| 19 | 19 | |
| 20 | 20 | export function setEnabled(v) { |
| 21 | 21 | enabled = !!v; |
| 22 | - try { localStorage.setItem(storageKey(), enabled ? '1' : '0'); } catch { /* localStorage lleno/bloqueado */ } | |
| 22 | + try { localStorage.setItem(storageKey(), enabled ? '1' : '0'); } catch { /* localStorage full/blocked */ } | |
| 23 | 23 | if (enabled) hookGlobalErrors(); |
| 24 | 24 | } |
| 25 | 25 | |
| @@ -36,7 +36,7 @@ | ||
| 36 | 36 | extra: String(opts.extra || '').slice(0, 2000), |
| 37 | 37 | }), |
| 38 | 38 | }); |
| 39 | - } catch { /* sin conexión o proxy caído: se descarta, no hay reintento */ } | |
| 39 | + } catch { /* offline or proxy down: dropped, no retry */ } | |
| 40 | 40 | } |
| 41 | 41 | |
| 42 | 42 | export function reportError(message, opts = {}) { return post('error', message, opts); } |
| @@ -54,8 +54,8 @@ | ||
| 54 | 54 | }); |
| 55 | 55 | } |
| 56 | 56 | |
| 57 | -// Llamar UNA vez al arrancar, con el nombre de la app (para distinguir | |
| 58 | -// elffuss-code de elffuss-claw en los informes) — lee la preferencia guardada. | |
| 57 | +// Call ONCE at startup with the name of the app (so elffuss-code and | |
| 58 | +// elffuss-claw can be told apart in the reports) — reads the stored preference. | |
| 59 | 59 | export function init(name) { |
| 60 | 60 | appName = name || appName; |
| 61 | 61 | try { enabled = localStorage.getItem(storageKey()) === '1'; } catch { enabled = false; } |