checkmate.blue Bot -- Specification #
Context #
checkmate.blue is a federated chess platform on the ATmosphere. The main app is a static SPA with no server. This bot is a separate project -- a persistent Node.js/TypeScript service that monitors the AT Protocol firehose, indexes games, manages the @checkmate.blue account, and plays chess against human opponents.
The bot solves several problems that a static SPA cannot:
- Game discovery -- the main app has no way to query all games globally without Constellation support. The bot indexes games from the firehose and exposes an API.
- Verified results -- anyone can write anything to their PDS. The bot replays PGNs through chess.js to verify results before indexing or posting.
- Engagement -- players can challenge the bot when no human opponent is available.
- Promotion -- the bot posts game results to the @checkmate.blue Bluesky feed, giving the platform visibility.
Architecture #
Jetstream (firehose)
|
v
+-------------------------------------+
| checkmate.blue Bot (Node.js) |
| |
| +-----------+ +----------------+ |
| | Firehose | | Chess Engine | |
| | Monitor | | (Stockfish) | |
| +-----+-----+ +-------+--------+ |
| | | |
| +-----v-----------------v--------+ |
| | Game Index (MySQL) | |
| +-----+--------------------------+ |
| | |
| +-----v-----+ +----------------+ |
| | Bluesky | | REST API | |
| | Poster | | (game list, | |
| | | | player stats) | |
| +------------+ +----------------+ |
+-------------------------------------+
| |
v v
@checkmate.blue checkmate.blue
Bluesky feed static SPA
Stack:
- Runtime: Node.js + TypeScript
- AT Protocol:
@atproto/api(same SDK as the main app) - Chess engine: Stockfish via native binary, run as child processes to avoid blocking the main event loop (one process per active game)
- Database: MySQL (handles concurrent writes from firehose, engine, and poster without contention)
- API: Hono HTTP server for the main app to query
1. Firehose Monitor #
The bot maintains a persistent Jetstream WebSocket connection watching for all blue.checkmate.game and blue.checkmate.challenge records across the entire network (no DID filter).
Connection #
wss://jetstream2.us-east.bsky.network/subscribe
?wantedCollections=blue.checkmate.game
&wantedCollections=blue.checkmate.challenge
&cursor={last_seen_time_us}
No wantedDids filter -- the bot watches everything.
Cursor persistence #
Checkpoint time_us periodically (every 100 events or every 5 seconds, whichever comes first). On restart, resume from the last checkpoint. A small number of events may be replayed after a crash -- the game index handles this via upsert on the AT URI, so reprocessing is idempotent.
Reconnection #
Same pattern as the main app: exponential backoff (1s to 30s), but no polling fallback needed since the bot doesn't need sub-second latency for indexing.
Event processing #
For each blue.checkmate.game event:
-
Create events: Index the new game record. Track which DID created it, the rkey, white/black DIDs, and status.
-
Update events: Update the indexed record. If
statuschanged tocompleted:- Fetch the PGN from the record
- Replay through chess.js to verify the result
- If verified, index as a completed game with the verified result
- If the result doesn't match the PGN (possible tampering), index with a
verified: falseflag - Post the result to Bluesky (see section 3)
-
Delete events: Set
deleted = trueon the indexed record. Do not remove from the database -- the record may be referenced by stats or posts. Deleted games are excluded from API responses. -
Challenge events: If a
blue.checkmate.challengerecord is created withopponentmatching any of the bot's DIDs, trigger the challenge acceptance flow (see section 4).
2. Game Index #
MySQL database with the following tables:
games #
| Column | Type | Description |
|---|---|---|
| id | INTEGER PK | Auto-increment |
| uri | TEXT UNIQUE | AT URI of the canonical record (no parentGameUri) |
| owner_did | TEXT | DID of the record owner |
| rkey | TEXT | Record key |
| white_did | TEXT | White player DID |
| black_did | TEXT | Black player DID |
| status | TEXT | waiting, active, completed, abandoned |
| result | TEXT | 1-0, 0-1, 1/2-1/2 |
| result_reason | TEXT | checkmate, resignation, etc. |
| move_count | INTEGER | Number of half-moves |
| verified | BOOLEAN | Whether the bot verified the result from PGN |
| pgn | TEXT | Full PGN (for verification and replay) |
| variant | TEXT | Game variant (standard, really-bad-chess, chess960) |
| starting_fen | TEXT | Starting FEN for variant games (extracted from PGN headers) |
| created_at | TEXT | ISO8601 |
| completed_at | TEXT | ISO8601 |
| last_activity | TEXT | ISO8601, updated on every event |
| posted | BOOLEAN | Whether the result was posted to Bluesky |
| deleted | BOOLEAN | Set to true when the record is deleted from the AT network |
Indexes: white_did, black_did, status, last_activity.
players #
| Column | Type | Description |
|---|---|---|
| did | TEXT PK | Player DID |
| handle | TEXT | Last known handle |
| last_game_at | TEXT | ISO8601 |
Player stats (wins, losses, draws, games played) are computed from the games table via queries rather than stored as denormalized columns. This avoids sync complexity when games are re-verified or deleted.
challenges #
| Column | Type | Description |
|---|---|---|
| id | INTEGER PK | Auto-increment |
| uri | TEXT UNIQUE | AT URI of the challenge record |
| owner_did | TEXT | DID of the challenger |
| rkey | TEXT | Record key |
| opponent_did | TEXT | DID of the challenged player |
| game_uri | TEXT | AT URI of the linked game |
| status | TEXT | open, accepted, declined, expired |
| created_at | TEXT | ISO8601 |
| deleted | BOOLEAN | Set to true when the record is deleted |
Indexes: opponent_did, status.
Deduplication #
Only index canonical records (no parentGameUri). When a record with parentGameUri appears, use it to confirm the pairing but don't create a duplicate entry.
API #
Simple REST endpoints for the main app to query:
GET /games/active-- active games, sorted by last activity (for homepage)GET /games/recent-- recently completed games with resultsGET /games/player/:did-- games for a specific playerGET /players/:did/stats-- win/loss/draw statsGET /challenges/open-- open challenges (for Phase 7 challenge board)
Responses are JSON. CORS enabled for checkmate.blue origin.
GET /health-- service health: database connectivity, Jetstream connection status, engine worker status, post queue depth, uptime
3. Bluesky Poster #
The bot authenticates as @checkmate.blue and posts game results to its Bluesky feed.
Authentication #
Use @atproto/api with app password (not OAuth -- the bot is a long-running service, not a browser app). Store credentials in config.json.
When to post #
Post when a game completes with a verified result. Only post if:
- The result is verified by replaying the PGN through chess.js
- The game had at least 5 moves (filter out abandoned/trivial games)
- The result hasn't already been posted (
posted = falsein the database)
Post format #
Win/loss:
{whiteHandle} vs {blackHandle}
{winnerHandle} wins by {reason} in {moveCount} moves
Play at checkmate.blue
Example:
@alice.bsky.social vs @bob.bsky.social
@alice.bsky.social wins by checkmate in 34 moves
Play at checkmate.blue
Draw:
@alice.bsky.social vs @bob.bsky.social
Draw by {reason} in {moveCount} moves
Play at checkmate.blue
Facets #
Include @mention facets for both players and a link facet for the game URL. Reuse the same buildFacets pattern from the main app (UTF-8 byte offset calculation).
Link embed #
Include an app.bsky.embed.external with:
uri: game URL (https://checkmate.blue/game/{ownerDid}/{rkey})title:{whiteHandle} vs {blackHandle}description:{result} by {reason} -- {moveCount} moves
Bot defeat posts #
When the bot loses a game, post a special message:
I just got beaten by @{opponentHandle}! {reason} in {moveCount} moves.
Think you can do the same? Challenge me at checkmate.blue
Rate limiting #
- Max one post per 30 seconds to avoid spamming followers
- Queue posts and drain at a steady rate
- If the queue grows too large (>50), start dropping low-move-count games
4. Chess Engine (Play Against the Bot) #
Players can challenge the bot to a game. The bot accepts challenges and plays using Stockfish.
Challenge acceptance #
When the firehose monitor detects a blue.checkmate.challenge with opponent matching any of the bot's three DIDs:
- Fetch the challenge record
- If status is
open, accept:- Fetch the linked game record (via
gameUri) - Create the bot's child game record with
parentGameUri - The game is now active
- Fetch the linked game record (via
When a blue.checkmate.game create event appears with the bot listed as a player and no linked challenge, treat it as a direct game invitation:
- Fetch the game record
- If status is
waitingand the bot is listed as white or black - Create the bot's child record with
parentGameUri
Difficulty via handle #
Variable number of ATmosphere accounts, one per difficulty level, configured in the engines array. Players challenge the one they want -- no protocol changes, no UI changes, the difficulty is obvious from the handle.
A single bot process manages all engine accounts. Each account authenticates with its own app password. The bot determines difficulty from which DID received the challenge. Anyone forking the project can define their own difficulty levels.
Move flow #
- Bot's Jetstream connection receives opponent's move (game record update)
- Load PGN into chess.js, verify it's the bot's turn
- Pass the FEN to Stockfish (running as a child process) with the configured depth limit
- Stockfish returns the best move
- Apply the move to chess.js, generate updated PGN
- Write to the bot's game record via
putRecord - Check if the game is over (checkmate, stalemate, draw)
- If over, write
status: completedwith the result
Game completion #
Each player writes completion to their own record (matching the main app's pattern). The bot writes status: completed to its record when:
- The bot's move results in checkmate, stalemate, or a draw condition
- The bot detects (via opponent's record update) that it has been checkmated or stalemated
- The opponent resigns (verified: the record owner claims they lost)
- A draw is agreed (both records show
1/2-1/2withagreement) - Auto-resign after 48 hours of inactivity
The bot does not resign mid-game based on evaluation. It always plays to the end.
Threefold repetition avoidance #
After applying Stockfish's suggested move, the bot checks chess.isThreefoldRepetition(). If the move would trigger a draw by repetition, the bot undoes it and tries other legal moves (shuffled randomly) until it finds one that doesn't repeat. If all moves cause repetition, the original Stockfish move is played.
Transient error retry #
PDS writes in playMove retry up to 2 times on transient network errors (socket resets, timeouts, fetch failures) with increasing backoff. The bot's lastKnownPly is only updated after a successful write, so a failed write doesn't block future attempts.
Game reconstruction on startup #
On startup, the bot queries the database for active games involving any engine DID. For each, it fetches the canonical record and finds the bot's child record via listRecords. If it's the bot's turn, it plays a move immediately. This ensures the bot recovers from restarts mid-game.
Stockfish as child processes #
Stockfish evaluations run as child processes, one per active game. This keeps the main event loop free for Jetstream events, API requests, and AT Protocol writes. If a Stockfish process crashes, it is respawned and the position is re-evaluated from the current PGN.
Artificial delay #
Add a realistic delay before responding:
- Easy: 2-5 seconds (random)
- Medium: 3-8 seconds
- Hard: 5-15 seconds
This prevents the bot from feeling like an instant machine and avoids rapid PDS writes.
Concurrent games #
The bot should handle multiple games simultaneously. Each game is independent state tracked by DID + rkey. Use a Map or the database to track active bot games.
Game limits #
- Max concurrent games is configurable per difficulty level (default 10 each). Reject new challenges if at capacity.
- Per-user limit: A user may have at most one active game against each bot account at a time. Reject new challenges from a user who already has an in-progress game with that bot.
- Auto-resign if a game has been inactive for 48 hours. These are not posted to the Bluesky feed.
5. Game Integrity #
The bot verifies all game results it indexes, not just its own games.
Verification process #
For every game that transitions to completed:
- Load the PGN from the record
- Replay through chess.js
- Call
gameResult(chess)to get the board-derived result - Compare with the claimed
resultandresultReason
Checkmate / stalemate / draw conditions: The PGN must produce the claimed result when replayed. If it doesn't match, mark verified: false.
Resignation: Can't be verified from PGN (the game isn't over on the board). Accept resignation claims if: the claimed loser is the record owner (you can only resign yourself, you can't claim your opponent resigned by writing to your own record).
Draw by agreement: Accept if both records show result: 1/2-1/2 and resultReason: agreement.
What verified means #
The verified field in the database indicates whether the bot independently confirmed the result. The API can expose this so the main app can show a verification badge. Unverified results are still indexed and displayed but flagged.
6. Handle Resolution #
The bot needs to resolve DIDs to handles for Bluesky posts (mentions, display names). Uses the same Microcosm Slingshot service as the main app (com.bad-example.identity.resolveMiniDoc).
Caching #
In-memory cache with TTL (handles can change). Since the bot is a long-running process unlike the browser SPA, stale handles are a real concern. Cache for 1 hour, refresh on miss. Fall back to the raw DID if resolution fails.
The API returns raw DIDs. The main app resolves handles client-side as it does today.
7. Configuration #
All configuration lives in a single config.json file (gitignored). A config.example.json is committed with the structure and sane defaults but no secrets. The engine array is variable-length -- anyone forking the project can define their own difficulty levels.
{
"bot": {
"handle": "checkmate.blue",
"did": "did:plc:...",
"appPassword": "..."
},
"engines": [
{ "id": "easy", "handle": "easy.checkmate.blue", "did": "did:plc:...", "appPassword": "...", "depth": 3, "delayRange": [2, 5], "maxConcurrentGames": 10 },
{ "id": "medium", "handle": "medium.checkmate.blue", "did": "did:plc:...", "appPassword": "...", "depth": 8, "delayRange": [3, 8], "maxConcurrentGames": 10 },
{ "id": "hard", "handle": "hard.checkmate.blue", "did": "did:plc:...", "appPassword": "...", "depth": 15, "delayRange": [5, 15], "maxConcurrentGames": 10 }
],
"mysql": {
"host": "localhost",
"port": 3306,
"user": "checkmate",
"password": "...",
"database": "checkmate_bot"
},
"jetstream": {
"url": "wss://jetstream2.us-east.bsky.network/subscribe"
},
"stockfish": {
"path": "/usr/bin/stockfish"
},
"api": {
"port": 3000
},
"posting": {
"minMoves": 5,
"rateLimitMs": 30000,
"perPairCooldownHours": 24,
"perPlayerMaxPostsPerDay": 5,
"dryRun": false
},
"games": {
"autoResignHours": 48
},
"logging": {
"level": "info",
"file": "./data/bot.log"
}
}
Dev mode #
Set posting.dryRun: true to log posts instead of publishing them. Use test AT Protocol accounts in the bot and engines fields. Point mysql.database at a separate dev database.
8. Logging #
Structured JSON logging to both stdout and a rotating log file. Every significant action gets a log entry with context.
Log levels #
- debug -- Jetstream events received, PGN parsing details, Stockfish evaluation output
- info -- game indexed, game verified, challenge accepted, move played, post published, bot started/stopped
- warn -- verification failed, Jetstream reconnect, rate limit hit, challenge rejected (at capacity)
- error -- PDS write failed, Stockfish crashed, database error, authentication failure
Context fields #
Every log entry includes:
timestamp(ISO8601)levelcomponent(firehose, engine, poster, verifier, api, database)message- Event-specific fields:
gameUri,did,rkey,result,moveCount,difficulty,error
Example entries #
{"ts":"2026-04-10T...","level":"info","component":"firehose","msg":"game completed","gameUri":"at://did:plc:.../blue.checkmate.game/abc","result":"1-0","reason":"checkmate","moveCount":34}
{"ts":"2026-04-10T...","level":"info","component":"engine","msg":"move played","difficulty":"medium","gameRkey":"xyz","move":"e2e4","thinkTimeMs":4200}
{"ts":"2026-04-10T...","level":"warn","component":"verifier","msg":"result mismatch","gameUri":"at://...","claimed":"1-0","verified":null}
{"ts":"2026-04-10T...","level":"error","component":"poster","msg":"post failed","error":"401 Unauthorized"}
9. Deployment #
The bot runs as a persistent Node.js process. Options:
- Systemd service on a VPS (Linode, etc.)
- Docker container with MySQL access
- Fly.io / Railway with managed MySQL
Requirements:
- MySQL access (local or remote)
- Outbound WebSocket (for Jetstream)
- Outbound HTTPS (for PDS reads/writes and Bluesky posts)
- Inbound HTTP (for the REST API, if exposed)
The REST API can be behind a reverse proxy (Caddy, nginx) or exposed directly if on a platform like Fly.io.
Graceful shutdown #
On SIGTERM/SIGINT:
- Stop accepting new Jetstream events
- Wait for in-progress Stockfish evaluations to complete (with a timeout)
- Flush the post queue (best-effort)
- Persist the Jetstream cursor
- Close database connections
- Exit
Monitoring #
Expose basic operational metrics via the /health endpoint and structured logging:
- Firehose: events processed/minute, current lag (now vs. last event
time_us), connection uptime - Engine: active games per difficulty, Stockfish worker count, average think time
- Poster: queue depth, posts published/hour, post failures
- API: request count, latency percentiles
- Database: connection pool status, query latency
Project structure #
atchess-bot/
├── src/
│ ├── index.ts # Entry point, wire everything together
│ ├── config.ts # Load + validate config.json
│ ├── logger.ts # Structured JSON logging (stdout + file)
│ ├── firehose.ts # Jetstream connection + event routing
│ ├── database.ts # MySQL schema, queries, migrations
│ ├── atproto.ts # Record CRUD (adapted from main app)
│ ├── poster.ts # Bluesky post composition + rate limiting
│ ├── engine.ts # Stockfish wrapper (child process management)
│ ├── bot-player.ts # Challenge acceptance + move handling
│ ├── verifier.ts # PGN replay + result verification
│ ├── api.ts # Hono REST API routes + health endpoint
│ ├── identity.ts # Handle resolution via Slingshot + caching
│ └── types.ts # Shared types + utilities
├── tests/
│ └── verifier.test.ts # Verification tests (vitest)
├── data/
│ └── bot.log # Log file (gitignored)
├── config.json # Configuration (gitignored)
├── config.example.json # Example config (committed)
├── Dockerfile # Production image (node + stockfish)
├── Dockerfile.dev # Development image (tsx watch)
├── docker-compose.yml # Development compose (mounts source)
├── package.json
└── tsconfig.json
Verification plan #
- Firehose monitor: Create a test game on checkmate.blue, verify the bot detects the create and update events, indexes the game correctly.
- Result verification: Complete a game (checkmate), verify the bot replays the PGN and marks it as verified. Then manually write a bogus result to a PDS record, verify the bot marks it unverified.
- Bluesky posting: Complete a verified game with >5 moves, verify a post appears on the @checkmate.blue feed with correct mentions and link.
- Challenge acceptance: Create a challenge targeting the bot's DID, verify it accepts and creates a child record.
- Chess engine: Play a game against the bot at each difficulty level, verify it responds with legal moves at appropriate delays.
- Bot defeat post: Beat the bot, verify it posts the special defeat message.
- API: Query each endpoint, verify correct JSON responses with expected data.
- Cursor persistence: Kill and restart the bot, verify it resumes from the last cursor without reprocessing old events.
- Concurrent games: Start multiple games against the bot, verify it tracks and responds to each independently.
Open questions #
Items flagged during spec review that need further discussion before implementation.
OQ-1: Post queue persistence RESOLVED #
On startup, mark all existing posted = false records as posted = true without posting. The bot only posts games that complete while it is running. If the bot was down, those posts are simply missed -- no backfill, no burst.
Post anti-spam thresholds #
Auto-posting must be restricted beyond the basic rate limit. Handles appear in every post, so bad actors could use the bot as a vehicle for spam (e.g., buy.viagra.pills vs at.viagra.com playing repeatedly). Thresholds:
- Per-pair cooldown: Max one post per unique player pair per 24 hours. Additional games between the same two players are indexed but not posted.
- Per-player cooldown: Max N posts featuring the same player per 24 hours (default 5). Prevents one active player from dominating the feed.
- Minimum account age: Do not post games involving accounts created within the last 24 hours. Reduces drive-by spam.
- Bot games exempt from per-pair cooldown -- bot games are always postable (subject to the normal rate limit) since the bot account is trusted.
These thresholds are configurable via config.json. Games that are suppressed are still indexed with posted = true (they were intentionally skipped, not missed).
OQ-2: PDS write conflicts (optimistic concurrency) RESOLVED #
Each player only writes to their own record, so there's no cross-player write race. The risk is the bot writing to its own record twice in parallel (e.g., duplicate Jetstream events for the same game). Two-layer defense:
- Per-game event queue: Process events for a given game serially. If multiple events arrive while a Stockfish evaluation is in progress, queue them and process one at a time.
swapRecord: EveryputRecordcall includes the last-known CID (matching the main app's pattern). If a write fails with a conflict, re-fetch the record, recompute, and retry once. A second failure indicates a bug -- log an error.
Additionally, the bot must validate incoming PGNs defensively:
- Reject illegal moves (replay through chess.js)
- Reject PGNs shorter than the last known state (prevents rewinding)
- Verify it's the bot's turn before computing a move
OQ-3: Handle resolution caching strategy RESOLVED #
The REST API returns raw DIDs only. The main app continues resolving handles client-side as it does today. The bot still resolves handles internally for Bluesky post composition (using Slingshot with a 1-hour in-memory cache), but this is not exposed through the API.
OQ-4: move_count units RESOLVED #
move_count unitsmove_countin the database stores half-moves (ply) -- this is whatchess.history().lengthreturns natively.- Post templates display full moves:
Math.ceil(moveCount / 2). Matches how chess players talk ("checkmate in 17 moves"). POST_MIN_MOVESrefers to full moves and defaults to 5 (i.e., 10 ply). A game must reach at least move 5 to be posted.