Commit Graph
44 Commits
Author SHA1 Message Date
ai-chess 141fb9022e runner: per-game advisory lock so restarts never run a turn twice 2026-10-18 15:54:26 +03:00
ai-chess 3d8e928a9e deploy: Dockerfile/compose for serv, footer theme switch, small UI fixes 2026-10-18 15:49:43 +03:00
ai-chess 5be4bd1da4 rewrite: TS monorepo — pi SDK stateless agents, Postgres+pg-boss, SvelteKit themed UI; legacy moved to legacy/ 2026-10-18 15:32:39 +03:00
ai-chess e23a07f07b feat(menu): in-progress game card replaces mode picker
When /api/state shows a live game, the home page now hides the mode
cards + setup form and shows an 'active-card' instead: ROUND IN
PROGRESS header with pulsing crimson dot, a diagonal 'LIVE' stamp,
white/black seat panels (agent / model / persona), VS divider with
'who's thinking' status, a gold WATCH LIVE button that routes to
/ai-vs-ai (or /play if either side is human), and a crimson ABORT
CURRENT ROUND escape hatch. menu.js polls every 3s so the meta strip
(move count, current thinker) stays fresh and the picker comes back as
soon as the game ends.

CSS housekeeping:
- Global [hidden] { display: none !important } — without it CSS rules
  like .modes { display: grid } override the HTML hidden attribute and
  the picker bled through the active-card.
- New tokens reuse the existing palette: gold for the watch CTA + meta,
  crimson for the LIVE stamp + abort, dashed rule + bone tones for
  seat borders. No new fonts or colors introduced — matches the
  Major Mono Display / JetBrains Mono tournament-bulletin style.
2026-05-15 04:10:46 +03:00
ai-chess 2038ec95c9 fix(tmux): non-blocking subprocess + stable pane indexing
Two issues kept the deployed container from finishing the tmux rebuild:

1. asyncio's subprocess.communicate() blocked forever on `tmux new-session`
   and `tmux split-window` because the spawned pane child (pane-agent.sh
   → claude/codex) inherited the wrapper's stdout/stderr pipe fds and kept
   them open. _run() now uses DEVNULL for stdin/stdout/stderr by default
   (capture_stdout=True for the lone capture-pane call), and stderr is no
   longer collected — exit code is enough for upstream.

2. tmux re-indexes panes in layout-traversal order after every split, so
   the original 'split black off white horizontally, then split log off
   white vertically' sequence ended with indices 0=white, 1=log, 2=black —
   but the coordinator's pane_for hardcoded black=1, so prompts to codex
   landed on the log pane instead. Reorder: split log off the bottom of
   white FIRST (gives 0=white,1=log), THEN split black off the right of
   white (now indices 0=white,1=black,2=log, matching the hardcoded map).

Plus a small docker-compose change: ~/.codex needs to be writable so
codex can persist its history/session state — without rw the CLI exits
immediately with 'Read-only file system'.
2026-05-15 02:33:26 +03:00
ai-chess 51e63a8c7a feat(docker): bake claude+codex CLI + auth into image, non-root user
Dockerfile additions:
- Node 20 (NodeSource repo) + @anthropic-ai/claude-code@2.1.141 via npm.
- codex 0.130.0 musl tarball from github releases, dropped into
  /usr/local/bin/codex.
