ChessMaster
Personal chess coaching platform that syncs games from Chess.com and Lichess, runs deep Stockfish analysis, detects systemic weaknesses across hundreds of games, and generates AI-powered coaching reports with spaced-repetition puzzle training.
Overview
ChessMaster — AI-Powered Personal Chess Coach
ChessMaster transforms raw game data into actionable coaching insights. Chess.com and Lichess show you blunders in individual games — ChessMaster detects the systemic patterns that keep repeating across your entire game history and generates a personalized training plan.
Architecture
Next.js 14 frontend communicates with a FastAPI (Python) backend over REST. The backend orchestrates multi-platform game sync, Stockfish engine analysis, cross-game pattern detection, and Claude-powered report generation.
The service layer contains 15+ specialized services — sync, analysis, patterns, time management, tilt detection, rating prediction, endgame classification, opponent scouting, puzzle generation with spaced repetition — all composable through shared filtering patterns.
SQLite with SQLAlchemy ORM handles storage. Smart indexing on playedat, openingeco, and timeclass keeps aggregate queries fast across thousands of games and hundreds of thousands of move analyses.
Multi-Platform Game Sync
Games are fetched from Chess.com (monthly archive endpoints) and Lichess (NDJSON streaming) in parallel with independent error handling — one platform failing doesn't block the other.
Deduplication uses platform + platformid as a unique constraint. Clock times are extracted from PGN [%clk H:M:S.F] comments for time management analysis. Lichess NDJSON streaming handles large game counts without memory issues.
Optimized Stockfish Analysis Pipeline
The key optimization: single-pass evaluation with carry-forward. Instead of evaluating both the position before and after each move (2 evals per move), the engine evaluates each position once — the evalafter for move M becomes evalbefore for move M+1. This cuts engine calls by 50%.
At depth 20, analysis runs 20 seconds per game. Moves are classified by centipawn loss: Great: CPL < 10 (best move found) Good: CPL 10-50 Inaccuracy: CPL 50-150 Mistake: CPL 150-300 Blunder: CPL > 300
A tactical motif detection algorithm uses ray-tracing to identify forks, pins, skewers, discovered attacks, and back-rank threats in blundered positions.
Cross-Game Pattern Engine
The pattern engine aggregates 12+ metrics across all analyzed games to surface systemic weaknesses rather than one-off errors:
1. Opening performance — win/loss/draw rate per ECO code with average CPL 2. Worst openings — minimum 3 games, sorted by win rate 3. Phase accuracy — separate CPL for opening, middlegame, and endgame (using material-based phase detection, not move count) 4. Phase blunder rate — percentage of blunders per game phase 5. Missed tactical motifs — forks, pins, skewers, discovered attacks, back-rank threats 6. Time trouble correlation — blunder rate in normal time vs. under 60 seconds 7. Color performance — white vs. black win rates and accuracy 8. Endgame conversion — percentage of won positions (eval >= 200cp) actually converted to wins 9. Blunder distribution — by move bucket (1-10, 11-20, 21-30, etc.) 10. Monthly trends — CPL improvement or degradation over time 11. Streak analysis — win/loss streaks and tilt patterns 12. Example positions — 10 worst blunders with FEN, CPL, and tactical classification
The same PatternEngine class handles filtering by platform and time class — composable filters reduce code duplication across 8+ analysis modes.
AI Coaching Report
Claude Sonnet generates personalized coaching reports from the pattern data, structured into 5 sections:
1. Player profile summary 2. Top 3-5 systemic weaknesses with actual FEN positions from the player's games 3. Opening repertoire advice based on win rates and CPL 4. Strengths to build on 5. 30-day training plan with specific exercises
The prompt includes the player's top 15 openings, missed tactical motifs, phase accuracy, time trouble stats, color performance, endgame conversion rates, and actual blunder positions — so advice is specific ("practice forks in K+P endgames when the opponent king is on the rim") rather than generic ("practice tactics").
Time Management Analytics
Time spent per move is calculated from consecutive clock readings. The system detects: Overthinking: opening moves with <10 CPL loss but >15 seconds spent Underthinking blunders: moves with >100 CPL loss but <5 seconds spent Time zone analysis: critical (0-30s), low (30-60s), normal (60-180s), comfortable (180+s) Time vs. accuracy curves: correlation between time spent and centipawn loss per move bucket
Tilt Detector
Session-based analysis (games within 4 hours grouped as one session): Win/loss/draw streak tracking with averages Blunder rate increase after 3+ consecutive losses Rating drop detection (sessions with >50-point drops) Auto-generated recommendations ("stop playing after a 3-loss streak")
Rating Predictor
Linear regression on rating vs. days played: Points-per-month projection Milestone estimates (when you'll hit 1000, 1200, 1500, etc.) Momentum comparison: last 30 games vs. prior 30 games Monthly weakness trends (CPL by phase over time)
Puzzle Training (SM-2 Spaced Repetition)
Every blunder and mistake automatically becomes a training puzzle. The SM-2 algorithm schedules reviews: Due puzzles first (nextreview <= now) Then never-attempted positions Then worst blunders (highest CPL) Ease factor adapts based on success rate: max(1.3, easefactor + (0.1 - (5 - rating) 0.08)) Filterable by game phase, tactical motif, platform, and time control
Opponent Scouting
Fetches the opponent's last 100 games, breaks down their opening repertoire by frequency, cross-references against the player's record in those specific openings, and generates preparation recommendations.
15+ services, 17 API routers, 109 backend tests, 19 frontend tests.
Learnings
1. Single-Pass Evaluation Halves Engine Costs — evaluating each position once and carrying forward the result (evalafter for move M = evalbefore for move M+1) eliminates redundant Stockfish calls. When processing thousands of games, this 50% reduction is the difference between hours and minutes.
2. Material-Based Phase Detection > Move Count — classifying game phase by remaining material (opening: fullmove <= 10 AND material >= 50pts; endgame: material <= 26 OR no queens AND material <= 30) handles Chess960, gambits, and unusual openings correctly. Move count fails for any non-standard game.
3. Cross-Game Pattern Detection Is the Real Value — individual game analysis (blunder classification) is commodity. The insight that changes behavior comes from aggregating across hundreds of games: "you blunder 3x more in endgames than middlegames" or "your fork detection drops 40% when you're in time trouble."
4. Composable Filters Prevent Service Explosion — the same PatternEngine class handles filtering by platform, time class, and game phase. Without composable filters, each combination would need its own service — 8+ analysis modes would become 24+ services.
5. SM-2 Spaced Repetition for Auto-Generated Puzzles — every blunder becomes a training puzzle with adaptive scheduling. The algorithm naturally surfaces the hardest problems more frequently while letting mastered positions fade, without manual curation.
6. Structured LLM Prompts with Real Game Data — generic chess advice is useless. Including actual FEN positions, CPL values, and opponent names in the Claude prompt forces specific, actionable recommendations instead of "practice more tactics."
7. NDJSON Streaming for Large Datasets — Lichess's NDJSON streaming API handles 1000+ games without buffering the entire response in memory. For any API that returns large collections, streaming prevents memory pressure.
8. Tactical Motif Detection via Ray-Tracing — detecting forks, pins, skewers, and discovered attacks by tracing attack lines from piece positions is computationally elegant. No need for ML — pure algorithmic detection on the board state.
9. Session-Based Tilt Detection — grouping games within 4-hour windows as sessions and tracking blunder rate increase after consecutive losses quantifies tilt. This turns a subjective feeling ("I'm playing badly") into actionable data ("your blunder rate increases 60% after 3 losses — stop playing").
10. Platform-Agnostic Data Normalization — unifying Chess.com and Lichess into a common schema at the ingestion layer means every downstream service (analysis, patterns, reports) works identically regardless of source. Add a third platform and nothing downstream changes.
Tags: Next.js, React, TypeScript, Tailwind CSS, FastAPI, Python, SQLite, SQLAlchemy, Stockfish, Claude AI, Recharts, chess.js, react-chessboard