A chess engine that plays in a browser tab
Open calichess.cc, set up any position, and it tells you the best move, how sure it is, and why, in one plain sentence. The engine behind it is one I wrote in Rust in about 36 hours. It runs inside the tab: no server, no account, nothing sent anywhere.

What runs in the tab
A chess engine has three parts. The board knows the rules. The evaluation scores a position in centipawns, hundredths of a pawn. The search walks the tree of future moves and brings those scores back to the present. Here each part is a Rust crate, and the whole chain ends in a WebAssembly file the browser runs in a background worker:
crates/board rules, bitboards, legal moves
|
v
crates/eval -------> crates/search/engine.rs PVS, transposition table, pruning, MultiPV
|
v
crates/wasm-bridge Rust compiled to WebAssembly, 191 KB gzipped
|
v
apps/web worker the search runs off the page's main thread
|
v
apps/web board, eval bar, the sentence you read
The board uses bitboards: 64-bit numbers with one bit per square, so "is this square attacked?" is a few arithmetic operations. Move generation is checked with perft, which counts every legal position to a fixed depth: 119,060,324 from the start at depth 6, in 3.55 s, exactly the published number.
The search
The search in engine.rs is principal variation search (PVS), a refinement of alpha-beta: search the expected best move with a full window, the rest with a narrow, cheaper one. Around it are the standard pieces of a modern engine:
- Transposition table: remembers positions already searched, reached by a different move order.
- Null-move pruning: "if I skip my turn and I'm still winning, this line is good enough to cut".
- Late move reductions: moves sorted late are probably bad, so search them shallower first.
- Futility, reverse futility and late move pruning: skip moves that cannot plausibly change the result.
- Quiescence with SEE: at the end of a line keep resolving captures, so a score is never taken mid-exchange.
The evaluation in tapered.rs is tapered: every term has a middlegame and an endgame weight, blended by the material left. The weights were fitted with Texel tuning on 2.2 M positions from Lichess games, so the score predicts real results.
No change on a hunch
The first version won 100 games to 0 against the old search. After that, every change played the previous version in an SPRT, a statistical test that keeps playing games until it can say with set confidence that the change gains Elo, or that it doesn't. Matches ran in fastchess at 5 s + 0.05 s per move, on balanced openings, using 10 cores. These are the changes that passed:
| Version | Commit | Change | Elo |
|---|---|---|---|
| v1 | bc22f777 | New PVS engine, against the old search | 100-0 |
| v2 | bc22f777 | Tapered eval, Texel-tuned on 2.2 M Lichess positions | +315 ± 82 |
| v3 | bd1469fb | Pseudo-legal move generation, ~3x nodes/s | +175 ± 42 |
| v4 | f6dff0e4 | Bitboard eval + threats, king safety, passers, mobility | +137 ± 36 |
| v5 | 2577ab12 | IIR, capture and continuation history, time by stability | +59 ± 26 |
| v6 | 69447565 | SEE pruning, with see() fixed | +60 ± 26 |
| v7 | 7bfa5603 | "Improving" flag in RFP, LMP and LMR | +19 ± 14 |
| v8 | 095961d4 | Pawn shelter and storm, minor-piece terms, endgame scale | +13.3 ± 8.4 |
| v9 | cee3b314 | Same tree, ~1.9x nodes/s | +117.4 ± 24.1 |
| v9.1 | 1402fbab | TT cutoffs inside null-move branches | +45.9 ± 16.4 |

