diff --git a/GLOSSARY.md b/GLOSSARY.md new file mode 100644 index 0000000..dde4092 --- /dev/null +++ b/GLOSSARY.md @@ -0,0 +1,63 @@ +# Chesstrainer + +An endgame trainer: the user plays a stored endgame position against +tablebase-optimal defence and is graded on every move. + +## Core model + +**Endgame**: +A stored chess position (FEN) plus metadata — side to move, result, rating, +tags — that can be played as a puzzle. +_Avoid_: Position, puzzle + +**Puzzle**: +A playable challenge derived from an endgame: play the winning (or drawing) +side correctly against tablebase-optimal defence. +_Avoid_: Endgame (the stored record), exercise + +**Attempt**: +One playthrough of a puzzle by a user, ending solved or failed. +_Avoid_: Run, session, game + +## Play + +**Winning side**: +The side that can force a win from the position; the side the user plays in +win-type endgames. + +**Drawing side**: +In draw endgames, the side that must hold the draw; the side the user plays. +_Avoid_: Defender + +**Optimal move**: +The tablebase's best move for the side to move (sharpest win / hardest defence). + +**Winning move**: +A move that keeps the win (the opponent is still lost). Passes. +_Avoid_: Good move, accurate move + +**Losing move**: +A move that throws away the result (the position becomes drawn or lost). +Fails the puzzle. +_Avoid_: Blunder, mistake + +**Conversion**: +The decisive zeroing move — a promotion — that ends a conversion-type puzzle. + +**Cutoff**: +The terminal condition short of mate at which a puzzle counts as solved: +promotion (still winning) for conversion puzzles, mate otherwise. + +## Infrastructure + +**Tablebase**: +A database of precomputed optimal outcomes for every position with at most +seven pieces, queried via the lichess API and cached. + +**Cooldown**: +Rate-limit state entered after a 429 from the lichess tablebase API, during +which the trainer blocks play. + +**Cache sweep**: +The periodic halving of LFU cache frequencies (weekly) that lets rarely-used +entries age out. diff --git a/docs/adr/0001-tablebase-via-lichess-api.md b/docs/adr/0001-tablebase-via-lichess-api.md new file mode 100644 index 0000000..c50d58b --- /dev/null +++ b/docs/adr/0001-tablebase-via-lichess-api.md @@ -0,0 +1,8 @@ +# Tablebase via the lichess API instead of self-hosting + +The trainer grades moves against Syzygy tablebases, but self-hosting them is not +possible yet, so we query the lichess tablebase API (`tablebase.lichess.ovh`) +over HTTP and cache responses. This couples the core play loop to a remote +service with rate limits (mitigated by a cooldown and an LFU cache), but avoids +the multi-terabyte 7-piece dataset and hosting cost until local tablebases are +viable. diff --git a/docs/adr/0002-client-authoritative-move-validation.md b/docs/adr/0002-client-authoritative-move-validation.md new file mode 100644 index 0000000..55a0894 --- /dev/null +++ b/docs/adr/0002-client-authoritative-move-validation.md @@ -0,0 +1,8 @@ +# Client-authoritative move legality; server grades via tablebase + +Moves are validated by chess.js on the client (which also renders the board); +the server never applies moves and trusts the client's FEN, only grading the +move against the tablebase. We chose this over server-side validation with Chex +because Chex's move-legality logic is immature, and the app is single-user with +no auth, so client tampering is not a threat. Revisit once the Chex fork is +fixed. diff --git a/docs/plans/mvp.md b/docs/plans/mvp.md new file mode 100644 index 0000000..26ca0f5 --- /dev/null +++ b/docs/plans/mvp.md @@ -0,0 +1,85 @@ +# MVP: endgame trainer play loop + +Goal: a user picks an endgame and plays it against tablebase-optimal defence, +with every move graded against the lichess tablebase, end-to-end. + +## Definition of done + +- On `/endgames/:id/play`, the seeded endgames (KR v K, KPPP v KPP) load and are + playable. +- The user plays `endgame.color`; a legal move is graded (optimal / winning / + losing) against the tablebase; the opponent auto-replies with optimal defence. +- A **losing move** fails the puzzle immediately; **checkmate or a winning + promotion** solves it. +- Draw endgames are playable: the user holds the draw (solves on chess.js + `isDraw()`), or fails on a losing move. +- Tablebase unavailability (429/network) blocks the session with a clear message. +- `times_attempted` / `times_solved` increment on finish. + +## Decisions (see GLOSSARY.md, docs/adr/) + +- Strict trainer; losing move fails. Optimal vs. winning-but-slower are two + feedback tiers; only losing moves fail. +- Client (chess.js) is authoritative for legality; server grades via tablebase + (ADR-0002). Tablebase via lichess API (ADR-0001). +- Server holds attempt state in `assigns`; the client is the only engine. +- Grading rule: a move passes iff its category ∈ {loss, syzygy-loss, maybe-loss} + (opponent still lost); `cursed-win`/`blessed-loss` normalise to draw. +- Cutoff: solve on checkmate or a winning promotion. +- LFU cache with weekly halving sweep. + +## Work breakdown + +### 0. Prerequisite bug fixes +- `Chesstrainer.Endgames.Tablebase.new/1`: return `{:ok, tablebase}` on a cache + hit (fix the `{:cache, _}` return + `@spec`); unwrap the tuple in + `Chesstrainer.Game.game_from_fen/2`. +- `Chesstrainer.Endgames.Tablebase.Parser`: normalise the full category + vocabulary to `:win | :draw | :loss | :unknown` + (`win/syzygy-win/maybe-win → :win`; `draw/cursed-win/blessed-loss → :draw`; + `loss/syzygy-loss/maybe-loss → :loss`). +- `assets/js/hooks/chessBoard.js`: add `promotion` (and `prev_fen`) to the + `endgame_move_played` payload for unambiguous UCI matching. + +### 1. LFU cache rewrite +- `Chesstrainer.Cache`: store `{key, value, freq, last_access}`; on `put`, if + over `@max_size`, evict lowest frequency (LRU tie-break). +- `Chesstrainer.Cache.Evict`: replace timestamp-based eviction with frequency. +- Add a weekly sweep that halves every entry's frequency + (`Chesstrainer.Cache` `handle_info` timer, alongside the existing backup). +- `Chesstrainer.Cache.Persist`: the DETS tuple format changes; drop old backups + (tablebase data is re-fetchable). + +### 2. Server attempt state + grading (`EndgameLive.Play`) +- `assigns`: `fen` (grading reference), `status` (`:playing | :solved | :failed + | :blocked`), `move_list`, `last_grade`. +- `handle_event("endgame_move_played", %{from, to, san, prev_fen, fen_after, + promotion})`: + 1. grade the move against `prev_fen`'s tablebase (match UCI; pass/fail); + 2. on fail → `status: :failed`, reveal the missed optimal move(s); + 3. on pass → pick the opponent reply (`moves[0]`) from `fen_after`'s + tablebase, push it to the client, update `fen`; + 4. detect solve (checkmate / winning promotion) and draw (for draw endgames). +- Block: when `Tablebase.new` returns `{:cooldown, _}` or `{:error, _}`, + set `status: :blocked` and surface a message. + +### 3. Client hook (`assets/js/hooks/chessBoard.js`) +- Send `prev_fen` + `fen_after` + `promotion` on each move. +- Apply the opponent reply (from the server) via chess.js and animate it. +- Report draw/mate (chess.js `isDraw()` / `isCheckmate()`) for terminal + detection. + +### 4. Feedback UI (`EndgameLive.Play` + components) +- Two-tier grade display (green "Best" vs. amber "Winning, but suboptimal"), + losing-move failure with the missed move, solved/failed banner, reset/retry. + +### 5. Counters +- Increment `times_attempted` on start; `times_solved` on solve (via + `Chesstrainer.Endgames`). + +## Out of scope (deferred) + +- Auth / user accounts: #3 +- Glicko rating for users and endgames (puzzle ELO): #4 +- Draw via cursed-win 50-move defences; material-based cutoffs; per-endgame + `win_condition` field.