- jq + xz-utils + gnupg apt packages.
- Symlink /usr/games/stockfish → /usr/local/bin/stockfish (Debian
  puts it under /usr/games which isn't on the default PATH).
- Non-root user 'chess' (uid 1000) because claude-code refuses to run
  with --dangerously-skip-permissions as root; HOME=/home/chess.
- Pre-seeded /home/chess/.claude/settings.json + /home/chess/.claude.json:
  - hasCompletedOnboarding=true / lastOnboardingVersion='2.1.141'
  - projects['/app'].hasTrustDialogAccepted=true (mirrors the user's
    claude-trust-current-dir helper, but baked since cwd is always /app)
  - permissions.defaultMode='bypassPermissions'
  - skipDangerousModePermissionPrompt=true
  Without these, every fresh tmux pane hangs on the theme picker, then
  the workspace-trust dialog, never reaching its first MCP call.

docker-compose.yml:
- ANTHROPIC_BASE_URL + ANTHROPIC_AUTH_TOKEN env (loaded from /opt/chessai/.env).
- ./secrets/codex mounted read-only at /home/chess/.codex so the user's
  cliproxyapi-flavored codex config + auth.json travel with the deploy
  but stay outside the image layers.

deploy/codex/config.toml:
- Minimal codex config (cliproxyapi provider, gpt-5.5 xhigh fast,
  chess MCP url placeholder overridden per-side by pane-agent.sh).

scripts/pane-agent.sh:
- Use CLAUDE_BIN / CODEX_BIN from PATH (mac vs linux dynamics);
  the inline -c mcp_servers.chess.url override removes the need for
  'codex mcp add/remove' that polluted ~/.codex/config.toml on Mac runs.

Verified end-to-end on chess.danosito.com: AI-vs-AI game starts,
claude (white) inside the container makes the first move with a
toxic russian comment, MCP HTTP roundtrip works.
2026-05-15 02:05:18 +03:00
ai-chess c2d3a47d4b feat: docker container + deploy on chess.danosito.com
Container:
- Dockerfile: python:3.12-slim with stockfish + tmux apt; src copied
  before pip install -e so the editable wheel actually finds ai_chess.
  fetch-vendor.sh runs at build time so the image is self-contained.
- docker-compose.yml: two networks (default + caddy-network), alias
  'chessai' on caddy-network, AI_CHESS_HOST=0.0.0.0 env so uvicorn
  listens on all interfaces (Caddy reverse-proxies over the network),
  volumes for games/, logs/, config/ to persist across rebuilds.
- __main__.py reads AI_CHESS_HOST + AI_CHESS_PORT from env (falls back
  to 127.0.0.1:7833 for local dev).
- .dockerignore excludes .git, .venv, runtime dirs, screenshots.
- deploy/chess.danosito.com.caddy: site snippet, imports header_common,
  reverse_proxy chessai:7833.

Live game UX fixes that landed alongside the deploy:
- Snap viewPly to null on every move event so an accidental
  history-scrub no longer leaves the board locked; previously the only
  way out was a hard refresh.
- movable.events.after wired in chessground constructor (instead of
  top-level events.move) so user moves are submitted only when they
  pass chessground's own legality check.
- Hide stockfish entirely in human-vs-AI: no eval bar, no best-move
  arrow, no pv string. AI-vs-AI keeps the full spectator HUD.

Coordinator / tmux:
- New-game rebuilds the 'chess' tmux session from scratch so
  pane-agent.sh picks up the new bindings (different agent on a side
  / human side) instead of running with stale state.
- /api/dispatch-first now queues the dispatch in a background task and
  sleeps 12 s first to let claude/codex finish booting inside the
  panes — paste-buffer was landing on a still-booting bash before.
2026-05-15 01:31:55 +03:00
ai-chess ab38cda1bd feat(menu): unified home screen + ai-vs-ai/play split + human mode
Routes:
- GET /        → menu.html (new home/menu).
- GET /ai-vs-ai → old index.html (AI-vs-AI live game).
- GET /play    → same index.html; app.js detects the human side from
  bindings and enables chessground move input on that side only.
- GET /games   → unchanged.

Backend:
- coordinator: 'human' is now an allowed agent type alongside claude/codex.
  start_new_game accepts overrides[side].agent = 'human'. _send_first /
  _send_turn / watchdog skip human sides.
- POST /api/human-move: humans submit moves from the browser (UCI/SAN
  + optional comment); rejected if it's not their turn or side isn't human.
- /api/options now also returns 'all_agents' = AI agents + 'human' for the
  human-vs-AI configurator.
- pane-agent.sh: when binding agent is 'human', the pane just prints a
  note and sleeps — no claude/codex is launched for that side.

Frontend menu (new public/menu.{html,css,js}):
- 'underground tournament' aesthetic: Major Mono Display title, JetBrains
  Mono body (Google Fonts), warm gold (#c0a060) / crimson (#c04040)
  accents, subtle film-grain overlay.
- Three big mode cards: 01 AI×AI, 02 HUMAN×AI, 03 GAMES·STATS.
- Inline configurator below the cards: WHITE / VS / BLACK columns with
  agent / model / persona selects, persona description preview, swap +
  randomize tools, abort-current warning that links to /api/abort-game.
- Start button routes to /ai-vs-ai or /play depending on whether a human
  side was picked. Enter submits.
- HUD strip with tmux / stockfish / games-played counters.

app.js changes:
- Chessground constructed with viewOnly toggling; renderBoard rebuilds
  movable.color + dests = legal moves at the live FEN from chess.js for
  the human's turn only; board is read-only when scrubbing history,
  during the AI's turn, or in AI-vs-AI.
- humanSide() helper reads bindings; orientation auto-flips when the
  human plays black.
2026-05-15 01:10:47 +03:00
ai-chess 42f23c71cc fix: backend lifespan tears down tmux 'chess' session
Agents that outlive the backend desync with state.game (in-memory only)
— they keep calling MCP move on a server that has no idea what game is
being played. Simpler than persisting game state across restarts:
backend startup kills any leftover 'chess' tmux session, backend
shutdown kills the current one. start.sh will spawn fresh agents that
are aligned with the empty server state on each launch.
2026-05-15 00:59:59 +03:00
ai-chess 4a57854d1e fix: revive dead stockfish + backfill missing evals on startup
If the stockfish child dies mid-game (e.g. user pkill'd it, OS OOM
killed it), eval_bridge silently lost analyses. Now:

- StockfishEngine.is_alive() checks the process' returncode.
- _analyze_and_publish() retries once: on first failure, drops the dead
  handle and calls start() before the second attempt.
- On lifespan startup, _backfill_missing_evals() replays the current
  game's history via python-chess to derive each FEN and analyzes any
  position that's missing from state.eval_cache. This catches the gap
  that opens whenever stockfish dies under a running game.

Doesn't help across backend restarts (state.game is still in-memory
only) — for that we'd need a per-move snapshot of the active game.

55 → 61 tests still pass; engine smoke test now uses is_alive() too.
2026-05-15 00:56:34 +03:00
ai-chess 21dd169dfa feat(ui): thinking timer replaces pv text
Compact 'agent_name думает m:ss' indicator with a pulsing dot, tabular
nums, lives in the same slot the stockfish PV used to occupy. Resets on
new_game (white starts thinking), flips to the opponent on every move,
clears on game_over / when scrubbing history. Tickers tick 1 Hz.
Drops the now-unused PV stringification in applyEvalForFen.
2026-05-15 00:52:40 +03:00
ai-chess e7c04a3d76 feat(ui): abort-game button next to new-game
Shows only while a game is in progress (hidden otherwise), red-tinted
to distinguish from new-game. Hits POST /api/abort-game after a small
confirm prompt. Game-over event hides it again.
2026-05-15 00:46:53 +03:00
ai-chess 37bac9b0f6 feat: prompt presets, setup dialog, /games + leaderboard, one-game gate
Backend:
- prompts.py: 5 personality presets (уличный_гопник default, профессор,
  поэт, молчун, шут). Each provides voice + label + description.
  build_system_prompt accepts `preset` parameter; the MCP-tools section
  + must-call-move rule is shared common tail.
- coordinator: `start_new_game` now accepts `overrides` ({white: {agent,
  model, prompt}, black: {...}}) — missing fields filled randomly.
  MODEL_OPTIONS published per agent.
- AppState.prompts tracks the preset id per side; persisted into game's
  agents dict and PGN.
- AppState.eval_cache cleared on new_game (was per-life-of-process before).
- persistence.save_game now stores full history (with comments) and the
  per-position eval cache in the game JSON.
- ChessGame.abort() — manual game termination with result='*' and
  Termination='aborted'.
- New endpoints:
  • GET  /api/options   — agents, models per agent, prompt presets.
  • GET  /api/stats     — leaderboard aggregated from games/*.json:
        per (agent, model) and per persona, with score = wins + 0.5*draws.
  • POST /api/abort-game — force-end current game.
- POST /api/new-game now returns 409 when a game is in progress.
- GET  /api/games[/{id}[/pgn]] also 409 while in progress — gallery is
  hidden behind the one-game-at-a-time rule.

Frontend:
- New setup dialog: per-side agent / model / persona selects, swap +
  random shortcuts, persona description preview, abort button inline
  when current game blocks the start.
- 'games & stats' link in the board footer; greyed out while a game is
  active.
- /games page reworked: leaderboard (player × model + by persona),
  games table with persona labels, replay panel showing eval per ply
  with prev/next/first/last + arrow-key nav.
- chess.js loadPgn → load_pgn fix consolidated; replay prefers saved
  history (comments + side) over PGN parse when available.
2026-05-15 00:40:35 +03:00
ai-chess 0657cec846 fix(ui): normalize FEN key for eval cache
python-chess always sets the en-passant target after a 2-square pawn
move; chess.js omits it when no capture is legally possible. That
disagreement skipped evals for plies after every double pawn push
(1.e4, 1...c5, 3.d4, ...). Use position + side-to-move + castling as
the lookup key on both producer and consumer; halfmove/fullmove
counters and en-passant target are dropped from the key.
2026-05-15 00:20:40 +03:00
ai-chess 1d023014bd chore: ignore stray screenshots from local debugging 2026-05-15 00:17:43 +03:00
ai-chess 0eec263fd8 feat(ui): floating moves under board, chat full-height right, refined eval bar
Layout (after iterative feedback):
- Two columns: board+eval (left, square) | chat full-height (right).
- Moves row floats just under the board as a compact one-row strip with
  the controls (new game / settings) — replaces the old right sidebar.
- Board sized imperatively via fitBoard + ResizeObserver; eval bar height
  matches the board exactly (no overflow into neighbours).

Eval bar:
- 36px wide (was 28); text fits without pill background.
- System sans-serif, 10.5px / 700 weight, tabular-nums.
- Text positioned on whichever side is winning (bottom-white-half when
  white ahead → dark text; top-black-half when black ahead → light).
- Sign now correct: backend stores raw cp from side-to-move; frontend
  flips when FEN says "b" so the bar always reflects white POV.

Replay:
- evalByFen on the client gets backfilled from /api/state's new `evals`
  list (backend keeps state.eval_cache per game). Clicking past bubbles
  now restores the stockfish eval for that ply.
- renderBoard clears stockfish arrow when no eval is known yet for the
  shown FEN, so the arrow no longer 'lags' onto the next position.

Auto-focus:
- Latest played move is highlighted in both the chat bubble list and
  the moves strip when in live mode (viewPly === null).
- scrollIntoView keeps the active bubble/SAN visible after each move.
2026-05-15 00:17:33 +03:00
ai-chess 3a9ba2ea49 feat(ui): eval bar as two opposing bars (black on top, white on bottom)
The dark container now visually represents the black share; the
bottom-anchored white fill grows/shrinks with the eval. cp range ±800
maps to full bar. Mate is pinned at 100%/0% with #M text. The score
label flips to the top when black is ahead so it stays inside the
darker half.
2026-05-14 23:55:33 +03:00
ai-chess 6f4525d59f feat(ui): chat-bubbles layout, fix eval bar visibility, no terminals
UI rewrite per user feedback:
- Remove agent terminal panels entirely (tmux runs headlessly).
- Left column: chat with colored bubbles per move (white→light, black→
  dark, click to jump to ply, label shows agent+side+SAN).
- Right column: SAN move history (lichess style, click to jump).
- Center: board, untouched, but now constrained so it stops overflowing.
- Eval bar between chat and board, vertical with cp/mate text; the
  earlier visual issue was pure CSS (no explicit height) — bar fills
  full column height now.
- Keyboard nav: ←/→/space.
- Bottom log strip kept (compact).

Backend: TmuxTailer no longer started in lifespan (UI doesn't need
term_chunk events). Stockfish + eval_bridge now log explicit errors
to backend.log on startup failure.
2026-05-14 23:51:24 +03:00
ai-chess 4c5b306a9a fix(mcp,start): JSON-RPC notifications return 202; no tmux attach
- mcp_post: notifications (no `id` field) → HTTP 202 with empty body,
  per streamable-HTTP MCP transport spec. Fixes rmcp 'transport channel
  closed' on codex's notifications/initialized.
- start.sh: don't attach to tmux; print URL only. Backend + tmux session
  run in background. UI is the only viewing surface.
- scripts/stop.sh: convenience teardown.
2026-05-14 23:41:11 +03:00
ai-chess e48f01dcb5 chore(gitignore): ignore .claude/ and .playwright-mcp/ 2026-05-14 23:35:21 +03:00
ai-chess 33d6af764a fix: ulid API + tolerate missing tmux + dispatch-first endpoint
- coordinator: use `ulid.new().str` (ulid-py 1.x API), not `ULID()`
- coordinator._submit: swallow tmux errors so game logic continues
- app: split first-prompt dispatch into POST /api/dispatch-first
- start.sh: POST /api/dispatch-first ~12s after tmux create
- test_coordinator: isolate GAMES_DIR via tmp_path
2026-05-14 23:34:03 +03:00
ai-chess de850a9a05 feat(scripts): start.sh — install deps, run backend, open tmux 2026-05-14 23:29:16 +03:00
ai-chess 266ff07a93 feat(scripts): pane-agent.sh launches claude/codex per side 2026-05-14 23:29:02 +03:00
ai-chess d5d5756b18 feat(ui): /games page with replay 2026-05-14 23:28:22 +03:00
ai-chess 62d66c5ab6 feat(ui): chessground + WS + xterm.js + settings dialog 2026-05-14 23:27:54 +03:00
ai-chess f4af57c5e9 fix(ui): chess.js/chessground are ESM, load via app.js imports 2026-05-14 23:27:16 +03:00
ai-chess 67e077ae49 feat(ui): HTML skeleton + 3-column grid CSS 2026-05-14 23:25:50 +03:00
ai-chess c53c666739 feat(vendor): fetch chessground/chess.js/xterm.js to public/vendor 2026-05-14 23:25:18 +03:00
ai-chess 94de1cc1f9 feat(app): lifespan wires coordinator, tailer, stockfish + eval bridge 2026-05-14 23:23:07 +03:00
ai-chess 601fd64b16 feat(coordinator): start game, dispatch prompts, watchdog 2026-05-14 23:21:20 +03:00
ai-chess e20c26a055 feat(tmux_tailer): poll capture-pane and publish term_chunk events 2026-05-14 23:19:24 +03:00
ai-chess 83e2fb8765 feat(app): FastAPI REST + WS + MCP HTTP transport
Implements build_app() with REST endpoints (/api/state, /api/games,
/api/settings, /api/new-game, /api/agent-binding), WebSocket /ws for
realtime events, and custom JSON-RPC MCP transport at /mcp/{side}
supporting initialize, tools/list, and tools/call with proper
content-wrapping and isError flag. Static UI mount guarded by
PUBLIC_DIR existence check. All 5 e2e tests pass.
2026-05-14 23:18:57 +03:00
ai-chess 4f096953d7 feat(mcp): per-side tool builders (get_board, move, resign, draw) 2026-05-14 23:16:24 +03:00
ai-chess 62fbe2ce54 feat(stockfish): async UCI wrapper with analyze(fen, depth) 2026-05-14 23:14:32 +03:00
ai-chess 84c905bcb3 feat(state): AppState singleton (settings, bus, game, bindings) 2026-05-14 23:13:25 +03:00
ai-chess c6c75138e8 feat(events): minimal asyncio pub/sub bus 2026-05-14 23:13:13 +03:00
ai-chess 8eca3a16de feat(tmux): async TmuxSession wrapper (paste-buffer + capture-pane) 2026-05-14 23:12:48 +03:00
ai-chess 0e3fba05b0 feat(prompts): toxic RU system + first/turn/watchdog prompts 2026-05-14 23:11:25 +03:00
ai-chess 66f52f7b9c feat(persistence): save/list/load games (PGN + JSON) 2026-05-14 23:09:46 +03:00
ai-chess da7f8954b6 test(chess_game): resign, draw, allow_illegal, PGN export 2026-05-14 23:08:42 +03:00
ai-chess b16d8292a8 feat(chess_game): ChessGame core (try_move, history, checkmate) 2026-05-14 23:07:32 +03:00
ai-chess 83b68305be feat(settings): Settings model + load/save 2026-05-14 23:05:09 +03:00
ai-chess 5fcb620ac2 feat(sides): Side enum with opposite/from_str 2026-05-14 23:03:29 +03:00
ai-chess c02b43abbf chore: bootstrap project (pyproject, deps, structure) 2026-05-14 23:02:29 +03:00