The bug that looked like bad luck
SEE pruning, skipping captures that lose material, is in every strong engine. Here it made the engine about 80 Elo weaker. That makes no sense for a standard technique, so I treated it as a bug report. Static exchange evaluation (SEE) plays out every capture on one square and folds the gains back from the deepest one. The loop stopped one step early, so the last recapture was never counted:
// crates/search/src/engine.rs, fn see(): fold the gains back from the deepest capture
- while depth > 1 {
- depth -= 1;
+ // Every gain[1..=depth] is a capture that was actually found, so all of them fold back.
+ while depth > 0 {
gain[depth - 1] = -i32::max(-gain[depth - 1], gain[depth]);
+ depth -= 1;
}
gain[0]
A queen taking a pawn defended by a pawn scored +100 (won a pawn) instead of −800 (lost the queen). The fix shipped with tests for exactly that:
// Queen takes a pawn defended by a pawn: dxe5 wins the queen.
assert_eq!(see_of("4k3/8/3p4/4p3/8/8/8/4Q1K1 w - - 0 1", "e1e5"), -800);
With the fix, the same pruning gained +60 (69447565). Since then, a known technique that loses a lot is a bug until proven otherwise.
Same tree, almost twice as fast
An audit showed speed, not evaluation, was the ceiling: 1.0-1.45 M nodes/s while engines of similar strength ran at 3.6-8.8 M. The rule for speed work was strict: it only counts if the search visits the exact same tree. A fixed benchmark (six positions, depth 15) visits 6,891,892 nodes before and after cee3b314. What changed:
- Prune (futility, LMP, SEE, delta) before making the move, using an exact bitboard
gives_check. - Reuse per-ply move buffers instead of initialising about 5 KB of lists per node.
- Pick moves on packed score and index keys, and cache the static evaluation and the pawn-and-king term.
Result: 1.28 M to 2.38 M nodes/s, and +117 Elo without a single new idea. On one thread of a Mac mini M4:
| Position, 5 s each | Depth | Nodes/s |
|---|---|---|
| Starting position | 19 | 2.28 M |
| Closed d4 middlegame | 20 | 2.40 M |
| Kiwipete | 20 | 1.86 M |
| Sicilian middlegame | 19 | 2.30 M |
| Bishop endgame | 31 | 3.34 M |
| Italian middlegame | 23 | 2.74 M |
An absolute number
Self-play only measures gains against yourself. For a rating on a public scale the engine played 600 games, 120 against each of five versions of Stash, an open engine with known CCRL ratings, at 8 s + 0.08 s per move:
| Opponent | Its CCRL rating | Rating this result implies |
|---|---|---|
| Stash 21 | 2713 | 3072 |
| Stash 25 | 2932 | 3008 |
| Stash 28 | 3082 | 3059 |
| Stash 31 | 3207 | 3083 |
| Stash 34 | 3314 | 2948 |
| All 600 games | ~3039 (3007-3071) |
Four best moves, explained
The view you use, Explore, asks the engine for its four best moves. MultiPV in engine.rs searches line 1, then searches again with that move excluded, and so on, all under one node budget:
/// MultiPV: the best `count` root moves, each with its own full-strength score and line.
/// Every depth searches line k with the first k-1 moves of that depth excluded, all under one
/// shared node budget. An interrupted depth is dropped unless no depth finished yet.
pub fn think_multi(&mut self, position: &Position, history_hashes: &[u64],
limits: EngineLimits<'_>, count: usize) -> MultiResult {
...
for depth in 1..=max_depth.min((MAX_PLY - 2) as u8) {
search.excluded.clear();
for index in 0..count {
let guess = lines.get(index).map(|line| line.score_cp);
let score = search.aspirate(position, depth, guess, root_in_check);
if search.aborted { break; }
let pv = search.line(0);
let Some(&mv) = pv.first() else { break; };
search.excluded.push(mv);
...
In the browser that budget is 100 k nodes for a quick answer and 300 k for a deeper one. At 1.0-1.5 M nodes/s in WebAssembly, Explore reaches depth 9-10 in about 200 ms and stops exactly on budget.
The sentence is not a template. Rust walks the best line and emits facts: threats it finds with SEE, captures, checks, mate, the material along the line. Then move-explanation.ts turns them into English or Spanish:
// crates/wasm-bridge/src/explanation.rs: facts, not sentences
pub struct ExplanationMoveDto {
pub mv: String,
pub piece: &'static str,
pub captured: Option<&'static str>,
pub promotion: Option<&'static str>,
pub castle: Option<&'static str>,
pub check: bool,
pub mate: bool,
pub threats: Vec<ExplanationSquareDto>,
pub saves_threatened: bool,
pub hangs: bool,
}

What did not work
Many ideas lost their match and stayed out:
| Experiment | Result |
|---|---|
| Singular extensions | −8 ± 16 (800 games) |
| History pruning, countermove, an LMR tweak | −7, +2, −5 (600 games each) |
| Eval re-labelled with Stockfish evals of Lichess positions | −158.6 ± 42.8 |
| Eval re-labelled with the engine's own search scores | −20.7 ± 17 |
| Evaluation cache | +2% nodes/s, inside noise |
The two re-labelling tunes taught the most: both improved their own training error and still lost games. So now an evaluation change must first lower prediction error on an independent dataset before it plays a single match. That offline gate would have rejected the −158.6 tune for free.
Delete before adding
The project had more paperwork than code. In those 36 hours the repository went from 1,355 files to 265: 157,518 lines removed, 13,540 added. I directed AI agents for the work. One model planned and checked evidence; cheaper ones wrote candidates in separate git worktrees, built the rival engines and ran the matches. Same rule for all of them: no claim without a number and the command that produced it.
Read the code
Try it at calichess.cc. The code, the benchmarks and a full case study with every commit are on GitHub, MIT licensed.
Follow-up: The four reconciliations, where the new engine met the old code.
In the repo: crates/search/src/engine.rs · crates/search/src/explore.rs · crates/eval/src/tapered.rs · crates/wasm-bridge/src/explanation.rs · apps/web/src/move-explanation.ts · docs/case-study-2026-11.md
Abre calichess.cc, pon cualquier posición y te dice la mejor jugada, qué tan seguro está y por qué, en una frase simple. El motor que hay detrás lo escribí en Rust en unas 36 horas. Corre dentro de la pestaña: sin servidor, sin cuenta, sin mandar nada a ningún lado.

Qué corre en la pestaña
Un motor de ajedrez tiene tres partes. El tablero conoce las reglas. La evaluación califica una posición en centipeones, centésimas de peón. La búsqueda recorre el árbol de jugadas futuras y trae esas calificaciones de vuelta al presente. Aquí cada parte es un crate de Rust, y la cadena termina en un archivo WebAssembly que el navegador corre en un worker en segundo plano:
crates/board rules, bitboards, legal moves
|
v
crates/eval -------> crates/search/engine.rs PVS, transposition table, pruning, MultiPV
|
v
crates/wasm-bridge Rust compiled to WebAssembly, 191 KB gzipped
|
v
apps/web worker the search runs off the page's main thread
|
v
apps/web board, eval bar, the sentence you read
El tablero usa bitboards: números de 64 bits con un bit por casilla, así que "¿esta casilla está atacada?" son unas cuantas operaciones aritméticas. La generación de jugadas se comprueba con perft, que cuenta cada posición legal hasta cierta profundidad: 119,060,324 desde el inicio a profundidad 6, en 3.55 s, exactamente el número publicado.
La búsqueda
La búsqueda en engine.rs es principal variation search (PVS), un refinamiento de alfa-beta: busca la jugada que espera mejor con ventana completa y las demás con una ventana angosta y más barata. Alrededor están las piezas estándar de un motor moderno:
- Tabla de transposición: recuerda posiciones ya buscadas, aunque se lleguen por otro orden de jugadas.
- Poda de movimiento nulo: "si me salto el turno y sigo ganando, esta línea ya es suficiente para cortarla".
- Reducciones tardías (LMR): las jugadas ordenadas al final probablemente son malas, así que primero se buscan menos profundo.
- Poda de futilidad, futilidad inversa y LMP: se salta jugadas que no pueden cambiar el resultado.
- Quiescencia con SEE: al final de una línea sigue resolviendo capturas, para no calificar a mitad de un intercambio.
La evaluación en tapered.rs es tapered: cada término tiene un peso de medio juego y otro de final, mezclados según el material que queda. Los pesos se ajustaron con Texel tuning sobre 2.2 M posiciones de partidas de Lichess, para que la calificación prediga resultados reales.
Ningún cambio por corazonada
La primera versión le ganó 100 a 0 a la búsqueda vieja. De ahí en adelante, cada cambio jugó contra la versión anterior en un SPRT, una prueba estadística que sigue jugando partidas hasta poder decir con una confianza fija si el cambio suma Elo o no. Las partidas corrieron en fastchess a 5 s + 0.05 s por jugada, con aperturas balanceadas, en 10 núcleos. Estos son los cambios que pasaron:
| Versión | Commit | Cambio | Elo |
|---|---|---|---|
| v1 | bc22f777 | Motor PVS nuevo, contra la búsqueda vieja | 100-0 |
| v2 | bc22f777 | Evaluación tapered, ajustada con Texel sobre 2.2 M posiciones de Lichess | +315 ± 82 |
| v3 | bd1469fb | Generación pseudo-legal, ~3x nodos/s | +175 ± 42 |
| v4 | f6dff0e4 | Evaluación con bitboards + amenazas, seguridad del rey, peones pasados, movilidad | +137 ± 36 |
| v5 | 2577ab12 | IIR, historia de capturas y de continuación, tiempo por estabilidad | +59 ± 26 |
| v6 | 69447565 | Poda SEE, con see() arreglado | +60 ± 26 |
| v7 | 7bfa5603 | Bandera "improving" en RFP, LMP y LMR | +19 ± 14 |
| v8 | 095961d4 | Escudo y avalancha de peones, piezas menores, escala de finales | +13.3 ± 8.4 |
| v9 | cee3b314 | El mismo árbol, ~1.9x nodos/s | +117.4 ± 24.1 |
| v9.1 | 1402fbab | Cortes de la TT dentro de ramas de movimiento nulo | +45.9 ± 16.4 |

El bug que parecía mala suerte
La poda SEE, saltarse capturas que pierden material, está en todos los motores fuertes. Aquí dejó al motor unos 80 Elo más débil. Eso no tiene sentido para una técnica estándar, así que lo traté como reporte de bug. La evaluación estática de intercambio (SEE) juega todas las capturas sobre una casilla y regresa las ganancias desde la más profunda. El ciclo se detenía un paso antes, así que la última recaptura nunca contaba:
// crates/search/src/engine.rs, fn see(): fold the gains back from the deepest capture
- while depth > 1 {
- depth -= 1;
+ // Every gain[1..=depth] is a capture that was actually found, so all of them fold back.
+ while depth > 0 {
gain[depth - 1] = -i32::max(-gain[depth - 1], gain[depth]);
+ depth -= 1;
}
gain[0]
Una dama que toma un peón defendido por un peón daba +100 (ganó un peón) en vez de −800 (perdió la dama). El arreglo salió con pruebas justo para eso:
// Queen takes a pawn defended by a pawn: dxe5 wins the queen.
assert_eq!(see_of("4k3/8/3p4/4p3/8/8/8/4Q1K1 w - - 0 1", "e1e5"), -800);
Con el arreglo, la misma poda sumó +60 (69447565). Desde entonces, una técnica conocida que pierde mucho es un bug hasta que se demuestre lo contrario.
El mismo árbol, casi el doble de rápido
Una auditoría mostró que el techo era la velocidad, no la evaluación: 1.0-1.45 M nodos/s, mientras motores de fuerza parecida corrían a 3.6-8.8 M. La regla para el trabajo de velocidad fue estricta: solo cuenta si la búsqueda visita exactamente el mismo árbol. Un benchmark fijo (seis posiciones, profundidad 15) visita 6,891,892 nodos antes y después de cee3b314. Qué cambió:
- Podar (futilidad, LMP, SEE, delta) antes de hacer la jugada, con un
gives_checkexacto en bitboards. - Reusar los buffers de jugadas por ply en vez de inicializar unos 5 KB de listas por nodo.
- Elegir jugadas con llaves empacadas de score e índice, y cachear la evaluación estática y el término de peones y rey.
Resultado: de 1.28 M a 2.38 M nodos/s, y +117 Elo sin una sola idea nueva. En un hilo de una Mac mini M4:
| Posición, 5 s cada una | Profundidad | Nodos/s |
|---|---|---|
| Posición inicial | 19 | 2.28 M |
| Medio juego cerrado de d4 | 20 | 2.40 M |
| Kiwipete | 20 | 1.86 M |
| Medio juego siciliano | 19 | 2.30 M |
| Final de alfiles | 31 | 3.34 M |
| Medio juego italiano | 23 | 2.74 M |
Un número absoluto
Jugar contra sí mismo solo mide mejoras relativas. Para un rating en una escala pública, el motor jugó 600 partidas, 120 contra cada una de cinco versiones de Stash, un motor abierto con rating CCRL conocido, a 8 s + 0.08 s por jugada:
| Rival | Su rating CCRL | Rating que implica el resultado |
|---|---|---|
| Stash 21 | 2713 | 3072 |
| Stash 25 | 2932 | 3008 |
| Stash 28 | 3082 | 3059 |
| Stash 31 | 3207 | 3083 |
| Stash 34 | 3314 | 2948 |
| Las 600 partidas | ~3039 (3007-3071) |
Las cuatro mejores jugadas, explicadas
La vista que usas, Explorar, le pide al motor sus cuatro mejores jugadas. El MultiPV de engine.rs busca la línea 1, luego busca otra vez sin esa jugada, y así, todo con un solo presupuesto de nodos:
/// MultiPV: the best `count` root moves, each with its own full-strength score and line.
/// Every depth searches line k with the first k-1 moves of that depth excluded, all under one
/// shared node budget. An interrupted depth is dropped unless no depth finished yet.
pub fn think_multi(&mut self, position: &Position, history_hashes: &[u64],
limits: EngineLimits<'_>, count: usize) -> MultiResult {
...
for depth in 1..=max_depth.min((MAX_PLY - 2) as u8) {
search.excluded.clear();
for index in 0..count {
let guess = lines.get(index).map(|line| line.score_cp);
let score = search.aspirate(position, depth, guess, root_in_check);
if search.aborted { break; }
let pv = search.line(0);
let Some(&mv) = pv.first() else { break; };
search.excluded.push(mv);
...
En el navegador ese presupuesto es de 100 k nodos para una respuesta rápida y 300 k para una más profunda. A 1.0-1.5 M nodos/s en WebAssembly, Explorar llega a profundidad 9-10 en unos 200 ms y se detiene justo en el presupuesto.
La frase no es una plantilla. Rust recorre la mejor línea y emite hechos: amenazas que encuentra con SEE, capturas, jaques, mate y el material a lo largo de la línea. Luego move-explanation.ts los convierte en español o inglés:
// crates/wasm-bridge/src/explanation.rs: facts, not sentences
pub struct ExplanationMoveDto {
pub mv: String,
pub piece: &'static str,
pub captured: Option<&'static str>,
pub promotion: Option<&'static str>,
pub castle: Option<&'static str>,
pub check: bool,
pub mate: bool,
pub threats: Vec<ExplanationSquareDto>,
pub saves_threatened: bool,
pub hangs: bool,
}

Lo que no funcionó
Muchas ideas perdieron su match y se quedaron fuera:
| Experimento | Resultado |
|---|---|
| Extensiones singulares | −8 ± 16 (800 partidas) |
| Poda por historia, countermove, un ajuste de LMR | −7, +2, −5 (600 partidas cada uno) |
| Evaluación re-etiquetada con evals de Stockfish sobre posiciones de Lichess | −158.6 ± 42.8 |
| Evaluación re-etiquetada con los scores de la propia búsqueda | −20.7 ± 17 |
| Caché de evaluación | +2% nodos/s, dentro del ruido |
Los dos re-etiquetados enseñaron más que nada: los dos mejoraron su propio error de entrenamiento y aun así perdieron partidas. Por eso ahora un cambio de evaluación primero tiene que bajar el error de predicción en un conjunto de datos independiente, antes de jugar una sola partida. Ese filtro offline habría rechazado gratis el ajuste de −158.6.
Borrar antes de agregar
El proyecto tenía más papeleo que código. En esas 36 horas el repositorio pasó de 1,355 archivos a 265: 157,518 líneas borradas y 13,540 agregadas. Dirigí agentes de IA para el trabajo. Un modelo planeaba y revisaba la evidencia; otros más baratos escribían candidatos en worktrees de git separados, compilaban los motores rivales y corrían las partidas. La misma regla para todos: ninguna afirmación sin un número y el comando que lo produjo.
Lee el código
Pruébalo en calichess.cc. El código, los benchmarks y un caso de estudio completo con cada commit están en GitHub, con licencia MIT.
Continuación: Las cuatro reconciliaciones, donde el motor nuevo se topó con el código viejo.
En el repo: crates/search/src/engine.rs · crates/search/src/explore.rs · crates/eval/src/tapered.rs · crates/wasm-bridge/src/explanation.rs · apps/web/src/move-explanation.ts · docs/case-study-2026-11.md