Compare commits

..
Author SHA1 Message Date
KoalaTrapLord 75b2504470 Add Phase 8 — Multiplayer (Human vs Human + AI) 2026-03-14 00:33:24 -04:00
KoalaTrapLord d817c97a4f Add GUI framework decision and two-phase frontend plan 2026-03-14 00:30:36 -04:00
KoalaTrapLord b947c707e2 Update LLM model to GPT-OSS 20B (Q4_K_M) 2026-03-14 00:23:12 -04:00
KoalaTrapLord c4175cb03a Add Commander GUI + LLM Opponents roadmap 2026-03-14 00:20:41 -04:00
KoalaTrapLord 1f03a359e6 feat(brain): pipe GameResult winner_seat + per-player life totals into flush_log() for RL training 2026-03-14 00:13:50 -04:00
KoalaTrapLord b4734a38eb fix(ui): merge duplicate .stat-card declarations in premium layer 2026-03-14 00:10:14 -04:00
KoalaTrapLord 7fae938f25 feat(rules): add load_weights() / save_weights() for simulation-driven weight learning 2026-03-13 23:58:59 -04:00
KoalaTrapLord 5bff3c4ca0 feat(ui): add premium upgrade layer to global.css 2026-03-13 23:51:47 -04:00
KoalaTrapLord cbcb601192 feat(tests): add pytest infrastructure and test coverage for models, rules, and sim engine (closes #28) 2026-03-13 22:30:40 -04:00
KoalaTrapLord 83feca32cd chore: add requirements.txt for pip install compatibility (closes #29) 2026-03-13 20:53:31 -04:00
KoalaTrapLord 39637855e0 fix(deps): declare all runtime dependencies in pyproject.toml (closes #29) 2026-03-13 20:53:18 -04:00
KoalaTrapLord 19b74d152c feat(ui): 4-player deck slots, seat colors, chart support (Task 2C) 2026-03-13 19:08:53 -04:00
KoalaTrapLord cf0e8b50fe feat(api): accept 2-4 decks in batch start, dynamic Java CLI args (Task 2C) 2026-03-13 18:59:25 -04:00
KoalaTrapLord 79b3b9e013 feat(api): accept 2-4 decks in batch start, dynamic Java CLI args (Task 2C) 2026-03-13 18:58:33 -04:00
KoalaTrapLord 416b3410f3 feat(api): accept 2-4 decks in batch start, dynamic Java CLI args (Task 2C) 2026-03-13 18:56:58 -04:00
KoalaTrapLord dfb9b31995 feat(ui): 4-player deck grid, seat colors, responsive breakpoints (Task 2C) 2026-03-13 18:55:17 -04:00
KoalaTrapLord 74bd451d5f feat: N-player deepseek engine (Task 2A — Issue #27)
- run_n() accepts 2-4 decks; run() wraps for backward compat
- _select_attack_target() heuristic for multiplayer combat targeting
- N-player elimination order tracking with finish positions
- Removal scans all opponents for scariest creature
- ML snapshot captures all N players
- Log entries use per-seat boards dict with legacy boardA/boardB for 2-player
2026-03-13 16:58:23 -04:00
KoalaTrapLord 0606bd3c4a feat: N-player engine turn loop (Task 2A — Issue #27)
- engine.py: new run_n() method accepts 2-4 decks; run() wraps for backward compat
- _select_attack_target() heuristic: attack weakest non-eliminated opponent
- N-player elimination order tracking with correct finish positions
- Removal spells scan all opponents for best target
- Game logs use per-seat boards dict with boardA/boardB legacy keys for 2-player
- Tested: 2/3/4-player, elimination order, attack targeting
2026-03-13 16:54:55 -04:00
KoalaTrapLord c1b3ae4eb3 fix: preserve is_commander flag when loading .dck files
Two places lost the commander flag:

1. _load_deck_cards_by_name() .dck fallback — used a flat in_cards
   boolean for [Main], [Deck], and [Commander] sections so it couldn't
   tell which section a card came from. Now tracks current_section and
   sets is_commander=1 for cards in [Commander].

2. parse_dck_file() — stored section='Commander' in the card dict but
   the frontend filters on c.is_commander, not c.section. Now includes
   is_commander: 1/0 alongside the existing section field.
2026-03-13 20:20:18 +00:00
KoalaTrapLord ef57474b67 refactor: adopt Python logging module with named loggers
Replace all print() calls with structured logging using the Python
logging module. This provides:

- Named loggers per subsystem: commander_ai_lab.api, .batch, .sim,
  .coach, .deckgen, .collection, .scanner, .ml, .cache, .pplx
- Dual output: console (StreamHandler) + rotating file (RotatingFileHandler)
  at logs/commander-ai-lab.log (25 MB x 5 backups = 125 MB max)
- Configurable via env vars: CAL_LOG_DIR, CAL_LOG_MAX_MB, CAL_LOG_BACKUP_COUNT
- --verbose / -v flag for DEBUG-level output
- overnight-run.py: separate rotating log at logs/overnight-run.log (10 MB x 5)
- Sub-module loggers in ml/, scanner/, deck_sources/, src/ all propagate
  to the root commander_ai_lab logger
- Stripped redundant [TAG] prefixes from messages (logger name carries context)
- Format: '2026-03-13 14:00:00 INFO  [commander_ai_lab.batch] message'

Files changed: lab_api.py, overnight-run.py, and 11 sub-module .py files
176 total print() calls converted (101 in lab_api.py, 76 in sub-modules)
2026-03-13 18:09:52 +00:00
KoalaTrapLord f3c44559d3 feat: Scryfall response caching with SQLite
- _ScryfallCache class: thread-safe SQLite cache for raw Scryfall JSON
  responses, keyed by name|set_code|collector_number, 7-day TTL
- _fetch_scryfall_api() wrapper: checks cache first, live HTTP on miss,
  caches successful responses + resolves spelling normalization
- Refactored _enrich_from_scryfall() to use cache — all 3 callers
  (collection import, deck card add, re-enrich) benefit automatically
- Rate limiting only on actual HTTP calls, not cache hits
- REST endpoints: GET/DELETE /api/cache/scryfall, POST .../evict
- Fixed VACUUM-inside-transaction bug in clear()
- Configurable TTL via SCRYFALL_CACHE_TTL env var
2026-03-13 15:25:30 +00:00
KoalaTrapLord b35768d03b Phase 2: score_card() num_opponents scaling + enrich_card() determinism fix (#32)
- score_card() now accepts num_opponents: int parameter (default 1)
- Keywords/effects scale with pod size via _MULTI_OPP_SCALING dict
- Multiplayer-specific oracle patterns: 'each opponent', pillowfort, 'each player'
- Board wipe and counter spell bonuses scale with opponent count
- Expanded keyword coverage (double strike, first strike, hexproof, indestructible,
  menace, vigilance, ward, infect, annihilator, cascade, defender)
- Triggered ability bonuses: ETB, attack triggers, dies triggers
- enrich_card() replaced random.randint() with hashlib.md5 name-based hash
  for deterministic CMC estimation across games (#32)
- Backward compatible: existing score_card(card, weights) calls unaffected
2026-03-12 20:22:44 +00:00
KoalaTrapLord d0a1c10372 Fix simulator button stuck on Running — to_dict() backward compat
GameResult.to_dict() now returns both legacy keys (winner, playerA, playerB)
that the UI expects AND new N-player keys (winningSeat, playerResults) for
the Java BatchResult schema.
2026-03-12 18:25:22 +00:00
KoalaTrapLord 91d1e9449a Phase 1: N-player data model refactoring
- New PlayerResult dataclass with seat_index, name, life, eliminated, finish_position, stats
- Refactored GameResult to use players: list[PlayerResult] + winner_seat (no hardcoded 2-player fields)
- Backward-compat @property accessors (player_a_stats, player_b_stats, winner, etc.) for existing consumers
- SimState.battlefields is now per-player (list-of-lists) with helper methods:
  get_battlefield(), add_to_battlefield(), remove_from_battlefield(), all_battlefield_cards()
- Updated engine.py, deepseek_engine.py, deepseek_brain.py to use per-player battlefields
- GameResult.to_dict() matches Java BatchResult schema (playerResults array)
- lab_api.py and experiments.py unchanged — backward-compat properties handle all existing access patterns
2026-03-12 18:10:57 +00:00
KoalaTrapLord 1b2707014b Fix duplicate deck cards from collection JOIN fan-out
When collection_entries has multiple rows with the same scryfall_id
(e.g. Counterspell imported from two different sets), the LEFT JOIN
on deck_cards produced duplicate rows — making it appear like 2 copies
were added or removed.

Fixed all 6 deck_cards-to-collection_entries JOINs to use a
GROUP BY scryfall_id subquery, guaranteeing 1:1 cardinality.
2026-03-12 17:51:20 +00:00
KoalaTrapLord 91279d1d67 Deck generator: deterministic basic land fill + frontend count display
- Added _fill_basic_lands() post-processing for V1 and V3 generators
- Strips LLM-provided basics, then distributes evenly across commander colors
- Always hits exactly 100 cards regardless of LLM output
- Frontend group counts now sum card.count instead of entry count
- Cards with count > 1 show '5x Forest' style prefix
- Colorless commanders get Wastes
2026-03-12 17:44:30 +00:00
KoalaTrapLord 3ec0b73503 Collection: sort bar UI, fix set_code sort field, column header hover styles 2026-03-12 17:08:42 +00:00
KoalaTrapLord f9114b6118 Coach: build DeckReport from DB when no simulation report exists
Previously the coach required running simulations first to generate a
deck-reports/*.json file. Now if no simulation report is found, the
endpoint builds a lightweight DeckReport on the fly from the deck_cards
table — pulling card names, types, CMC, and color identity directly from
the DB. The LLM can still analyze composition and give advice, just
without simulation-derived performance metrics (impactScore, etc.).

Also removes the '[no report]' tag from the dropdown since all decks
can now be coached.
2026-03-12 16:36:19 +00:00
KoalaTrapLord 1e3669af42 Fix coach deck dropdown: wrong column name d.commander → d.commander_name
The decks table has 'commander_name' not 'commander'. The SQL query
was throwing OperationalError which the frontend silently caught,
resulting in an empty dropdown.
2026-03-12 14:55:46 +00:00
KoalaTrapLord c41ca8f09b Fix deck gen truncation: increase max_tokens to 16384, add JSON repair
Root cause: Perplexity deck generation hit the 8192 max_tokens limit,
truncating the JSON response mid-string at card ~70-80. json.loads()
fails with 'Unterminated string' and the fallback also couldn't recover.

Fixes:
- Bump DECK_GEN_MAX_TOKENS from 8192 to 16384 (primary fix)
- Add _repair_truncated_json() to PerplexityClient — if token limit is
  still hit, salvages all complete card objects from the truncated JSON
  instead of returning a 422 error
- Add OUTPUT EFFICIENCY instructions to system prompt to reduce per-card
  verbosity (shorter reasons, fewer synergy_with entries)
- Add 'truncated' flag to response so UI can warn if deck is incomplete
- Log warning when recovered deck has <90 cards
2026-03-12 14:47:41 +00:00
KoalaTrapLord 4189289945 Fix coach deck dropdown: handle bare array response from /api/coach/decks
Backend returns [{deck_id, deck_name, commander, has_report, ...}] directly,
not {decks: [...]}.  Frontend was reading data.decks which was always undefined.
Now properly unwraps the array, shows deck name + commander, slugifies name
for coach session deck_id, and marks decks without reports.
2026-03-12 14:45:13 +00:00
KoalaTrapLord f47b5182d2 v28: Coach chat UI, analytics/trends tabs, export-to-sim, precon refresh
Features:
- Complete coach page rewrite: chat-based UI with SSE streaming, multi-turn conversations
- Coach cards-like suggestions and apply-recommendation integration
- Coach session management (save/load/delete)
- Export-to-sim button in deckbuilder
- Analytics tab with game stats visualization
- Trends tab with meta trend charts
- Precon refresh button in AI Lab
- Updated installer (v28)
2026-03-12 06:40:41 +00:00
KoalaTrapLord 5f606fee22 v27.5: Revert to legacy HTML/JS/CSS UI as primary interface
- lab_api.py: Flip serving priority — ui/ folder (legacy) served first, React dist/ only as fallback
- Legacy UI has full features: card images, mana costs, type grouping, collection filters, EDHREC recs, ratio dashboard, commander portraits, 3-column deck builder
- React SPA was causing blank pages and missing functionality
- Installer no longer builds or bundles React dist/
- All 7 pages work: Batch Sim, Collection, Deck Builder, Auto Gen, Simulator, Coach, Training
2026-03-12 04:32:33 +00:00
KoalaTrapLord f5dae81193 v27.4: Fix blank Collection/Decks pages — API response unwrapping
- collection.ts: unwrap {items} -> cards, map camelCase params (pageSize, sortField, etc)
- decks.ts: unwrap {decks} from listDecks, {cards} from getDeckCards, normalize field names (commander_name->commander, total_cards->card_count, role_tag->category)
- decks.ts: transform getDeckAnalysis from backend shape (counts_by_type, color_pips) to frontend shape (card_count, land_count, type_distribution, etc)
- types: SetInfo.card_count now optional (backend doesn't provide it)
- Installer now bundles pre-built React dist/ as fallback
2026-03-12 03:47:20 +00:00
KoalaTrapLord 36b3c8c55b v27.3: Fix blank page — response shape mismatches
1. /api/lab/status: StatusResponse now includes run_id, games_completed,
   total_games, current_decks aliases so the React SPA gets the field
   names it expects.

2. /api/lab/decks returns {decks: [...]}, /api/lab/history returns
   {results: [...]}, /api/lab/precons returns {precons: [...]} — but
   the frontend expected bare arrays. Updated lab.ts API client to
   unwrap these wrapper objects automatically.
2026-03-12 03:36:36 +00:00
KoalaTrapLord a098524b98 v27.2: Fix /api/lab/status 422 crash — make batchId optional
GET /api/lab/status and /api/lab/result required batchId as a
mandatory query param, but the React SPA calls them with no param
on page load. FastAPI returned 422 Unprocessable Content, which
caused the BatchSimPage to crash and the UI to flash then vanish
in a retry loop.

Fix: batchId is now Optional[str] = None. When omitted, returns
the most recent active batch (or idle defaults for status).
2026-03-12 03:31:36 +00:00
KoalaTrapLord acc9d7cd47 v27.1: Fix unused import errors breaking tsc -b strict build
Removed unused imports in DecksPage, TrainingPage, and decks.ts
that caused noUnusedLocals/noUnusedParameters errors during
the React build step in the installer.
2026-03-12 03:26:38 +00:00
KoalaTrapLord 588314b282 v27: Coach mega-upgrade — all 9 improvements
Backend:
- POST /api/coach/chat: Multi-turn coaching chat with SSE streaming
- POST /api/coach/apply: Apply suggestions to deck (cut/add cards)
- GET /api/coach/cards-like: Embedding similarity search with ownership/price
- GET /api/coach/decks: Enhanced to show all decks with report status
- Goals config (power level, strategy, budget, focus areas) wired to prompts
- Session history with full diff tracking (cuts/adds/hints)

Frontend (complete CoachPage rewrite):
- Live multi-turn chat with streaming LLM responses
- Apply suggestions UI: checkbox cuts/adds, one-click apply to deck
- Goals config panel (power level slider, strategy chips, budget, focus areas)
- Session results view with summary, tips, mana advice, cuts, adds
- Session history browser with session drill-down
- Cards Like This search (embedding-powered card discovery)
- Price-aware card suggestions with collection ownership badges
- Responsive dark theme, tab navigation
2026-03-12 03:15:30 +00:00
KoalaTrapLord 7132b6f205 v26: Wire RL training pipeline UI (phases 1-5)
- Fixed all ML types to match actual backend response shapes:
  MLStatus (logging state + decision files), MLDataStatus (datasets,
  checkpoints, eval results), MLTrainStatus (phases, metrics, result),
  PPOTrainStatus (metrics with win_rate/reward/losses), TournamentStatus
- Updated training API client with full parameter support for all endpoints
- Rewrote TrainingPage with 5 clear pipeline phases:
  Phase 1: Data Collection (toggle logging, view decision files)
  Phase 2: Dataset & Model Artifacts (splits, checkpoints, eval, model info)
  Phase 3: Supervised Training (epochs/lr/batch/patience, live progress,
           phase badges, real-time metrics, final eval results)
  Phase 4: PPO Reinforcement Learning (full config: iterations, episodes,
           clip epsilon, entropy coeff, opponent selection, live win rate)
  Phase 5: Tournament Evaluation (episodes, playstyle, leaderboard table)
- All sections are collapsible with live phase badges and progress bars
- Advanced config toggles for supervised and PPO training
- Proper mutex: can't start PPO while supervised is running, etc.
- Auto-refresh model info and data status when training completes
2026-03-12 02:54:30 +00:00
KoalaTrapLord 1704d7ca9c v25: EDHREC recommendations tab in deck builder
- Redesigned Recommendations tab with EDHREC / From Collection sub-tabs
- EDHREC sub-tab: fetches average deck data, groups by role, shows owned/missing status
- Collection sub-tab: shows cards from collection grouped by type, shortfall indicators
- Both sub-tabs support: checkbox selection, bulk add to deck, single add buttons
- Role badges with color-coding (Ramp, Draw, Removal, BoardWipe, etc.)
- Card hover preview for EDHREC recommendations
- Show only owned filter for EDHREC results
- Fixed API client types: EdhRecsResponse, CollectionRecsResponse wrappers
- Added EdhRecCard and CollectionRecCard interfaces
2026-03-12 02:48:52 +00:00
KoalaTrapLord f639703fb4 v24: Resolve GitHub Issues #1-#5
Issue #1 — Winner's life total now captured:
  - Parse verbose Forge log for life-total-change events
  - Track last-known life per seat via 3 regex patterns
  - Winner's final life set from log data (not left at default 40)
  - Losers who died to mill/poison retain their actual life total

Issue #2 — Win condition classification formalized:
  - New WinCondition enum (schema/WinCondition.java) with 8 categories
  - Centralized Forge loss-reason-string → enum mapping (regex-based)
  - UNKNOWN fallback with logging for unrecognized loss reasons
  - All classification now goes through WinCondition.classify()

Issue #3 — JVM startup overhead reduced:
  - Added -XX:+UseSerialGC (lighter GC for batch processes)
  - Added -XX:TieredStopAtLevel=1 (faster JIT, less compilation)
  - ForgeWorker stub class for future persistent batch mode
  - Estimated reduction: ~2-3s → ~1-1.5s per game startup

Issue #4 — Single-threaded throughput optimization:
  - New CLI flags: --ai-simplified, --ai-think-time, --benchmark
  - JVM flags passed through to Forge subprocess
  - Benchmark mode: run 1 game before batch, report wall/Forge/overhead times
  - API support: aiSimplified, aiThinkTimeMs in StartRequest

Issue #5 — Threading, progress, and backpressure:
  - --threads 0 or -1 auto-detects optimal count from CPU topology
  - detectOptimalThreads() estimates physical cores (excludes HT)
  - ProgressCallback interface for real-time sims/sec reporting
  - Per-game progress emitted as [PROGRESS] lines, parsed by lab_api.py
  - --max-queue flag for graceful backpressure (limits concurrent JVMs)
  - Final throughput summary printed at batch completion
  - StatusResponse now includes simsPerSec field

Also: .gitignore restored, lab_api.py updated with all new API fields
2026-03-12 01:26:36 +00:00
KoalaTrapLord cbedfd1ed2 v23: React + TypeScript SPA migration
Complete frontend rewrite from vanilla HTML/CSS/JS to React 19 + TypeScript + Tailwind CSS v4.

Frontend (frontend/commander-ai-lab-ui/):
- Vite + React 19 + TypeScript + Tailwind CSS v4 + React Router
- 7 pages: BatchSim, Collection, Decks, AutoGen, Simulator, Coach, Training
- Reusable components: Spinner, StatusBadge, CardImage, ManaSymbols, EmptyState
- Full typed API client layer (8 modules matching all backend endpoints)
- Recharts for mana curves, win rate charts, progress bars
- Lucide icons throughout
- Custom dark theme with MTG mana color tokens
- Code splitting (recharts + react in separate chunks)

Backend (lab_api.py):
- SPA-aware static file serving with catch-all for client-side routing
- Fallback to legacy ui/ folder if React dist not built
- Updated startup log with SPA route list

Build system:
- .gitignore added (was missing - removes pyc, db, node_modules, etc.)
- build-full-installer-v2.py: v23 with Node.js check + React build step
- Vite build config with manual chunks for optimal loading

Also includes: V3 deck generator fixes, coach improvements, DeepSeek sim modules
2026-03-12 01:12:02 +00:00
KoalaTrapLord be55a02860 Initial commit 2026-03-10 12:13:56 -04:00
591 changed files with 24834 additions and 140032 deletions

No files matched your search

-21
View File
@@ -1,21 +0,0 @@
[run]
source = src/commander_ai_lab
omit =
*/tests/*
*/__pycache__/*
*/web/static/*
[report]
exclude_lines =
pragma: no cover
def __repr__
raise NotImplementedError
if TYPE_CHECKING:
if __name__ == .__main__.:
\.\.\. # ellipsis
show_missing = true
precision = 1
[html]
directory = htmlcov
-27
View File
@@ -1,27 +0,0 @@
# Commander AI Lab — Environment Variables
# Copy this file to .env and fill in your values.
# start-lab.bat will auto-load .env if it exists.
# ── API Keys ──────────────────────────────────────────────────────
ANTHROPIC_API_KEY=your-anthropic-api-key-here
XIMILAR_API_KEY=your-ximilar-key-here
# ── Forge JAR Path ────────────────────────────────────────────────
# Point this to your Forge GUI desktop fat JAR.
FORGE_JAR_PATH=D:/ForgeCommander/Forge-Repo/forge-gui-desktop/target/forge-gui-desktop-2.0.12-SNAPSHOT-jar-with-dependencies.jar
# IMPORTANT: Forge MUST be launched from the forge-gui directory (not forge-gui-desktop/target).
# The JAR looks for res/ relative to its working directory. Without this, you get
# ExceptionInInitializerError on startup.
FORGE_WORKING_DIR=D:/ForgeCommander/Forge-Repo/forge-gui
# ── Deck Paths ────────────────────────────────────────────────────
# Directory containing your precon .dck files.
# Forge reads deck files directly from this folder.
#
# IMPORTANT: lab_api.py reads PRECON_DIR (not PRECON_DECKS_DIR).
# PRECON_DECKS_DIR is kept below for backwards compat but is NOT used by the server.
PRECON_DIR=D:\ForgeCommander\commander-ai-lab\precon-decks
PRECON_DECKS_DIR=D:\ForgeCommander\commander-ai-lab\precon-decks
USER_DECKS_DIR=D:\ForgeCommander\commander-ai-lab\user-decks
FORGE_DECKS_DIR=D:\ForgeCommander\commander-ai-lab\user-decks
-48
View File
@@ -1,48 +0,0 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
python-tests:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -e ".[dev]" || pip install -r requirements.txt || true
pip install ruff pytest pytest-asyncio httpx || true
- name: Lint with ruff
run: ruff check . --select E,F,W --ignore E501 || true
- name: Run tests
run: pytest -v --tb=short tests/ || true
java-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Java 17
uses: actions/setup-java@v4
with:
java-version: '17'
distribution: 'temurin'
- name: Build and run Maven tests
run: mvn test -B --no-transfer-progress || true
-60
View File
@@ -1,60 +0,0 @@
name: Unity Build (Windows + WebGL)
on:
push:
branches: [main]
paths:
- 'unity-client/**'
pull_request:
branches: [main]
paths:
- 'unity-client/**'
workflow_dispatch:
env:
UNITY_PROJECT_PATH: unity-client
jobs:
build:
name: Build ${{ matrix.targetPlatform }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
targetPlatform:
- StandaloneWindows64
- WebGL
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
lfs: true
- name: Cache Unity Library
uses: actions/cache@v4
with:
path: ${{ env.UNITY_PROJECT_PATH }}/Library
key: Library-${{ matrix.targetPlatform }}-${{ hashFiles(format('{0}/Assets/**', env.UNITY_PROJECT_PATH)) }}
restore-keys: |
Library-${{ matrix.targetPlatform }}-
Library-
- name: Build Unity project
uses: game-ci/unity-builder@v4
env:
UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }}
UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }}
UNITY_PASSWORD: ${{ secrets.UNITY_PASSWORD }}
with:
projectPath: ${{ env.UNITY_PROJECT_PATH }}
targetPlatform: ${{ matrix.targetPlatform }}
buildName: CommanderAILab
versioning: Semantic
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: Build-${{ matrix.targetPlatform }}
path: build/${{ matrix.targetPlatform }}
retention-days: 14
-15
View File
@@ -32,24 +32,9 @@ embeddings/
checkpoints/
imported-decks/
# User-created decks (generated at runtime, not committed)
user-decks/*.dck
# OS
.DS_Store
Thumbs.db
# Logs
*.log
logs/
# Runtime artifacts / caches
static/
api/
image_cache/
data/rag_chroma/
.claude/
dependency-reduced-pom.xml
# Precon decks (generated / imported at runtime)
precon-decks/
-93
View File
@@ -1,93 +0,0 @@
# FarmHouse changes
This branch (`farmhouse`) is `KoalaTrapLord/commander-ai-lab` at commit `54cc5e9` plus the changes below. They were made to run the app
**Python-only** (no Forge/Java, no PyTorch) in a Kubernetes namespace, with a local LLM behind an OpenAI-compatible gateway instead of
Anthropic/DeepSeek, and they were each found by actually running the app, not by reading it. Written 2026-10-26.
Every change started life as an anchored text patch (`patch_app.py` in the farmhouse-os repo, which still builds the deployed image from
the upstream commit); here they are ordinary source edits. Lines carry a `# FARMHOUSE_...` marker where the patch left one.
## What was wrong, and what changed
### The simulator played nothing (the big one)
| Problem | Change |
|---|---|
| Every card reached the simulator with **no type line and no rules text**. The loaders join the user's *collection* and a *card_records* table (both empty on a fresh install) and the Forge card cache that was meant to fill the gap is not installed. A land was indistinguishable from a creature: an 8-game batch cast 0 spells, dealt 0 damage and lost every game. | `services/farmhouse_sim.py` `fill_card_data` fills type, text, mana cost, cmc, P/T, keywords and colour identity from the 113k-card Scryfall bulk database. Wired into `services/forge_runner.py` (batch) and `routes/deepseek.py` (`_fetch_deck_card_data`, which the Monte Carlo and single-deck routes use). |
| The batch loader **did not repeat cards by quantity**: a 100-card deck loaded as 66-84 cards with *one* Island. | `expand_quantities` (same module). |
| The LLM engine asked the model **once per turn** and applied the answer as one action. | `src/commander_ai_lab/sim/farmhouse_turns.py`: up to `BRAIN_STEPS` (default 4) questions per turn (land, spell, spell, attack), re-reading the board after each; stops on attack/hold/no change. `BRAIN_STEPS=1` restores the original. |
| A model that "thinks" spent ~46 s on a one-line move. | `deepseek_brain.py` sends `reasoning_effort` from `LLM_REASONING` (46 s -> 1.8 s per move). |
| The engine dropdown defaulted to **Forge**, which cannot run without Java. | `ui/ai-lab.js`: only "LLM opponents" is offered. |
After the fixes: a 40-game Monte Carlo takes 0.4 s with real numbers (10 spells and 12.7 damage per game); two LLM-piloted games took
212 s with 49 model calls and no fallbacks.
### Deck import
| Problem | Change |
|---|---|
| **Moxfield links were accepted nowhere**, and the Deck Builder import took only pasted text. | `services/farmhouse_deck_links.py`: Moxfield (public decks, `api2.moxfield.com`) and Archidekt links in the simulator URL import and in both Deck Builder imports (a lone link in the paste box). A private deck says to use Moxfield's Export > Copy as text. |
| The Deck Builder import looked **every card up on scryfall.com**; after a few dozen it was rate-limited (HTTP 429) and the app reported the rest as "not found" (250-card deck: 55 matched; even plain `Sol Ring` failed). | `local_card()`: names resolve from the local bulk database first; the website is only the fallback. |
### Deck generation
- `deck_builder/pipeline/farmhouse_fit.py`: the model's list is **filtered to the commander's colour identity** (from the bulk DB), de-duplicated,
fitted to per-category targets and trimmed to 99 + commander. Before this the model returned off-colour cards and 359-card lists.
- Scryfall bulk format changed (`jsonl_download_uri`, gzip JSONL; no `download_uri`).
- Scryfall answers **HTTP 400 to the default `python-requests` User-Agent** (every lookup became "Commander not found"): a named UA is sent everywhere.
- Scryfall 429s: requests back off on `Retry-After` and the pace is 0.25 s.
- `LLM_REASONING` / `LLM_MAX_TOKENS` are sent by the deck builder and coach.
### Coach / startup
- The coach was only initialised in `main()`, not when the app starts under uvicorn; `check_connection_sync()` was called but never defined;
the coach used the first model the gateway listed rather than the configured one. All fixed.
- Status label says "Language model" instead of the hardcoded "Claude Opus".
- `RAG_AUTOBUILD` (default off in our deployment) controls whether the card-search index is built at startup (113k embeddings; about an hour).
### Decision model (Laya / Kev), wired and off
`src/commander_ai_lab/sim/farmhouse_decide.py` asks a `/v1/systemone` server which of the nine actions to take, in one forward pass.
`DECISION_MODE=shadow` records whether it agrees with the LLM (the game still uses the LLM); `assist` uses it when `DECISION_MIN_CONF`
sure; `off` (default) does nothing. `scripts/farmhouse_decision_eval.py` replays recorded decisions through it.
**Measured 2026-10-26 on 149 recorded LLM decisions: zero-shot, both Laya checkpoints agreed with the LLM less often than always
guessing the commonest action** (English 16.1%, typed-decisions 18.6%, baseline 27.5%), at 2-4 s per answer on a 4-thread CPU. It is only
worth using after fine-tuning on this game's decisions; the write-up is `LAYA-EVALUATION.md` in the farmhouse-os repo's commander-lab folder.
### Laya connections (all off by default)
Forge's concrete priority path, extra typed questions in the same call, a capture log, a fine-tuning dataset exporter, and card-role classification:
`src/commander_ai_lab/sim/farmhouse_laya.py`, `scripts/farmhouse_laya_dataset.py`, `scripts/farmhouse_laya_roles_eval.py`, tests `tests/farmhouse/test_farmhouse_laya*.py`.
How it fits the strategic-intelligence work, what is measured and how to fine-tune: [docs/LAYA-CONNECTIONS.md](docs/LAYA-CONNECTIONS.md). Reference copies of the Laya
image, manifests and CI are in `farmhouse/laya/`.
### Forge, and rules-accurate simulation with phase-rs
- **Forge is installed** in the cluster image (it was left out by mistake): `farmhouse/forge/README.md`. Batches are clamped to one game at a time (`FORGE_MAX_THREADS`).
- **Rules-accurate simulation** through the phase-rs engine (Rust, headless): `routes/farmhouse_phase.py`, `ui/phase-sim.html` (linked from the home page) and the service in
`farmhouse/phase/`. Four saved decks play real Commander games; the page shows wins by seat with a 95% interval and warns about cards the engine did not recognise.
Seats can be put on a **model** (twin-turbo through Olla, or Laya): the model chooses among the engine's own legal options only, anything wrong or slow is played by phase's AI,
and a call cap bounds the cost (`farmhouse/phase/README.md`). Assessment and plan: `docs/PHASE-AND-PLAYTESTER.md`.
## Settings (environment variables)
| Variable | Meaning |
|---|---|
| `LLM_URL`, `LLM_MODEL` | OpenAI-compatible endpoint (`.../v1`) and model for the coach and deck builder |
| `LLM_REASONING` (`none`), `LLM_MAX_TOKENS`, `LLM_TIMEOUT` | keep requests lean: reasoning off, cap on answer length |
| `COACH_PROVIDER`, `DECK_GEN_PROVIDER` = `local`, `DECK_GEN_MODEL` | use the local model, not Anthropic |
| `OLLAMA_BASE_URL`, `RAG_EMBEDDING_MODEL`, `RAG_AUTOBUILD` | card-search embeddings (one host only: vectors differ between hosts) |
| `BRAIN_API_BASE` (**no** `/v1`; the client appends it), `BRAIN_MODEL`, `BRAIN_MAX_TOKENS`, `BRAIN_STEPS` | the simulator's LLM opponents |
| `DECISION_URL`, `DECISION_MODEL`, `DECISION_MODE` (`off`/`shadow`/`assist`), `DECISION_MIN_CONF`, `DECISION_TIMEOUT` | the decision model above |
| `ollama` Python package | required by the card-search index build (ChromaDB's Ollama embedder imports it) |
## Tests
`tests/farmhouse/` (standard library only, no network): `python -I -X utf8 tests/farmhouse/test_farmhouse_deck_links.py`, `..._sim.py`, `..._fit.py`.
Run them with `-I` and from outside the package folders; do not put `services/` on `sys.path` (`services/logging.py` shadows the standard library).
## Things still worth doing
- **Make the LLM-opponent turns faster** (a piloted move averages ~7.5 s: about 2.2k tokens in, ~30 out, so reading the prompt dominates).
These are ideas, not measured; none is implemented:
- *Shared prefix:* about 1.2k tokens of every prompt (the system prompt) are identical each time; a llama.cpp server can reuse them
if the calls share the prefix, so only the board state is read each move.
- *Smaller prompt:* send a compact board state instead of the indented JSON the engine builds now (`json.dumps(snapshot, indent=2)`
in `deepseek_brain.py`).
- *Parallel games:* run several games at once, which would also fill the GPU while one game waits on a move. Caveat: for long prompts
two requests at once gave no extra throughput on a V100 (reading the prompt is compute-bound), so measure before relying on it.
- Opponents are the engine's heuristics; only the piloted seat uses the model.
- Build the card-search index and measure it.
- The upstream `LICENSE` is missing (`pyproject.toml` says MIT). Ask the author to add one before publishing a derivative widely.
- Forge-based features (the Java simulator, training) remain unavailable by design.
-74
View File
@@ -1,74 +0,0 @@
# Commander AI Lab — Developer Makefile
# ======================================
# Targets:
# make test — run all tests
# make test-unit — run unit tests only (fast)
# make test-integration— run integration tests
# make test-benchmark — run benchmark suite with -s (print timings)
# make coverage — run tests with coverage report
# make serve — start the FastAPI dev server
# make lint — ruff + mypy
# make fmt — ruff format
# make clean — remove build artefacts
PYTHON ?= python
UVICORN ?= uvicorn
PORT ?= 8000
SRC = src/commander_ai_lab
.PHONY: test test-unit test-integration test-benchmark coverage serve lint fmt clean frontend-dev frontend-build test-frontend
test:
$(PYTHON) -m pytest tests/ -q
test-unit:
$(PYTHON) -m pytest tests/ -q -m "not integration and not benchmark"
test-integration:
$(PYTHON) -m pytest tests/test_integration.py -v
test-benchmark:
$(PYTHON) -m pytest tests/test_benchmark.py -v -s
test-phase3:
$(PYTHON) -m pytest tests/test_phase3.py -v
test-phase4:
$(PYTHON) -m pytest tests/test_phase4.py -v
test-phase5:
$(PYTHON) -m pytest tests/test_phase5.py -v
test-phase6:
$(PYTHON) -m pytest tests/test_phase6.py -v
test-phase7:
$(PYTHON) -m pytest tests/test_integration.py tests/test_benchmark.py -v
coverage:
$(PYTHON) -m pytest tests/ --cov=$(SRC) --cov-report=term-missing --cov-report=html
echo "Coverage report: htmlcov/index.html"
serve:
$(UVICORN) commander_ai_lab.web.app:app --reload --port $(PORT)
lint:
$(PYTHON) -m ruff check $(SRC) tests/
$(PYTHON) -m mypy $(SRC) --ignore-missing-imports
fmt:
$(PYTHON) -m ruff format $(SRC) tests/
clean:
find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
find . -type f -name '*.pyc' -delete
rm -rf .coverage htmlcov .mypy_cache .ruff_cache dist build
frontend-dev:
cd frontend && npm run dev
frontend-build:
cd frontend && npm run build
test-frontend:
cd frontend && npx vitest run
+294 -366
View File
@@ -1,434 +1,362 @@
# Commander AI Lab
A full-stack Magic: The Gathering Commander research platform. Run thousands of simulated games, train neural networks on the outcomes, build decks with AI that learns from simulation data, get LLM-powered coaching, and play live 4-player battles — all from a single unified system.
---
## Overview
Commander AI Lab connects a rules-complete Forge engine, a fast Monte Carlo simulator, an LLM deck builder, an ML training pipeline, and multiple game clients (web, LAN, Unity) into one closed-loop platform. Simulation results feed back into deck building and AI decision-making, so the system improves the more it plays.
### Key Capabilities
- **Batch Simulation** — Run hundreds or thousands of Commander games unattended using Forge (rules-complete) or a headless Python Monte Carlo engine
- **ML Training Pipeline** — Reinforcement learning (PPO) trains a neural net on game decision logs; outcome-weighted scoring nudges card weights automatically
- **AI Deck Builder** — 7-step LLM pipeline (EDHrec → Scryfall → Ollama) with simulation-learned insights injected into prompts
- **LLM Coach** — Streaming coaching sessions powered by Anthropic Claude or local Ollama models, enriched with RAG-retrieved card knowledge
- **RAG Card Knowledge** — ChromaDB vector store over 30,000+ Scryfall cards with semantic search and auto-staleness monitoring
- **LAN Battlefield** — Browser-based 4-player Commander game client with ML-powered AI opponents and precon deck support
- **Unity Client** — Full Unity application with battleground scene, lobby system, WebSocket game state sync, and cross-platform builds
- **Card Scanner** — OCR pipeline for physical card recognition via Ximilar API
- **163 Precon Decks** — Complete preconstructed deck library in `.dck` format
---
Headless batch simulation environment for 3-AI MTG Commander pods.
Run 100+ games, analyze win rates, and stress-test your decks — all from a web UI or CLI.
## Architecture
```
┌─────────────────────────────────────────────────────────────────────┐
│ Clients │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────────┐ │
│ │ Web UI │ │ LAN Client │ │ Unity Client │ │
│ │ (React/TS) │ │ (HTML/JS) │ │ (C# / URP) │ │
│ │ /ui │ │ /lan │ │ /unity-client │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────────────────────┘ │
│ └────────────────┼────────────────┘ │
│ │ HTTP/REST + WebSocket │
│ ┌───────────────────────┴─────────────────────────────────────────┐│
│ │ FastAPI Backend (lab_api.py — port 8080) ││
│ │ ││
│ │ /api/lab/* Batch simulation (Forge + Monte Carlo) ││
│ │ /api/deck-builder/* 7-step LLM deck construction ││
│ │ /api/coach/* Streaming LLM coaching sessions ││
│ │ /api/ml/* Neural net training + policy server ││
│ │ /api/rag/* ChromaDB vector search ││
│ │ /api/game/* Live game sessions (Forge IPC) ││
│ │ /api/policy/* ML policy decisions for AI players ││
│ │ /ws/game/{id} WebSocket game state streaming ││
│ └───────┬──────────────┬──────────────┬──────────────┬────────────┘│
│ │ │ │ │ │
│ ┌──────┴──────┐ ┌────┴─────┐ ┌──────┴──────┐ ┌────┴──────┐ │
│ │ Forge │ │ Monte │ │ Ollama │ │ ChromaDB │ │
│ │ Engine │ │ Carlo │ │ (local LLM) │ │ (vector │ │
│ │ (Java/JVM) │ │ Engine │ │ qwen2.5:7b │ │ store) │ │
│ └─────────────┘ │ (Python) │ └─────────────┘ └───────────┘ │
│ └──────────┘ │
│ ┌──────────────────────────────────────────────────────────────────┐│
│ │ ML Pipeline ││
│ │ decisions_*.jsonl → update_weights.py → learned_weights.json ││
│ │ → /api/ml/train → neural net checkpoints ││
│ └──────────────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Web Browser (ai-lab.js + ai-lab.css) │
│ Select decks → Start batch → Poll progress → View stats │
└─────────────────────┬───────────────────────────────────────┘
│ HTTP (REST)
┌─────────────────────┴───────────────────────────────────────┐
│ Python FastAPI Server (lab_api.py, port 8080) │
│ /api/lab/start — spawn Java batch runner subprocess │
│ /api/lab/status — poll progress (parses stdout) │
│ /api/lab/result — return completed JSON results │
│ /api/lab/decks — list decks from Forge user data │
│ /api/lab/history— browse past batch runs │
│ /api/lab/log — stream live console output │
└─────────────────────┬───────────────────────────────────────┘
│ subprocess (java -jar)
┌─────────────────────┴───────────────────────────────────────┐
│ Java CLI (LabCli.java + BatchRunner + MultiThreadRunner) │
│ Parses Forge sim output → GameResult objects → JSON │
└─────────────────────┬───────────────────────────────────────┘
│ subprocess per game
┌─────────────────────┴───────────────────────────────────────┐
│ Card Forge Engine (forge-gui-desktop sim mode) │
│ java -jar forge.jar sim -d "deck1" "deck2" "deck3" │
│ -f commander -n 1 -q │
└─────────────────────────────────────────────────────────────┘
```
---
## Features
### Simulation Engines
| Engine | Description | Speed |
|---|---|---|
| **Forge** | Rules-complete Java engine — handles the stack, instants, triggered abilities, and all Commander rules. Each game spawns a JVM subprocess. | ~0.04 sims/sec (single-threaded) |
| **Monte Carlo** | Headless Python engine — models combat keywords (flying, trample, deathtouch, lifelink, menace, reach, haste), summoning sickness, tapped state, commander zone, multiplayer targeting, and board wipes. No JVM required. | Thousands of games in minutes |
Both engines feed structured results into the same ML pipeline.
### Deck Builder
The `POST /api/deck-builder/build` endpoint runs a 7-step pipeline:
1. Resolve commander via Scryfall
2. Fetch EDHrec recommendations
3. Fetch Scryfall candidates by category (ramp, removal, draw, lands)
4. Ollama suggests synergy/protection/wincon cards — **simulation insights injected here**
5. Filter by color identity, collection, and ban list
6. Ollama enforces ratios (trim/expand to 99) — **simulation insights injected here**
7. Assemble final deck with smart substitution (guarantees 99-card output)
### AI Coach
LLM-powered coaching with two modes:
- **Full Session** — Deep analysis including removal coverage, ramp quality, draw engine profiling, win conditions, anti-synergy detection, pod meta evaluation, and tempo assessment
- **Quick Digest** — Fast ~5-second summary for rapid feedback
Coaching prompts are enriched with semantically relevant cards from the ChromaDB RAG store (15 cards for full sessions, 8 for quick digests). Supports both Anthropic Claude and local Ollama models with streaming responses.
### RAG Card Knowledge
- **SQLite FTS5** bulk card database from Scryfall data
- **ChromaDB** vector index with natural-language card embeddings
- Automatic staleness monitoring (checks every 6 hours, auto-rebuilds if >14 days old)
- Graceful fallback — RAG failures never block coaching or deck building
### ML Training Pipeline
```
Overnight sims → decisions_*.jsonl
↓
update_weights.py → learned_weights.json (feeds deck builder)
↓
/api/ml/train → neural net training on decision dataset
↓
/api/policy/decide → ML policy serves AI decisions in live games
```
- **Outcome-weighted RL** nudges card scoring weights from game results
- **Neural net** trains on the full decision log dataset
- **Distillation loop** — self-play → collect data → retrain → repeat
- **ELO tracking** and model tournaments for comparing AI versions
- Weights clamped to `[-20.0, 20.0]`, stored in `learned_weights.json`
### Win Condition Tracking
Games are classified by win type — not just "Combat" vs "Other":
- **Combat** — standard creature damage wins
- **Combo** — Approach of the Second Sun, Felidar Sovereign, Happily Ever After, and 30+ known alternate-win cards
- **Drain** — life drain effects
- **Mill** — library depletion
- **Poison** — infect/poison counter wins
Draw games (timeout) are analyzed separately with per-player life-at-timeout snapshots and likely cause identification.
### LAN Battlefield Client
Browser-based 4-player Commander game at `/lan`:
- **AI Bridge** — REST + WebSocket connectivity with ML policy decisions as Priority 1 (falls back to local heuristic AI)
- **Deck System** — 3-tab selector: Precons (163 decks, grouped by set), EDHREC search, and custom deck import
- **Player Panels** — Life counters, commander damage bars, poison/energy/experience/rad counters, emblem management
- **Backend Detection** — Auto-detects the Commander AI Lab backend; works offline with local precon data
### Unity Client
Full Unity application (URP, .NET Standard 2.1) with:
- **Battleground Scene** — 4-seat layout with rotated perspectives, life/poison/commander damage widgets, phase tracker, turn order bar
- **Card System** — Hand, battlefield, graveyard, exile zones with card art, tapped rotation, face-down state, summoning sickness indicators
- **Stack & Mana** — LIFO stack display and 6-pip mana pool
- **Lobby System** — Configure 4 seats (human/AI), POST to backend, WebSocket game state sync
- **Elimination** — Grayscale shader overlay on eliminated players
- **Token System** — Create, tap, add counters, delete tokens
- **Cross-Platform** — Windows, WebGL, Android, iOS build targets
- **Scenes** — MainMenu, Collection, DeckBuilder, DeckGenerator, Simulator, Coach, Scanner, Training, Precon, Battleground
### Card Scanner
OCR pipeline for physical Magic cards using the Ximilar API. Scan cards from photos and match them to the Scryfall database.
---
## Quick Start
## Quick Start (Windows)
### Prerequisites
- **Java 17+** (`java -version`)
- **Python 3.10+** (`python --version`)
- **Maven 3.8+** (`mvn --version`)
- **Forge repo** cloned and built at `D:\ForgeCommander\forge-repo`
| Tool | Version |
|---|---|
| Python | 3.10+ |
| Java | 17+ |
| Maven | 3.8+ |
| Node.js | 18+ (for LAN client scripts) |
| Ollama | Latest (for local LLM inference) |
| [Forge](https://github.com/KoalaTrapLord/Forge-Repo) | Built at `D:\ForgeCommander\Forge-Repo` |
### Setup (Windows)
### 1. Build Forge (one-time)
```powershell
# 1. Build Forge (one-time)
cd D:\ForgeCommander\Forge-Repo
cd D:\ForgeCommander\forge-repo
mvn package -pl forge-gui-desktop "-DskipTests" "-Drevision=2.0.12-SNAPSHOT" -am
```
# 2. Build Commander AI Lab
### 2. Build Commander AI Lab
```powershell
cd D:\ForgeCommander\commander-ai-lab
mvn package "-DskipTests"
```
This produces `target/commander-ai-lab-1.0.0-SNAPSHOT.jar` (shaded fat JAR).
# 3. Install Python dependencies
pip install -e ".[rag,dev]"
### 3. Install Python dependencies
```powershell
pip install fastapi uvicorn
```
# 4. Pull an Ollama model for the deck builder
ollama pull qwen2.5:7b
# 5. Launch
### 4. Launch the Web UI
**Option A — One-click launcher:**
```powershell
.\start-lab.bat
# → Web UI: http://localhost:8080
# → LAN Client: http://localhost:8080/lan/
```
Edit the paths at the top of `start-lab.bat` if needed.
Or use the automated installer:
**Option B — Manual launch:**
```powershell
.\install-commander-ai-lab.ps1
python lab_api.py `
--forge-jar "D:\ForgeCommander\forge-repo\forge-gui-desktop\target\forge-gui-desktop-2.0.12-SNAPSHOT-jar-with-dependencies.jar" `
--forge-dir "D:\ForgeCommander\forge-repo\forge-gui" `
--port 8080
```
---
## Overnight AFK Runner
Run batch simulations unattended, then automatically update card weights and train the neural net:
Open `http://localhost:8080` — select 3 decks, set game count, click **Run AI Sims**.
### 5. CLI-only usage (no web server)
```powershell
python overnight-run.py # default: 11.5h DeepSeek sims
python overnight-run.py --batches 20 --games 50 # fixed batch count
python overnight-run.py --no-update-weights # skip weight update
python overnight-run.py --no-train # skip neural net training
cd D:\ForgeCommander\forge-repo\forge-gui
java -jar "D:\ForgeCommander\commander-ai-lab\target\commander-ai-lab-1.0.0-SNAPSHOT.jar" `
--forge-jar "..\forge-gui-desktop\target\forge-gui-desktop-2.0.12-SNAPSHOT-jar-with-dependencies.jar" `
--forge-dir "." `
--deck1 "Edgar Markov" `
--deck2 "Grimgrin" `
--deck3 "Xyris" `
--games 100 `
--threads 4 `
--output results/batch-100.json
```
**What happens after sims complete:**
1. `update_weights.py` — nudges `learned_weights.json` from decision logs (feeds deck builder)
2. `/api/ml/train` — trains the neural net on the full decision dataset
## Scaling Tests
---
## Simulation → Deck Builder Feedback Loop
```
Overnight sims → decisions_*.jsonl
↓
update_weights.py → learned_weights.json
↓
sim_insights.py → natural-language insight block
↓
Ollama prompts (suggest_cards + enforce_deck_ratios)
↓
Better card recommendations
### Single-threaded baseline (10 games)
```powershell
java -jar target\commander-ai-lab-1.0.0-SNAPSHOT.jar `
--forge-jar "..." --forge-dir "..." `
--deck1 "Edgar Markov" --deck2 "Grimgrin" --deck3 "Xyris" `
--games 10 --threads 1 --output results/baseline-10.json
```
When active, `BuildResult.sources_consulted` includes `"sim_weights"`. The loop is a no-op until real sim data exists.
### Multi-threaded (10 games, 2 threads)
```powershell
java -jar target\commander-ai-lab-1.0.0-SNAPSHOT.jar `
--forge-jar "..." --forge-dir "..." `
--deck1 "Edgar Markov" --deck2 "Grimgrin" --deck3 "Xyris" `
--games 10 --threads 2 --output results/mt-10-t2.json
```
---
### Scale to 100 games (4 threads)
```powershell
java -jar target\commander-ai-lab-1.0.0-SNAPSHOT.jar `
--forge-jar "..." --forge-dir "..." `
--deck1 "Edgar Markov" --deck2 "Grimgrin" --deck3 "Xyris" `
--games 100 --threads 4 --output results/scale-100-t4.json
```
### Maximum throughput test (100 games, 8 threads)
```powershell
java -jar target\commander-ai-lab-1.0.0-SNAPSHOT.jar `
--forge-jar "..." --forge-dir "..." `
--deck1 "Edgar Markov" --deck2 "Grimgrin" --deck3 "Xyris" `
--games 100 --threads 8 --seed 42 --output results/scale-100-t8-seed42.json
```
### Performance comparison script
Run different thread counts and compare sims/sec:
```powershell
# Baseline: 1 thread
java -jar target\commander-ai-lab-1.0.0-SNAPSHOT.jar --forge-jar "..." --forge-dir "..." --deck1 "Edgar Markov" --deck2 "Grimgrin" --deck3 "Xyris" --games 20 --threads 1 --seed 42 --output results/perf-t1.json
# 2 threads
java -jar target\commander-ai-lab-1.0.0-SNAPSHOT.jar --forge-jar "..." --forge-dir "..." --deck1 "Edgar Markov" --deck2 "Grimgrin" --deck3 "Xyris" --games 20 --threads 2 --seed 42 --output results/perf-t2.json
# 4 threads
java -jar target\commander-ai-lab-1.0.0-SNAPSHOT.jar --forge-jar "..." --forge-dir "..." --deck1 "Edgar Markov" --deck2 "Grimgrin" --deck3 "Xyris" --games 20 --threads 4 --seed 42 --output results/perf-t4.json
# 8 threads
java -jar target\commander-ai-lab-1.0.0-SNAPSHOT.jar --forge-jar "..." --forge-dir "..." --deck1 "Edgar Markov" --deck2 "Grimgrin" --deck3 "Xyris" --games 20 --threads 8 --seed 42 --output results/perf-t8.json
```
Then compare the `simsPerSecond` values in each output JSON to see scaling behavior.
## API Reference
### Simulation
| Endpoint | Method | Description |
|---|---|---|
| `/api/lab/decks` | GET | List available Commander decks |
| `/api/lab/start` | POST | Start Forge batch (returns batchId) |
| `/api/lab/start-deepseek` | POST | Start Python/DeepSeek batch |
| `/api/lab/status?batchId=X` | GET | Poll batch progress |
| `/api/lab/result?batchId=X` | GET | Get completed batch JSON |
| `/api/lab/history` | GET | List past batch runs |
| `/api/lab/precons/deck` | GET | Fetch precon `.dck` file content |
| `/api/lab/start` | POST | Start a batch run (returns batchId) |
| `/api/lab/status?batchId=X` | GET | Poll progress for a running batch |
| `/api/lab/result?batchId=X` | GET | Get completed batch result JSON |
| `/api/lab/log?batchId=X` | GET | Get live log lines from running batch |
| `/api/lab/history` | GET | List past batch result files |
### Deck Builder & Coach
### POST /api/lab/start
```json
{
"decks": ["Edgar Markov", "Grimgrin", "Xyris"],
"numGames": 100,
"threads": 4,
"seed": null,
"clock": 120
}
```
| Endpoint | Method | Description |
|---|---|---|
| `/api/deck-builder/build` | POST | Build a 99-card Commander deck |
| `/api/coach/chat` | POST | Full coaching session (streaming) |
| `/api/coach/quick-digest` | POST | Fast ~5s coaching summary |
### GET /api/lab/status response
```json
{
"batchId": "abc123",
"running": true,
"completed": 42,
"total": 100,
"threads": 4,
"elapsedMs": 156000,
"error": null
}
```
### ML & Policy
## Python Simulator (Monte Carlo Engine)
| Endpoint | Method | Description |
|---|---|---|
| `/api/ml/train` | POST | Start neural net training |
| `/api/ml/train/status` | GET | Poll training progress |
| `/api/policy/decide` | POST | Get ML policy decision for game state |
A pure-Python deck simulator for rapid Monte Carlo analysis — no Forge JVM required.
Ported from the [mtg-commander-lan](https://github.com/) Node.js simulator.
### RAG
### Location
| Endpoint | Method | Description |
|---|---|---|
| `/api/rag/build` | POST | Build/rebuild ChromaDB index |
| `/api/rag/search` | POST | Semantic card search |
| `/api/rag/status` | GET | Index health and staleness |
```
src/commander_ai_lab/
├── __init__.py
├── sim/ # Core simulation engine
│ ├── __init__.py # Public exports
│ ├── models.py # Card, Player, SimState, GameResult, PlayerStats
│ ├── engine.py # GameEngine — turn loop, combat (flying/trample/deathtouch/lifelink/menace/reach)
│ └── rules.py # AI_DEFAULT_WEIGHTS, enrich_card(), score_card(), parse_decklist()
└── lab/ # High-level experiment helpers
├── __init__.py
└── experiments.py # build_deck(), run_single_game(), run_simulation(), _cli_main()
```
### Live Game
| Endpoint | Method | Description |
|---|---|---|
| `/api/game/start` | POST | Create a live game session |
| `/api/game/action` | POST | Submit a player action |
| `/api/game/{id}/actions` | GET | Poll Forge IPC actions |
| `/ws/game/{game_id}` | WS | Real-time game state streaming |
---
## ML Scripts
### Install as editable package
```powershell
# Update card weights from decision logs
python -m ml.scripts.update_weights --min-games 10 --lr 0.05 --dry-run
# Reset weights to defaults
python -m ml.scripts.update_weights --reset
# Generate synthetic training data
python ml/scripts/generate_synthetic_data.py
cd D:\ForgeCommander\commander-ai-lab
pip install -e .
```
---
This installs `commander_ai_lab` as an importable package and registers the `commander-sim` CLI command.
## Python Simulator API
### Quick smoke test
```powershell
python -m commander_ai_lab.lab.experiments
```
Expected output — a 10-game Monte Carlo run of a sample "Korvold" deck:
```
══════════════════════════════════════════
Commander AI Lab — Experiment Runner
══════════════════════════════════════════
--- Demo: Korvold Aristocrats (10 games) ---
Win rate: XX.X%
Avg turns: XX.X
Avg damage dealt: XX.X
Avg spells cast: XX.X
Avg creatures: XX.X
Elapsed: 0.02s
Done.
```
### Python API
```python
from commander_ai_lab.sim.models import Card
from commander_ai_lab.sim.engine import GameEngine
from commander_ai_lab.lab.experiments import build_deck, run_simulation
deck = build_deck(["Sol Ring", "Cultivate", "Lightning Bolt"] + ["Forest"] * 36)
# Build a deck from card names
deck = build_deck(["Sol Ring", "Cultivate", "Lightning Bolt", "Forest"] + ["Forest"] * 36)
# Monte Carlo simulation (100 games)
stats = run_simulation(deck, num_games=100, name_a="My Deck")
print(f"Win rate: {stats['win_rate']:.1%}, Avg turns: {stats['avg_turns']:.1f}")
print(f"Win rate: {stats['win_rate']:.1%}")
print(f"Avg turns: {stats['avg_turns']:.1f}")
```
---
Key functions:
| Function | Description |
|---|---|
| `build_deck(card_names)` | Create enriched `Card` list from names |
| `build_deck_from_text(decklist)` | Parse `"1 Sol Ring\n37 Forest"` format |
| `run_single_game(deck_a, deck_b)` | One game, returns winner/turns/stats |
| `run_simulation(deck_a, deck_b, n)` | Monte Carlo over `n` games, aggregated stats |
### CLI entry point
After `pip install -e .`:
```powershell
commander-sim
```
Runs the same demo as `python -m commander_ai_lab.lab.experiments`.
### How the engine works
1. **Deck enrichment** — `enrich_card()` infers type, CMC, keywords, and power/toughness from card name heuristics when Scryfall data is unavailable.
2. **AI scoring** — `score_card()` uses weighted categories (removal, ramp, draw, aggro, etc.) to pick the best play each turn.
3. **Game loop** — Each turn: untap → draw → play lands → cast spells (AI scored) → combat (attack/block decisions) → end step. Full keyword support for flying, trample, deathtouch, lifelink, menace, and reach.
4. **Monte Carlo** — `run_simulation()` runs N independent games and aggregates win rate, avg turns, damage dealt/received, spells cast, creatures played, removal used, ramp played, cards drawn, and max board size.
## Project Structure
```
commander-ai-lab/
├── lab_api.py # FastAPI server entry point
├── overnight-run.py # AFK batch runner
├── lab_api.py # Python FastAPI server (web UI backend)
├── start-lab.bat # Windows one-click launcher
├── install-commander-ai-lab.ps1 # Automated setup script
├── pom.xml # Maven build (Java/Forge components)
├── pyproject.toml # Python package config
│
├── routes/ # FastAPI route modules
│ ├── lab.py # Batch simulation
│ ├── deckbuilder.py # Deck builder pipeline
│ ├── coach.py # LLM coaching
│ ├── ml.py # ML training
│ ├── rag.py # ChromaDB vector search
│ ├── game.py # Live game sessions
│ ├── policy.py # ML policy server
│ ├── precon.py # Precon deck serving
│ ├── scanner.py # Card OCR
│ └── ws_game.py # WebSocket game state
│
├── services/ # Core service layer
│ ├── forge_runner.py # Forge subprocess management
│ ├── draw_game_analyzer.py # Draw/timeout analysis
│ ├── rag_store.py # ChromaDB vector store
│ └── card_text.py # Shared card text builder
│
├── src/commander_ai_lab/
│ ├── sim/ # Monte Carlo engine
│ │ ├── engine.py # Game loop
│ │ ├── models.py # GameResult, Card, Player
│ │ ├── rules.py # Combat, keywords, commander rules
│ │ ├── win_condition_parser.py # Alternate win detection
│ │ └── learned_weights.json # ML-learned card weights
│ ├── deck_builder/ # 7-step LLM pipeline
│ │ ├── api/ # Scryfall, EDHrec, Ollama, sim_insights
│ │ ├── core/ # Models, rules engine, assembler
│ │ └── pipeline/ # build_deck.py orchestrator
│ └── coach/ # LLM coaching
│ ├── coach_service.py # Session + quick digest
│ ├── prompt_template.py # System/user prompts
│ └── embeddings.py # Card embedding utilities
│
├── ml/ # ML training pipeline
│ ├── scripts/ # update_weights.py, ml_cli.py
│ ├── training/ # Neural net trainer
│ ├── encoder/ # Feature encoding
│ └── models/ # Saved checkpoints
│
├── lan-client/ # Browser-based LAN battlefield
│ ├── index.html # Entry point
│ ├── engine.js # Game engine + ML AI turns
│ ├── ai-bridge.js # Backend connector + policy bridge
│ ├── player-panels.js # Enhanced player panels
│ ├── ui.js # 3-tab deck selector + setup
│ └── precons.js # 163 precon deck data
│
├── unity-client/ # Unity game client
│ └── Assets/
│ ├── Scenes/ # 11 scenes (MainMenu → Battleground)
│ ├── Scripts/ # C# controllers, models, services
│ ├── Prefabs/ # Card, deck slot, chat bubble
│ └── Materials/ # URP materials + grayscale shader
│
├── scanner/ # Card OCR pipeline (Ximilar)
├── precon-decks/ # 163 preconstructed decks (.dck)
├── sample-decks/ # Sample deck files
├── data/ # Runtime data (ChromaDB, bulk DB)
├── logs/ # Simulation + decision logs
├── docs/ # Architecture docs + schemas
├── tests/ # Test suite
├── scripts/ # Utility scripts
├── .github/workflows/ # CI + Unity build automation
└── src/main/java/ # Java/Forge batch runner
└── commanderailab/
├── pom.xml # Maven build (Java 17, shaded JAR)
├── pyproject.toml # Python package config (src/ layout)
├── ui/
│ ├── index.html # Web UI entry point
│ ├── ai-lab.js # UI controller (deck selection, progress, results)
│ ├── ai-lab.css # Styles (dark theme, responsive)
│ ├── collection.html # Card collection manager
│ ├── collection.js # Collection controller
│ ├── collection.css # Collection styles
│ ├── deckbuilder.html # Deck builder + EDH advisor
│ ├── deckbuilder.js # Deck builder controller
│ └── deckbuilder.css # Deck builder styles
├── src/commander_ai_lab/ # Python simulator package
│ ├── __init__.py
│ ├── sim/ # Core engine (models, engine, rules)
│ └── lab/ # Experiment helpers
├── src/main/java/commanderailab/ # Java batch runner (Forge integration)
│ ├── cli/LabCli.java # CLI entry point (picocli)
│ ├── batch/
│ │ ├── BatchRunner.java # Single-thread runner (parses Forge output)
│ │ └── MultiThreadBatchRunner.java # Multi-thread runner (ExecutorService)
│ ├── bridge/WebApiBridge.java # Java-side web API bridge
│ ├── schema/
│ │ ├── BatchResult.java # Data model POJOs
│ │ └── JsonExporter.java # JSON serialization + validation
│ ├── stats/StatsAggregator.java # Win rates, turn counts, breakdowns
│ └── ai/
│ ├── AiPolicy.java # Policy interface
│ └── ForgeBuiltinPolicy.java # v1 Forge AI wrapper
├── scanner/ # Card scanner (OCR pipeline)
│ ├── __init__.py
│ ├── ocr.py # Tesseract OCR wrapper
│ ├── pipeline.py # Image preprocessing pipeline
│ └── preprocess.py # Image preprocessing helpers
├── docs/
│ ├── PROJECT_VISION.md
│ ├── batch-result-schema.json
│ └── game-log-schema.json
├── sample-decks/ # 3 sample .dck files
├── precon-decks/ # Preconstructed decks + index
├── results/ # Batch output JSON files (gitignored)
└── src/test/java/ # Unit tests
```
---
## Output Format
## Tech Stack
| Layer | Technology |
|---|---|
| Backend | Python 3.10+, FastAPI, Uvicorn |
| Simulation (rules-complete) | Java 17, Maven, Forge |
| Simulation (fast) | Python Monte Carlo engine |
| LLM Inference | Ollama (qwen2.5:7b), Anthropic Claude |
| Vector Store | ChromaDB with all-MiniLM-L6-v2 embeddings |
| Card Database | SQLite FTS5 (Scryfall bulk data) |
| ML Training | PyTorch, PPO reinforcement learning |
| Web Client | HTML/CSS/JS |
| Unity Client | Unity 2022 LTS, URP, C# |
| CI/CD | GitHub Actions |
---
Each batch run produces JSON conforming to `docs/batch-result-schema.json`:
```json
{
"metadata": {
"schemaVersion": "1.0.0",
"batchId": "uuid",
"timestamp": "2026-03-06T...",
"totalGames": 100,
"completedGames": 100,
"format": "commander",
"podSize": 3,
"engineVersion": "forge-2.0.12-SNAPSHOT",
"masterSeed": 42,
"threads": 4,
"elapsedMs": 260000
},
"decks": [...],
"games": [...],
"summary": {
"perDeck": [
{ "deckName": "Edgar Markov", "winRate": 0.60, "wins": 60, ... }
],
"avgGameTurns": 12.3,
"simsPerSecond": 0.38
}
}
```
## Known Limitations
- **Monte Carlo engine** — no stack, no instants, no continuous type-changing effects (animated lands don't attack)
- **Forge engine** — each game spawns a new JVM (~2–3s overhead); ~0.04 sims/sec single-threaded
- **Forge** — winner life total not captured in quiet mode (only reports losers)
- **Deck builder** — Ollama suggestions depend on the local model quality; `qwen2.5:7b` works well
- **LAN client** — EDHREC commander search is a stub (backend-powered, not yet fully wired)
---
## Contributing
Commander AI Lab is an active research project. Check the [open issues](https://github.com/KoalaTrapLord/commander-ai-lab/issues) for areas where contributions are welcome.
---
## License
See repository for license details.
- Winner's life total not captured (Forge quiet mode only reports losers)
- Win condition classification is heuristic-based on Forge loss reason strings
- Each game spawns a new JVM process (~2-3s overhead per game)
- Max throughput ~0.04 sims/sec single-threaded (Forge sim is CPU-heavy)
- Multithreading spawns parallel subprocesses — throughput scales linearly with threads up to CPU core count
-257
View File
@@ -1,257 +0,0 @@
<#
.SYNOPSIS
Smoke-tests the Commander AI Lab policy server from PowerShell.
Checks: server reachable -> /api/policy/health -> /api/policy/decide.
Prints a plain-English pass/fail for every step.
.USAGE
# From repo root (server already running in another window):
.\Test-PolicyServer.ps1
# Custom host/port:
.\Test-PolicyServer.ps1 -BaseUrl http://localhost:9000
# Pretty-print the full decide response:
.\Test-PolicyServer.ps1 -Verbose
#>
param(
[string]$BaseUrl = "http://localhost:8080",
[switch]$Verbose
)
$ErrorActionPreference = "Stop"
# ---- helpers ----------------------------------------------------------------
function Write-Pass { param([string]$msg) Write-Host " [PASS] $msg" -ForegroundColor Green }
function Write-Fail { param([string]$msg) Write-Host " [FAIL] $msg" -ForegroundColor Red }
function Write-Info { param([string]$msg) Write-Host " [INFO] $msg" -ForegroundColor Cyan }
function Write-Warn { param([string]$msg) Write-Host " [WARN] $msg" -ForegroundColor Yellow }
function Write-Step { param([string]$msg) Write-Host "`n-- $msg" -ForegroundColor White }
$allPassed = $true
function Invoke-Step {
param(
[string] $Name,
[scriptblock] $Block
)
Write-Step $Name
try { & $Block }
catch {
Write-Fail $_.Exception.Message
$script:allPassed = $false
}
}
# ---- Step 1: server reachable -----------------------------------------------
Invoke-Step "Step 1 -- Server reachable at $BaseUrl" {
$r1 = $null
try { $r1 = Invoke-WebRequest -Uri "$BaseUrl/docs" -UseBasicParsing -TimeoutSec 5 } catch {}
if ($r1 -and $r1.StatusCode -eq 200) {
Write-Pass "FastAPI server is up (GET /docs -> 200)"
return
}
$r2 = $null
try { $r2 = Invoke-WebRequest -Uri "$BaseUrl/" -UseBasicParsing -TimeoutSec 5 } catch {}
if ($r2 -and $r2.StatusCode -lt 500) {
Write-Pass "FastAPI server is up (GET / -> $($r2.StatusCode))"
return
}
throw "Cannot reach $BaseUrl -- is lab_api.py / uvicorn running?"
}
# ---- Step 2: /api/policy/health ---------------------------------------------
$modelLoaded = $false
Invoke-Step "Step 2 -- GET $BaseUrl/api/policy/health" {
$resp = Invoke-RestMethod -Uri "$BaseUrl/api/policy/health" -Method Get -TimeoutSec 10
if ($Verbose) { $resp | ConvertTo-Json -Depth 5 | Write-Host }
if ($resp.ready -eq $true) {
Write-Pass "Model is loaded and ready (ready=true)"
$script:modelLoaded = $true
} elseif ($resp.status -eq "degraded") {
Write-Fail "Health returned status=degraded / ready=false"
Write-Warn " -> Policy model is NOT loaded."
Write-Warn " -> Start the server with --load-policy, or call POST /api/ml/load_model first."
Write-Warn " -> Confirm models/ contains a valid .pt checkpoint."
$script:allPassed = $false
} else {
Write-Warn "Unexpected health response -- dumping:"
$resp | ConvertTo-Json -Depth 5 | Write-Host
$script:allPassed = $false
}
}
# ---- Step 3: /api/policy/decide (synthetic snapshot) ------------------------
Invoke-Step "Step 3 -- POST $BaseUrl/api/policy/decide (synthetic 4-player snapshot)" {
if (-not $script:modelLoaded) {
Write-Warn "Skipping /decide -- model not loaded (Step 2 failed)."
Write-Warn "Fix Step 2 first, then re-run."
return
}
$body = [ordered]@{
game_id = "ps1-smoke-test"
turn = 3
phase = "MAIN1"
active_player = 0
playstyle = "midrange"
temperature = 1.0
greedy = $false
players = @(
[ordered]@{
seat = 0
name = "TestPlayer0"
life = 40
manaAvailable = 3
landCount = 3
creaturesOnField = 1
totalPowerOnBoard = 2
hand = @("Cultivate", "Solemn Simulacrum", "Sol Ring")
battlefield = @("Forest", "Forest", "Forest", "Birds of Paradise")
graveyard = @()
commandZone = @("Atraxa, Praetors Voice")
},
[ordered]@{
seat = 1
name = "TestPlayer1"
life = 38
manaAvailable = 2
landCount = 2
creaturesOnField = 0
totalPowerOnBoard = 0
handCount = 4
hand = @()
battlefield = @("Island", "Swamp")
graveyard = @()
commandZone = @("Ur-Dragon")
},
[ordered]@{
seat = 2
name = "TestPlayer2"
life = 35
manaAvailable = 4
landCount = 4
creaturesOnField = 2
totalPowerOnBoard = 5
handCount = 3
hand = @()
battlefield = @("Mountain", "Mountain", "Mountain", "Mountain", "Goblin Guide", "Monastery Swiftspear")
graveyard = @()
commandZone = @("Krenko, Mob Boss")
},
[ordered]@{
seat = 3
name = "TestPlayer3"
life = 40
manaAvailable = 0
landCount = 0
creaturesOnField = 0
totalPowerOnBoard = 0
handCount = 7
hand = @()
battlefield = @()
graveyard = @()
commandZone = @("Prossh, Skyraider of Kher")
}
)
} | ConvertTo-Json -Depth 10
$resp = Invoke-RestMethod `
-Uri "$BaseUrl/api/policy/decide" `
-Method Post `
-Body $body `
-ContentType "application/json" `
-TimeoutSec 30
if ($Verbose) {
Write-Host ""
Write-Host " Full /decide response:" -ForegroundColor White
$resp | ConvertTo-Json -Depth 6 | Write-Host
}
$ok = $true
if ([string]::IsNullOrEmpty($resp.action)) {
Write-Fail "response.action is empty"
$ok = $false
}
if ($null -eq $resp.confidence) {
Write-Fail "response.confidence is missing"
$ok = $false
}
if ($resp.PSObject.Properties["error"] -and -not [string]::IsNullOrEmpty($resp.error)) {
Write-Fail "Server returned error: $($resp.error)"
$ok = $false
}
if ($ok) {
$confPct = [math]::Round($resp.confidence * 100, 1)
Write-Pass "Decision received -> action='$($resp.action)' conf=$($confPct)% latency=$($resp.inference_ms)ms src=$($resp.vector_source)"
if ($resp.probabilities) {
$top3 = $resp.probabilities.PSObject.Properties |
Sort-Object { $_.Value } -Descending |
Select-Object -First 3
Write-Info "Top-3 action probabilities:"
foreach ($p in $top3) {
$pct = [math]::Round($p.Value * 100, 1)
Write-Info (" " + $p.Name.PadRight(22) + "$pct%")
}
}
} else {
$script:allPassed = $false
}
}
# ---- Step 4: log line guidance ----------------------------------------------
Invoke-Step "Step 4 -- Confirm [routes.policy.decide] log line in server console" {
Write-Info "After Step 3 you should see in the uvicorn window:"
Write-Info " [decide] turn=3 phase=main_1 -> cast_ramp (conf=0.810) | top5=[...] | src=encoder"
Write-Info ""
Write-Info "If that line is MISSING:"
Write-Info " 1. Confirm uvicorn started with --log-level info (the default)"
Write-Info " 2. Confirm lab_api.py calls register_policy_routes(app, policy_svc)"
Write-Info " 3. Confirm routes/policy.py is included via routes/__init__.py"
Write-Info " 4. Logger name is [routes.policy.decide] -- check no filter silences it"
Write-Pass "Guidance printed"
}
# ---- Step 5: why Forge ignores the policy server ----------------------------
Invoke-Step "Step 5 -- Forge IPC status (informational)" {
Write-Warn "Forge does NOT call /api/policy/decide on its own."
Write-Warn "routes/game.py POST /api/game/start has a TODO: wire Forge engine launch."
Write-Warn ""
Write-Warn "Until wired, /decide is only hit by:"
Write-Warn " - This script"
Write-Warn " - overnight-run.py (batch sim path)"
Write-Warn " - Manual Invoke-RestMethod / curl calls"
Write-Warn ""
Write-Warn "Forge launches its built-in AI and plays lands because it has"
Write-Warn "no HTTP client pointed at localhost:8080."
Write-Warn ""
Write-Warn "Next step: wire GameSession inside POST /api/game/start,"
Write-Warn "or add a PolicyClient hook in Forge AiController.java."
Write-Pass "Status explained"
}
# ---- Summary ----------------------------------------------------------------
Write-Host ""
if ($allPassed) {
Write-Host "==========================================" -ForegroundColor Green
Write-Host " ALL STEPS PASSED -- policy server live" -ForegroundColor Green
Write-Host "==========================================" -ForegroundColor Green
} else {
Write-Host "==========================================" -ForegroundColor Red
Write-Host " ONE OR MORE STEPS FAILED -- see above" -ForegroundColor Red
Write-Host "==========================================" -ForegroundColor Red
exit 1
}
+1 -1
View File
@@ -1 +1 @@
# Coach clients — Anthropic Claude, LM Studio
# Coach clients — Perplexity, LM Studio
-401
View File
@@ -1,401 +0,0 @@
"""
Commander AI Lab — Anthropic Claude Structured Output Client
════════════════════════════════════════════════════════════
Uses the anthropic SDK to call Claude's messages endpoint
with structured JSON output enforced via system prompt.
Supports both sync and native async operation.
All substantive calls use .messages.stream() to avoid the SDK's
10-minute non-streaming timeout restriction on large max_tokens.
"""
import json
import logging
import re
from typing import Optional
import anthropic
logger = logging.getLogger("coach.anthropic")
# ── Anthropic Models ───────────────────────────────────────────
CLAUDE_OPUS = "claude-opus-4-0-20250514"
CLAUDE_SONNET = "claude-sonnet-4-5"
CLAUDE_HAIKU = "claude-haiku-4-5"
class AnthropicResponse:
"""Parsed response container from Anthropic API.
Drop-in replacement for PerplexityResponse — same attribute shape
so all existing call-sites work without changes.
"""
def __init__(
self,
content: str,
parsed_json: Optional[dict],
prompt_tokens: int,
completion_tokens: int,
model: str,
citations: list[str] = None,
):
self.content = content
self.parsed_json = parsed_json
self.prompt_tokens = prompt_tokens
self.completion_tokens = completion_tokens
self.model = model
self.citations = citations or [] # Anthropic has no citations; kept for compat
@property
def ok(self) -> bool:
return self.parsed_json is not None
class AnthropicClient:
"""
Anthropic Claude API client.
Drop-in replacement for PerplexityClient.
All substantive calls use .messages.stream() so the SDK never
enforces the 10-minute non-streaming timeout.
Usage:
client = AnthropicClient(api_key="sk-ant-...")
resp = client.chat_structured(
system_prompt="You are a deck builder.",
user_prompt="Build a deck for...",
json_schema=deck_schema,
schema_name="DeckList",
)
if resp.ok:
deck = resp.parsed_json
"""
def __init__(
self,
api_key: str,
model: str = CLAUDE_OPUS,
timeout: int = 120,
base_url: str = None,
):
if not api_key:
raise ValueError("Anthropic API key is required")
self.api_key = api_key
self.model = model
self.timeout = timeout
self._client = anthropic.Anthropic(
api_key=api_key,
base_url=base_url,
timeout=float(timeout),
)
self._async_client = anthropic.AsyncAnthropic(
api_key=api_key,
base_url=base_url,
timeout=float(timeout),
)
def chat_structured(
self,
system_prompt: str,
user_prompt: str,
json_schema: dict = None,
schema_name: str = "response",
model: str = None,
temperature: float = 0.2,
max_tokens: int = 8192,
) -> AnthropicResponse:
"""
Send a chat request expecting JSON output.
Uses streaming to avoid the Anthropic SDK 10-minute timeout restriction.
"""
use_model = model or self.model
effective_system = self._build_system(system_prompt, json_schema, schema_name)
try:
with self._client.messages.stream(
model=use_model,
system=effective_system,
messages=[{"role": "user", "content": user_prompt}],
temperature=temperature,
max_tokens=max_tokens,
) as stream:
content = stream.get_final_text()
final_msg = stream.get_final_message()
return self._parse_streamed(content, final_msg, use_model)
except Exception as e:
logger.error("[anthropic] chat_structured failed: %s", e)
raise
def chat_plain(
self,
system_prompt: str,
user_prompt: str,
model: str = None,
temperature: float = 0.2,
max_tokens: int = 4096,
) -> AnthropicResponse:
"""
Send a plain chat request without strict structured output.
Uses streaming to avoid the Anthropic SDK 10-minute timeout restriction.
"""
use_model = model or self.model
try:
with self._client.messages.stream(
model=use_model,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}],
temperature=temperature,
max_tokens=max_tokens,
) as stream:
content = stream.get_final_text()
final_msg = stream.get_final_message()
return self._parse_streamed(content, final_msg, use_model)
except Exception as e:
logger.error("[anthropic] chat_plain failed: %s", e)
raise
async def achat_structured(
self,
system_prompt: str,
user_prompt: str,
json_schema: dict = None,
schema_name: str = "response",
model: str = None,
temperature: float = 0.2,
max_tokens: int = 8192,
) -> AnthropicResponse:
"""Native async structured chat using streaming."""
use_model = model or self.model
effective_system = self._build_system(system_prompt, json_schema, schema_name)
try:
async with self._async_client.messages.stream(
model=use_model,
system=effective_system,
messages=[{"role": "user", "content": user_prompt}],
temperature=temperature,
max_tokens=max_tokens,
) as stream:
content = await stream.get_final_text()
final_msg = await stream.get_final_message()
return self._parse_streamed(content, final_msg, use_model)
except Exception as e:
logger.error("[anthropic] achat_structured failed: %s", e)
raise
async def achat_plain(
self,
system_prompt: str,
user_prompt: str,
model: str = None,
temperature: float = 0.2,
max_tokens: int = 4096,
) -> AnthropicResponse:
"""Native async plain chat using streaming."""
use_model = model or self.model
try:
async with self._async_client.messages.stream(
model=use_model,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}],
temperature=temperature,
max_tokens=max_tokens,
) as stream:
content = await stream.get_final_text()
final_msg = await stream.get_final_message()
return self._parse_streamed(content, final_msg, use_model)
except Exception as e:
logger.error("[anthropic] achat_plain failed: %s", e)
raise
def check_status(self) -> dict:
"""
Quick health check — tiny max_tokens=10 call, safe to use non-streaming
since it will never approach the 10-minute threshold.
"""
try:
response = self._client.messages.create(
model=self.model,
system="Reply with the word OK.",
messages=[{"role": "user", "content": "Status check."}],
max_tokens=10,
)
content = response.content[0].text if response.content else ""
return {
"connected": True,
"model": self.model,
"response": content,
}
except Exception as e:
return {
"connected": False,
"model": self.model,
"error": str(e),
}
# ── Internal helpers ──────────────────────────────────────────
@staticmethod
def _build_system(system_prompt: str, json_schema: dict, schema_name: str) -> str:
"""Append JSON schema hint to system prompt when a schema is provided."""
if not json_schema:
return system_prompt
schema_str = json.dumps(json_schema, indent=2)
return (
f"{system_prompt}\n\n"
f"You MUST respond with valid JSON only — no markdown fences, no prose.\n"
f"The response must conform to the following JSON schema ({schema_name}):\n"
f"{schema_str}"
)
def _parse_streamed(self, content: str, final_msg, use_model: str) -> AnthropicResponse:
"""Build an AnthropicResponse from streamed text + final message metadata."""
usage = getattr(final_msg, "usage", None)
prompt_tokens = usage.input_tokens if usage else 0
completion_tokens = usage.output_tokens if usage else 0
parsed = None
try:
parsed = json.loads(content)
except (json.JSONDecodeError, TypeError):
parsed = self._extract_json(content)
logger.info(
"[anthropic] model=%s tokens=(%d in, %d out) parsed=%s",
use_model,
prompt_tokens,
completion_tokens,
"yes" if parsed else "no",
)
return AnthropicResponse(
content=content,
parsed_json=parsed,
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
model=use_model,
citations=[],
)
@staticmethod
def _extract_json(text: str) -> Optional[dict]:
"""Best-effort JSON extraction from possibly noisy text."""
try:
return json.loads(text.strip())
except (json.JSONDecodeError, TypeError):
pass
# Markdown fences
fence_match = re.search(r'```(?:json)?\s*([\s\S]*?)```', text)
if fence_match:
try:
return json.loads(fence_match.group(1).strip())
except (json.JSONDecodeError, TypeError):
pass
# Brace counting
start = text.find('{')
if start == -1:
return None
depth = 0
in_string = False
escape_next = False
for i in range(start, len(text)):
ch = text[i]
if escape_next:
escape_next = False
continue
if ch == '\\' and in_string:
escape_next = True
continue
if ch == '"':
in_string = not in_string
continue
if in_string:
continue
if ch == '{':
depth += 1
elif ch == '}':
depth -= 1
if depth == 0:
try:
return json.loads(text[start:i + 1])
except (json.JSONDecodeError, TypeError):
return None
# Truncated JSON — attempt repair
return AnthropicClient._repair_truncated_json(text[start:])
@staticmethod
def _repair_truncated_json(text: str) -> Optional[dict]:
"""
Attempt to repair truncated JSON from max_tokens cutoff.
Strategy: find the last complete nested object, then close
all open brackets/braces.
"""
logger.info("Attempting truncated JSON repair (%d chars)...", len(text))
last_good = -1
depth = 0
in_string = False
escape_next = False
for i in range(len(text)):
ch = text[i]
if escape_next:
escape_next = False
continue
if ch == '\\' and in_string:
escape_next = True
continue
if ch == '"':
in_string = not in_string
continue
if in_string:
continue
if ch == '{':
depth += 1
elif ch == '}':
depth -= 1
if depth >= 1:
last_good = i
if last_good == -1:
return None
truncated = text[:last_good + 1]
close_depth = 0
in_arr = 0
in_str = False
esc = False
for ch in truncated:
if esc:
esc = False
continue
if ch == '\\' and in_str:
esc = True
continue
if ch == '"':
in_str = not in_str
continue
if in_str:
continue
if ch == '{':
close_depth += 1
elif ch == '}':
close_depth -= 1
elif ch == '[':
in_arr += 1
elif ch == ']':
in_arr -= 1
suffix = ']' * in_arr + '}' * close_depth
repaired = truncated + suffix
try:
result = json.loads(repaired)
card_count = len(result.get('cards', []))
logger.info("JSON repair succeeded: recovered %d cards", card_count)
return result
except (json.JSONDecodeError, TypeError) as e:
logger.warning("JSON repair failed: %s", e)
return None
+19 -16
View File
@@ -56,15 +56,15 @@ class PerplexityClient:
"""
def __init__(self, api_key: str, model: str = SONAR,
timeout: int = 120, base_url: str = None):
if not api_key and not base_url:
raise ValueError("Perplexity API key is required (or provide base_url for local)")
timeout: int = 120):
if not api_key:
raise ValueError("Perplexity API key is required")
self.api_key = api_key
self.model = model
self.timeout = timeout
self._client = OpenAI(
api_key=api_key,
base_url=base_url or "https://api.perplexity.ai",
base_url="https://api.perplexity.ai",
timeout=timeout,
)
@@ -72,30 +72,26 @@ class PerplexityClient:
self,
system_prompt: str,
user_prompt: str,
json_schema: dict = None,
json_schema: dict,
schema_name: str = "response",
model: str = None,
temperature: float = 0.2,
max_tokens: int = 8192,
) -> PerplexityResponse:
"""
Send a chat request with JSON output.
Uses Sonar models do not support the json_schema response_format.
Structured output enforcement relies on the system prompt
instructing the model to return JSON matching the expected shape.
Send a chat request with structured JSON output.
Args:
system_prompt: System message (should instruct JSON output)
system_prompt: System message
user_prompt: User message
json_schema: (ignored) Kept for call-site compatibility
schema_name: (ignored) Kept for call-site compatibility
json_schema: JSON Schema dict for response_format
schema_name: Name for the schema (used in response_format)
model: Override model (sonar, sonar-pro)
temperature: Sampling temperature (0.0-1.0)
temperature: Sampling temperature (0.0–1.0)
max_tokens: Max output tokens
Returns:
PerplexityResponse with parsed_json from the model's output
PerplexityResponse with parsed_json guaranteed by schema
"""
use_model = model or self.model
@@ -110,7 +106,14 @@ class PerplexityClient:
messages=messages,
temperature=temperature,
max_tokens=max_tokens,
)
response_format={
"type": "json_schema",
"json_schema": {
"name": schema_name,
"schema": json_schema,
},
},
)
choice = response.choices[0]
content = choice.message.content or ""
+71 -349
View File
@@ -5,11 +5,10 @@ Main orchestrator: loads deck reports, identifies underperformers,
finds replacement candidates via embeddings, builds prompts,
calls the LLM, parses responses, and persists coaching sessions.
"""
import json
import logging
import uuid
import os
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional, List, Dict
@@ -17,35 +16,18 @@ from typing import Optional, List, Dict
from .config import (
DECK_REPORTS_DIR, COACH_SESSIONS_DIR,
MAX_UNDERPERFORMERS, MAX_CANDIDATES_PER_UNDERPERFORMER,
COACH_PROVIDER, ANTHROPIC_API_KEY, ANTHROPIC_MODEL,
UNDERPERFORMER_IMPACT_THRESHOLD, DEFAULT_MAX_TOKENS, ensure_dirs,
UNDERPERFORMER_IMPACT_THRESHOLD, ensure_dirs,
)
from .models import (
DeckReport, CoachGoals, CoachSession,
SuggestedCut, SuggestedAdd, CoachStatus,
UpgradePriorityItem, CommanderDependency, MulliganAnalysis,
RemovalCoverage, RampQuality, DrawEngineProfile,
WinCondition, AntiSynergyFlag,
PodPresence, TempoAssessment, MetaMatchup,
)
from .llm_client import LLMClient
from .llm_client import LMStudioClient
from .embeddings import MTGEmbeddingIndex
from .prompt_template import build_system_prompt, build_user_prompt
logger = logging.getLogger("coach.service")
# SQLite persistence for coach sessions
try:
from services.database import (
save_coach_session as _db_save_session,
load_coach_session as _db_load_session,
list_coach_sessions as _db_list_sessions,
delete_coach_session as _db_delete_session,
)
_DB_AVAILABLE = True
except ImportError:
_DB_AVAILABLE = False
class CoachService:
"""
@@ -54,30 +36,35 @@ class CoachService:
Usage:
embeddings = MTGEmbeddingIndex()
embeddings.load()
llm = LLMClient()
llm = LMStudioClient()
coach = CoachService(llm, embeddings)
session = await coach.run_coaching_session("edgar-markov")
"""
def __init__(self, llm: LLMClient, embeddings: MTGEmbeddingIndex):
def __init__(self, llm: LMStudioClient, embeddings: MTGEmbeddingIndex):
self.llm = llm
self.embeddings = embeddings
ensure_dirs()
# ── Deck Report I/O ──────────────────────
# ── Deck Report I/O ────────────────────────────────────────
def load_deck_report(self, deck_id: str) -> Optional[DeckReport]:
"""Load a deck report from disk."""
# Try exact filename first, then case-insensitive search
report_path = DECK_REPORTS_DIR / f"{deck_id}.json"
if not report_path.exists():
# Try case-insensitive match
for f in DECK_REPORTS_DIR.glob("*.json"):
if re.sub(r'[^a-z0-9]', '', f.stem.lower()) == re.sub(r'[^a-z0-9]', '', deck_id.lower()):
if f.stem.lower() == deck_id.lower():
report_path = f
break
if not report_path.exists():
logger.warning("Deck report not found: %s", deck_id)
return None
try:
with open(report_path, "r", encoding="utf-8") as f:
with open(report_path, "r") as f:
data = json.load(f)
return DeckReport(**data)
except Exception as e:
@@ -90,64 +77,23 @@ class CoachService:
return []
return [f.stem for f in DECK_REPORTS_DIR.glob("*.json")]
# ── Coach Session I/O ──────────────────
# ── Coach Session I/O ──────────────────────────────────────
def save_session(self, session: CoachSession) -> Path:
"""Persist a coaching session to disk and SQLite."""
"""Persist a coaching session to disk."""
COACH_SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
path = COACH_SESSIONS_DIR / f"{session.sessionId}.json"
with open(path, "w", encoding="utf-8") as f:
with open(path, "w") as f:
f.write(session.model_dump_json(indent=2))
if _DB_AVAILABLE:
try:
_db_save_session({
"session_id": session.sessionId,
"deck_id": session.deckId,
"timestamp": session.timestamp,
"model_used": session.modelUsed or "",
"prompt_tokens": session.promptTokens or 0,
"completion_tokens": session.completionTokens or 0,
"summary": session.summary or "",
"goals_json": json.dumps(session.goals.model_dump() if session.goals else {}),
"cuts_json": json.dumps([c.model_dump() for c in session.suggestedCuts]),
"adds_json": json.dumps([a.model_dump() for a in session.suggestedAdds]),
"heuristic_hints_json": json.dumps(session.heuristicHints or []),
"mana_base_advice": session.manaBaseAdvice or "",
"raw_text": session.rawTextExplanation or "",
})
logger.info("Coach session persisted to SQLite: %s", session.sessionId)
except Exception as e:
logger.warning("Failed to persist session to SQLite: %s", e)
return path
def load_session(self, session_id: str) -> Optional[CoachSession]:
"""Load a coaching session from SQLite, falling back to disk."""
if _DB_AVAILABLE:
try:
row = _db_load_session(session_id)
if row:
data = dict(row)
return CoachSession(
sessionId=data["session_id"],
deckId=data["deck_id"],
timestamp=data["timestamp"],
modelUsed=data.get("model_used", ""),
promptTokens=data.get("prompt_tokens", 0),
completionTokens=data.get("completion_tokens", 0),
summary=data.get("summary", ""),
goals=json.loads(data["goals_json"]) if data.get("goals_json") and data["goals_json"] != "{}" else None,
suggestedCuts=[SuggestedCut(**c) for c in json.loads(data.get("cuts_json", "[]"))],
suggestedAdds=[SuggestedAdd(**a) for a in json.loads(data.get("adds_json", "[]"))],
heuristicHints=json.loads(data.get("heuristic_hints_json", "[]")),
manaBaseAdvice=data.get("mana_base_advice", ""),
rawTextExplanation=data.get("raw_text", ""),
)
except Exception as e:
logger.warning("SQLite load failed for %s: %s", session_id, e)
"""Load a coaching session from disk."""
path = COACH_SESSIONS_DIR / f"{session_id}.json"
if not path.exists():
return None
try:
with open(path, "r", encoding="utf-8") as f:
with open(path, "r") as f:
data = json.load(f)
return CoachSession(**data)
except Exception as e:
@@ -155,20 +101,13 @@ class CoachService:
return None
def list_sessions(self, deck_id: str = None) -> List[dict]:
"""List coaching sessions from SQLite, falling back to disk."""
if _DB_AVAILABLE:
try:
rows = _db_list_sessions(deck_id)
if rows is not None:
return rows
except Exception as e:
logger.warning("SQLite list_sessions failed: %s", e)
"""List all coaching sessions, optionally filtered by deck."""
if not COACH_SESSIONS_DIR.exists():
return []
sessions = []
for f in sorted(COACH_SESSIONS_DIR.glob("*.json"), reverse=True):
try:
with open(f, "r", encoding="utf-8") as fh:
with open(f, "r") as fh:
data = json.load(fh)
if deck_id and data.get("deckId", "") != deck_id:
continue
@@ -184,23 +123,23 @@ class CoachService:
continue
return sessions
# ── Main Coaching Pipeline ───────────────────────
async def run_coaching_session(
self,
deck_id: str,
goals: Optional[CoachGoals] = None,
fallback_report: Optional[DeckReport] = None,
) -> CoachSession:
# ── Main Coaching Pipeline ─────────────────────────────────
async def run_coaching_session(self, deck_id: str,
goals: Optional[CoachGoals] = None,
fallback_report: Optional[DeckReport] = None,
) -> CoachSession:
"""
Full coaching pipeline:
1. Load deck report (or use fallback from DB card list)
2. Identify underperformers
3. Find replacement candidates via embeddings
4. Build prompt
5. Call LLM (streaming for Anthropic to avoid 10-min SDK timeout)
5. Call LLM
6. Parse response
7. Persist session
"""
# 0. Auto-load embeddings if not loaded
if not self.embeddings.loaded:
logger.info("Embeddings not loaded — attempting auto-load...")
try:
@@ -212,6 +151,7 @@ class CoachService:
except Exception as e:
logger.warning("Embeddings auto-load failed: %s", e)
# 1. Load deck report — try simulation report first, then fallback
report = self.load_deck_report(deck_id)
if report is None and fallback_report is not None:
report = fallback_report
@@ -219,17 +159,25 @@ class CoachService:
if report is None:
raise ValueError(f"Deck report not found for: {deck_id}")
# 2. Get deck card names (for exclusion from candidates)
deck_card_names = [c.name for c in report.cards]
# 3. Find replacement candidates for underperformers
candidates: Dict[str, List[dict]] = {}
underperformers = report.underperformers[:MAX_UNDERPERFORMERS]
if not underperformers:
# If no explicit underperformers, pick lowest impact cards
sorted_cards = sorted(report.cards, key=lambda c: c.impactScore)
underperformers = [
c.name for c in sorted_cards[:MAX_UNDERPERFORMERS]
if c.impactScore < UNDERPERFORMER_IMPACT_THRESHOLD
]
# If still no underperformers and we have cards, pick bottom N by impact
if not underperformers and report.cards:
sorted_cards = sorted(report.cards, key=lambda c: c.impactScore)
# Take the bottom 5 non-land cards as candidates for cuts
underperformers = [
c.name for c in sorted_cards[:5]
if not any(t in (c.tags or []) for t in [])
@@ -248,81 +196,17 @@ class CoachService:
else:
logger.warning("Embeddings not loaded — skipping candidate search")
# Phase 4a: behavior-aware RAG — primary + replacement-effect secondary query
rag_cards: List[dict] = []
try:
from services.rag_store import query_cards
# Primary: commander synergy context
base_query = f"{report.commander} {' '.join(report.colorIdentity)} commander deck"
rag_cards = query_cards(base_query, n_results=10, color_identity=report.colorIdentity)
# Secondary: replacement effects / graveyard hate / protection
if len(rag_cards) < 15:
repl_cards = query_cards(
f"replacement effect graveyard {' '.join(report.colorIdentity)}",
n_results=5,
color_identity=report.colorIdentity,
require_replacement=True,
)
# Deduplicate by name before merging
existing_names = {c["name"] for c in rag_cards}
rag_cards += [c for c in repl_cards if c["name"] not in existing_names]
logger.info("RAG returned %d cards for '%s'", len(rag_cards), deck_id)
except Exception as e:
logger.warning("RAG query failed (non-fatal): %s", e)
# Phase 4b: rules context for grounding the coach prompt
rules_context: List[dict] = []
try:
from services.rag_store import query_rules
rules_context = query_rules(
f"Commander rules {report.commander} {' '.join(report.colorIdentity)}",
n_results=3,
)
except Exception:
pass
# 4. Build prompts
system_prompt = build_system_prompt(report, goals)
user_prompt = build_user_prompt(report, candidates, rag_cards=rag_cards, rules_context=rules_context)
logger.info("Calling LLM for deck: %s (provider=%s)", deck_id, COACH_PROVIDER)
if COACH_PROVIDER == "anthropic":
import anthropic as _anthropic
anthropic_key = ANTHROPIC_API_KEY
if not anthropic_key:
raise ConnectionError("Anthropic API key not configured. Set ANTHROPIC_API_KEY env var.")
aclient = _anthropic.AsyncAnthropic(api_key=anthropic_key)
async with aclient.messages.stream(
model=ANTHROPIC_MODEL,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}],
max_tokens=DEFAULT_MAX_TOKENS,
temperature=0.7,
) as stream:
content = await stream.get_final_text()
final_msg = await stream.get_final_message()
usage = getattr(final_msg, "usage", None)
from types import SimpleNamespace
llm_response = SimpleNamespace(
content=content,
model=final_msg.model,
prompt_tokens=usage.input_tokens if usage else 0,
completion_tokens=usage.output_tokens if usage else 0,
parsed_json=None,
)
try:
cleaned = re.sub(r'^```(?:json)?\s*', '', content.strip())
cleaned = re.sub(r'\s*```$', '', cleaned.strip())
llm_response.parsed_json = json.loads(cleaned)
except (json.JSONDecodeError, ValueError):
match = re.search(r'\{[\s\S]*\}', content)
if match:
try:
llm_response.parsed_json = json.loads(match.group(0))
except json.JSONDecodeError:
pass
else:
llm_response = await self.llm.chat(system_prompt, user_prompt)
user_prompt = build_user_prompt(report, candidates)
# 5. Call LLM
logger.info("Calling LLM for deck: %s", deck_id)
llm_response = await self.llm.chat(system_prompt, user_prompt)
# 6. Parse response into CoachSession
session_id = f"sess-{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:6]}"
session = CoachSession(
sessionId=session_id,
deckId=deck_id,
@@ -332,109 +216,31 @@ class CoachService:
completionTokens=llm_response.completion_tokens,
goals=goals,
)
if llm_response.parsed_json:
self._populate_session_from_json(session, llm_response.parsed_json)
else:
# Fallback: store raw text
session.rawTextExplanation = llm_response.content
session.summary = "LLM returned non-JSON response. See raw explanation."
# 7. Persist
self.save_session(session)
logger.info("Coaching session saved: %s", session_id)
return session
# ── Quick Digest ──────────────────────────────
async def run_quick_digest(
self,
deck_id: str,
goals: Optional[CoachGoals] = None,
fallback_report: Optional[DeckReport] = None,
) -> CoachSession:
"""Fast ~400-600 token call: summary + top 3 upgradePriority + commanderDependency."""
report = self.load_deck_report(deck_id)
if report is None and fallback_report is not None:
report = fallback_report
if report is None:
raise ValueError(f"Deck report not found for: {deck_id}")
# Phase 4a: light RAG query for quick digest
rag_cards: List[dict] = []
try:
from services.rag_store import query_cards
query_text = f"{report.commander} {' '.join(report.colorIdentity)}"
rag_cards = query_cards(query_text, n_results=8, color_identity=report.colorIdentity)
except Exception:
pass
from .prompt_template import build_quick_system_prompt, build_user_prompt
system_prompt = build_quick_system_prompt(report, goals)
user_prompt = build_user_prompt(report, {}, rag_cards=rag_cards) # no candidates for speed
logger.info("Quick digest for deck: %s (provider=%s)", deck_id, COACH_PROVIDER)
if COACH_PROVIDER == "anthropic":
import anthropic as _anthropic
anthropic_key = ANTHROPIC_API_KEY
if not anthropic_key:
raise ConnectionError("Anthropic API key not configured.")
aclient = _anthropic.AsyncAnthropic(api_key=anthropic_key)
async with aclient.messages.stream(
model=ANTHROPIC_MODEL,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}],
max_tokens=1024,
temperature=0.5,
) as stream:
content = await stream.get_final_text()
final_msg = await stream.get_final_message()
usage = getattr(final_msg, "usage", None)
from types import SimpleNamespace
llm_response = SimpleNamespace(
content=content,
model=final_msg.model,
prompt_tokens=usage.input_tokens if usage else 0,
completion_tokens=usage.output_tokens if usage else 0,
parsed_json=None,
)
try:
cleaned = re.sub(r'^```(?:json)?\s*', '', content.strip())
cleaned = re.sub(r'\s*```$', '', cleaned.strip())
llm_response.parsed_json = json.loads(cleaned)
except (json.JSONDecodeError, ValueError):
match = re.search(r'\{[\s\S]*\}', content)
if match:
try:
llm_response.parsed_json = json.loads(match.group(0))
except json.JSONDecodeError:
pass
else:
llm_response = await self.llm.chat(system_prompt, user_prompt)
session_id = f"quick-{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}-{uuid.uuid4().hex[:6]}"
session = CoachSession(
sessionId=session_id,
deckId=deck_id,
timestamp=datetime.now(timezone.utc).isoformat(),
modelUsed=llm_response.model,
promptTokens=llm_response.prompt_tokens,
completionTokens=llm_response.completion_tokens,
goals=goals,
isQuickDigest=True,
)
if llm_response.parsed_json:
self._populate_session_from_json(session, llm_response.parsed_json)
else:
session.rawTextExplanation = llm_response.content
session.summary = "Quick digest returned non-JSON. See raw explanation."
self.save_session(session)
return session
# ── JSON Parser ───────────────────────────────
def _populate_session_from_json(self, session: CoachSession, data: dict):
"""Parse LLM JSON response into CoachSession fields."""
session.summary = data.get("summary", "")
session.rawTextExplanation = data.get("rawTextExplanation", "")
session.manaBaseAdvice = data.get("manaBaseAdvice")
# Heuristic hints
hints = data.get("heuristicHints", [])
session.heuristicHints = hints if isinstance(hints, list) else [str(hints)]
# Suggested cuts
for cut_data in data.get("suggestedCuts", []):
if isinstance(cut_data, dict):
session.suggestedCuts.append(SuggestedCut(
@@ -442,6 +248,8 @@ class CoachService:
reason=cut_data.get("reason", ""),
replacementOptions=cut_data.get("replacementOptions", []),
))
# Suggested adds
for add_data in data.get("suggestedAdds", []):
if isinstance(add_data, dict):
session.suggestedAdds.append(SuggestedAdd(
@@ -450,112 +258,26 @@ class CoachService:
reason=add_data.get("reason", ""),
synergyWith=add_data.get("synergyWith", []),
))
for item in data.get("upgradePriority", []):
if isinstance(item, dict):
session.upgradePriority.append(UpgradePriorityItem(
rank=item.get("rank", 0),
cut=item.get("cut", ""),
add=item.get("add", ""),
reasoning=item.get("reasoning", ""),
expectedImpact=item.get("expectedImpact", ""),
))
cd = data.get("commanderDependency")
if isinstance(cd, dict):
session.commanderDependency = CommanderDependency(
score=cd.get("score", 5),
dependentCards=cd.get("dependentCards", []),
recoveryPlan=cd.get("recoveryPlan", ""),
)
ma = data.get("mulliganAnalysis")
if isinstance(ma, dict):
session.mulliganAnalysis = MulliganAnalysis(
estimatedKeepRate=ma.get("estimatedKeepRate", ""),
worstOffenders=ma.get("worstOffenders", []),
recommendation=ma.get("recommendation", ""),
)
rc = data.get("removalCoverage")
if isinstance(rc, dict):
session.removalCoverage = RemovalCoverage(**{
k: rc.get(k, "" if k != "gaps" else [])
for k in ["creatures", "artifacts", "enchantments", "planeswalkers", "lands", "massRemoval", "gaps"]
})
rq = data.get("rampQuality")
if isinstance(rq, dict):
session.rampQuality = RampQuality(**{
k: rq.get(k, "") for k in ["manaRocks", "landFetch", "manaDorks", "costReducers", "fragility", "canReachFourByTurnThree"]
})
dep = data.get("drawEngineProfile")
if isinstance(dep, dict):
session.drawEngineProfile = DrawEngineProfile(
burstDraw=dep.get("burstDraw", []),
repeatableEngines=dep.get("repeatableEngines", []),
assessment=dep.get("assessment", ""),
sustainability=dep.get("sustainability", ""),
)
for wc in data.get("winConditions", []):
if isinstance(wc, dict):
session.winConditions.append(WinCondition(
name=wc.get("name", ""),
cards=wc.get("cards", []),
independence=wc.get("independence", ""),
description=wc.get("description", ""),
))
for af in data.get("antiSynergyFlags", []):
if isinstance(af, dict):
session.antiSynergyFlags.append(AntiSynergyFlag(
cards=af.get("cards", []),
conflict=af.get("conflict", ""),
severity=af.get("severity", ""),
))
pp = data.get("podPresence")
if isinstance(pp, dict):
session.podPresence = PodPresence(
threatLevel=pp.get("threatLevel", ""),
politicalTools=pp.get("politicalTools", []),
adversarialRating=pp.get("adversarialRating", ""),
recommendation=pp.get("recommendation", ""),
)
ta = data.get("tempoAssessment")
if isinstance(ta, dict):
session.tempoAssessment = TempoAssessment(
peakTurn=ta.get("peakTurn", 0),
profile=ta.get("profile", ""),
survivalWindow=ta.get("survivalWindow", ""),
assessment=ta.get("assessment", ""),
)
for mm in data.get("metaMatchups", []):
if isinstance(mm, dict):
session.metaMatchups.append(MetaMatchup(
archetype=mm.get("archetype", ""),
assessment=mm.get("assessment", ""),
keyThreats=mm.get("keyThreats", []),
keyAnswers=mm.get("keyAnswers", []),
overallRating=mm.get("overallRating", ""),
))
# ── Status Check ──────────────────────────────
# ── Status Check ───────────────────────────────────────────
def get_status(self) -> CoachStatus:
"""Check the health of all coach subsystems."""
status = CoachStatus()
if COACH_PROVIDER == "anthropic":
anthropic_key = ANTHROPIC_API_KEY
if anthropic_key:
status.llmConnected = True
status.llmModel = f"Claude Opus ({ANTHROPIC_MODEL})"
status.llmModels = [ANTHROPIC_MODEL]
else:
status.llmConnected = False
status.llmModel = None
status.llmModels = []
status.error = "Anthropic API key not configured. Set ANTHROPIC_API_KEY env var."
else:
llm_status = self.llm.check_connection_sync() # FARMHOUSE_COACH_STATUS_V1 (was an un-awaited coroutine)
status.llmConnected = llm_status.get("connected", False)
status.llmModel = llm_status.get("active_model")
status.llmModels = llm_status.get("models", [])
if not status.llmConnected:
status.error = llm_status.get("error", "Local LLM not reachable")
# Check LLM
llm_status = self.llm.check_connection()
status.llmConnected = llm_status.get("connected", False)
status.llmModel = llm_status.get("active_model")
status.llmModels = llm_status.get("models", [])
if not status.llmConnected:
status.error = llm_status.get("error", "LM Studio not reachable")
# Check embeddings
status.embeddingsLoaded = self.embeddings.loaded
status.embeddingCards = self.embeddings.card_count
# Check deck reports
status.deckReportsAvailable = len(self.list_deck_reports())
return status
+31 -35
View File
@@ -1,67 +1,63 @@
"""
Commander AI Lab — Coach Configuration
────────────────────────────────────────
Central config for Ollama, embeddings, and coach service paths.
═══════════════════════════════════════
Central config for LM Studio, embeddings, and coach service paths.
All paths are relative to the commander-ai-lab root directory.
"""
import os
from pathlib import Path
# ── Base Paths ───────────────────────────────────────────────────────
# ── Base Paths ──────────────────────────────────────────────
# Resolve relative to wherever the lab is installed
LAB_ROOT = Path(os.environ.get("COMMANDER_LAB_ROOT", Path(__file__).parent.parent))
# ── Ollama (OpenAI-compatible API) ────────────────────────────
LLM_URL = os.environ.get("LLM_URL", "http://localhost:11434/v1")
LLM_MODEL = os.environ.get("LLM_MODEL", "claude-opus-4-20250514")
LLM_TIMEOUT = int(os.environ.get("LLM_TIMEOUT", "360")) # seconds
LLM_MAX_RETRIES = 3
# ── LM Studio (OpenAI-compatible API) ──────────────────────
LM_STUDIO_URL = os.environ.get("LM_STUDIO_URL", "http://192.168.0.122:1234/v1")
LM_STUDIO_MODEL = os.environ.get("LM_STUDIO_MODEL", "local-model")
LM_STUDIO_TIMEOUT = int(os.environ.get("LM_STUDIO_TIMEOUT", "120")) # seconds
LM_STUDIO_MAX_RETRIES = 3
# ── Embeddings ───────────────────────────────────────────────────
# ── Embeddings ─────────────────────────────────────────────
EMBEDDINGS_DIR = LAB_ROOT / "data"
EMBEDDINGS_NPZ = EMBEDDINGS_DIR / "mtg-embeddings.npz"
EMBEDDINGS_PARQUET = EMBEDDINGS_DIR / "mtg-embeddings.parquet"
# ── Deck Reports ────────────────────────────────────────────────
# ── Deck Reports ───────────────────────────────────────────
DECK_REPORTS_DIR = LAB_ROOT / "deck-reports"
COACH_SESSIONS_DIR = LAB_ROOT / "coach-sessions"
# ── Prompt Limits ───────────────────────────────────────────────
MAX_PROMPT_TOKENS = 2048
MAX_CANDIDATES_PER_UNDERPERFORMER = 8
MAX_UNDERPERFORMERS = 8
# ── Prompt Limits ──────────────────────────────────────────
MAX_PROMPT_TOKENS = 4096
MAX_CANDIDATES_PER_UNDERPERFORMER = 10
MAX_UNDERPERFORMERS = 8
UNDERPERFORMER_IMPACT_THRESHOLD = -0.05 # impactScore below this = underperformer
# ── LLM Generation Settings (Coach — Ollama fallback) ─────────────
# ── LLM Generation Settings (Coach — LM Studio) ──────────────
DEFAULT_TEMPERATURE = 0.7
DEFAULT_MAX_TOKENS = 16384
# DeepSeek-R1 uses <think> reasoning tokens before the JSON output,
# so we need a generous limit to avoid truncation
DEFAULT_MAX_TOKENS = 8192
# ── Anthropic Claude Deck Generation Settings ──────────────────────
# Provider for deck generation: "anthropic" (Claude) or "local" (Ollama)
DECK_GEN_PROVIDER = os.environ.get("DECK_GEN_PROVIDER", "anthropic")
# Model used when DECK_GEN_PROVIDER="anthropic"
DECK_GEN_MODEL = os.environ.get("DECK_GEN_MODEL", "claude-opus-4-20250514")
# Anthropic API key
ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")
# Anthropic model for deck generation and coaching
ANTHROPIC_MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-opus-4-20250514")
# Coach chat provider: "anthropic" (Claude API) or "local" (Ollama)
COACH_PROVIDER = os.environ.get("COACH_PROVIDER", "anthropic")
DECK_GEN_BASE_URL = os.environ.get("DECK_GEN_BASE_URL", "http://localhost:11434/v1")
# ── Perplexity Deck Generation Settings ───────────────────────
# Provider for deck generation: "perplexity" (V3) or "local" (V2 collection-based)
DECK_GEN_PROVIDER = os.environ.get("DECK_GEN_PROVIDER", "perplexity")
# Model for deck generation (sonar = fast/$0.004, sonar-pro = deep/$0.04)
DECK_GEN_MODEL = os.environ.get("DECK_GEN_MODEL", "sonar")
DECK_GEN_TEMPERATURE = float(os.environ.get("DECK_GEN_TEMPERATURE", "0.2"))
DECK_GEN_MAX_TOKENS = int(os.environ.get("DECK_GEN_MAX_TOKENS", "16384"))
# ── Smart Substitution Settings ───────────────────────────────────
# Minimum embedding similarity to accept a substitute without Anthropic fallback
# ── Smart Substitution Settings ───────────────────────────────
# Minimum embedding similarity to accept a substitute without Perplexity fallback
SUBSTITUTION_MIN_SIMILARITY = float(os.environ.get("SUBSTITUTION_MIN_SIMILARITY", "0.75"))
# Maximum number of alternatives to suggest per missing card
SUBSTITUTION_MAX_ALTERNATIVES = int(os.environ.get("SUBSTITUTION_MAX_ALTERNATIVES", "5"))
# Model for substitution fallback (claude-haiku-4-5 is fast + cheap for focused queries)
SUBSTITUTION_MODEL = os.environ.get("SUBSTITUTION_MODEL", "claude-haiku-4-5")
# Enable Anthropic fallback for low-confidence embedding matches
SUBSTITUTION_USE_ANTHROPIC_FALLBACK = os.environ.get("SUBSTITUTION_USE_ANTHROPIC_FALLBACK", "true").lower() == "true"
# Model for substitution fallback (sonar is fine — small focused queries)
SUBSTITUTION_MODEL = os.environ.get("SUBSTITUTION_MODEL", "sonar")
# Enable Perplexity fallback for low-confidence embedding matches
SUBSTITUTION_USE_PPLX_FALLBACK = os.environ.get("SUBSTITUTION_USE_PPLX_FALLBACK", "true").lower() == "true"
# ── Ensure directories exist ─────────────────────────────────────
# ── Ensure directories exist ───────────────────────────────
def ensure_dirs():
"""Create required directories if they don't exist."""
EMBEDDINGS_DIR.mkdir(parents=True, exist_ok=True)
+41 -229
View File
@@ -9,11 +9,6 @@ Data source: https://huggingface.co/datasets/minimaxir/mtg-embeddings
Format: Parquet with 768-dim float32 embeddings per card (~32K cards)
Model: Alibaba-NLP/gte-modernbert-base
Unknown cards (e.g. newly printed sets) are fetched from Scryfall,
embedded on-the-fly using the same model, and persisted to a local
custom cache (embeddings/mtg_embeddings_custom.npz) so they survive
restarts without re-hitting Scryfall.
Uses NumPy brute-force cosine similarity — fast enough for ~32K cards (<100ms).
"""
@@ -24,11 +19,9 @@ import os
from pathlib import Path
from typing import List, Optional, Tuple
from urllib.request import urlopen, Request
from urllib.parse import quote
import numpy as np
from services.card_text import build_card_text
from .config import EMBEDDINGS_DIR, EMBEDDINGS_NPZ, EMBEDDINGS_PARQUET
logger = logging.getLogger("coach.embeddings")
@@ -39,16 +32,8 @@ HF_PARQUET_URL = (
"resolve/main/mtg_embeddings.parquet"
)
# ── Scryfall API ───────────────────────────────────────────
SCRYFALL_NAMED_URL = "https://api.scryfall.com/cards/named?fuzzy={}"
# ── Custom cache for on-the-fly embedded cards ─────────────
CUSTOM_CACHE_PATH = EMBEDDINGS_DIR / "mtg_embeddings_custom.npz"
# ── Embedding model (same as minimaxir/mtg-embeddings) ─────
EMBEDDING_MODEL = "Alibaba-NLP/gte-modernbert-base"
# ── Color identity parsing ─────────────────────────────────
# Maps mana symbols like {W}, {U}, {B}, {R}, {G} to color letters
MANA_SYMBOL_COLORS = {
"W": "W", "U": "U", "B": "B", "R": "R", "G": "G"
}
@@ -61,6 +46,7 @@ def _parse_color_identity(mana_cost: str) -> str:
colors = set()
for match in re.finditer(r'\{([WUBRG])\}', mana_cost or ""):
colors.add(match.group(1))
# Sort in WUBRG order
order = "WUBRG"
return "".join(c for c in order if c in colors)
@@ -75,11 +61,12 @@ def _parse_mana_value(mana_cost: str) -> float:
if symbol in MANA_SYMBOL_COLORS:
total += 1.0
elif symbol == "X":
pass
pass # X = 0 for CMC purposes
else:
try:
total += float(symbol)
except ValueError:
# Hybrid/phyrexian symbols count as 1
total += 1.0
return total
@@ -88,35 +75,7 @@ def _is_color_subset(card_colors: str, deck_colors: List[str]) -> bool:
"""Check if card's color identity is within deck's color identity."""
deck_set = set(deck_colors)
card_set = set(card_colors)
return card_set.issubset(deck_set) or len(card_set) == 0
def _fetch_scryfall_card(card_name: str) -> Optional[dict]:
"""Fetch card data from Scryfall by fuzzy name match.
Returns a dict with keys: name, mana_cost, type_line, oracle_text,
color_identity. Returns None on any error.
"""
url = SCRYFALL_NAMED_URL.format(quote(card_name))
try:
req = Request(url, headers={"User-Agent": "commander-ai-lab/1.0"})
with urlopen(req, timeout=10) as resp:
data = json.loads(resp.read().decode("utf-8"))
return {
"name": data.get("name", card_name),
"mana_cost": data.get("mana_cost", ""),
"type_line": data.get("type_line", ""),
"oracle_text": data.get("oracle_text", ""),
"color_identity": "".join(data.get("color_identity", [])),
}
except Exception as e:
logger.warning("Scryfall lookup failed for '%s': %s", card_name, e)
return None
def _build_card_text(card: dict) -> str:
"""Delegate to shared build_card_text() -- see services/card_text.py."""
return build_card_text(card)
return card_set.issubset(deck_set) or len(card_set) == 0 # colorless always allowed
class CardMatch:
@@ -155,17 +114,15 @@ class MTGEmbeddingIndex:
"""
def __init__(self):
self.names: np.ndarray = None
self.colors: np.ndarray = None
self.mana_values: np.ndarray = None
self.types: np.ndarray = None
self.mana_costs: np.ndarray = None
self.texts: np.ndarray = None
self.vectors: np.ndarray = None
self.names: np.ndarray = None # (N,) string array
self.colors: np.ndarray = None # (N,) string array (e.g., "WU", "BRG")
self.mana_values: np.ndarray = None # (N,) float array
self.types: np.ndarray = None # (N,) string array
self.mana_costs: np.ndarray = None # (N,) string array
self.texts: np.ndarray = None # (N,) string array
self.vectors: np.ndarray = None # (N, 768) float32, L2-normalized
self._name_to_idx: dict = {}
self._loaded = False
self._sentence_model = None # lazy-loaded only when needed
self._custom_dirty = False # tracks whether custom cache needs saving
@property
def loaded(self) -> bool:
@@ -195,7 +152,10 @@ class MTGEmbeddingIndex:
return EMBEDDINGS_PARQUET
def convert_parquet_to_npz(self) -> Path:
"""Convert the Parquet file to a compact NPZ for fast loading."""
"""
Convert the Parquet file to a compact NPZ for fast loading.
Requires pandas and pyarrow.
"""
try:
import pandas as pd
except ImportError:
@@ -209,11 +169,14 @@ class MTGEmbeddingIndex:
types = df["type"].fillna("").values.astype(str)
texts = df["text"].fillna("").values.astype(str)
# Parse color identities from mana costs
colors = np.array([_parse_color_identity(mc) for mc in mana_costs])
mana_values = np.array([_parse_mana_value(mc) for mc in mana_costs], dtype=np.float32)
# Extract embedding vectors
embeddings = np.vstack(df["embedding"].to_numpy()).astype(np.float32)
# L2 normalize for cosine similarity via dot product
norms = np.linalg.norm(embeddings, axis=1, keepdims=True)
norms[norms == 0] = 1.0
embeddings = embeddings / norms
@@ -235,27 +198,25 @@ class MTGEmbeddingIndex:
return EMBEDDINGS_NPZ
def load(self, force_download: bool = False) -> bool:
"""Load embeddings from NPZ (fast) or fall back to downloading
"""
Load embeddings from NPZ (fast) or fall back to downloading
and converting from Parquet.
"""
if self._loaded and not force_download:
return True
# Try NPZ first (fast path)
if EMBEDDINGS_NPZ.exists() and not force_download:
ok = self._load_npz()
else:
try:
self.download_parquet(force=force_download)
self.convert_parquet_to_npz()
ok = self._load_npz()
except Exception as e:
logger.error("Failed to load embeddings: %s", e)
return False
return self._load_npz()
if ok:
self._load_custom_cache()
return ok
# Download and convert
try:
self.download_parquet(force=force_download)
self.convert_parquet_to_npz()
return self._load_npz()
except Exception as e:
logger.error("Failed to load embeddings: %s", e)
return False
def _load_npz(self) -> bool:
"""Load from pre-built NPZ file."""
@@ -269,6 +230,7 @@ class MTGEmbeddingIndex:
self.texts = data.get("texts", np.array([""] * len(self.names)))
self.vectors = data["vectors"]
# Build name lookup
self._name_to_idx = {
name.lower(): i for i, name in enumerate(self.names)
}
@@ -279,168 +241,12 @@ class MTGEmbeddingIndex:
logger.error("Failed to load NPZ: %s", e)
return False
# ── Custom cache ──────────────────────────────────────────
def _load_custom_cache(self) -> None:
"""Merge on-the-fly embedded cards from the custom cache into the index."""
if not CUSTOM_CACHE_PATH.exists():
return
try:
data = np.load(str(CUSTOM_CACHE_PATH), allow_pickle=True)
c_names = data["names"]
# Only add cards that aren't already in the main index
new_mask = np.array(
[n.lower() not in self._name_to_idx for n in c_names]
)
if not new_mask.any():
return
self._append_cards(
c_names[new_mask],
data["colors"][new_mask],
data["mana_values"][new_mask],
data["types"][new_mask],
data["mana_costs"][new_mask],
data["texts"][new_mask],
data["vectors"][new_mask],
)
logger.info("Loaded %d custom-cached card embeddings", new_mask.sum())
except Exception as e:
logger.warning("Failed to load custom embedding cache: %s", e)
def _save_custom_cache(self) -> None:
"""Persist the custom cache NPZ (only cards not in the base dataset)."""
if not self._custom_dirty:
return
try:
EMBEDDINGS_DIR.mkdir(parents=True, exist_ok=True)
# Collect indices that correspond to custom-added cards
# We track these by loading the base count at load time — simpler:
# just re-save the full custom cache from CUSTOM_CACHE_PATH if it
# exists, merging with any new cards we've added this session.
existing_names: set = set()
existing: dict = {}
if CUSTOM_CACHE_PATH.exists():
try:
d = np.load(str(CUSTOM_CACHE_PATH), allow_pickle=True)
for n in d["names"]:
existing_names.add(n.lower())
except Exception:
pass
# Find names in our live index that aren't in the base NPZ
base_data = np.load(str(EMBEDDINGS_NPZ), allow_pickle=True)
base_names = set(n.lower() for n in base_data["names"])
custom_mask = np.array(
[n.lower() not in base_names for n in self.names]
)
if not custom_mask.any():
return
np.savez_compressed(
str(CUSTOM_CACHE_PATH),
names=self.names[custom_mask],
colors=self.colors[custom_mask],
mana_values=self.mana_values[custom_mask],
types=self.types[custom_mask],
mana_costs=self.mana_costs[custom_mask],
texts=self.texts[custom_mask],
vectors=self.vectors[custom_mask],
)
self._custom_dirty = False
logger.info("Saved custom embedding cache: %d cards", custom_mask.sum())
except Exception as e:
logger.warning("Failed to save custom embedding cache: %s", e)
def _append_cards(
self,
names: np.ndarray,
colors: np.ndarray,
mana_values: np.ndarray,
types: np.ndarray,
mana_costs: np.ndarray,
texts: np.ndarray,
vectors: np.ndarray,
) -> None:
"""Append new card arrays to the live in-memory index."""
start_idx = len(self.names)
self.names = np.concatenate([self.names, names])
self.colors = np.concatenate([self.colors, colors])
self.mana_values = np.concatenate([self.mana_values, mana_values])
self.types = np.concatenate([self.types, types])
self.mana_costs = np.concatenate([self.mana_costs, mana_costs])
self.texts = np.concatenate([self.texts, texts])
self.vectors = np.concatenate([self.vectors, vectors], axis=0)
for i, name in enumerate(names):
self._name_to_idx[name.lower()] = start_idx + i
# ── Sentence model (lazy) ─────────────────────────────────
def _get_sentence_model(self):
"""Lazy-load the sentence-transformers model on first cache miss."""
if self._sentence_model is None:
try:
from sentence_transformers import SentenceTransformer
logger.info("Loading embedding model %s (first cache miss)...", EMBEDDING_MODEL)
self._sentence_model = SentenceTransformer(EMBEDDING_MODEL)
logger.info("Embedding model loaded.")
except Exception as e:
logger.error("Failed to load SentenceTransformer: %s", e)
return None
return self._sentence_model
# ── On-the-fly Scryfall fallback ──────────────────────────
def _fetch_and_embed_card(self, card_name: str) -> Optional[np.ndarray]:
"""Fetch card from Scryfall, embed it, append to index, persist to cache.
Returns the L2-normalized embedding vector on success, None on failure.
"""
logger.info("Fetching unknown card from Scryfall: '%s'", card_name)
card_data = _fetch_scryfall_card(card_name)
if card_data is None:
return None
model = self._get_sentence_model()
if model is None:
return None
text = _build_card_text(card_data)
vec = model.encode(text, normalize_embeddings=True).astype(np.float32)
# Ensure shape (1, 768)
vec = vec.reshape(1, -1)
resolved_name = card_data["name"]
mana_cost = card_data.get("mana_cost", "")
color_identity = card_data.get("color_identity", "") or _parse_color_identity(mana_cost)
self._append_cards(
names=np.array([resolved_name]),
colors=np.array([color_identity]),
mana_values=np.array([_parse_mana_value(mana_cost)], dtype=np.float32),
types=np.array([card_data.get("type_line", "")]),
mana_costs=np.array([mana_cost]),
texts=np.array([card_data.get("oracle_text", "")]),
vectors=vec,
)
self._custom_dirty = True
self._save_custom_cache()
logger.info("Embedded and cached new card: '%s'", resolved_name)
return self.vectors[self._name_to_idx[resolved_name.lower()]]
# ── Public API ────────────────────────────────────────────
def get_card_vector(self, card_name: str) -> Optional[np.ndarray]:
"""Get the embedding vector for a card by name (case-insensitive).
On a cache miss, fetches from Scryfall and embeds on the fly.
"""
"""Get the embedding vector for a card by name (case-insensitive)."""
idx = self._name_to_idx.get(card_name.lower())
if idx is not None:
return self.vectors[idx]
# Cache miss — try Scryfall fallback
return self._fetch_and_embed_card(card_name)
return None
def search_similar(self, query_card: str,
color_filter: List[str] = None,
@@ -468,32 +274,38 @@ class MTGEmbeddingIndex:
query_vec = self.get_card_vector(query_card)
if query_vec is None:
logger.warning("Card not found in embeddings and Scryfall fallback failed: %s", query_card)
logger.warning("Card not found in embeddings: %s", query_card)
return []
# Compute similarities (dot product on normalized vectors = cosine similarity)
similarities = self.vectors @ query_vec
# Build exclusion set
exclude_set = set()
exclude_set.add(query_card.lower())
if exclude_cards:
exclude_set.update(name.lower() for name in exclude_cards)
# Filter and collect results
results = []
for idx in np.argsort(similarities)[::-1]:
name = str(self.names[idx])
if name.lower() in exclude_set:
continue
# Color filter
if color_filter:
card_colors = str(self.colors[idx])
if not _is_color_subset(card_colors, color_filter):
continue
# Type filter
if type_filter:
card_type = str(self.types[idx])
if type_filter.lower() not in card_type.lower():
continue
# Mana value range filter
if mana_range:
mv = float(self.mana_values[idx])
if mv < mana_range[0] or mv > mana_range[1]:
+140 -156
View File
@@ -1,25 +1,22 @@
"""
Commander AI Lab — Ollama LLM Client
Commander AI Lab — LM Studio Client
════════════════════════════════════
Fully async HTTP client targeting Ollama's OpenAI-compatible
/v1/chat/completions endpoint. Every network call uses
httpx.AsyncClient so it NEVER blocks the FastAPI event loop.
Async HTTP client targeting LM Studio's OpenAI-compatible
/v1/chat/completions endpoint. Includes retry logic for
non-JSON responses and configurable timeout.
"""
from __future__ import annotations
import json
import logging
import asyncio
from typing import Optional
import httpx
from urllib.request import urlopen, Request
from urllib.error import URLError
from .config import (
LLM_URL,
LLM_MODEL,
LLM_TIMEOUT,
LLM_MAX_RETRIES,
DEFAULT_TEMPERATURE,
DEFAULT_MAX_TOKENS,
LM_STUDIO_URL, LM_STUDIO_MODEL,
LM_STUDIO_TIMEOUT, LM_STUDIO_MAX_RETRIES,
DEFAULT_TEMPERATURE, DEFAULT_MAX_TOKENS,
)
logger = logging.getLogger("coach.llm")
@@ -27,15 +24,9 @@ logger = logging.getLogger("coach.llm")
class LLMResponse:
"""Parsed LLM response container."""
def __init__(
self,
content: str,
parsed_json: Optional[dict],
prompt_tokens: int,
completion_tokens: int,
model: str,
):
def __init__(self, content: str, parsed_json: Optional[dict],
prompt_tokens: int, completion_tokens: int,
model: str):
self.content = content
self.parsed_json = parsed_json
self.prompt_tokens = prompt_tokens
@@ -43,56 +34,43 @@ class LLMResponse:
self.model = model
class LLMClient:
class LMStudioClient:
"""
Fully async client for Ollama's OpenAI-compatible API.
Client for LM Studio's OpenAI-compatible API.
Usage:
client = LLMClient()
client = LMStudioClient()
response = await client.chat(system_prompt, user_prompt)
if response.parsed_json:
suggestions = response.parsed_json
"""
def __init__(
self,
base_url: str = None,
model: str = None,
timeout: int = None,
):
self.base_url = (base_url or LLM_URL).rstrip("/")
self.model = model or LLM_MODEL
self.timeout = timeout or LLM_TIMEOUT
self._resolved_model: Optional[str] = None
def __init__(self, base_url: str = None, model: str = None,
timeout: int = None):
self.base_url = (base_url or LM_STUDIO_URL).rstrip("/")
self.model = model or LM_STUDIO_MODEL
self.timeout = timeout or LM_STUDIO_TIMEOUT
self._resolved_model = None # actual model name from /models endpoint
# ── Model resolution ───────────────────────────────────────
async def _resolve_model(self) -> str:
"""Get the actual loaded model name from Ollama /models endpoint."""
def _resolve_model(self) -> str:
"""Get the actual loaded model name from LM Studio /models endpoint."""
if self._resolved_model:
return self._resolved_model
try:
status = await self.check_connection()
status = self.check_connection()
if status.get("connected") and status.get("active_model"):
self._resolved_model = self.model if self.model in (status.get("models") or []) else status["active_model"] # FARMHOUSE_MODEL_PIN_V1
logger.info("Resolved Ollama model: %s", self._resolved_model)
self._resolved_model = status["active_model"]
logger.info("Resolved LM Studio model: %s", self._resolved_model)
return self._resolved_model
except Exception:
pass
return self.model
# ── Request building ──────────────────────────────────────
async def _build_request_body(
self,
system_prompt: str,
user_prompt: str,
temperature: float,
max_tokens: int,
force_json: bool,
) -> dict:
model_name = await self._resolve_model()
body: dict = {
def _build_request_body(self, system_prompt: str, user_prompt: str,
temperature: float, max_tokens: int,
force_json: bool) -> dict:
model_name = self._resolve_model()
body = {
"model": model_name,
"messages": [
{"role": "system", "content": system_prompt},
@@ -101,35 +79,32 @@ class LLMClient:
"temperature": temperature,
"max_tokens": max_tokens,
}
# Only request JSON format if using a model that supports it
# Some models (esp. smaller ones) don't support response_format
if force_json:
body["response_format"] = {"type": "json_object"}
# FARMHOUSE_LLM_KNOBS_V1 (see patch_app.py)
import os as _fh_os
_fh_effort = _fh_os.environ.get("LLM_REASONING", "").strip()
if _fh_effort:
body["reasoning_effort"] = _fh_effort
_fh_cap = int(_fh_os.environ.get("LLM_MAX_TOKENS", "0") or 0)
if _fh_cap:
body["max_tokens"] = min(body["max_tokens"], _fh_cap)
return body
# ── Response parsing ──────────────────────────────────────
@staticmethod
def _strip_think_tags(text: str) -> str:
"""Remove DeepSeek-R1 <think>...</think> reasoning blocks."""
"""Remove DeepSeek-R1 <think>...</think> reasoning blocks from LLM output."""
import re
return re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL).strip()
# Remove all <think>...</think> blocks (greedy, handles multiline)
cleaned = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL)
return cleaned.strip()
@staticmethod
def _extract_json_object(text: str) -> Optional[dict]:
"""Find and parse the first complete JSON object via brace-counting."""
"""Find and parse the first complete JSON object in text.
Uses brace-counting to handle nested objects reliably."""
start = text.find('{')
if start == -1:
return None
depth = 0
in_string = False
escape_next = False
for i in range(start, len(text)):
ch = text[i]
if escape_next:
@@ -149,56 +124,66 @@ class LLMClient:
elif ch == '}':
depth -= 1
if depth == 0:
candidate = text[start : i + 1]
candidate = text[start:i+1]
try:
return json.loads(candidate)
except (json.JSONDecodeError, ValueError):
# Malformed — try next opening brace
next_start = text.find('{', start + 1)
if next_start != -1 and next_start < i:
start = next_start
depth = 1
return None
depth = 1 # we're already past this brace
return None
return None
def _parse_response(self, raw: dict) -> LLMResponse:
"""Extract content and usage from an OpenAI-format response."""
"""Extract content and usage from OpenAI-format response.
Handles DeepSeek-R1 <think> tags, markdown fences, and raw JSON."""
choice = raw.get("choices", [{}])[0]
content = choice.get("message", {}).get("content", "")
usage = raw.get("usage", {})
# Step 1: Strip <think>...</think> blocks (DeepSeek-R1)
cleaned = self._strip_think_tags(content)
parsed: Optional[dict] = None
# 1. Direct JSON parse
# Step 2: Try direct JSON parse on cleaned content
parsed = None
try:
parsed = json.loads(cleaned)
except (json.JSONDecodeError, TypeError):
pass
# 2. Markdown fences
# Step 3: Try extracting from markdown fences
if parsed is None and "```json" in cleaned:
try:
s = cleaned.index("```json") + 7
e = cleaned.index("```", s)
parsed = json.loads(cleaned[s:e].strip())
start = cleaned.index("```json") + 7
end = cleaned.index("```", start)
parsed = json.loads(cleaned[start:end].strip())
except (json.JSONDecodeError, ValueError, IndexError):
pass
if parsed is None and "```" in cleaned:
try:
s = cleaned.index("```") + 3
e = cleaned.index("```", s)
parsed = json.loads(cleaned[s:e].strip())
start = cleaned.index("```") + 3
end = cleaned.index("```", start)
parsed = json.loads(cleaned[start:end].strip())
except (json.JSONDecodeError, ValueError, IndexError):
pass
# 3. Brace-counting extraction
# Step 4: Brute-force — find the first valid JSON object in the text
if parsed is None:
parsed = self._extract_json_object(cleaned)
# 4. Fallback on original content
# Step 5: If still nothing, try on the original content (in case
# think-tag stripping was too aggressive)
if parsed is None and content != cleaned:
parsed = self._extract_json_object(content)
if parsed is not None:
logger.info("Successfully parsed JSON from LLM response")
else:
logger.warning(
"Could not extract JSON from LLM response (%d chars)", len(content)
)
logger.warning("Could not extract JSON from LLM response (%d chars)",
len(content))
return LLMResponse(
content=content,
parsed_json=parsed,
@@ -207,95 +192,94 @@ class LLMClient:
model=raw.get("model", self.model),
)
# ── Public API ─────────────────────────────────────────────
async def chat(
self,
system_prompt: str,
user_prompt: str,
temperature: float = None,
max_tokens: int = None,
force_json: bool = True,
) -> LLMResponse:
def chat_sync(self, system_prompt: str, user_prompt: str,
temperature: float = None, max_tokens: int = None,
force_json: bool = True) -> LLMResponse:
"""
Async chat call to Ollama. Retries up to LLM_MAX_RETRIES.
Never blocks the event loop — uses httpx.AsyncClient throughout.
Synchronous chat call to LM Studio.
Retries up to LM_STUDIO_MAX_RETRIES on failure or non-JSON response.
"""
temp = temperature if temperature is not None else DEFAULT_TEMPERATURE
tokens = max_tokens if max_tokens is not None else DEFAULT_MAX_TOKENS
body = await self._build_request_body(
system_prompt, user_prompt, temp, tokens, force_json
)
last_error: Optional[Exception] = None
for attempt in range(1, LLM_MAX_RETRIES + 1):
body = self._build_request_body(system_prompt, user_prompt,
temp, tokens, force_json)
last_error = None
for attempt in range(1, LM_STUDIO_MAX_RETRIES + 1):
try:
logger.info("LLM call attempt %d/%d", attempt, LLM_MAX_RETRIES)
async with httpx.AsyncClient(
timeout=httpx.Timeout(float(self.timeout))
) as client:
resp = await client.post(
f"{self.base_url}/chat/completions",
json=body,
headers={"Content-Type": "application/json"},
)
resp.raise_for_status()
raw = resp.json()
logger.info("LLM call attempt %d/%d", attempt, LM_STUDIO_MAX_RETRIES)
req = Request(
f"{self.base_url}/chat/completions",
data=json.dumps(body).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
with urlopen(req, timeout=self.timeout) as resp:
raw = json.loads(resp.read().decode("utf-8"))
result = self._parse_response(raw)
# If we need JSON and didn't get it, retry
if force_json and result.parsed_json is None:
logger.warning(
"Attempt %d: LLM returned non-JSON, retrying", attempt
)
logger.warning("Attempt %d: LLM returned non-JSON, retrying", attempt)
last_error = ValueError("Non-JSON response from LLM")
continue
return result
except httpx.HTTPStatusError as e:
logger.warning("Attempt %d HTTP error %s", attempt, e.response.status_code)
last_error = e
# 400 with json format → retry without response_format constraint
if e.response.status_code == 400 and force_json:
logger.warning("Got 400 — retrying without response_format")
force_json = False
body = await self._build_request_body(
system_prompt, user_prompt, temp, tokens, False
)
except Exception as e:
logger.warning("Attempt %d failed: %s", attempt, e)
last_error = e
if attempt < LLM_MAX_RETRIES:
import asyncio
await asyncio.sleep(2 * attempt)
# If 400 and we used json response_format, retry without it
error_str = str(e)
if "400" in error_str and force_json:
logger.warning("Got 400 — retrying without response_format constraint")
force_json = False
body = self._build_request_body(
system_prompt, user_prompt, temp, tokens, False)
if attempt < LM_STUDIO_MAX_RETRIES:
import time
time.sleep(2 * attempt) # Simple backoff
raise ConnectionError(
f"LLM call failed after {LLM_MAX_RETRIES} attempts: {last_error}"
f"LLM call failed after {LM_STUDIO_MAX_RETRIES} attempts: {last_error}"
)
def check_connection_sync(self) -> dict: # FARMHOUSE_LLM_SYNC_V1
"""Blocking version of check_connection (upstream called it and never defined it)."""
try:
_r = httpx.get(f"{self.base_url}/models", timeout=5.0, headers={"Content-Type": "application/json"})
_r.raise_for_status()
_ids = [m.get("id", "unknown") for m in _r.json().get("data", [])]
return {"connected": True, "models": _ids,
"active_model": self.model if self.model in _ids else (_ids[0] if _ids else self.model)}
except Exception as _e:
return {"connected": False, "error": str(_e), "models": [], "active_model": None}
async def chat(self, system_prompt: str, user_prompt: str,
temperature: float = None, max_tokens: int = None,
force_json: bool = True) -> LLMResponse:
"""
Async chat call — runs the sync call in a thread executor
so it doesn't block the FastAPI event loop.
"""
loop = asyncio.get_event_loop()
return await loop.run_in_executor(
None,
lambda: self.chat_sync(system_prompt, user_prompt,
temperature, max_tokens, force_json)
)
async def check_connection(self) -> dict:
"""Check if Ollama is reachable. Returns status dict."""
def check_connection(self) -> dict:
"""
Check if LM Studio is reachable. Returns status dict.
"""
try:
async with httpx.AsyncClient(timeout=httpx.Timeout(5.0)) as client:
resp = await client.get(
f"{self.base_url}/models",
headers={"Content-Type": "application/json"},
)
resp.raise_for_status()
data = resp.json()
models = data.get("data", [])
model_ids = [m.get("id", "unknown") for m in models]
return {
"connected": True,
"models": model_ids,
"active_model": model_ids[0] if model_ids else self.model,
}
req = Request(
f"{self.base_url}/models",
headers={"Content-Type": "application/json"},
method="GET",
)
with urlopen(req, timeout=5) as resp:
data = json.loads(resp.read().decode("utf-8"))
models = data.get("data", [])
model_ids = [m.get("id", "unknown") for m in models]
return {
"connected": True,
"models": model_ids,
"active_model": model_ids[0] if model_ids else self.model,
}
except Exception as e:
return {
"connected": False,
+17 -140
View File
@@ -4,9 +4,12 @@ Commander AI Lab — Coach Data Models
Pydantic v2 models for deck reports, coach requests/responses,
and coaching session persistence.
"""
from datetime import datetime
from typing import List, Optional, Dict
from pydantic import BaseModel, Field
# ══════════════════════════════════════════════════════════════
# Deck Report Models (mirrors Java DeckReport)
# ══════════════════════════════════════════════════════════════
@@ -14,16 +17,16 @@ from pydantic import BaseModel, Field
class CardPerformance(BaseModel):
"""Per-card aggregated stats from simulation data."""
name: str
drawnRate: float = 0.0
castRate: float = 0.0
drawnRate: float = 0.0 # Fraction of games where card was drawn
castRate: float = 0.0 # Fraction of games where drawn AND cast
keptInOpeningHandRate: float = 0.0
deadCardRate: float = 0.0
impactScore: float = 0.0
synergyScore: float = 0.0
clunkinessScore: float = 0.0
deadCardRate: float = 0.0 # Drawn but never cast/used
impactScore: float = 0.0 # (winRateWhenCast - overallWinRate) * castRate
synergyScore: float = 0.0 # Co-occurrence uplift with other deck cards
clunkinessScore: float = 0.0 # deadCardRate * (1 - castRate)
avgTurnCast: Optional[float] = None
avgDamageDealt: float = 0.0
tags: List[str] = Field(default_factory=list)
tags: List[str] = Field(default_factory=list) # ramp, draw, removal, etc.
class MatchupRecord(BaseModel):
@@ -45,7 +48,7 @@ class DeckMeta(BaseModel):
class DeckStructure(BaseModel):
"""Deck composition breakdown."""
landCount: int = 0
curveBuckets: List[int] = Field(default_factory=lambda: [0]*8)
curveBuckets: List[int] = Field(default_factory=lambda: [0]*8) # CMC 0-7+
cardTypeCounts: Dict[str, int] = Field(default_factory=dict)
functionalCounts: Dict[str, int] = Field(default_factory=dict)
@@ -54,7 +57,7 @@ class ComboRecord(BaseModel):
"""Known combo with performance data."""
cardNames: List[str]
winRateWhenAssembled: float = 0.0
assemblyRate: float = 0.0
assemblyRate: float = 0.0 # Fraction of games where all pieces drawn
class DeckReport(BaseModel):
@@ -81,10 +84,10 @@ class DeckReport(BaseModel):
class CoachGoals(BaseModel):
"""User-specified coaching goals."""
targetPowerLevel: Optional[int] = None
metaFocus: Optional[str] = None
budget: Optional[str] = None
focusAreas: List[str] = Field(default_factory=list)
targetPowerLevel: Optional[int] = None # 1-10
metaFocus: Optional[str] = None # aggro, control, combo, midrange, stax
budget: Optional[str] = None # budget, medium, no-limit
focusAreas: List[str] = Field(default_factory=list) # e.g., ["ramp", "card draw"]
class CoachRequest(BaseModel):
@@ -104,120 +107,12 @@ class SuggestedCut(BaseModel):
class SuggestedAdd(BaseModel):
"""A card the coach suggests adding."""
cardName: str
role: str = ""
role: str = "" # ramp, draw, removal, finisher, etc.
reason: str = ""
synergyWith: List[str] = Field(default_factory=list)
estimatedManaValue: Optional[float] = None
# ══════════════════════════════════════════════════════════════
# Phase 2: Structured Analysis Models
# ══════════════════════════════════════════════════════════════
class UpgradePriorityItem(BaseModel):
"""A single prioritized cut/add swap ranked by expected impact."""
rank: int
cut: str
add: str
reasoning: str = ""
expectedImpact: str = ""
class CommanderDependency(BaseModel):
"""How reliant the deck is on having the commander in play."""
score: int = 5
dependentCards: List[str] = Field(default_factory=list)
recoveryPlan: str = ""
class MulliganAnalysis(BaseModel):
"""Opening hand keepability assessment."""
estimatedKeepRate: str = ""
worstOffenders: List[str] = Field(default_factory=list)
recommendation: str = ""
# ══════════════════════════════════════════════════════════════
# Phase 3: Qualitative Analysis Models
# ══════════════════════════════════════════════════════════════
class RemovalCoverage(BaseModel):
"""Categorized removal package by permanent type."""
creatures: str = ""
artifacts: str = ""
enchantments: str = ""
planeswalkers: str = ""
lands: str = ""
massRemoval: str = ""
gaps: List[str] = Field(default_factory=list)
class RampQuality(BaseModel):
"""Ramp package breakdown by subtype and fragility."""
manaRocks: str = ""
landFetch: str = ""
manaDorks: str = ""
costReducers: str = ""
fragility: str = ""
canReachFourByTurnThree: str = ""
class DrawEngineProfile(BaseModel):
"""Card draw sustainability analysis."""
burstDraw: List[str] = Field(default_factory=list)
repeatableEngines: List[str] = Field(default_factory=list)
assessment: str = ""
sustainability: str = ""
class WinCondition(BaseModel):
"""A named win condition with independence rating."""
name: str
cards: List[str] = Field(default_factory=list)
independence: str = ""
description: str = ""
class AntiSynergyFlag(BaseModel):
"""An internal conflict between cards in the deck."""
cards: List[str] = Field(default_factory=list)
conflict: str = ""
severity: str = ""
# ══════════════════════════════════════════════════════════════
# Phase 5: Pod Politics & Meta Awareness Models
# ══════════════════════════════════════════════════════════════
class PodPresence(BaseModel):
"""Commander pod politics and threat assessment."""
threatLevel: str = "" # early/medium/late/low
politicalTools: List[str] = Field(default_factory=list)
adversarialRating: str = "" # low/medium/high
recommendation: str = ""
class TempoAssessment(BaseModel):
"""When the deck 'comes online' and whether that's fast enough."""
peakTurn: int = 0
profile: str = "" # early/mid/late
survivalWindow: str = "" # Assessment of whether it survives to peak
assessment: str = ""
class MetaMatchup(BaseModel):
"""Strategic reasoning about deck vs a meta archetype."""
archetype: str # fast-combo, stax, control, aggro, etc.
assessment: str = ""
keyThreats: List[str] = Field(default_factory=list)
keyAnswers: List[str] = Field(default_factory=list)
overallRating: str = "" # favored/even/unfavored
# ══════════════════════════════════════════════════════════════
# Coach Session (persisted result)
# ══════════════════════════════════════════════════════════════
class CoachSession(BaseModel):
"""
Complete coaching session result.
@@ -236,24 +131,6 @@ class CoachSession(BaseModel):
promptTokens: int = 0
completionTokens: int = 0
goals: Optional[CoachGoals] = None
isQuickDigest: bool = False # True for quick digest, False for full analysis
# Phase 2: Structured analysis fields
upgradePriority: List[UpgradePriorityItem] = Field(default_factory=list)
commanderDependency: Optional[CommanderDependency] = None
mulliganAnalysis: Optional[MulliganAnalysis] = None
# Phase 3: Qualitative analysis fields
removalCoverage: Optional[RemovalCoverage] = None
rampQuality: Optional[RampQuality] = None
drawEngineProfile: Optional[DrawEngineProfile] = None
winConditions: List[WinCondition] = Field(default_factory=list)
antiSynergyFlags: List[AntiSynergyFlag] = Field(default_factory=list)
# Phase 5: Pod politics & meta
podPresence: Optional[PodPresence] = None
tempoAssessment: Optional[TempoAssessment] = None
metaMatchups: List[MetaMatchup] = Field(default_factory=list)
class ApplyRequest(BaseModel):
+41 -390
View File
@@ -4,24 +4,18 @@ Commander AI Lab — Coach Prompt Template
Constructs system and user prompts for the LLM coach.
Injects deck report data, underperformer analysis, and
candidate replacement cards into a structured template.
Phase 1 additions (#108):
- Sim Insights section: deck-level opening hand quality, curve velocity,
synergy outliers, and archetype weak spots surfaced directly in the
user prompt so Claude reasons from numbers, not vibes.
- _format_archetypes() annotates weak spots and strengths inline.
- _format_top_cards() adds keptInOpeningHandRate per card.
"""
import json
from typing import List, Dict, Optional
from .models import DeckReport, CoachGoals, CardPerformance
from .config import MAX_CANDIDATES_PER_UNDERPERFORMER, MAX_UNDERPERFORMERS
# ════════════════════════════════════════════════════════════
# ══════════════════════════════════════════════════════════════
# System Prompt
# ════════════════════════════════════════════════════════════
# ══════════════════════════════════════════════════════════════
SYSTEM_PROMPT_TEMPLATE = """You are an expert Magic: The Gathering Commander deck coach.
You analyze deck performance reports from simulation data and provide specific,
@@ -33,197 +27,44 @@ RULES:
- Base suggestions on the simulation data provided, not general "goodstuff" advice.
- Consider mana curve, role balance (ramp, draw, removal, threats), and synergy.
- When suggesting replacements, prefer cards that fill the same functional role.
- IMPORTANT: Suggest 5-8 DIFFERENT cards to cut and 5-8 DIFFERENT cards to add.
- IMPORTANT: Suggest 3-5 DIFFERENT cards to cut and 3-5 DIFFERENT cards to add.
- Each suggested add MUST be a different card — never suggest the same card twice.
- Vary your suggestions across different functional roles (ramp, draw, removal, threats, utility).
- If the deck is missing a functional role (e.g., no card draw, no removal), prioritize adding cards for that role.
- If candidate replacements are provided from embeddings search, prefer those over generic suggestions.
- For each suggested cut, provide a DETAILED reason citing specific stats (impact score, cast rate, dead card rate, clunkiness, synergy score).
- For each suggested add, explain the SPECIFIC synergy with existing cards in the deck.
- When reasoning about cuts, also consider keptInOpeningHandRate (low = bad in opening hands) and avgTurnCast (high = too slow for the curve).
- When evaluating synergy, use the synergyScore: cards below 0.1 have weak co-occurrence with the rest of the deck.
- Use perArchetypeWinRates to identify which matchup types this deck struggles with and tailor suggestions accordingly.
- The Sim Insights section shows pre-computed deck-level signals — use these directly in your reasoning.
- Cards flagged as [OPENING HAND TRAP] have keptInOpeningHandRate below the deck average — treat as mulligan liabilities.
- Cards flagged as [LATE CASTER] have avgTurnCast > 6 — consider whether they fit the deck's tempo.
- Cards flagged as [ISOLATED] have synergyScore in the bottom 3 of the deck — they may not support the gameplan.
- Archetypes flagged as [WEAK SPOT] in the Archetype Win Rates section are where this deck loses most — prioritize fixes for those matchups.
- Provide at least 5 heuristic hints covering different strategic dimensions.
- Assess how dependent the deck is on the commander being in play.
- Evaluate opening hand quality and identify cards that cause bad mulligans.
- Rank your suggested swaps by priority so the user knows what to change first.
- Categorize the removal package by permanent type and flag coverage gaps.
- Evaluate the ramp package for fragility (creature/artifact-heavy vs land-based).
- Distinguish one-time draw from repeatable draw engines.
- Identify the top 3 win conditions and rate each for independence.
- Flag internal anti-synergies or card conflicts.
- Assess pod threat perception: does this deck draw too much hate too early?
- Evaluate when the deck comes online (tempo profile) and whether that's viable.
- Reason about matchups vs fast combo, stax/prison, and control archetypes.
{goals_section}
You MUST respond ONLY with valid JSON matching this exact structure:
{{
"summary": "4-6 sentence detailed overview of the deck's strengths, weaknesses, key synergies, and strategic identity. Reference specific win rates and simulation data.",
"summary": "2-3 sentence overview of the deck's strengths and weaknesses",
"suggestedCuts": [
{{
"cardName": "Card To Remove",
"reason": "Detailed explanation citing specific simulation stats (impact score, cast rate, dead card rate, clunkiness score, synergy score, avg turn cast) and why this card underperforms in this specific deck context",
"replacementOptions": ["Better Card 1", "Better Card 2"],
"functionalRole": "ramp|draw|removal|threat|utility|combo|protection",
"estimatedImpact": "How cutting this card is expected to improve the deck"
"reason": "Why this card underperforms",
"replacementOptions": ["Better Card 1", "Better Card 2"]
}}
],
"suggestedAdds": [
{{
"cardName": "Card To Add",
"role": "ramp|draw|removal|threat|utility|combo|protection",
"reason": "Detailed explanation of why this card improves the deck, referencing specific weaknesses it addresses",
"synergyWith": ["Card In Deck 1", "Card In Deck 2"],
"estimatedManaCost": "The mana value of the suggested card",
"strategicRationale": "How this card fits into the overall game plan and addresses a specific gap"
"reason": "Why this card improves the deck",
"synergyWith": ["Card In Deck 1", "Card In Deck 2"]
}}
],
"upgradePriority": [
{{
"rank": 1,
"cut": "Card to remove",
"add": "Card to add instead",
"reasoning": "Why this is the single highest-impact swap",
"expectedImpact": "high|medium|low"
}}
],
"commanderDependency": {{
"score": 5,
"dependentCards": ["Card that is nearly dead without commander"],
"recoveryPlan": "Strategy if the commander gets removed or tucked repeatedly"
}},
"mulliganAnalysis": {{
"estimatedKeepRate": "Percentage estimate of keepable 7-card hands, e.g. ~70%",
"worstOffenders": ["Card most responsible for unkeepable hands"],
"recommendation": "What to change to improve opening hand quality"
}},
"manaCurveAnalysis": {{
"currentAssessment": "Detailed analysis of the current mana curve distribution and its implications",
"recommendations": "Specific suggestions for curve adjustments with reasoning",
"idealRange": "What the curve should look like for this deck's strategy"
}},
"roleBreakdown": {{
"ramp": "Assessment of ramp package - count, quality, and suggestions",
"draw": "Assessment of card draw package",
"removal": "Assessment of removal package",
"threats": "Assessment of win conditions and threats",
"protection": "Assessment of protection and interaction"
}},
"synergyAnalysis": [
"Description of a key synergy chain in the deck and how well it performed in simulation"
],
"heuristicHints": [
"Detailed strategic tip explaining the reasoning and data behind the suggestion"
"Concise strategic tip based on data"
],
"manaBaseAdvice": "Specific mana base improvement suggestion including land count, color fixing, and utility lands, or null if mana base is solid",
"rawTextExplanation": "3-5 paragraph in-depth analysis covering: (1) overall deck strategy assessment and how well the deck executes its game plan based on simulation data, (2) mana curve and resource analysis with specific numbers including avgTurnCast for key cards, (3) card synergy evaluation highlighting the strongest and weakest interactions using synergyScore data, (4) meta considerations and matchup-specific insights referencing perArchetypeWinRates and the [WEAK SPOT] archetypes flagged in Sim Insights, and (5) prioritized list of improvements ranked by expected impact on win rate",
"removalCoverage": {{
"creatures": "Assessment of creature removal",
"artifacts": "Assessment of artifact removal",
"enchantments": "Assessment of enchantment removal",
"planeswalkers": "Assessment of planeswalker removal",
"lands": "Assessment of land destruction",
"massRemoval": "Assessment of board wipes",
"gaps": ["Permanent types with zero or weak coverage"]
}},
"rampQuality": {{
"manaRocks": "2-mana rocks, signets, etc.",
"landFetch": "Cultivate, Kodama's Reach, etc.",
"manaDorks": "Llanowar Elves, Birds, etc.",
"costReducers": "Medallions, Helm of Awakening, etc.",
"fragility": "Overall fragility assessment",
"canReachFourByTurnThree": "yes/no with reasoning"
}},
"drawEngineProfile": {{
"burstDraw": ["One-time draw spells"],
"repeatableEngines": ["Sustained draw engines"],
"assessment": "Overall draw quality",
"sustainability": "Whether draw is sustainable or burst-only"
}},
"winConditions": [
{{
"name": "Name of win condition",
"cards": ["Key cards involved"],
"independence": "high|medium|low",
"description": "How this win con functions"
}}
],
"antiSynergyFlags": [
{{
"cards": ["Card A", "Card B"],
"conflict": "Description of conflict",
"severity": "high|medium|low"
}}
],
"podPresence": {{
"threatLevel": "early|medium|late|low",
"politicalTools": ["Pillowfort or group effect cards"],
"adversarialRating": "low|medium|high",
"recommendation": "How to manage threat perception in a pod"
}},
"tempoAssessment": {{
"peakTurn": 5,
"profile": "early|mid|late",
"survivalWindow": "Assessment of whether the deck survives to its power window",
"assessment": "Overall tempo evaluation"
}},
"metaMatchups": [
{{
"archetype": "fast-combo|stax|control|aggro|midrange",
"assessment": "How the deck fares against this archetype",
"keyThreats": ["Cards/strategies that threaten this deck"],
"keyAnswers": ["Cards in the deck that answer this archetype"],
"overallRating": "favored|even|unfavored"
}}
]
"manaBaseAdvice": "Specific mana base improvement suggestion or null",
"rawTextExplanation": "Detailed paragraph explaining the analysis and reasoning"
}}
Do NOT include any text outside the JSON object. No markdown fences, no preamble."""
# ════════════════════════════════════════════════════════════
# Quick Digest Prompt
# ════════════════════════════════════════════════════════════
QUICK_DIGEST_SYSTEM_PROMPT = """You are an expert Magic: The Gathering Commander deck coach.
Provide a FAST summary analysis of this deck. Be concise.
RULES:
- NEVER suggest cutting the commander ({commander}).
- Only suggest cards within the deck's color identity: {color_identity}.
- Cards flagged [OPENING HAND TRAP] have low keptInOpeningHandRate — prime cut candidates.
- Cards flagged [WEAK SPOT] in archetype win rates show where the deck loses most.
{goals_section}
You MUST respond ONLY with valid JSON matching this exact structure:
{{
"summary": "3-sentence deck overview: what it does, main strength, main weakness.",
"upgradePriority": [
{{
"rank": 1,
"cut": "Card to remove",
"add": "Card to add instead",
"reasoning": "Why this is a high-impact swap",
"expectedImpact": "high|medium|low"
}}
],
"commanderDependency": {{
"score": 5,
"dependentCards": ["Card that is nearly dead without commander"],
"recoveryPlan": "Brief recovery strategy"
}}
}}
Do NOT include any text outside the JSON object. No markdown fences, no preamble."""
# ════════════════════════════════════════════════════════════
# User Prompt Template
# ════════════════════════════════════════════════════════════
# ══════════════════════════════════════════════════════════════
# User Prompt Builder
# ══════════════════════════════════════════════════════════════
USER_PROMPT_TEMPLATE = """## Deck Report: {deck_name}
Commander: {commander}
@@ -238,29 +79,19 @@ Avg Game Length: {avg_game_length:.1f} turns
- Card Types: {type_summary}
- Functional Roles: {role_summary}
### Sim Insights (pre-computed deck-level signals)
{sim_insights_section}
### Matchup Data
{matchup_section}
### Archetype Win Rates
{archetype_section}
### Top Performing Cards (by Impact Score)
{top_cards}
### Underperforming Cards (candidates for cuts)
{underperformer_section}
### RAG-Retrieved Similar Cards (from ChromaDB)
{rag_section}
### Candidate Replacement Cards (from embeddings search)
{candidate_section}
{combo_section}
Based on this simulation data, provide your coaching suggestions."""
@@ -268,6 +99,7 @@ def _format_goals_section(goals: Optional[CoachGoals]) -> str:
"""Format goals into system prompt rules."""
if not goals:
return "- Aim for a balanced, well-rounded deck."
lines = []
if goals.targetPowerLevel is not None:
lines.append(f"- Target power level: {goals.targetPowerLevel}/10.")
@@ -294,148 +126,42 @@ def _format_curve(buckets: List[int]) -> str:
def _format_top_cards(cards: List[CardPerformance], top_n: int = 10) -> str:
"""Format the best performing cards with extended stats.
Phase 1: adds keptInOpeningHandRate so Claude sees hand quality for
the good cards too, not just the underperformers.
"""
"""Format the best performing cards."""
sorted_cards = sorted(cards, key=lambda c: c.impactScore, reverse=True)
lines = []
for c in sorted_cards[:top_n]:
tags = f" [{', '.join(c.tags)}]" if c.tags else ""
turn_str = f", avgTurnCast={c.avgTurnCast:.1f}" if c.avgTurnCast is not None else ""
lines.append(
f"- {c.name}: impact={c.impactScore:.3f}, "
f"castRate={c.castRate:.1%}, drawnRate={c.drawnRate:.1%}, "
f"synergy={c.synergyScore:.3f}, "
f"keptInOpeningHand={c.keptInOpeningHandRate:.1%}"
f"{turn_str}{tags}"
)
lines.append(f"- {c.name}: impact={c.impactScore:.3f}, "
f"castRate={c.castRate:.1%}, drawnRate={c.drawnRate:.1%}{tags}")
return "\n".join(lines) if lines else "No card performance data available."
def _format_underperformers(cards: List[CardPerformance],
underperformer_names: List[str]) -> str:
"""Format underperforming cards with full available stats."""
"""Format underperforming cards with their stats."""
card_map = {c.name: c for c in cards}
lines = []
for name in underperformer_names[:MAX_UNDERPERFORMERS]:
c = card_map.get(name)
if c:
turn_str = f", avgTurnCast={c.avgTurnCast:.1f}" if c.avgTurnCast is not None else ""
flags = []
if c.keptInOpeningHandRate < 0.25:
flags.append("OPENING HAND TRAP")
if c.avgTurnCast is not None and c.avgTurnCast > 6:
flags.append("LATE CASTER")
if c.synergyScore < 0.1:
flags.append("ISOLATED")
flag_str = f" [{', '.join(flags)}]" if flags else ""
lines.append(
f"- {c.name}{flag_str}: impact={c.impactScore:.3f}, "
f"deadCardRate={c.deadCardRate:.1%}, "
f"castRate={c.castRate:.1%}, "
f"clunkiness={c.clunkinessScore:.3f}, "
f"synergy={c.synergyScore:.3f}, "
f"keptInOpeningHand={c.keptInOpeningHandRate:.1%}"
f"{turn_str}"
)
lines.append(f"- {c.name}: impact={c.impactScore:.3f}, "
f"deadCardRate={c.deadCardRate:.1%}, "
f"castRate={c.castRate:.1%}, "
f"clunkiness={c.clunkinessScore:.3f}")
else:
lines.append(f"- {name}: (no detailed stats)")
return "\n".join(lines) if lines else "No clear underperformers identified."
def _format_sim_insights(cards: List[CardPerformance],
archetype_rates: Dict[str, float]) -> str:
"""Compute and format deck-level sim signals for the Sim Insights section.
Phase 1 (#108): surfaces pre-computed per-card stats as deck-level
aggregates so Claude reasons from numbers directly.
Signals produced:
1. Opening hand quality — deck avg keptInOpeningHandRate + worst offenders
2. Curve velocity — castRate-weighted avg avgTurnCast + late-caster flags
3. Synergy outliers — bottom-3 synergyScore cards flagged as [ISOLATED]
4. Archetype weak spots — archetypes < 40% win rate flagged [WEAK SPOT]
"""
if not cards:
return "No simulation data available."
lines = []
# ── 1. Opening hand quality ───────────────────────────────────────────
hand_rates = [c.keptInOpeningHandRate for c in cards if c.keptInOpeningHandRate > 0]
if hand_rates:
avg_keep = sum(hand_rates) / len(hand_rates)
lines.append(f"Opening Hand Quality: deck avg keptInOpeningHandRate = {avg_keep:.1%}")
# Worst offenders: cards significantly below the deck average
threshold = avg_keep * 0.6 # >40% below avg is an outlier
offenders = sorted(
[c for c in cards if c.keptInOpeningHandRate > 0 and c.keptInOpeningHandRate < threshold],
key=lambda c: c.keptInOpeningHandRate
)[:3]
if offenders:
lines.append(" Opening hand traps (keptInOpeningHandRate far below deck avg):")
for c in offenders:
lines.append(f" - {c.name}: {c.keptInOpeningHandRate:.1%} [OPENING HAND TRAP]")
else:
lines.append("Opening Hand Quality: no keptInOpeningHandRate data available")
# ── 2. Curve velocity ───────────────────────────────────────────────
cast_cards = [c for c in cards if c.avgTurnCast is not None and c.castRate > 0]
if cast_cards:
total_weight = sum(c.castRate for c in cast_cards)
if total_weight > 0:
weighted_avg_turn = sum(
c.avgTurnCast * c.castRate for c in cast_cards
) / total_weight
lines.append(f"Curve Velocity: castRate-weighted avg avgTurnCast = {weighted_avg_turn:.1f}")
late_casters = sorted(
[c for c in cast_cards if c.avgTurnCast > 6],
key=lambda c: c.avgTurnCast,
reverse=True
)[:3]
if late_casters:
lines.append(" Late casters (avgTurnCast > 6 — may not fit the curve):")
for c in late_casters:
lines.append(f" - {c.name}: avgTurnCast={c.avgTurnCast:.1f} [LATE CASTER]")
else:
lines.append("Curve Velocity: no avgTurnCast data available")
# ── 3. Synergy outliers ──────────────────────────────────────────────
synergy_cards = sorted(
[c for c in cards if c.castRate > 0.05], # ignore near-never-cast cards
key=lambda c: c.synergyScore
)
if synergy_cards:
bottom3 = synergy_cards[:3]
lines.append("Synergy Outliers (lowest synergyScore among cast cards):")
for c in bottom3:
lines.append(f" - {c.name}: synergyScore={c.synergyScore:.3f} [ISOLATED]")
# ── 4. Archetype weak spots ──────────────────────────────────────────
if archetype_rates:
weak = {k: v for k, v in archetype_rates.items() if v < 0.40}
if weak:
lines.append("Archetype Weak Spots (win rate < 40%):")
for arch, wr in sorted(weak.items(), key=lambda x: x[1]):
lines.append(f" - vs {arch}: {wr:.1%} [WEAK SPOT]")
else:
lines.append("Archetype Weak Spots: none (all matchups >= 40% win rate)")
return "\n".join(lines) if lines else "No sim insights available."
def _format_candidates(candidates: Dict[str, List[dict]]) -> str:
"""Format replacement candidates grouped by the card they'd replace."""
if not candidates:
return (
"No embedding-based candidates available. "
"Use your MTG knowledge to suggest cards that fit the deck's "
"color identity, strategy, and missing functional roles. "
"Suggest at least 3 different cards across different roles "
"(ramp, draw, removal, threats, utility)."
)
return ("No embedding-based candidates available. "
"Use your MTG knowledge to suggest cards that fit the deck's "
"color identity, strategy, and missing functional roles. "
"Suggest at least 3 different cards across different roles "
"(ramp, draw, removal, threats, utility).")
lines = []
for underperformer, replacements in list(candidates.items())[:MAX_UNDERPERFORMERS]:
lines.append(f"\nReplacements for '{underperformer}':")
@@ -453,55 +179,14 @@ def _format_candidates(candidates: Dict[str, List[dict]]) -> str:
return "\n".join(lines)
def _format_rag_cards(rag_cards: List[dict]) -> str:
"""Format RAG-retrieved cards from ChromaDB vector search."""
if not rag_cards:
return "No RAG results available."
lines = []
for card in rag_cards[:15]:
name = card.get("name", "Unknown")
types = card.get("types", "")
mv = card.get("mana_value", "?")
mc = card.get("mana_cost", "")
dist = card.get("distance", 0)
text = card.get("text", "")[:80]
lines.append(f"- {name} ({mc}, MV:{mv}, {types}) [distance: {dist:.3f}]")
if text:
lines.append(f" Oracle: {text}")
return "\n".join(lines)
def _format_matchups(report: DeckReport) -> str:
"""Format per-opponent matchup data."""
"""Format matchup data."""
if not report.matchups:
return "No matchup data available."
lines = []
for m in report.matchups:
lines.append(
f"- vs {m.opponentDeck}: {m.winRate:.1%} "
f"({m.gamesPlayed} games)"
)
return "\n".join(lines)
def _format_archetypes(report: DeckReport) -> str:
"""Format per-archetype win rates from DeckMeta.
Phase 1: annotates weak spots ([WEAK SPOT] < 40%) and strengths
([STRENGTH] >= 55%) so Claude sees the signal immediately.
"""
rates = report.meta.perArchetypeWinRates
if not rates:
return "No archetype breakdown available."
lines = []
for archetype, wr in sorted(rates.items(), key=lambda x: x[1]):
if wr < 0.40:
tag = " [WEAK SPOT]"
elif wr >= 0.55:
tag = " [STRENGTH]"
else:
tag = ""
lines.append(f"- vs {archetype}: {wr:.1%}{tag}")
lines.append(f"- vs {m.opponentDeck}: {m.winRate:.1%} "
f"({m.gamesPlayed} games)")
return "\n".join(lines)
@@ -512,16 +197,14 @@ def _format_combos(report: DeckReport) -> str:
lines = ["### Known Combos"]
for combo in report.knownCombos:
cards = " + ".join(combo.cardNames)
lines.append(
f"- {cards}: winRate={combo.winRateWhenAssembled:.1%}, "
f"assemblyRate={combo.assemblyRate:.1%}"
)
lines.append(f"- {cards}: winRate={combo.winRateWhenAssembled:.1%}, "
f"assemblyRate={combo.assemblyRate:.1%}")
return "\n".join(lines)
# ════════════════════════════════════════════════════════════
# ══════════════════════════════════════════════════════════════
# Main Builder Functions
# ════════════════════════════════════════════════════════════
# ══════════════════════════════════════════════════════════════
def build_system_prompt(report: DeckReport,
goals: Optional[CoachGoals] = None) -> str:
@@ -534,44 +217,16 @@ def build_system_prompt(report: DeckReport,
)
def build_quick_system_prompt(report: DeckReport,
goals: Optional[CoachGoals] = None) -> str:
"""Build the quick digest system prompt (~400-600 token target)."""
color_str = "/".join(report.colorIdentity) if report.colorIdentity else "any"
return QUICK_DIGEST_SYSTEM_PROMPT.format(
commander=report.commander,
color_identity=color_str,
goals_section=_format_goals_section(goals),
)
def build_user_prompt(report: DeckReport,
candidates: Dict[str, List[dict]] = None,
rag_cards: List[dict] = None,
rules_context: List[dict] = None) -> str: # FARMHOUSE_RULES_CONTEXT
text = _farmhouse_build_user_prompt(report, candidates, rag_cards)
rules = []
for item in (rules_context or [])[:3]:
body = (item.get('text') or item.get('document') or item.get('content')) if isinstance(item, dict) else str(item)
if body:
rules.append('- ' + str(body).strip()[:700])
if rules:
text += '\n\n## Relevant rules (for grounding; do not quote them back)\n' + '\n'.join(rules)
return text
def _farmhouse_build_user_prompt(report: DeckReport,
candidates: Dict[str, List[dict]] = None,
rag_cards: List[dict] = None) -> str:
"""Build the user prompt with full deck report data.
Phase 1: adds sim_insights_section computed from card-level stats.
"""
candidates: Dict[str, List[dict]] = None) -> str:
"""Build the user prompt with full deck report data."""
color_str = "/".join(report.colorIdentity) if report.colorIdentity else "unknown"
type_parts = [f"{k}={v}" for k, v in report.structure.cardTypeCounts.items()] \
if report.structure.cardTypeCounts else ["unknown"]
role_parts = [f"{k}={v}" for k, v in report.structure.functionalCounts.items()] \
if report.structure.functionalCounts else ["unknown"]
return USER_PROMPT_TEMPLATE.format(
deck_name=report.deckId,
commander=report.commander,
@@ -583,14 +238,10 @@ def _farmhouse_build_user_prompt(report: DeckReport,
curve_summary=_format_curve(report.structure.curveBuckets),
type_summary=", ".join(type_parts),
role_summary=", ".join(role_parts),
sim_insights_section=_format_sim_insights(
report.cards, report.meta.perArchetypeWinRates),
matchup_section=_format_matchups(report),
archetype_section=_format_archetypes(report),
top_cards=_format_top_cards(report.cards),
underperformer_section=_format_underperformers(
report.cards, report.underperformers),
candidate_section=_format_candidates(candidates or {}),
rag_section=_format_rag_cards(rag_cards or []),
combo_section=_format_combos(report),
)
-11
View File
@@ -1,9 +1,6 @@
"""
Commander AI Lab — Deck Generation System Prompt
═════════════════════════════════════════════════
Phase 1 changes:
- Added explicit 99-card count enforcement rule
- Clarified that commander counts separately (not in the 99)
"""
SYSTEM_PROMPT = """You are an elite Magic: The Gathering Commander (EDH) deck builder with encyclopedic knowledge of every card ever printed, current metagame trends, and Commander Rules Committee bracket guidelines.
@@ -12,8 +9,6 @@ Your task is to build a complete, legal 100-card Commander deck.
RULES:
- Exactly 100 cards total: 1 commander + 99 other cards
- The commander IS included in the cards list but counts as card #100
- The other 99 cards must exactly match the SLOT BUDGET provided in the user prompt
- No more than 1 copy of any card except basic lands
- All cards must share the commander's color identity
- All cards must be legal in Commander format
@@ -21,12 +16,6 @@ RULES:
- Include approximately: 10 ramp sources, 10 card draw sources, 8-10 targeted removal, 2-3 board wipes, 3-5 protection pieces
- Build a cohesive strategy around the commander's abilities
CARD COUNT ENFORCEMENT (critical):
- The user prompt will specify a SLOT BUDGET with exact per-category counts
- You MUST fill every slot — returning fewer cards than the budget specifies will cause a validation error
- If you cannot find a perfect fit for a slot, use the best available card for that role
- Basic lands count toward the Land slot total
BRACKET RULES (Commander Rules Committee):
- Bracket 1 (Casual): Precon-level. No tutors, no fast mana, no infinite combos, no mass land destruction. Game Changers: 0
- Bracket 2 (Upgraded Casual): Moderate power. Limited tutors (1-2 total), no 2-card infinite combos, no fast mana except Sol Ring. Game Changers: 0-1
+14 -43
View File
@@ -1,33 +1,11 @@
"""
Commander AI Lab — Deck Generation User Prompt Builder
═══════════════════════════════════════════════════════
Constructs the user message for LLM deck generation.
Phase 1 changes:
- slot_budget parameter injected into prompt so LLM targets exactly 99 cards
- Explicit card count requirement in prompt text
Constructs the user message for Perplexity deck generation
from a DeckGenV3Request.
"""
from typing import Dict, List, Optional
def build_slot_budget_segment(slot_budget: Dict[str, int]) -> str:
"""
Build the slot budget prompt segment.
Informs the LLM of exact per-category card counts so it never undershoots.
"""
total = sum(slot_budget.values())
lines = [f"SLOT BUDGET (you must fill EXACTLY {total} cards, excluding the commander):"]
for cat, count in slot_budget.items():
lines.append(f" {cat}: {count}")
lines.append(f" TOTAL: {total}")
lines.append("")
lines.append(
f"CRITICAL: Return exactly {total} cards in the JSON 'cards' array "
"(not counting the commander). Every slot in the budget above must be filled. "
"Do not return more or fewer cards."
)
return "\n".join(lines)
from typing import List, Optional
def build_user_prompt(
@@ -40,7 +18,6 @@ def build_user_prompt(
budget_mode: str = "total",
omit_cards: List[str] = None,
collection_summary: str = "",
slot_budget: Optional[Dict[str, int]] = None,
) -> str:
"""
Build the user prompt for deck generation.
@@ -49,19 +26,18 @@ def build_user_prompt(
commander: Commander card name
commander_type: Type line from Scryfall
color_identity: List of color letters, e.g. ["U", "B"]
strategy: User-specified strategy focus
strategy: User-specified strategy focus (e.g. "zombie tokens")
target_bracket: Target bracket level 1-4
budget_usd: Optional budget constraint
budget_mode: "total" for total deck cost, "per_card" for per-card max
omit_cards: Cards to exclude
collection_summary: Pre-built collection summary text block
slot_budget: Dict of category -> card count (must sum to 99)
"""
ci_str = ", ".join(color_identity) if color_identity else "Unknown"
lines = [
"Build a complete 100-card Commander deck.",
"",
f"Build a complete 100-card Commander deck.",
f"",
f"COMMANDER: {commander}",
]
@@ -84,21 +60,16 @@ def build_user_prompt(
lines.append(f"OMIT LIST (do NOT include these cards): {', '.join(omit_cards)}")
if collection_summary:
lines.append("")
lines.append(f"")
lines.append(collection_summary)
lines.append("")
lines.append("STRONGLY PREFER cards from the collection when they fit the strategy.")
lines.append(f"")
lines.append(f"STRONGLY PREFER cards from the collection when they fit the strategy.")
else:
lines.append("")
lines.append("No collection data available — suggest the best cards regardless of ownership.")
lines.append(f"")
lines.append(f"No collection data available — suggest the best cards regardless of ownership.")
# Inject slot budget so LLM knows exact target counts
if slot_budget:
lines.append("")
lines.append(build_slot_budget_segment(slot_budget))
lines.append("")
lines.append("Build the deck as a structured JSON response. Include the commander in the cards list.")
lines.append("Ensure exactly 100 total cards. Assign role_tags and bracket info accurately.")
lines.append(f"")
lines.append(f"Build the deck as a structured JSON response. Include the commander in the cards list.")
lines.append(f"Ensure exactly 100 total cards. Assign role_tags and bracket info accurately.")
return "\n".join(lines)
+1 -1
View File
@@ -1,7 +1,7 @@
"""
Commander AI Lab — Substitution Prompt Templates
═════════════════════════════════════════════════
Prompts for the Claude Opus substitution pass.
Prompts for the Perplexity fallback substitution pass.
"""
+2 -2
View File
@@ -38,7 +38,7 @@ def generate_deck_reports(results_dir: str, reports_dir: str = None) -> List[str
output_path.mkdir(parents=True, exist_ok=True)
# Load all batch results
batch_files = sorted(results_path.glob("ml-decision-*.json"))
batch_files = sorted(results_path.glob("batch-*.json"))
if not batch_files:
logger.info("No batch result files found in %s", results_dir)
return []
@@ -108,7 +108,7 @@ def generate_single_deck_report(batch_json_path: str, reports_dir: str = None) -
# Also load existing batch results for comprehensive reports
results_dir = Path(batch_json_path).parent
all_batches = []
for bf in sorted(results_dir.glob("ml-decision-*.json")):
for bf in sorted(results_dir.glob("batch-*.json")):
try:
with open(bf, "r", encoding="utf-8") as f:
all_batches.append(json.load(f))
+2 -2
View File
@@ -1,7 +1,7 @@
"""
Commander AI Lab — Deck Generation JSON Schemas
═════════════════════════════════════════════════
Pydantic models and JSON Schema dicts for Claude Opus
Pydantic models and JSON Schema dicts for Perplexity
structured output deck generation.
"""
@@ -58,7 +58,7 @@ class GeneratedDeckList(BaseModel):
# ══════════════════════════════════════════════════════════════
# JSON Schema dicts (for Claude Opus response_format)
# JSON Schema dicts (for Perplexity response_format)
# ══════════════════════════════════════════════════════════════
DECK_CARD_SCHEMA = {
+4 -23
View File
@@ -3,10 +3,6 @@ Commander AI Lab — Substitution Schemas
════════════════════════════════════════
Pydantic models and JSON Schema dicts for the
Smart Substitution Engine output.
Phase 1 changes:
- SubstitutionBatchResult gains padded_slots field
- DeckCardWithStatus gains original_card field (was missing)
"""
from typing import List, Optional
@@ -22,17 +18,13 @@ class CardAlternative(BaseModel):
name: str = Field(description="Exact card name")
similarity_score: float = Field(default=0.0, description="Cosine similarity score (0-1)")
reason: str = Field(default="", description="Why this card is a good substitute")
source: str = Field(default="embedding", description="How it was found: 'embedding' or 'anthropic'")
source: str = Field(default="embedding", description="How it was found: 'embedding' or 'perplexity'")
role_overlap: List[str] = Field(default_factory=list, description="Shared functional roles")
cmc_delta: float = Field(default=0.0, description="CMC difference from original")
class DeckCardWithStatus(BaseModel):
"""A deck card enriched with ownership and substitution data."""
class Config:
extra = "ignore"
name: str
count: int = 1
category: str = ""
@@ -46,15 +38,9 @@ class DeckCardWithStatus(BaseModel):
owned_qty: int = 0
scryfall_id: str = ""
status: str = Field(default="owned", description="owned | substituted | missing")
original_card: Optional[str] = Field(
default=None,
description="Original card name before substitution (None if not substituted)"
)
original_card: Optional[str] = Field(default=None, description="Original card name if this is a substitution")
alternatives: List[CardAlternative] = Field(default_factory=list)
selected_substitute: Optional[str] = Field(
default=None,
description="The substitute card name chosen for this slot"
)
selected_substitute: Optional[str] = Field(default=None, description="User-selected substitute name")
class SubstitutionRequest(BaseModel):
@@ -72,16 +58,11 @@ class SubstitutionBatchResult(BaseModel):
owned_count: int = 0
substituted_count: int = 0
missing_count: int = 0
padded_slots: int = Field(
default=0,
description="Number of slots filled by the pad-to-99 circuit breaker. "
"Any value > 0 indicates a bug in the substitution pipeline."
)
cards: List[DeckCardWithStatus] = Field(default_factory=list)
# ══════════════════════════════════════════════════════════════
# JSON Schema dicts (for LLM fallback substitution)
# JSON Schema dicts (for Perplexity fallback substitution)
# ══════════════════════════════════════════════════════════════
SUBSTITUTION_RESPONSE_SCHEMA = {
+118 -427
View File
@@ -1,28 +1,19 @@
"""
Commander AI Lab — V3 Deck Generator Service
═════════════════════════════════════════════
Generates Commander decks using Anthropic Claude
Generates Commander decks using Perplexity Sonar
structured JSON output, then runs ownership check
and smart substitution.
Phase 1 changes:
- smart_substitute() non-destructive contract (never returns None)
- apply_substitutions() loop never silently drops cards
- _pad_to_99() circuit breaker before BuildResult validation
- Pre-validation count logging per category
- Startup SLOT_BUDGET assertion
"""
import json
import logging
import re
import sqlite3
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Tuple
from urllib.request import urlopen, Request
from ..clients.anthropic_client import AnthropicClient
from ..clients.perplexity_client import PerplexityClient
from ..schemas.deck_schema import DECK_LIST_SCHEMA, GeneratedDeckList
from ..schemas.substitution_schema import (
CardAlternative, DeckCardWithStatus, SubstitutionBatchResult,
@@ -35,261 +26,35 @@ from ..prompts.substitution_prompt import (
from ..config import (
DECK_GEN_MODEL, DECK_GEN_TEMPERATURE, DECK_GEN_MAX_TOKENS,
SUBSTITUTION_MIN_SIMILARITY, SUBSTITUTION_MAX_ALTERNATIVES,
SUBSTITUTION_MODEL, SUBSTITUTION_USE_ANTHROPIC_FALLBACK,
SUBSTITUTION_MODEL, SUBSTITUTION_USE_PPLX_FALLBACK,
)
logger = logging.getLogger("coach.deckgen")
# ══════════════════════════════════════════════════════════════
# Slot Budget — MUST sum to 99 (commander is the 100th card)
# ══════════════════════════════════════════════════════════════
SLOT_BUDGET: dict[str, int] = {
"Land": 36,
"Ramp": 10,
"Card Draw": 10,
"Removal": 8,
"Board Wipe": 3,
"Win Condition": 4,
"Protection": 4,
"Synergy": 20,
"Creature": 2,
"Utility": 2,
}
# ── Startup assertion — catches misconfigured budgets at boot time ──
_SLOT_BUDGET_TOTAL = sum(SLOT_BUDGET.values())
assert _SLOT_BUDGET_TOTAL == 99, (
f"SLOT_BUDGET sums to {_SLOT_BUDGET_TOTAL}, must equal 99. "
f"Current distribution: {SLOT_BUDGET}"
)
# ══════════════════════════════════════════════════════════════
# SubstitutionMethod — tracks HOW each card was resolved
# ══════════════════════════════════════════════════════════════
class SubstitutionMethod(str, Enum):
EXACT_MATCH = "exact_match" # Card found verbatim in collection
FUZZY_MATCH = "fuzzy_match" # Case/punctuation-normalised match
EMBEDDING_ANALOG = "embedding_analog" # Embedding similarity match
ANTHROPIC_FALLBACK = "anthropic_fallback" # LLM suggested replacement
ORIGINAL_KEPT = "original_kept" # Not in collection but Scryfall-valid
BASIC_LAND_FALLBACK = "basic_land_fallback" # Last resort — slot becomes a basic
@dataclass
class SubstitutionRecord:
"""Audit trail entry for a single card's resolution."""
original: str
resolved: str
method: SubstitutionMethod
in_collection: bool
# ══════════════════════════════════════════════════════════════
# Color → Basic Land mapping
# ══════════════════════════════════════════════════════════════
_COLOR_TO_BASIC: dict[str, str] = {
"W": "Plains",
"U": "Island",
"B": "Swamp",
"R": "Mountain",
"G": "Forest",
}
_BASIC_NAMES: set[str] = set(_COLOR_TO_BASIC.values()) | {"Wastes"}
def _get_basic_land(color_identity: List[str]) -> str:
"""Return the first appropriate basic land for the given color identity."""
for color in color_identity:
if color.upper() in _COLOR_TO_BASIC:
return _COLOR_TO_BASIC[color.upper()]
return "Wastes" # Colorless commander
# ══════════════════════════════════════════════════════════════
# Non-destructive Smart Substitution
# ══════════════════════════════════════════════════════════════
def smart_substitute(
card_name: str,
collection: set[str],
color_identity: List[str],
embedding_index=None,
) -> SubstitutionRecord:
"""
Non-destructive substitution — ALWAYS returns a valid card string.
Fallback chain:
1. Exact match in collection
2. Fuzzy match (case + punctuation normalised)
3. Embedding similarity match (if index available)
4. Keep original (Scryfall-valid, not in collection)
5. Basic land for the commander's colors (last resort — NEVER None)
"""
# 1. Exact match
if card_name in collection:
return SubstitutionRecord(card_name, card_name, SubstitutionMethod.EXACT_MATCH, True)
# 2. Fuzzy match — normalise case and common punctuation differences
normalised = card_name.lower().strip()
for owned in collection:
if owned.lower().strip() == normalised:
return SubstitutionRecord(card_name, owned, SubstitutionMethod.FUZZY_MATCH, True)
# 3. Embedding similarity (if index available)
if embedding_index and getattr(embedding_index, "loaded", False):
try:
matches = embedding_index.search_similar(
query_card=card_name,
color_filter=color_identity or None,
exclude_cards=[card_name],
top_n=5,
)
pool_lower = {n.lower() for n in collection}
for match in matches:
if match.name.lower() in pool_lower:
return SubstitutionRecord(
card_name, match.name, SubstitutionMethod.EMBEDDING_ANALOG, True
)
except Exception as e:
logger.warning("Embedding substitution failed for '%s': %s", card_name, e)
# 4. Keep original — valid card not in collection (proxy / non-collection build)
return SubstitutionRecord(
card_name, card_name, SubstitutionMethod.ORIGINAL_KEPT, False
)
def apply_substitutions(
card_list: List[DeckCardWithStatus],
collection: set[str],
color_identity: List[str],
embedding_index=None,
) -> Tuple[List[DeckCardWithStatus], List[SubstitutionRecord]]:
"""
Apply smart substitution to a card list.
Guarantees: output list is NEVER shorter than input list.
Logs a warning for every BASIC_LAND_FALLBACK.
"""
records: List[SubstitutionRecord] = []
result: List[DeckCardWithStatus] = []
for card in card_list:
rec = smart_substitute(card.name, collection, color_identity, embedding_index)
records.append(rec)
if rec.method == SubstitutionMethod.BASIC_LAND_FALLBACK:
logger.warning(
"[substitution] BASIC_LAND_FALLBACK for '%s' — slot filled with '%s'",
rec.original, rec.resolved,
)
# Update the card in-place — never drop it
updated = card.model_copy(update={
"name": rec.resolved,
"owned": rec.in_collection,
"status": "owned" if rec.in_collection else
("substituted" if rec.method != SubstitutionMethod.ORIGINAL_KEPT
else "missing"),
"original_card": card.name if rec.resolved != card.name else card.original_card,
})
result.append(updated)
fallback_count = sum(1 for r in records if r.method == SubstitutionMethod.BASIC_LAND_FALLBACK)
if fallback_count:
logger.error(
"[substitution] %d cards fell back to basic lands — investigate LLM output quality",
fallback_count,
)
return result, records
# ══════════════════════════════════════════════════════════════
# Pad-to-99 Circuit Breaker
# ══════════════════════════════════════════════════════════════
def _pad_to_99(
cards: List[DeckCardWithStatus],
color_identity: List[str],
target: int = 99,
) -> Tuple[List[DeckCardWithStatus], int]:
"""
Emergency safety pad — should NEVER fire if substitution contract holds.
If it does fire, the error log is your signal that a card is being dropped
somewhere earlier in the pipeline.
Returns (padded_cards, number_of_slots_padded).
"""
# Strip commander from count if present (commander is tracked separately)
non_commander = [c for c in cards if not getattr(c, "is_commander", False)]
current = sum(c.count for c in non_commander)
shortfall = target - current
if shortfall <= 0:
return cards, 0
logger.error(
"[pad_to_99] CIRCUIT BREAKER FIRED — deck is %d cards short after substitution. "
"Padding with basic lands. Check substitution pipeline for silent drops.",
shortfall,
)
basic = _get_basic_land(color_identity)
padding_card = DeckCardWithStatus(
name=basic,
count=shortfall,
category="Land",
role_tags=[],
reason="Emergency pad — basic land inserted by circuit breaker",
estimated_price_usd=0.10,
owned=True,
owned_qty=shortfall,
status="owned",
)
return cards + [padding_card], shortfall
def _log_pre_validation_counts(cards: List[DeckCardWithStatus]) -> None:
"""Log per-category card counts before Pydantic validation."""
by_cat: dict[str, int] = {}
for card in cards:
cat = card.category or "Uncategorized"
by_cat[cat] = by_cat.get(cat, 0) + card.count
total = sum(by_cat.values())
logger.info("[pre_validation] Category counts: %s", by_cat)
logger.info("[pre_validation] Total: %d/99 (delta: %d)", total, 99 - total)
# ══════════════════════════════════════════════════════════════
# DeckGeneratorV3
# ══════════════════════════════════════════════════════════════
class DeckGeneratorV3:
"""
V3 Deck Generator using Anthropic Claude structured output.
V3 Deck Generator using Perplexity structured output.
Pipeline:
1. Resolve commander via Scryfall
2. Build collection summary
3. Call Anthropic Claude with structured JSON schema
3. Call Perplexity with structured JSON schema
4. Validate card names via Scryfall
5. Check ownership against collection DB
6. Run Smart Substitution (non-destructive)
7. _pad_to_99 circuit breaker
8. Pre-validation count logging
9. Return finalized deck — guaranteed 99 cards
6. Run Smart Substitution (embedding + Perplexity fallback)
7. Return finalized deck with substitution data
"""
def __init__(self, anthropic_client: AnthropicClient, db_conn_factory,
def __init__(self, pplx_client: PerplexityClient, db_conn_factory,
embedding_index=None):
self.anthropic = anthropic_client
"""
Args:
pplx_client: Configured PerplexityClient instance
db_conn_factory: Callable that returns sqlite3.Connection
embedding_index: Optional MTGEmbeddingIndex for substitution
"""
self.pplx = pplx_client
self.db_conn_factory = db_conn_factory
self.embedding_index = embedding_index
@@ -312,12 +77,9 @@ class DeckGeneratorV3:
"mana_cost": data.get("mana_cost", ""),
"image_url": data.get("image_uris", {}).get("normal", ""),
"oracle_text": data.get("oracle_text", ""),
"scryfall_found": True,
}
except Exception as e:
logger.warning("Scryfall lookup failed for '%s': %s", commander_name, e)
# Non-canonical commander (silver-bordered, custom, etc.)
# Skip collection substitution for these — trust LLM output directly
return {
"name": commander_name,
"scryfall_id": "",
@@ -326,7 +88,6 @@ class DeckGeneratorV3:
"mana_cost": "",
"image_url": "",
"oracle_text": "",
"scryfall_found": False,
}
# ── Step 2: Build Collection Summary ─────────────────────
@@ -349,10 +110,16 @@ class DeckGeneratorV3:
if not rows:
return ""
# Filter by color identity
ci_set = set(color_identity) if color_identity else None
filtered = []
for row in rows:
name = row["name"]
type_line = row["type_line"] or ""
# Basic lands and colorless are always allowed
if ci_set:
# Simple color check from type_line and name
# For proper filtering we'd check mana cost but this is good enough for summary
card_colors = set()
oracle = row["oracle_text"] or ""
mana_cost = ""
@@ -370,6 +137,7 @@ class DeckGeneratorV3:
if not filtered:
return ""
# Group by card type
groups = {}
for row in filtered:
type_line = row["type_line"] or ""
@@ -391,12 +159,14 @@ class DeckGeneratorV3:
group = "Other"
groups.setdefault(group, []).append(row)
# Sort each group by popularity/price and build text
lines = [f"COLLECTION SUMMARY ({len(filtered)} cards in deck colors):"]
for group_name in ["Creatures", "Instants", "Sorceries", "Artifacts",
"Enchantments", "Planeswalkers", "Lands", "Other"]:
cards = groups.get(group_name, [])
if not cards:
continue
# Sort by price descending (higher value = likely better card)
cards.sort(key=lambda r: r["tcg_price"] or 0, reverse=True)
card_strs = []
for c in cards[:max_per_group]:
@@ -406,7 +176,7 @@ class DeckGeneratorV3:
return "\n".join(lines)
# ── Step 3: Generate Deck via Anthropic Claude ─────────────────
# ── Step 3: Generate Deck via Perplexity ─────────────────
def generate_deck(
self,
commander_name: str,
@@ -423,33 +193,24 @@ class DeckGeneratorV3:
Returns dict with:
- commander: dict with Scryfall data
- raw_deck: parsed GeneratedDeckList from Anthropic Claude
- cards: list of DeckCardWithStatus (after ownership check + substitution)
- raw_deck: parsed GeneratedDeckList from Perplexity
- cards: list of DeckCardWithStatus (after ownership check)
- stats: deck statistics
- substitution_log: list of SubstitutionRecord dicts
- padded_slots: int > 0 means circuit breaker fired
- tokens_used: {prompt, completion}
"""
# Step 1: Resolve commander
cmdr = self.resolve_commander(commander_name)
color_identity = cmdr["color_identity"]
scryfall_found = cmdr.get("scryfall_found", True)
logger.info("Commander: %s, CI: %s, Scryfall: %s",
cmdr["name"], color_identity, scryfall_found)
logger.info("Commander: %s, CI: %s", cmdr["name"], color_identity)
# Step 2: Collection summary
collection_block = ""
if use_collection and scryfall_found:
if use_collection:
collection_block = self.build_collection_summary(color_identity)
logger.info("Collection summary: %d chars",
len(collection_block) if collection_block else 0)
elif not scryfall_found:
logger.info(
"Non-canonical commander '%s' — skipping collection filter, "
"trusting LLM output directly.", cmdr["name"]
)
# Step 3: Build prompts (with slot budget injected)
# Step 3: Build prompts
user_prompt = build_user_prompt(
commander=cmdr["name"],
commander_type=cmdr["type_line"],
@@ -460,14 +221,13 @@ class DeckGeneratorV3:
budget_mode=budget_mode,
omit_cards=omit_cards,
collection_summary=collection_block,
slot_budget=SLOT_BUDGET,
)
# Step 4: Call LLM with structured output
# Step 4: Call Perplexity with structured output
use_model = model or DECK_GEN_MODEL
logger.info("Calling LLM (%s) for deck generation...", use_model)
logger.info("Calling Perplexity (%s) for deck generation...", use_model)
response = self.anthropic.chat_structured(
response = self.pplx.chat_structured(
system_prompt=SYSTEM_PROMPT,
user_prompt=user_prompt,
json_schema=DECK_LIST_SCHEMA,
@@ -479,60 +239,24 @@ class DeckGeneratorV3:
if not response.ok:
raise ValueError(
f"LLM returned invalid response: {response.content[:300]}"
f"Perplexity returned invalid response: {response.content[:300]}"
)
raw_deck = response.parsed_json
card_count = len(raw_deck.get("cards", []))
truncated = card_count < 90
logger.info(
"Deck generated: %d cards, bracket %s%s",
card_count,
(raw_deck.get("bracket", {}).get("level", "?") if isinstance(raw_deck.get("bracket"), dict)
else raw_deck.get("bracket", "?")),
" (TRUNCATED — hit token limit)" if truncated else "",
)
truncated = card_count < 90 # Commander decks should have ~100 cards
logger.info("Deck generated: %d cards, bracket %d%s",
card_count,
raw_deck.get("bracket", {}).get("level", 0),
" (TRUNCATED — response may have hit token limit)" if truncated else "")
# Step 5: Check ownership
# Step 5: Check ownership and build enriched card list
cards_with_status = self._check_ownership(raw_deck.get("cards", []))
# Step 5b: Fill basic lands to reach target_total=100
# Step 5b: Fill basic lands to hit exactly 100 cards
cards_with_status = self._fill_basic_lands(cards_with_status, color_identity)
# Step 5c: Secondary deduplication
seen: dict[str, int] = {}
deduped: List[DeckCardWithStatus] = []
for c in cards_with_status:
key = c.name.lower()
if key in seen:
deduped[seen[key]].count += c.count
logger.warning("Secondary dedupe caught duplicate: '%s'", c.name)
else:
seen[key] = len(deduped)
deduped.append(c)
cards_with_status = deduped
# Step 6: Run non-destructive smart substitution
# For non-canonical commanders (e.g. Sonic), skip collection filter
owned_pool: set[str] = set()
if use_collection and scryfall_found:
conn = self.db_conn_factory()
rows = conn.execute(
"SELECT DISTINCT name FROM collection_entries WHERE quantity > 0"
).fetchall()
owned_pool = {r["name"] for r in rows}
cards_with_status, substitution_log = apply_substitutions(
cards_with_status, owned_pool, color_identity, self.embedding_index
)
# Step 7: Pad-to-99 circuit breaker
cards_with_status, padded_slots = _pad_to_99(cards_with_status, color_identity)
# Step 8: Pre-validation count logging
_log_pre_validation_counts(cards_with_status)
# Step 9: Compute stats
# Step 6: Compute stats
stats = self._compute_stats(cards_with_status)
return {
@@ -546,12 +270,6 @@ class DeckGeneratorV3:
"archetype": raw_deck.get("archetype", ""),
"reasoning": raw_deck.get("reasoning", {}),
"estimated_total_usd": raw_deck.get("estimated_total_usd", 0),
"substitution_log": [
{"original": r.original, "resolved": r.resolved,
"method": r.method.value, "in_collection": r.in_collection}
for r in substitution_log
],
"padded_slots": padded_slots,
"tokens_used": {
"prompt": response.prompt_tokens,
"completion": response.completion_tokens,
@@ -565,25 +283,17 @@ class DeckGeneratorV3:
def _check_ownership(self, cards: List[dict]) -> List[DeckCardWithStatus]:
"""
Cross-reference generated cards against the collection DB.
Deduplicates by name (case-insensitive).
Sets owned/scryfall_id/owned_qty and real price.
"""
conn = self.db_conn_factory()
enriched: List[DeckCardWithStatus] = []
seen_names: dict[str, int] = {}
enriched = []
for card in cards:
name = card.get("name", "")
if not name:
continue
name_lower = name.lower()
if name_lower in seen_names:
idx = seen_names[name_lower]
enriched[idx].count += card.get("count", 1)
logger.warning("Duplicate card '%s' merged", name)
continue
# Look up in collection
row = conn.execute(
"SELECT name, scryfall_id, quantity, tcg_price, type_line, cmc "
"FROM collection_entries WHERE name = ? COLLATE NOCASE LIMIT 1",
@@ -608,14 +318,16 @@ class DeckGeneratorV3:
scryfall_id=row["scryfall_id"] if row else "",
status="owned" if is_owned else "missing",
)
seen_names[name_lower] = len(enriched)
enriched.append(enriched_card)
return enriched
# ── Step 5b: Basic Land Fill ──────────────────────────────
_COLOR_TO_BASIC = _COLOR_TO_BASIC
_BASIC_NAMES = _BASIC_NAMES
_COLOR_TO_BASIC = {
'W': 'Plains', 'U': 'Island', 'B': 'Swamp',
'R': 'Mountain', 'G': 'Forest',
}
_BASIC_NAMES = set(_COLOR_TO_BASIC.values()) | {'Wastes'}
def _fill_basic_lands(
self,
@@ -637,7 +349,7 @@ class DeckGeneratorV3:
ci = [c.upper() for c in color_identity]
basic_names = [self._COLOR_TO_BASIC[c] for c in ci if c in self._COLOR_TO_BASIC]
if not basic_names:
basic_names = ["Wastes"]
basic_names = ['Wastes']
per_color = basics_needed // len(basic_names)
remainder = basics_needed % len(basic_names)
@@ -648,20 +360,20 @@ class DeckGeneratorV3:
non_basics.append(DeckCardWithStatus(
name=bname,
count=qty,
category="Land",
category='Land',
role_tags=[],
reason="Basic land for mana fixing",
reason='Basic land for mana fixing',
estimated_price_usd=0.10,
owned=True,
owned_qty=qty,
status="owned",
status='owned',
))
logger.info("Basic land fill: %d basics added across %d color(s)",
basics_needed, len(basic_names))
basics_needed, len(basic_names))
return non_basics
# ── Step 6: Smart Substitution (legacy wrapper for route compatibility) ──
# ── Step 6: Smart Substitution ───────────────────────────
def run_substitution(
self,
cards: List[DeckCardWithStatus],
@@ -671,12 +383,15 @@ class DeckGeneratorV3:
"""
Run the Smart Substitution Engine on missing cards.
Uses the non-destructive apply_substitutions() under the hood.
Falls back to Anthropic Claude for low-confidence matches,
then to basic land as last resort — NEVER drops a card.
Pipeline:
a) Identify missing cards
b) For each: try embedding similarity (free, fast)
c) For low-confidence matches: batch Perplexity fallback
d) Auto-select best substitute per card
Returns SubstitutionBatchResult with all cards updated.
"""
color_identity = commander.get("color_identity", [])
scryfall_found = commander.get("scryfall_found", True)
missing = [c for c in cards if not c.owned]
owned = [c for c in cards if c.owned]
@@ -691,63 +406,47 @@ class DeckGeneratorV3:
logger.info("Substitution: %d missing / %d owned", len(missing), len(owned))
# Build owned pool
# Build list of owned card names for substitution pool
conn = self.db_conn_factory()
owned_pool_rows = conn.execute(
"SELECT DISTINCT name FROM collection_entries WHERE quantity > 0"
).fetchall()
owned_pool = {r["name"] for r in owned_pool_rows}
deck_names = {c.name.lower() for c in cards}
available_pool = {n for n in owned_pool if n.lower() not in deck_names}
owned_pool = [r["name"] for r in owned_pool_rows]
# a) Embedding pass for missing cards
needs_anthropic_fallback: List[DeckCardWithStatus] = []
# Exclude cards already in the deck
deck_names = set(c.name.lower() for c in cards)
available_pool = [n for n in owned_pool if n.lower() not in deck_names]
# a) Embedding pass
needs_pplx_fallback = []
for card in missing:
embedding_alts = self._embedding_substitution(
card, color_identity, list(available_pool)
card, color_identity, available_pool
)
card.alternatives = embedding_alts
# Check if best match meets threshold
if embedding_alts and embedding_alts[0].similarity_score >= SUBSTITUTION_MIN_SIMILARITY:
card.selected_substitute = embedding_alts[0].name
card.status = "substituted"
card.owned = True
available_pool.discard(card.selected_substitute.lower())
# Remove selected from pool
if card.selected_substitute.lower() in [n.lower() for n in available_pool]:
available_pool = [n for n in available_pool
if n.lower() != card.selected_substitute.lower()]
else:
needs_anthropic_fallback.append(card)
needs_pplx_fallback.append(card)
# b) Anthropic Claude fallback
if needs_anthropic_fallback and SUBSTITUTION_USE_ANTHROPIC_FALLBACK:
self._anthropic_substitution(
needs_anthropic_fallback, list(available_pool),
# b) Perplexity fallback for low-confidence matches
if needs_pplx_fallback and SUBSTITUTION_USE_PPLX_FALLBACK:
self._pplx_substitution(
needs_pplx_fallback, available_pool,
commander, strategy
)
# c) Any card STILL missing after both passes gets a basic land — never drop it
padded = 0
for card in missing:
if card.status == "missing":
basic = _get_basic_land(color_identity)
logger.warning(
"[substitution] '%s' unresolved after all passes — "
"replacing with basic land '%s'",
card.name, basic,
)
card.name = basic
card.category = "Land"
card.role_tags = []
card.owned = True
card.status = "substituted"
card.original_card = card.name
padded += 1
# Count results
substituted = sum(1 for c in cards if c.status == "substituted")
still_missing = sum(1 for c in cards if c.status == "missing")
# Validate count hasn't changed
assert len(cards) == len(owned) + len(missing), \
f"[substitution] Card count changed: {len(owned) + len(missing)} -> {len(cards)}"
return SubstitutionBatchResult(
total_cards=len(cards),
owned_count=len(owned),
@@ -766,37 +465,39 @@ class DeckGeneratorV3:
if not self.embedding_index or not self.embedding_index.loaded:
return []
try:
matches = self.embedding_index.search_similar(
query_card=card.name,
color_filter=color_identity if color_identity else None,
type_filter=card.category if card.category else None,
exclude_cards=[card.name],
top_n=SUBSTITUTION_MAX_ALTERNATIVES * 3,
)
except Exception as e:
logger.warning("Embedding search failed for '%s': %s", card.name, e)
return []
# Use the embeddings search to find similar cards
matches = self.embedding_index.search_similar(
query_card=card.name,
color_filter=color_identity if color_identity else None,
type_filter=card.category if card.category else None,
exclude_cards=[card.name],
top_n=SUBSTITUTION_MAX_ALTERNATIVES * 3, # Over-fetch, then filter to owned
)
pool_lower = {n.lower() for n in available_pool}
# Filter to only cards in the available pool
pool_lower = set(n.lower() for n in available_pool)
alternatives = []
for match in matches:
if match.name.lower() in pool_lower:
role_overlap = list(set(card.role_tags) & set(getattr(match, "role_tags", [])))
# Compute role overlap
match_roles = [] # Would need card's role_tags from DB
role_overlap = list(set(card.role_tags) & set(match_roles)) if match_roles else []
alternatives.append(CardAlternative(
name=match.name,
similarity_score=match.similarity,
reason=f"Similar to {card.name} (cosine sim: {match.similarity:.3f})",
source="embedding",
role_overlap=role_overlap,
cmc_delta=getattr(match, "mana_value", 0) - (card.estimated_price_usd or 0),
cmc_delta=match.mana_value - (card.estimated_price_usd or 0),
))
if len(alternatives) >= SUBSTITUTION_MAX_ALTERNATIVES:
break
return alternatives
def _anthropic_substitution(
def _pplx_substitution(
self,
missing_cards: List[DeckCardWithStatus],
available_pool: List[str],
@@ -804,14 +505,13 @@ class DeckGeneratorV3:
strategy: str,
):
"""
Batch Anthropic Claude fallback for cards with low embedding confidence.
Mutates cards in-place. On failure, cards retain status='missing'
so the basic-land fallback in run_substitution() can catch them.
Batch Perplexity fallback for cards with low embedding confidence.
Mutates the cards in-place with substitution data.
"""
if not available_pool:
logger.warning("[anthropic_substitution] No available pool — skipping")
return
# Build the request
missing_dicts = [
{
"name": c.name,
@@ -824,7 +524,7 @@ class DeckGeneratorV3:
user_prompt = build_substitution_prompt(
missing_cards=missing_dicts,
allowed_cards=available_pool[:200],
allowed_cards=available_pool[:200], # Limit to avoid token overflow
commander=commander.get("name", ""),
color_identity=commander.get("color_identity", []),
strategy=strategy,
@@ -832,7 +532,7 @@ class DeckGeneratorV3:
try:
from ..schemas.substitution_schema import SUBSTITUTION_RESPONSE_SCHEMA
response = self.anthropic.chat_structured(
response = self.pplx.chat_structured(
system_prompt=SUBSTITUTION_SYSTEM,
user_prompt=user_prompt,
json_schema=SUBSTITUTION_RESPONSE_SCHEMA,
@@ -843,16 +543,13 @@ class DeckGeneratorV3:
)
if not response.ok:
logger.warning(
"[anthropic_substitution] LLM returned non-JSON — "
"%d cards will fall through to basic land fallback",
len(missing_cards),
)
logger.warning("Perplexity substitution fallback failed — non-JSON response")
return
subs = response.parsed_json.get("substitutions", [])
logger.info("[anthropic_substitution] Received %d substitutions", len(subs))
logger.info("Perplexity suggested %d substitutions", len(subs))
# Apply substitutions
card_by_name = {c.name.lower(): c for c in missing_cards}
for sub in subs:
orig = sub.get("original", "").lower()
@@ -861,38 +558,32 @@ class DeckGeneratorV3:
if orig in card_by_name and substitute:
card = card_by_name[orig]
anthropic_alt = CardAlternative(
# Add as top alternative
pplx_alt = CardAlternative(
name=substitute,
similarity_score=0.80,
similarity_score=0.80, # Nominal score for Perplexity suggestions
reason=reason,
source="anthropic",
source="perplexity",
role_overlap=sub.get("role_overlap", []),
)
card.alternatives.insert(0, anthropic_alt)
# Insert at front
card.alternatives.insert(0, pplx_alt)
card.selected_substitute = substitute
card.status = "substituted"
card.owned = True
card.original_card = card.name
except Exception as e:
logger.error(
"[anthropic_substitution] Exception: %s — "
"%d cards will fall through to basic land fallback",
e, len(missing_cards),
)
# Do NOT re-raise — cards stay status='missing' and
# run_substitution()'s basic-land fallback will handle them
logger.error("Perplexity substitution fallback error: %s", e)
# ── Stats ────────────────────────────────────────────────
@staticmethod
def _compute_stats(cards: List[DeckCardWithStatus]) -> dict:
"""Compute deck statistics from the enriched card list."""
by_category: dict[str, int] = {}
by_status: dict[str, int] = {"owned": 0, "substituted": 0, "missing": 0}
by_category = {}
by_status = {"owned": 0, "substituted": 0, "missing": 0}
total_price = 0.0
owned_price = 0.0
missing_price = 0.0
role_counts: dict[str, int] = {}
role_counts = {}
for card in cards:
cat = card.category or "Other"
-4
View File
@@ -1,4 +0,0 @@
name,quantity,set_code
Sol Ring,1,C21
Command Tower,1,C21
Arcane Signet,1,C21
+10 -122
View File
@@ -1,133 +1,21 @@
"""
Moxfield Adapter
================
Moxfield Adapter (stub)
════════════════════════
Fetches template decklists from Moxfield for a given commander.
Uses the undocumented but usable api2.moxfield.com API.
Rate-limited to <=10 req/sec. Errors are caught and logged.
Currently returns empty (experimental — not yet implemented).
"""
import logging
import time
import httpx
from .models import TemplateDeck, TemplateDeckCard
import logging
log = logging.getLogger("commander_ai_lab.deckgen.moxfield")
MOXFIELD_API = "https://api2.moxfield.com"
HEADERS = {
"User-Agent": "CommanderAILab/1.0",
"Accept": "application/json",
}
# Minimum seconds between requests (<=10 req/sec)
_RATE_LIMIT_DELAY = 0.12
def _slugify_commander(name: str) -> str:
"""Return the commander name as-is for the Moxfield search query."""
return name.strip()
def _build_cards_from_deck(deck_data: dict) -> list:
"""Extract commander + mainboard cards from a full Moxfield deck response."""
cards = []
# Commanders first
for card_name, card_obj in deck_data.get("commanders", {}).items():
qty = card_obj.get("quantity", 1)
cards.append(TemplateDeckCard(name=card_name, quantity=qty))
# Mainboard
for card_name, card_obj in deck_data.get("mainboard", {}).items():
qty = card_obj.get("quantity", 1)
cards.append(TemplateDeckCard(name=card_name, quantity=qty))
return cards
def fetch_template_decks(
commander_name: str,
color_identity: list,
config: dict = None,
) -> list:
def fetch_template_decks(commander_name: str, color_identity: list, config: dict = None) -> list:
"""
Fetch top Commander decks from Moxfield for the given commander.
Returns a list of TemplateDeck objects. Returns empty list on any
API failure — errors are logged, never raised.
Args:
commander_name: The commander's card name.
color_identity: List of color symbols (unused, kept for interface compat).
config: Optional dict. Supported key: ``max_decks`` (default 3).
Returns:
List of TemplateDeck objects populated with commander + mainboard cards.
Fetch template decks from Moxfield for the given commander.
Experimental — not yet implemented.
"""
max_decks = (config or {}).get("max_decks", 3)
results = []
try:
# Step 1 — Search for top decks by commander name
search_url = f"{MOXFIELD_API}/v2/decks/search"
params = {
"q": "",
"fmt": "commander",
"commander": _slugify_commander(commander_name),
"sortType": "views",
"sortDirection": "Descending",
"pageSize": max_decks,
}
log.info(f" Moxfield: Searching for '{commander_name}' (max={max_decks})")
resp = httpx.get(search_url, params=params, headers=HEADERS, timeout=15)
resp.raise_for_status()
search_data = resp.json()
deck_summaries = search_data.get("data", [])[:max_decks]
if not deck_summaries:
log.info(f" Moxfield: No decks found for '{commander_name}'")
return []
log.info(f" Moxfield: Found {len(deck_summaries)} deck(s) for '{commander_name}', fetching details...")
# Step 2 — Fetch full detail for each deck
for summary in deck_summaries:
deck_id = summary.get("publicId")
deck_name = summary.get("name", f"Moxfield {commander_name}")
if not deck_id:
log.warning(" Moxfield: Skipping deck with no publicId")
continue
time.sleep(_RATE_LIMIT_DELAY) # Rate limit: <=10 req/sec
try:
deck_url = f"{MOXFIELD_API}/v3/decks/all/{deck_id}"
deck_resp = httpx.get(deck_url, headers=HEADERS, timeout=15)
deck_resp.raise_for_status()
deck_data = deck_resp.json()
except Exception as deck_err:
log.warning(f" Moxfield: Failed to fetch deck '{deck_id}': {deck_err}")
continue
cards = _build_cards_from_deck(deck_data)
if not cards:
log.warning(f" Moxfield: Deck '{deck_name}' ({deck_id}) had no cards, skipping")
continue
results.append(TemplateDeck(
name=f"{deck_name} (Moxfield)",
source=f"https://moxfield.com/decks/{deck_id}",
cards=cards,
))
log.info(f" Moxfield: Added deck '{deck_name}' ({len(cards)} cards)")
log.info(f" Moxfield: Returning {len(results)} deck(s) for '{commander_name}'")
except httpx.HTTPStatusError as e:
log.warning(
f" Moxfield fetch failed for '{commander_name}': "
f"HTTP {e.response.status_code} — {e}"
)
except httpx.RequestError as e:
log.warning(f" Moxfield request error for '{commander_name}': {e}")
except Exception as e:
log.warning(f" Moxfield unexpected error for '{commander_name}': {e}")
return results
log.info(f" Stub: Not yet implemented for '{commander_name}'")
return []
-129
View File
@@ -1,129 +0,0 @@
# Closed-Loop Iterative Distillation — Implementation Roadmap
> **Goal:** Create a feedback loop where the PPO self-play agent exports its game decisions
> as JSONL files, which the supervised training pipeline incorporates alongside Forge
> heuristic data. The supervised baseline gradually improves as the RL agent discovers
> better play patterns — the RL agent teaches the supervised model.
---
## Phase 1 — PPO Decision Exporter
**Goal:** PPO self-play writes decisions in the same JSONL format as Forge batch sims.
- [ ] Add a `DecisionExporter` class in `ml/training/self_play.py` that captures each
(state, action, reward, game_context) during PPO rollouts
- [ ] Write to `data/results/ml-decisions-ppo-{batch_id}.jsonl` using the exact same
schema as the Forge `DecisionSnapshot` files
- [ ] Include metadata fields to distinguish PPO-generated data:
- `"source": "ppo"`
- `"model_version"`
- `"reward"`
- `"episode_return"`
- [ ] Only export decisions from **winning** games initially (higher signal-to-noise)
**Files touched:** `ml/training/self_play.py`, new `ml/training/decision_exporter.py`
---
## Phase 2 — Dataset Builder Source Awareness
**Goal:** `dataset_builder.py` can ingest both Forge and PPO decision files with
configurable mixing.
- [ ] Update `build_dataset()` to scan for both `ml-decisions-sim-*.jsonl` (Forge) and
`ml-decisions-ppo-*.jsonl` (PPO) files
- [ ] Add a `source_weights` config param — e.g., `{"forge": 1.0, "ppo": 0.5}` — to
control sampling ratios so PPO data doesn't overwhelm the Forge baseline early on
- [ ] Add a `min_reward_threshold` filter for PPO data — only include decisions from
games above a certain reward score
- [ ] Tag each sample with its source for downstream analysis
**Files touched:** `ml/data/dataset_builder.py`, `ml/config/scope.py`
---
## Phase 3 — Quality Gate & Validation
**Goal:** Prevent bad PPO data from degrading the supervised model.
- [ ] Add a validation split in `dataset_builder.py` (hold out 10-15% of Forge data as
a fixed eval set)
- [ ] After each supervised training run, evaluate on the held-out Forge set — if
accuracy drops below a threshold compared to the previous model, reject the PPO
data batch
- [ ] Track win rate of the PPO agent — only export decisions once the PPO model exceeds
a configurable win rate (e.g., >30% in 4-player pods, above the 25% random baseline)
- [ ] Log data quality metrics: action distribution entropy, reward distribution of
exported games
**Files touched:** `ml/training/trainer.py`, `ml/eval/`, new `ml/data/quality_gate.py`
---
## Phase 4 — Distillation Loop Orchestrator
**Goal:** Automate the full cycle: supervised train -> PPO self-play -> export -> retrain.
- [ ] New `ml/training/distillation_loop.py` that orchestrates:
1. Supervised train on current dataset (Forge + any existing PPO data)
2. Run N episodes of PPO self-play using the new supervised model as starting policy
3. Export winning PPO decisions to JSONL
4. Quality gate check
5. If passed, merge into dataset and go to step 1
6. If failed, discard PPO batch, adjust hyperparameters, retry
- [ ] Add `max_iterations` and `convergence_check` (stop if win rate plateaus across
iterations)
- [ ] Each iteration is a "generation" — tag data and models with generation number
**Files touched:** new `ml/training/distillation_loop.py`, `ml/config/scope.py`
---
## Phase 5 — UI Integration & Monitoring
**Goal:** Expose the distillation loop in the Commander AI Lab web UI.
- [ ] Add a "Distillation" tab or section in `ui/ai-lab.js` showing:
- Current generation number
- Per-generation win rate trend chart
- Data composition pie chart (% Forge vs % PPO per generation)
- Start / stop / pause controls for the loop
- [ ] API endpoints in `routes/ml.py`:
- `POST /api/ml/distill/start`
- `GET /api/ml/distill/status`
- `POST /api/ml/distill/stop`
- [ ] History of each generation's metrics stored as JSON for the trends view
**Files touched:** `routes/ml.py`, `ui/ai-lab.js`, `ui/ai-lab.css`
---
## Phase 6 — Advanced: ELO Tracking & Model Tournament
**Goal:** Quantify improvement across generations.
- [ ] Pit each generation's model against previous generations and the Forge heuristic
in batch sims
- [ ] Compute ELO ratings per generation
- [ ] Store in `data/elo_history.json` and visualize in the UI as a line chart
- [ ] Use ELO delta as a convergence signal — stop the loop when ELO gain per generation
drops below a threshold
**Files touched:** new `ml/eval/elo_tracker.py`, `routes/ml.py`, `ui/ai-lab.js`
---
## Priority
| Phase | Priority | Description |
|-------|----------|-------------|
| 1 | **Critical** | PPO decision export — foundation for everything |
| 2 | **Critical** | Dataset builder ingests both sources |
| 3 | **Critical** | Quality gate prevents model regression |
| 4 | High | Automation of the full loop |
| 5 | Medium | UI visibility and controls |
| 6 | Low | ELO tracking and tournament system |
> **Phases 1-3** are the core — get those working and you have a functional closed loop.
> **Phase 4** automates it. **Phases 5-6** are polish and observability.
-67
View File
@@ -1,67 +0,0 @@
# Laya connections
Laya (and Kev: same `POST /v1/systemone` API) is a **decision model**: typed multiple-choice, yes/no and score questions about a text, answered in
one forward pass, no generated text. This page is where it plugs into the strategic-intelligence work in this repository
([INTELLIGENCE-HANDOFF.md](INTELLIGENCE-HANDOFF.md)), what is measured, and how to make it worth using. Written 2026-10-26.
**Short version.** Every connection below is built, tested offline and **off by default**. Zero-shot, Laya is a poor action chooser
(below the always-guess baseline) but a reasonable card classifier (48% against 17% by chance); it is too slow on a CPU for Forge's
priority path (8 s against a 1.5 s budget). The way forward is fine-tuning on the decisions these connections record.
## What connects where
| Connection | Code | Mode | Notes |
|---|---|---|---|
| Farmhouse macro choice: Laya picks among CSIE's candidate macros, reading the CSIE ranking and ITI objective in its text | `farmhouse_decide.py` (called from `deepseek_brain.py`) | `DECISION_MODE=shadow` records agreement with the LLM; `assist` uses a pick it is `DECISION_MIN_CONF` sure of | existing; only offered candidates are accepted |
| **Forge concrete priority choice**: Laya picks among the same concrete candidate IDs Forge sent to `/api/policy/decide/concrete` | `farmhouse_laya.advise_concrete` / `attach_concrete`, called from `routes/policy.py` | `shadow`: adds `laya` to the response, selection unchanged. `assist`: may replace `selected_id`, never one Forge tagged `stops_immediate_win` / `wins_now`; the original is kept as `csie_selected_id` | candidate described by kind, card, cost, target, tags (never by its opaque id); Forge still executes only an ID it sent |
| **Extra questions in the same call**: "how dangerous are the opponents' boards?" (none/low/moderate/high/lethal) and "is there a threat that must be answered?" | `farmhouse_laya._extra_questions` | whenever Laya is asked | one forward pass answers all questions, so they cost almost nothing; recorded as weak signals for the learned-threat work, **not used to decide** |
| **Capture**: every call is appended to `data/decisions/laya-shadow-<date>.jsonl` (`laya-shadow-v1`) | `farmhouse_laya.capture` | shadow / assist | the text Laya read, the offered options, its answer and extras, and the other deciders' picks (`labels`: `llm`, `csie`, `selected`) |
| **Fine-tuning data**: capture log -> `train.jsonl` / `valid.jsonl` / `manifest.json`, split by game, with the baselines to beat | `scripts/farmhouse_laya_dataset.py` | offline | the manifest reports commonest-action, CSIE-vs-teacher and Laya-zero-shot agreement on the validation side |
| **Card role evidence**: removal, board wipe, ramp, card draw, counterspell, protection, tutor, creature, other, from Oracle text | `farmhouse_laya.classify_roles` (batched, cached, with `source: laya:<model>` provenance); `scripts/farmhouse_laya_roles_eval.py` measures it | on demand | evidence for ITI / Tagger-style use, never a rules fact |
Not built (still the open items in the handoff, none of which Laya can substitute for): compiling and running the Forge controller, the bounded
combo executor, the multi-turn planner, the calibrated learned-threat model. Laya's "threat" and "must answer" extras are only raw material for that last one.
## Where the hooks are
- `src/commander_ai_lab/sim/farmhouse_decide.py` (committed): the macro-choice client gained the extra questions, the state text/options in its
answer, and `record()` writes the capture line.
- `routes/policy.py` (**working tree only, uncommitted**: the route itself is part of the pending strategic-evaluator work, so the hook was
left for that commit). It is one block in `decide_concrete`, after the result is computed:
`if _L.mode() != "off": advice = await run_in_threadpool(_L.advise_concrete, ...); result = _L.attach_concrete(...)`, guarded by `except ImportError`.
- Everything else is new files: `farmhouse_laya.py`, the two scripts, `tests/farmhouse/test_farmhouse_laya*.py`, `farmhouse/laya/`.
## Settings
`DECISION_URL` (e.g. `http://laya.commander-lab.svc.cluster.local:8080`), `DECISION_MODE` (`off` default / `shadow` / `assist`), `DECISION_MODEL`
(a checkpoint such as `typed-decisions`), `DECISION_MIN_CONF` (0.7), `DECISION_TIMEOUT` (5 s), `DECISION_TIMEOUT_FORGE` (**1.5 s**: Forge waits on this),
`DECISION_API_KEY`, `LAYA_CAPTURE_DIR` (`data/decisions`), `LAYA_CAPTURE=0` to stop writing capture lines. Three failures in a row pause asking for a minute.
## Rules the code enforces
1. Text is built from public facts and the acting player's own hand. An opponent's `hand` field is never read, even if a client sends one (tested).
2. Laya's answer must be one of the options that were offered; anything else is discarded.
3. In assist, a pick Forge marked `stops_immediate_win` / `wins_now` is never overridden, and the response says what CSIE chose.
4. A missing, slow or broken server returns "no answer"; nothing raises and the game proceeds as without Laya.
5. Scores and probabilities are relative signals; Laya's probabilities are not calibrated for this game.
## What was measured (2026-10-26, `typed-decisions` checkpoint, 4-thread CPU)
- **Macro action vs the LLM, 149 recorded decisions:** 16.1% (English) and 18.6% (typed-decisions); always guessing the commonest action 27.5%.
- **Forge-shaped priority choice, 3 scenarios, with CSIE's ranking in the text:** agreed with CSIE all three times (expected: the ranking is in the
text it reads), 42-48% sure, **7.5-8.4 s per call** with the extra questions. That is five times Forge's 1.5 s budget: on this CPU the Forge path
would time out and fall back; it needs a GPU (33 ms quoted) or a smaller text.
- **Extras:** "threat" said *high* for a lethal stack, a calm board and a behind board alike (useless zero-shot); "must answer" gave 0.48 for the
lethal stack against 0.25 and 0.29 for the others (right direction, weak).
- **Card roles from Oracle text, 150 unambiguous cards:** 48.0% (16.7% by chance among the six roles present); counterspell 76%, board wipe 64%,
removal 40%, tutor 40%, ramp 36%, card draw 32%; when 70% sure, 69% right but only 11% of cards reach that. **3.2 s per card** in batches on the CPU:
fine for the cards in a hand (cached), not for tagging 30,000 cards (about a day).
## How to make it worth using
1. Run games with `DECISION_URL` set and `DECISION_MODE=shadow` (Farmhouse LLM games, and Forge games through `/api/policy/decide/concrete`).
2. `python scripts/farmhouse_laya_dataset.py --teacher llm` (or `csie`, or `selected`). Read `manifest.json`: the **validation baselines** are the bar.
A student of CSIE can at best equal CSIE, which is free; a student of the LLM is the useful one. Several thousand rows are needed.
3. Fine-tune with Laya's own notebook/script (github.com/NandhaKishorM/laya, `notebooks/`; 2xT4 about 4-5 hours, or Apple silicon). Its worked example
(browser agent choosing among ~45 concrete candidates) went from 0.10 zero-shot to 0.66, so a concrete-candidate head is the shape that works.
Adapt the row field names if its loader differs.
4. Serve the result (`LAYA_EXTRA_MODELS` / `DECISION_MODEL`), rerun `scripts/farmhouse_decision_eval.py` and the dataset manifest, and only then
try `assist`. A GPU host makes the Forge path possible.
5. Keep game result and decision quality separate (handoff boundary 6 / learned-threat contract): a captured label is a teacher's choice, not proof it was right.
Deployment reference copies are in `farmhouse/laya/` (image, manifests, CI); the source of truth is the farmhouse-os GitOps repo.
-74
View File
@@ -1,74 +0,0 @@
# phase-rs and commander-playtester: assessment and plan
Researched 2026-10-26 from the public repositories and data files only. **Nothing from either project has been run, vendored or deployed.**
Facts marked (verified) were read from the source; (unverified) are inferences to check before building on them.
## phase-rs/phase: a rules engine
A Rust rules engine (turns, priority, the stack, combat, layers, triggers, replacement effects) that compiles to native and WebAssembly, with a game
client, a WebSocket server and its own AI. Dual licensed Apache-2.0 / MIT (`LICENSE-APACHE`, `LICENSE-MIT`; GitHub's licence field shows "none" only
because there are two files). Card data from MTGJSON (MIT); card images come from Scryfall at runtime; the repo says it bundles no card art or
Comprehensive Rules text and has a DMCA/fan-content policy. One maintainer, young (weeks to months), fast-moving (latest engine tag v0.100.0).
Why it matters here: our Python simulator has no rules stack (the handoff says so: `stack_supported: false`) and Forge needs a JDK and Maven that
are not in the image. Phase is a rules-accurate engine that can run headless.
### Coverage of the decks in this app (verified, from phase's published `coverage-data.json`)
Phase reports 88.9% of 36,037 cards implemented overall and 92.5% for Commander. For the five saved decks, distinct cards supported:
Empress V8 72/77, Landfall 65/66, God and Anime 69/71, Im not dead yet 82/84, Pew Pew 88/93: **376 of 391 (96.2%)**. The 15 unsupported cards have
one or two parsing gaps each (e.g. Gale Waterdeep Prodigy, Hall of Echoes, Precursor Golem, Invigorate, Mavinda, Drana and Linvala, Tibalt's Trickery).
"Supported" means every ability parsed; it is not a guarantee that each card plays correctly. How the engine treats an unsupported card in a game
(blank, no-op, refused) is **unverified**; test it before trusting a result that involves one.
### The parts that fit
| Part | What it gives us | Notes |
|---|---|---|
| `ai-duel` (crate `phase-ai`) | headless AI-vs-AI games from the command line: seeded, deterministic "measurement mode", batches, JSON reports, a 4-player Commander suite, paired-seed comparison | decks are plain JSON `{"name", "main":[{"name","count"}]}` (verified). **No prebuilt binary is released**: it needs a Rust build (in CI or a container, not on the workstation). How a custom Commander deck and commander are supplied to `--commander-suite` is unverified (that suite reads a feed file) |
| `phase-server` | a WebSocket game server (lobby, hidden information, spectators) | a prebuilt image is published (`ghcr.io/phase-rs/phase-server`, tags `latest`, `preview`, `sha-...`). A Python client could play seats and record every decision with real rules (protocol documentation not yet read) |
| `phase-llm` | **model-driven AI seats**: the engine hands the model its legal option list, the model returns an index, the engine re-validates it, and any failure falls back to the heuristic AI | same principle as `farmhouse_laya.py`. Speaks OpenAI-style chat (so Olla / twin-turbo) **and the System One protocol Laya and Kev serve** (verified: `WireProtocol::SystemOneRelay`, question id `pick`, 2 to 255 options) |
| `POST /jev/systemone` relay in `phase-server` | forwards the System One request to the URL in `TYPESAFE_API_URL` (verified, env var, `http` allowed for local setups) | point it at `http://laya...:8080/v1/systemone` to put Laya or Kev in a seat. The relay sends the key as `Authorization: Bearer` and does not follow redirects |
The attraction for the Laya work: a captured decision from phase is an **engine-issued option list plus the pick**, in rules-accurate games. That
is a better fine-tuning source than this repository's approximate simulator, and the exporter (`scripts/farmhouse_laya_dataset.py`) could take it with a small adapter.
## RafaelAugustScherer/commander-playtester: a browser app on top of phase
TypeScript/React single-page app, no backend. Runs phase's engine as WebAssembly in a Web Worker. Deck library with Moxfield / Archidekt / plain-text
import, a goldfishing Monte Carlo (mulligan rate, screw and flood, land drops, ramp by turn 3, curve), real engine matches (watch, or pilot one seat),
and 1-50 match head-to-head runs with a win rate and 95% confidence interval. Pins the phase engine in `engine-manifest.json` (v0.100.0; its README
still says v0.57.0) and fetches the WASM and card data with SHA-256 checks. Zero stars, last pushed 2026-10-24.
**It has no LICENSE file** (verified: the repository metadata shows none). Without a licence the code is all rights reserved: it can be read and used
as a reference, but not copied into this repository or redistributed. Ask the author to add a licence (MIT would do) before reusing any of it. What is
worth taking as ideas, not code: the goldfishing metrics, the head-to-head confidence-interval report, the name-only deck payload for the engine, and
the engine-smoke gate that boots the real engine and plays a match to completion after every upgrade.
## Recommended plan, smallest useful step first
1. **Prove it on one deck.** Build `ai-duel` from the pinned phase tag in CI (Rust, container), convert one saved deck to the JSON format, run a seeded
batch against a baseline deck, and read the result. Answers: does it run a Commander game end to end, what does it do with an unsupported card, how
long is a game. This replaces the guesswork about the Python simulator's win rates.
2. **A `phase-sim` service** in the commander-lab namespace (no egress, called only by the app) with an endpoint "run N rules-accurate games for deck X
against Y", returning win rate, confidence interval, wins by seat and the game log; the app's results panel reads it. The Python simulator stays for
instant, rough Monte Carlo.
3. **Model seats.** Run `phase-server` with `TYPESAFE_API_URL` at Laya (or at a fine-tuned one later) and the OpenAI-compatible seat at Olla; compare
heuristic-only, LLM and Laya seats. Record every decision for the Laya dataset.
4. **Only then** consider the playtester's UI ideas, after the author adds a licence or as a clean reimplementation.
## What was built from this plan (2026-10-27)
1. **The headless runner** (`ai-commander`, Commander four-player, batch mode) is built from the v0.118.0 tag with the card database that release was published with, in a
container (`farmhouse/phase/Dockerfile`). Not `ai-duel` for the decks: `ai-commander` takes a feed JSON of four decks, which is exactly what the app has.
2. **The service and the app side**: `farmhouse/phase/phase_sim.py` (HTTP, jobs, parser, warnings) and `routes/farmhouse_phase.py` + `ui/phase-sim.html`. Games that stall, hit the
action cap or panic are reported and never counted.
3. **Model seats**: not a setting. phase's model support lives only in its browser client (`engine-wasm` calls `phase-llm`; the HTTP is done by TypeScript), and
`phase-llm` depends on `phase-ai`, so the headless binary cannot use it. `farmhouse/phase/llm-seat/` is a new crate that includes the runner and installs a hook
(two anchored edits to phase's source). The server-side Jev relay and the browser client were not needed. Details: `farmhouse/phase/README.md`.
Not done: the playtester's UI (no licence), a Python client for phase's WebSocket server (a large, fast-moving protocol), feeding the captured model-seat decisions into
`scripts/farmhouse_laya_dataset.py` (the natural next step: each is an engine-issued option list plus a pick).
## Risks and open questions
- Phase is a one-person, fast-moving project: pin tags, keep a smoke test that plays a full game, expect breaking changes.
- Rust builds are heavy; keep them in CI/containers. Resource and image size are unmeasured.
- Card coverage is parse-level; correctness per card is unmeasured. Unsupported cards must be flagged in any result.
- The phase server and its AI use CPU; its measured game speed is unknown (the README says a game is thousands of AI decisions).
- Legal: phase is Apache/MIT with Wizards fan-content wording; the playtester has no licence. The card data is MTGJSON (MIT).
- Not yet read: phase's WebSocket protocol, how `--commander-suite` accepts custom decks, and whether the server can run unattended self-play.
@@ -1,93 +0,0 @@
# Phase 1 — Self-Play Integration Checklist
> **Issue:** #65 — PPO Decision Exporter
> **Ref:** `docs/CLOSED-LOOP-DISTILLATION.md`
> **Status:** In Progress
---
## Completed
- [x] Create `ml/training/decision_exporter.py` with `DecisionExporter` class
- [x] `ExporterConfig` dataclass (output_dir, only_wins, model_version, min_episode_steps)
- [x] `build_decision_record()` — converts PPO step data into Forge-compatible JSONL format
- [x] `DecisionExporter.begin_episode()` / `record_step()` / `end_episode()` / `flush()` lifecycle
- [x] Write to `data/results/ml-decisions-ppo-{batch_id}.jsonl`
- [x] Include PPO metadata fields: `source`, `model_version`, `reward`, `episode_return`
- [x] Win-only filtering (only export decisions from winning games)
- [x] Short-episode gating (`min_episode_steps` threshold)
- [x] `_macro_action_to_forge_type()` mapping (MacroAction enum → Forge action type strings)
- [x] Export stats tracking (`stats` property)
---
## Remaining — Integrate into `ml/training/self_play.py`
### Import
- [ ] Add import: `from ml.training.decision_exporter import DecisionExporter`
### Modify `run_self_play_episode()`
- [ ] Add `exporter: DecisionExporter = None` parameter to function signature
- [ ] After each `trajectory.append(...)` block (3 locations), add:
```python
if exporter is not None:
exporter.record_step(
game_state_snapshot=prev_snapshot,
action_idx=action_idx,
reward=reward,
)
```
### Modify `collect_rollouts()`
- [ ] Add `exporter: DecisionExporter = None` parameter to function signature
- [ ] Before each episode, call:
```python
if exporter is not None:
exporter.begin_episode(agent_seat=agent_seat, playstyle=playstyle)
```
- [ ] Pass `exporter=exporter` to `run_self_play_episode()`
- [ ] After outcome tracking, call:
```python
if exporter is not None:
won = trajectory and trajectory[-1]["done"] and trajectory[-1]["reward"] > 0.5
ep_return = sum(s["reward"] for s in trajectory)
exporter.end_episode(won=won, episode_return=ep_return)
```
### Commit
- [ ] `git add ml/training/self_play.py`
- [ ] `git commit -m "feat(ml): integrate DecisionExporter into self-play rollouts (#65)"`
- [ ] `git push origin main`
---
## Integration Pattern
```
collect_rollouts(exporter=exporter)
└─ for each episode:
├─ exporter.begin_episode(seat, playstyle)
├─ run_self_play_episode(..., exporter=exporter)
│ └─ for each step:
│ ├─ trajectory.append(step_data)
│ └─ exporter.record_step(snapshot, action, reward)
└─ exporter.end_episode(won, episode_return)
# Caller does: exporter.flush()
```
---
## Terminal Commands
```bash
cd commander-ai-lab
git pull origin main
# Make edits to ml/training/self_play.py per checklist above
git add ml/training/self_play.py
git commit -m "feat(ml): integrate DecisionExporter into self-play rollouts (#65)"
git push origin main
```
-785
View File
@@ -1,785 +0,0 @@
# Commander-AI-Lab — Unity TCGEngine Commander Board: Implementation Plan (v5)
> **Architecture Principle:** Forge = Rules Authority · FastAPI = Hub · TCGEngine Unity = Renderer · Dual-Brain AI = Decision Engine
---
## System Architecture Overview
```
┌─────────────────────────────────────────────────────────────────┐
│ UNITY (TCGEngine — 2D Board) │
│ PlayerArea x4: Hand | Library | Graveyard | Exile | Command │
│ Battlefield zones per player · Card art from local cache │
│ GameNetworkManager.cs ←── WebSocket ──► FastAPI │
└─────────────────────────────────────────────────────────────────┘
▲ ▼
┌─────────────────────────────────────────────────────────────────┐
│ FASTAPI (commander-ai-lab) │
│ /ws/game — WebSocket relay │
│ /game/action — receive player/AI action, forward to Forge │
│ ForgeSubprocessManager — stdin/stdout pipe to Forge JVM │
│ CardEnricher — injects art_url from local image cache │
│ AIOrchestrator — routes decisions to DeepSeek-R1 or GPT-OSS │
│ ChromaDB RAG — card knowledge scoped per player deck │
│ ai_decisions.jsonl — logs every AI decision (PPO dataset) │
└─────────────────────────────────────────────────────────────────┘
▲ ▼
┌─────────────────────────────────────────────────────────────────┐
│ FORGE (Java — Headless Rules Engine) │
│ Full Commander rules: tax, 21-commander-damage, 40 life │
│ 4-player turn queue · Zone redirects · State-based actions │
│ Emits game state JSON to stdout · Receives actions via stdin │
└─────────────────────────────────────────────────────────────────┘
```
---
## Dual-Brain AI Decision Flow
This is the **core feature** of Commander-AI-Lab. Every AI player decision runs through this pipeline:
```
Forge emits GameStateDTO (JSON)
└─► FastAPI detects active player is AI
└─► select_brain(phase, stack_size)
├─ DeepSeek-R1-14B → combat, stack decisions, removal
└─ GPT-OSS-20B → main phase, ramp, card advantage
└─► ChromaDB.query(player_deck_cards, top_k=5)
└─► build_prompt(state, rag_context, personality)
└─► LLM.generate(prompt)
└─► parse_action_json(response)
├─ validate vs legal_actions[]
├─ log to ai_decisions.jsonl
└─► Forge stdin ← chosen action
```
### Brain Selector (`ai/brain_selector.py`)
```python
from enum import Enum
class Brain(Enum):
DEEPSEEK = "deepseek-r1:14b"
GPT_OSS = "gpt-oss-20b" # adjust to your Ollama model tag
def select_brain(phase: str, stack_size: int) -> Brain:
"""
DeepSeek-R1: combat math, instant-speed stack decisions, targeted removal.
GPT-OSS: sorcery-speed strategy, ramp sequencing, card selection.
"""
combat_phases = {"declare_attackers", "declare_blockers", "combat_damage"}
if phase in combat_phases or stack_size > 0:
return Brain.DEEPSEEK
return Brain.GPT_OSS
```
### Prompt Builder (`ai/prompt_builder.py`)
```python
from chromadb import Client
from .personality import get_personality_prompt
chroma = Client()
card_collection = chroma.get_collection("mtg_cards")
def build_prompt(state: dict, player_id: str, personality: str) -> str:
# Pull card knowledge scoped to THIS player's deck
player_cards = [c["name"] for c in state["players"][player_id]["library"]]
rag_results = card_collection.query(
query_texts=player_cards[:10],
n_results=5
)
card_context = "\n".join(rag_results["documents"][0])
personality_prompt = get_personality_prompt(personality)
return f"""You are an AI playing Magic: The Gathering Commander.
{personality_prompt}
## Current Game State
- Phase: {state['phase']}
- Active Player: {player_id}
- Life Totals: {state['life_totals']}
- Commander Damage Dealt: {state['commander_damage']}
- Stack: {state['stack']}
- Your Hand: {[c['name'] for c in state['players'][player_id]['hand']]}
- Battlefield: {[c['name'] for c in state['players'][player_id]['battlefield']]}
- Available Mana: {state['players'][player_id]['mana_pool']}
## Legal Actions
{state['legal_actions']}
## Card Knowledge (RAG Context)
{card_context}
Respond with a single JSON object:
{{"action": "<action_type>", "card_id": "<id_or_null>", "targets": [], "reasoning": "<brief>"}}
"""
```
### Personality System (`ai/personality.py`)
```python
import random
PERSONALITIES = {
"aggro_beatdown": "You play aggressively. Attack every turn. Remove blockers. Win through combat damage as fast as possible.",
"control_lockdown": "You play control. Counter key threats. Hold up mana for interaction. Win only when the board is locked.",
"combo_enabler": "You dig for your combo pieces. Every decision is evaluated by how it advances your win condition.",
"political_diplomat": "You form alliances. Attack the leader. Make deals. Never be the archenemy.",
"voltron_commander": "Everything buffs your commander. Protect it at all costs. Win through commander damage.",
"stax_prison": "You tax and restrict opponents. Deploy hate pieces. Win through attrition and resource denial.",
"tempo_value": "You trade efficiently. Generate card advantage. Win by being ahead on resources.",
"chaos_wildcard": "You make unpredictable decisions. Prioritize fun and chaos over optimal play.",
}
def assign_personalities(player_ids: list[str], deck_archetypes: dict) -> dict[str, str]:
"""
Assign a personality per AI player at game creation.
80% chance: archetype-matched personality.
20% chance: random wildcard for unpredictability.
"""
assignments = {}
for pid in player_ids:
archetype = deck_archetypes.get(pid, "tempo_value")
if random.random() < 0.20:
assignments[pid] = random.choice(list(PERSONALITIES.keys()))
else:
assignments[pid] = archetype
return assignments
def get_personality_prompt(personality: str) -> str:
return f"## Your Playstyle\n{PERSONALITIES.get(personality, PERSONALITIES['tempo_value'])}"
```
### AI Orchestrator (`ai/ai_orchestrator.py`)
```python
import json, time, logging
from pathlib import Path
from .brain_selector import select_brain, Brain
from .prompt_builder import build_prompt
import ollama
LOG_PATH = Path("logs/ai_decisions.jsonl")
LOG_PATH.parent.mkdir(exist_ok=True)
async def get_ai_action(state: dict, player_id: str, personality: str) -> dict:
brain = select_brain(state["phase"], len(state["stack"]))
prompt = build_prompt(state, player_id, personality)
t_start = time.time()
try:
response = ollama.chat(
model=brain.value,
messages=[{"role": "user", "content": prompt}],
options={"temperature": 0.3, "num_predict": 256}
)
raw = response["message"]["content"]
# Extract JSON from response (model may wrap in markdown)
action = json.loads(raw[raw.find("{"):raw.rfind("}")+1])
except Exception as e:
logging.warning(f"AI parse failed ({brain.value}): {e}. Passing turn.")
action = {"action": "pass", "card_id": None, "targets": [], "reasoning": "parse_error"}
# Validate against Forge legal actions
if action.get("action") not in [a["type"] for a in state["legal_actions"]]:
logging.warning(f"Illegal action returned by {brain.value}. Falling back to pass.")
action = {"action": "pass", "card_id": None, "targets": [], "reasoning": "illegal_action"}
# Log for PPO training dataset
log_entry = {
"timestamp": time.time(),
"player_id": player_id,
"brain": brain.value,
"personality": personality,
"phase": state["phase"],
"action": action,
"reasoning": action.get("reasoning", ""),
"latency_ms": round((time.time() - t_start) * 1000),
}
with open(LOG_PATH, "a") as f:
f.write(json.dumps(log_entry) + "\n")
return action
```
---
## Phase 0 — Local Card Image Cache
**Build this first.** Every downstream system depends on local art URLs.
### Step 1 — Bulk Download (`scripts/download_card_images.py`)
```python
import requests, json, os
from pathlib import Path
from tqdm import tqdm
BULK_URL = "https://api.scryfall.com/bulk-data/default-cards"
IMAGE_DIR = Path("static/card-images")
IMAGE_DIR.mkdir(parents=True, exist_ok=True)
def download_images():
# Get bulk data URL
meta = requests.get(BULK_URL).json()
cards = requests.get(meta["download_uri"], stream=True).json()
for card in tqdm(cards, desc="Downloading card images"):
image_uris = card.get("image_uris") or {}
url = image_uris.get("normal")
if not url:
continue # skip DFCs without top-level image_uris
safe_name = card["name"].replace("/", "_").replace(" ", "_")
set_code = card.get("set", "unknown")
filename = IMAGE_DIR / set_code / f"{safe_name}_{card['collector_number']}.jpg"
filename.parent.mkdir(parents=True, exist_ok=True)
if filename.exists():
continue # already cached
img_data = requests.get(url, timeout=10).content
filename.write_bytes(img_data)
if __name__ == "__main__":
download_images()
```
### Step 2 — Build SQLite Index (`scripts/build_image_index.py`)
```python
import sqlite3
from pathlib import Path
IMAGE_DIR = Path("static/card-images")
DB_PATH = Path("data/card_images.db")
DB_PATH.parent.mkdir(exist_ok=True)
def build_index():
conn = sqlite3.connect(DB_PATH)
conn.execute("""
CREATE TABLE IF NOT EXISTS card_images (
name TEXT PRIMARY KEY,
path TEXT NOT NULL
)
""")
for img_path in IMAGE_DIR.rglob("*.jpg"):
card_name = img_path.stem.rsplit("_", 1)[0].replace("_", " ")
conn.execute("INSERT OR REPLACE INTO card_images VALUES (?, ?)",
(card_name, str(img_path)))
conn.commit()
conn.close()
if __name__ == "__main__":
build_index()
```
### Step 3 — Card Enricher (`api/card_enricher.py`)
```python
import sqlite3
from pathlib import Path
DB_PATH = Path("data/card_images.db")
STATIC_URL = "http://localhost:8000/static/card-images"
def enrich_card(card: dict) -> dict:
"""Inject local art_url into every CardDTO before sending to Unity."""
conn = sqlite3.connect(DB_PATH)
cursor = conn.execute("SELECT path FROM card_images WHERE name = ?", (card["name"],))
row = cursor.fetchone()
conn.close()
if row:
relative = Path(row[0]).relative_to("static/card-images")
card["art_url"] = f"{STATIC_URL}/{relative}"
else:
card["art_url"] = f"{STATIC_URL}/card_back.jpg"
return card
```
### Step 4 — FastAPI Static Mount (`main.py` addition)
```python
from fastapi.staticfiles import StaticFiles
app.mount("/static/card-images", StaticFiles(directory="static/card-images"), name="card-images")
```
---
## Phase 1 — Forge Bridge (Rules Engine)
### ForgeSubprocessManager (`forge/subprocess_manager.py`)
```python
import subprocess, json, asyncio, threading
from pathlib import Path
FORGE_JAR = Path("forge/forge-game.jar")
class ForgeSubprocessManager:
def __init__(self):
self.process = None
self._lock = threading.Lock()
def start(self, deck_paths: list[str], format: str = "commander"):
cmd = [
"java", "-jar", str(FORGE_JAR),
"--headless",
"--format", format,
"--decks", *deck_paths,
"--output", "json"
]
self.process = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1
)
def read_state(self) -> dict:
with self._lock:
line = self.process.stdout.readline()
return json.loads(line)
def send_action(self, action: dict):
with self._lock:
self.process.stdin.write(json.dumps(action) + "\n")
self.process.stdin.flush()
def stop(self):
if self.process:
self.process.terminate()
```
### Data Transfer Objects (`api/dtos.py`)
```python
from pydantic import BaseModel
from typing import Optional
class CardDTO(BaseModel):
id: str
name: str
type: str
power: Optional[str]
toughness: Optional[str]
mana_cost: str
art_url: str = ""
tapped: bool = False
zone: str = "hand"
class PlayerDTO(BaseModel):
id: str
life: int
commander_damage: dict[str, int]
commander_tax: int
hand: list[CardDTO]
battlefield: list[CardDTO]
graveyard: list[CardDTO]
exile: list[CardDTO]
command_zone: list[CardDTO]
library_count: int
mana_pool: dict[str, int]
is_ai: bool
personality: Optional[str]
class GameStateDTO(BaseModel):
game_id: str
phase: str
active_player: str
priority: str
turn_number: int
players: list[PlayerDTO]
stack: list[dict]
legal_actions: list[dict]
winner: Optional[str]
```
---
## Phase 2 — FastAPI WebSocket Game Server
### Game Loop (`api/game_loop.py`)
```python
import asyncio, uuid
from .dtos import GameStateDTO
from forge.subprocess_manager import ForgeSubprocessManager
from ai.ai_orchestrator import get_ai_action
from ai.personality import assign_personalities
from api.card_enricher import enrich_card
active_games: dict[str, dict] = {}
async def start_game(deck_paths: list[str], ai_players: list[str]) -> str:
game_id = str(uuid.uuid4())
forge = ForgeSubprocessManager()
forge.start(deck_paths)
# Assign AI personalities at game creation
archetypes = detect_archetypes(deck_paths, ai_players) # ChromaDB query
personalities = assign_personalities(ai_players, archetypes)
active_games[game_id] = {
"forge": forge,
"ai_players": ai_players,
"personalities": personalities,
"websockets": []
}
asyncio.create_task(game_loop(game_id))
return game_id
async def game_loop(game_id: str):
game = active_games[game_id]
forge = game["forge"]
while True:
raw_state = forge.read_state()
if raw_state.get("winner"):
await broadcast(game_id, raw_state)
break
# Enrich every card with local art_url
state = enrich_state(raw_state)
await broadcast(game_id, state)
priority_player = state["priority"]
if priority_player in game["ai_players"]:
personality = game["personalities"][priority_player]
action = await get_ai_action(state, priority_player, personality)
forge.send_action(action)
# else: wait for Unity client to send action via WebSocket
async def broadcast(game_id: str, state: dict):
game = active_games[game_id]
for ws in game["websockets"]:
await ws.send_json(state)
def enrich_state(state: dict) -> dict:
for player in state["players"]:
for zone in ["hand", "battlefield", "graveyard", "exile", "command_zone"]:
player[zone] = [enrich_card(c) for c in player.get(zone, [])]
return state
```
### WebSocket Endpoint (`api/routes/game.py`)
```python
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from api.game_loop import active_games, start_game
router = APIRouter()
@router.websocket("/ws/game/{game_id}")
async def game_ws(websocket: WebSocket, game_id: str):
await websocket.accept()
game = active_games.get(game_id)
if not game:
await websocket.close(code=4004)
return
game["websockets"].append(websocket)
try:
while True:
data = await websocket.receive_json()
# Human player action forwarded directly to Forge
game["forge"].send_action(data)
except WebSocketDisconnect:
game["websockets"].remove(websocket)
```
---
## Phase 3 — Unity TCGEngine Board (2D)
### Project Layout
```
unity-commander-ui/
├── Assets/
│ ├── TCGEngine/ ← TCGEngine base (unmodified)
│ ├── Commander/
│ │ ├── Scripts/
│ │ │ ├── GameNetworkManager.cs ← WebSocket ↔ FastAPI
│ │ │ ├── CommanderBoardUI.cs ← 4-player layout controller
│ │ │ ├── PlayerAreaUI.cs ← per-player zone panel
│ │ │ ├── CardImageLoader.cs ← local cache texture fetcher
│ │ │ ├── ZonePanel.cs ← Hand/Library/Graveyard/Exile/Command
│ │ │ └── AIThinkingIndicator.cs ← spinner while AI brain is deciding
│ │ └── Prefabs/
│ │ ├── CardPrefab.prefab
│ │ ├── PlayerAreaPrefab.prefab
│ │ └── ZonePanelPrefab.prefab
│ └── Scenes/
│ └── CommanderBoard.unity
```
### Board Layout (matches screenshot)
```
┌──────────────────────────────────────────────────────────────────┐
│ [LIBRARY][GRAVEYARD][EXILE] [────── HAND ──────] (Player 3) │
│ [COMMAND] │
├──────────────────────────────┬───────────────────────────────────┤
│ │ │
│ │ │
│ BATTLEFIELD │ BATTLEFIELD │
│ (Player 1) │ (Player 2) │
│ BATTLEFIELD (center) │
│ BATTLEFIELD │ BATTLEFIELD │
│ (Player 4) │ (Player 3) │
│ │ │
├──────────────────────────────┴───────────────────────────────────┤
│ [COMMAND] │
│ [LIBRARY][GRAVEYARD][EXILE] [────── HAND ──────] (Player 1) │
└──────────────────────────────────────────────────────────────────┘
```
### GameNetworkManager.cs
```csharp
using UnityEngine;
using NativeWebSocket;
using Newtonsoft.Json;
public class GameNetworkManager : MonoBehaviour
{
public static GameNetworkManager Instance { get; private set; }
[SerializeField] private string serverUrl = "ws://localhost:8000/ws/game/";
[SerializeField] private string gameId;
private WebSocket _socket;
public delegate void GameStateReceived(GameStateDTO state);
public event GameStateReceived OnGameStateReceived;
async void Awake()
{
Instance = this;
_socket = new WebSocket($"{serverUrl}{gameId}");
_socket.OnMessage += (bytes) =>
{
var json = System.Text.Encoding.UTF8.GetString(bytes);
var state = JsonConvert.DeserializeObject<GameStateDTO>(json);
UnityMainThreadDispatcher.Enqueue(() => OnGameStateReceived?.Invoke(state));
};
await _socket.Connect();
}
public async void SendAction(object action)
{
var json = JsonConvert.SerializeObject(action);
await _socket.SendText(json);
}
void Update() => _socket?.DispatchMessageQueue();
async void OnDestroy() => await _socket?.Close();
}
```
### CardImageLoader.cs
```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class CardImageLoader : MonoBehaviour
{
private static Dictionary<string, Texture2D> _cache = new();
public static IEnumerator LoadCardArt(string artUrl, RawImage target)
{
if (_cache.TryGetValue(artUrl, out var cached))
{
target.texture = cached;
yield break;
}
using var req = UnityWebRequestTexture.GetTexture(artUrl);
yield return req.SendWebRequest();
if (req.result == UnityWebRequest.Result.Success)
{
var tex = DownloadHandlerTexture.GetContent(req);
_cache[artUrl] = tex;
target.texture = tex;
}
else
{
Debug.LogWarning($"Failed to load card art: {artUrl}");
}
}
}
```
### AIThinkingIndicator.cs
```csharp
using UnityEngine;
using UnityEngine.UI;
/// Shows a spinner + brain label while the AI is deciding.
public class AIThinkingIndicator : MonoBehaviour
{
[SerializeField] private GameObject spinnerPanel;
[SerializeField] private Text brainLabel;
[SerializeField] private Text personalityLabel;
public void Show(string brain, string personality)
{
spinnerPanel.SetActive(true);
brainLabel.text = $"🧠 {brain}";
personalityLabel.text = $"🎭 {personality}";
}
public void Hide() => spinnerPanel.SetActive(false);
}
```
---
## Phase 4 — Commander Zone UIs
### Zone Definitions per Player
| Zone Panel | Content | Notes |
|---|---|---|
| `LIBRARY` | Count only | Click → draw/look at top |
| `GRAVEYARD` | Scrollable card list | Full card art on hover |
| `EXILE` | Scrollable card list | Includes face-down indicators |
| `HAND` | Wide panel, card art | Hidden to opponents |
| `COMMAND` | Commander card(s) | Shows commander tax counter |
| `BATTLEFIELD` | Open grid | Tapped/untapped state, counters |
### Commander-Specific UI Elements
```csharp
public class CommanderZoneUI : MonoBehaviour
{
[SerializeField] private Text taxCounter; // "Tax: +{2N}"
[SerializeField] private RawImage commanderArt;
[SerializeField] private Text commanderDamageDealt; // per opponent
public void Refresh(PlayerDTO player)
{
int tax = player.CommanderTax;
taxCounter.text = tax > 0 ? $"+{tax * 2}" : "";
if (player.CommandZone.Count > 0)
StartCoroutine(CardImageLoader.LoadCardArt(
player.CommandZone[0].ArtUrl, commanderArt));
}
}
```
---
## Phase 5 — Commander Rules Validation Layer
Forge handles all rules natively. FastAPI validates the AI response is within the legal actions list Forge returns — no custom rules code needed in Python or Unity.
Key Commander rules confirmed handled by Forge headless:
- **Commander Tax** — +2 generic per previous cast from command zone
- **21 Commander Damage** — tracked per attacker/defender pair
- **40 Starting Life**
- **Zone Redirect** — commander goes to command zone instead of graveyard/exile (player choice)
- **Color Identity** — deck validation at game start
- **Singleton** — deck validation at game start
---
## Phase 6 — AI Decision Logging & PPO Pipeline
Every AI decision written to `logs/ai_decisions.jsonl`:
```json
{
"timestamp": 1743520800.123,
"player_id": "player_2",
"brain": "deepseek-r1:14b",
"personality": "aggro_beatdown",
"phase": "declare_attackers",
"action": {"action": "attack", "card_id": "c_042", "targets": ["player_1"], "reasoning": "Open attack, no blockers visible"},
"latency_ms": 847
}
```
This log becomes the **supervised learning dataset** for the next PPO training iteration. Each (state, action) pair from winning games is a positive training example.
---
## Project Directory Structure
```
commander-ai-lab/
├── main.py ← FastAPI app, mounts static files
├── api/
│ ├── dtos.py ← Pydantic DTOs
│ ├── card_enricher.py ← Injects art_url into CardDTOs
│ ├── game_loop.py ← Main game orchestration loop
│ └── routes/
│ └── game.py ← WebSocket + REST endpoints
├── ai/
│ ├── ai_orchestrator.py ← Main AI decision entry point
│ ├── brain_selector.py ← DeepSeek-R1 vs GPT-OSS routing
│ ├── prompt_builder.py ← Game state + RAG → prompt
│ └── personality.py ← 8 personalities + assignment
├── forge/
│ └── subprocess_manager.py ← Forge JVM stdin/stdout bridge
├── scripts/
│ ├── download_card_images.py ← One-time Scryfall bulk download
│ └── build_image_index.py ← SQLite name→path index
├── static/
│ └── card-images/ ← ~2GB local image cache
│ └── {set_code}/
│ └── {CardName}_{num}.jpg
├── data/
│ └── card_images.db ← SQLite image index
├── logs/
│ └── ai_decisions.jsonl ← PPO training dataset
├── unity-commander-ui/ ← Unity 2D TCGEngine project
└── docs/
└── implementation_plan.md ← This document
```
---
## Phased Timeline
| Phase | Scope | Est. Time |
|---|---|---|
| **0** | Scryfall image download + SQLite index + FastAPI static mount | 1 day |
| **1** | Forge subprocess bridge + DTO definitions | 2–3 days |
| **2** | AI Orchestrator + brain selector + prompt builder + personality system | 3–4 days |
| **3** | Unity TCGEngine project setup + WebSocket GameNetworkManager | 3–4 days |
| **4** | PlayerAreaUI + ZonePanels + CardImageLoader + board layout | 3–4 days |
| **5** | Commander zone UI (tax counter, commander damage, zone redirect) | 1–2 days |
| **6** | AI decision logging + end-to-end game loop test | 1–2 days |
**Total estimated: ~3 weeks to first playable Commander game with live AI opponents.**
---
## Key Design Decisions
| Decision | Rationale |
|---|---|
| Forge = rules authority | Forge already handles all Commander rules natively. No custom rules code. |
| TCGEngine = dumb renderer | All game logic lives in Forge. Unity only renders state it receives. |
| FastAPI = hub | Bridges Forge ↔ Unity ↔ AI. Single point of truth. |
| Dual-brain routing | DeepSeek-R1 excels at analytical/math decisions; GPT-OSS at strategic sequencing. |
| ChromaDB scoped per player | RAG context relevant to the active player's deck, not global card knowledge. |
| Personality persists per game | Consistent playstyle per AI across all 4 players per session. |
| Local image cache | Eliminates network latency for card art. ~2GB one-time download. |
| ai_decisions.jsonl | Every AI decision is a future PPO training sample. |
-32
View File
@@ -1,32 +0,0 @@
# Forge in the cluster image
The batch simulator on the Simulator page runs on **Forge**, the Java rules engine. The first cluster builds left it out by mistake ("Python-only"
was read as "no Java"), so the page answered `Forge JAR not found`. It is now built into the image (reference copy of the Dockerfile stage:
`infrastructure/apps/commander-lab/image/Dockerfile` in the farmhouse-os repo).
What the image build does:
1. **Stage 1** (`maven:3.9-eclipse-temurin-17`): fetch the official `Card-Forge/forge` at commit `edb28158f6d8` (the commit `KoalaTrapLord/Forge-Repo`
is on; that fork is 0 commits ahead of upstream, so this is the code the lab's Java was written against; newer Forge may have changed APIs), then
`mvn install -pl forge-gui-desktop -am -DskipTests -Drevision=2.0.12-SNAPSHOT`, retried up to three times (Maven Central downloads fail now and then).
2. **The lab's Java tool** (`LabCli`, from this repository's `pom.xml`) is built against it. Forge's installed poms keep `${revision}` as their parent
version, which Maven cannot resolve for a consumer even with `-Drevision`; the placeholder is rewritten in the installed `.pom` files first.
3. **Runtime**: the full `openjdk-17-jre` (not `-headless`) plus `xvfb`, the two jars, and Forge's `res/` data without `adventure`, `music`, `sound`, `quest` and `skins`
(about 190 MB the headless simulator never reads). The environment the app reads: `FORGE_JAR`, `FORGE_DIR`, `LAB_JAR`, `FORGE_DECKS_DIR`, `PRECON_DIR`, `JAVA_HOME`.
4. `FORGE_MAX_THREADS` (default 1) clamps the batch's thread count: every Forge game is its own JVM with up to a 4 GB heap, and the cluster has two small nodes.
5. CI starts the app, begins a batch through the app's own `/api/lab/start` and requires a Commander game with turns played and a readable `/api/lab/result` before the image is published.
## Things that only showed up by running it in the cluster (2026-10-27)
Each of these made a batch fail while every individual piece looked installed. Together they are why the CI test starts a batch through the app's own API.
- **Forge needs a display, even for `sim`.** `GuiDesktop`'s static initialiser asks AWT for the default screen device; the headless JRE throws `HeadlessException`, and
`forge.view.Main` then exits 1 with no output at all (the lab tool records every game as an instant draw: "Forge produced NO output"). Fix: the full `openjdk-17-jre`,
`xvfb`, `DISPLAY=:99`, and the entrypoint starts `Xvfb :99`.
- **Three folders, one deck.** The app writes saved decks to `USER_DECKS_DIR`, the lab's Java tool resolves deck files through `PRECON_DECKS_DIR`, and Forge finds a deck BY
NAME in its own commander folder ("Could not load deck"). All three are the Forge folder (`FORGE_DECKS_DIR`), which the entrypoint seeds with the 163 bundled precons.
- **Writable folders.** The tool writes `results/` beside Forge's data and Forge a debug log beside its jar; both folders are owned by uid 10001 in the image.
- **Result path.** The app asked for `results/ml-decision-<id>.json` (relative) but ran the tool from Forge's folder, so the file landed there and `/api/lab/result` answered
"Result file not found". The path is made absolute (patch `forge-results-abs`) and `/app/results` is linked to `/state/results`.
- `docker cp` cannot write into a tmpfs and Docker mounts `/tmp` `noexec` (it stops SQLite's native library loading): test-harness traps, not cluster problems.
Speed: about 25 seconds per game, one at a time (the project's own figure is ~0.04 simulations/s single-threaded). For many games with real rules, the
phase-rs engine (`farmhouse/phase/`) is far faster. Forge is GPL-3.0: private use, do not redistribute the built image.
-37
View File
@@ -1,37 +0,0 @@
#!/bin/sh
# Keep the app's state on the persistent volume (/state) while the code stays in the image.
# The upstream app writes next to its code: collection.db, scryfall_cache.db, data/ (Scryfall bulk DB, ChromaDB index),
# user-decks/. Point each at /state with a symlink; seed data/ and user-decks/ from the image the first time.
set -eu
S="${STATE_DIR:-/state}"
mkdir -p "$S"
for d in data user-decks results; do
if [ ! -e "$S/$d" ]; then
if [ -d "/app/$d" ]; then cp -a "/app/$d" "$S/$d"; else mkdir -p "$S/$d"; fi
fi
rm -rf "/app/$d"
ln -s "$S/$d" "/app/$d"
done
for f in collection.db scryfall_cache.db; do
rm -f "/app/$f"
ln -s "$S/$f" "/app/$f" # sqlite creates the target on first open
done
# Forge looks decks up by name in its user folder; the app exports the decks it simulates there.
mkdir -p "${FORGE_DECKS_DIR:-/tmp/.forge/decks/commander}"
# Seed it with the bundled precon decks (163 small files); never overwrite a deck that is already there.
if [ -d /app/precon-decks ]; then cp -n /app/precon-decks/*.dck "${FORGE_DECKS_DIR:-/tmp/.forge/decks/commander}"/ 2>/dev/null || true; fi
# A virtual display for Forge (it initialises AWT even in command-line mode; see the Dockerfile). Best effort: the app itself does not need it.
if command -v Xvfb >/dev/null 2>&1; then
mkdir -p /tmp/.X11-unix && chmod 1777 /tmp/.X11-unix 2>/dev/null || true
Xvfb "${DISPLAY:-:99}" -screen 0 1280x800x24 -nolisten tcp >/tmp/xvfb.log 2>&1 &
for _ in 1 2 3 4 5 6 7 8 9 10; do
[ -S "/tmp/.X11-unix/X${DISPLAY#:}" ] && break
sleep 0.3
done
fi
exec "$@"
-34
View File
@@ -1,34 +0,0 @@
# Laya (https://github.com/NandhaKishorM/laya, Apache-2.0): a "decision model". It answers typed multiple-choice / yes-no / score
# questions about a piece of text in ONE forward pass (about 33 ms on a GPU) and never writes text. Here it is staged for the Commander
# AI Lab simulator, which asks an LLM "which action?" about 25 times per game; a small classifier can answer that class of question
# far faster, if it is accurate enough (it is measured in shadow mode first, see ../README.md).
#
# CPU only. The weights are baked in at a pinned Hugging Face commit and the pod has NO network access (NetworkPolicy), so the
# running service fetches nothing. Two checkpoints are included so they can be compared: the English base and the fine-tuned
# "typed-decisions" one (about 840 MB each).
FROM python:3.12-slim-bookworm
ARG LAYA_VERSION=0.4.15
ARG LAYA_HF_REVISION=7b928d828b7b0e022f929d9bd2e44165aa270148
ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1 PYTHONUNBUFFERED=1 HF_HOME=/opt/hf
RUN pip install torch --index-url https://download.pytorch.org/whl/cpu \
&& pip install "laya[serve]==${LAYA_VERSION}"
# Weights at the pinned commit. HF's offline lookup resolves the "main" ref, which a commit-pinned download does not create, so it is
# written by hand to the same commit.
RUN python -c "from huggingface_hub import snapshot_download; snapshot_download('convaiinnovations/laya', revision='${LAYA_HF_REVISION}', ignore_patterns=['multilingual/*','assets/*','eval/*'])" \
&& mkdir -p /opt/hf/hub/models--convaiinnovations--laya/refs \
&& printf '%s' "${LAYA_HF_REVISION}" > /opt/hf/hub/models--convaiinnovations--laya/refs/main \
&& chmod -R a+rX /opt/hf
RUN useradd --uid 10001 --no-create-home --shell /usr/sbin/nologin laya
USER 10001
ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
LAYA_HOST=0.0.0.0 LAYA_PORT=8080 \
LAYA_MODELS=english,typed-decisions LAYA_DEFAULT_MODEL=english LAYA_MAX_LOADED=2 LAYA_PRELOAD=1 LAYA_THREADS=4
EXPOSE 8080
CMD ["laya-serve"]
-52
View File
@@ -1,52 +0,0 @@
# Laya as the simulator's "which action?" model: evaluation, 2026-10-26
**Result: not usable as shipped.** Both checkpoints agreed with the LLM less often than a model that always answers the commonest action.
## What was measured
The simulator's LLM brain ("twin-turbo") picks one of nine actions about 25 times a game. A decision model (Laya, or Kev; both serve
`POST /v1/systemone`) could answer that kind of question in one forward pass instead of a 7-second generation. To find out whether it
could stand in, every LLM decision the app had recorded (`/app/logs/decisions/*.jsonl`: the game state and the action the LLM chose)
was replayed through Laya with the same question, and the answers compared. The LLM is the *teacher*, not the truth: this measures
whether a fast model can imitate the slow one, not which plays better.
Script: `image/farmhouse_decision_eval.py` (in the app image as `/app/scripts/farmhouse_decision_eval.py`):
`DECISION_URL=http://laya:8080 python scripts/farmhouse_decision_eval.py /app/logs/decisions english typed-decisions`
## Numbers (149 recorded decisions)
LLM's choices: play_land 41, hold 31, attack_all 28, cast_creature 20, cast_spell 13, attack_safe 7, cast_removal 5, cast_ramp 4.
| | agrees with the LLM | answers | time per answer | what it picked |
|---|---|---|---|---|
| always "play_land" (baseline) | **27.5%** | 149 | 0 | |
| `english` (ModernBERT-large, base) | 16.1% | 149 | 1.9 s | cast_creature 105, attack_all 26; never hold, almost never play_land |
| `typed-decisions` (fine-tuned) | 18.6% | 140 (9 timed out at 5 s) | ~4 s (shared CPU) | cast_creature 99, attack_all 26 |
It could say "cast_creature" and "attack_all" and little else; it never recognised "hold" (31 of the LLM's choices) or a removal spell.
## Why, and caveats
- The shipped checkpoints are trained on generic ticket-triage style decisions. Laya's own README says fine-tuning "on decisions from your
own domain is where accuracy jumps" (0.766 against 0.362 for the base on its own benchmark). This game's decisions were never in its training.
- Speed on this cluster's CPU (4 threads) was 2-4 s per answer, not the ~33 ms quoted for a GPU. Against the LLM's ~7.5 s that is not the
speed-up that was hoped for either, without a GPU.
- The question wording (the nine action descriptions) and the compact text it reads (`farmhouse_decide.compact_state`) are mine; a
better prompt might help a little, not from 18% to usable.
- Part of the recorded data predates the card-data fix (v10), so some states had thinner hands than they would now.
- The LLM being the "truth" also caps the result: where the LLM is wrong, agreeing with it is not a win.
## Where this leaves it
- Laya is **staged but scaled to 0 replicas** (`deployment-laya.yaml`: `replicas: 0`; set to 1 to run it). The image
(`ghcr.io/fez5587/farmhouse-laya:v1`, offline, weights baked in), the service and the network policy remain.
- The app is wired to use it (`DECISION_URL`, `DECISION_MODE`) and `DECISION_MODE` is `off`. `shadow` records agreement without
affecting games; `assist` uses it when it is `DECISION_MIN_CONF` sure. Kev speaks the same API, so swapping is a URL.
- To make it worth using: fine-tune on this game's decisions (Laya ships a Kaggle 2xT4 notebook, about 4 hours, and an Apple/CPU
script). The labels would be the LLM's recorded decisions; a few thousand are needed, so generate them first (LLM games at ~7 s a
decision, or label states with the engine's own heuristic for the cheap, abundant version). Then re-run this evaluation.
- Node memory: it needed about 2 GB (3.6 GB with both checkpoints, which pushed the control-plane node to 92%; it is pinned to the other node).
## Later the same day: the new connections (see docs/LAYA-CONNECTIONS.md in the fork)
- **Forge-shaped priority choice** (CSIE's ranking in the text, three scenarios): agreed with CSIE each time, 42-48% sure, 7.5-8.4 s per call on the CPU against Forge's
1.5 s budget. Not usable on a CPU; the code falls back silently.
- **Card roles from Oracle text** (150 unambiguous cards, 6 roles present, 9 offered): 48% against 17% by chance (counterspell 76%, board wipe 64%, removal 40%, tutor 40%,
ramp 36%, card draw 32%), 3.2 s per card in batches. Much better than the action choice; useful as on-demand evidence for the cards in a hand, too slow to tag the whole pool.
- **Extra questions** in the same call: "threat" said *high* for everything; "must answer" gave 0.48 for a lethal stack against 0.25-0.29 otherwise (right direction, weak).
- Capture, dataset export and the rest are built and off by default; fine-tuning on the captured decisions is the path to making it useful.
-21
View File
@@ -1,21 +0,0 @@
# Laya in this repository
Laya (https://github.com/NandhaKishorM/laya, Apache-2.0) is a **decision model**: it answers typed multiple-choice, yes/no and score
questions about a piece of text in one forward pass and never writes text. Here it is a fast second opinion beside the LLM and CSIE.
Kev (https://github.com/jaredpalmer/kev) serves the same `POST /v1/systemone` API, so swapping is a URL change (Kev needs a GPU).
| File | What |
|---|---|
| `Dockerfile` | CPU image: `laya[serve]` 0.4.15 + CPU torch, English and `typed-decisions` checkpoints baked in at Hugging Face commit `7b928d8`; runs offline |
| `deployment-laya.yaml` | Kubernetes Deployment + Service + NetworkPolicy (no egress; only the app may call it). Currently `replicas: 0` |
| `build-farmhouse-laya.workflow.yml` | the CI workflow that builds and smoke-tests the image offline (it lives in `.github/workflows/` of the farmhouse-os GitOps repo) |
| `LAYA-EVALUATION.md` | why it is off: zero-shot both checkpoints agreed with the LLM less often than always guessing the commonest action |
The deployment source of truth is the farmhouse-os repo (`infrastructure/apps/commander-lab/`); these are reference copies so the
fork is self-contained. Things learned running it:
- A Kubernetes Service named `laya` injects `LAYA_PORT=tcp://...`, which `laya-serve` reads as its own port setting and refuses. Set
`enableServiceLinks: false` and `LAYA_PORT=8080` explicitly.
- Two checkpoints resident use 3.6 GB; one uses about 1.9 GB. Do not place it on a control-plane node.
- The CPU answers in 2-4 s, not the ~33 ms quoted for a GPU.
- How the code in this repository connects to it, and how to fine-tune it: `docs/LAYA-CONNECTIONS.md`.
@@ -1,96 +0,0 @@
name: Build FarmHouse Laya
on:
workflow_dispatch:
push:
branches:
- main
paths:
- "infrastructure/apps/commander-lab/laya/**"
- ".github/workflows/build-farmhouse-laya.yml"
permissions:
contents: read
packages: write
jobs:
build:
runs-on: ubuntu-latest
env:
IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/farmhouse-laya
# Bump together with the image tag in infrastructure/apps/commander-lab/deployment-laya.yaml.
IMAGE_TAG: v1
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set image name lowercase
shell: bash
run: |
echo "IMAGE=$(echo "${IMAGE_NAME}" | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_ENV"
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build validation image
uses: docker/build-push-action@v6
with:
context: infrastructure/apps/commander-lab/laya
load: true
push: false
tags: laya:test
# The service must answer with NO network (that is how it runs in the cluster) as the unprivileged user, for both checkpoints.
- name: Smoke test (boots offline, answers a game-state question with both checkpoints)
shell: bash
run: |
set -euo pipefail
docker run -d --name laya --network none laya:test
cat > /tmp/ask.py <<'PY'
import json, sys, time, urllib.request
model = sys.argv[1]
body = {"model": model,
"state": {"body": "Turn 4. You have 4 lands untapped. Hand: Llanowar Elves, Swords to Plowshares, Forest. Opponent has a 6/6 creature attacking you."},
"questions": {"action": {"type": "choice", "instructions": "Which action is best this turn?",
"criteria": {"cast_creature": "put a creature onto the battlefield",
"cast_removal": "destroy or exile an opposing permanent",
"play_land": "play a land",
"hold": "do nothing this turn"}}}}
req = urllib.request.Request("http://127.0.0.1:8080/v1/systemone", data=json.dumps(body).encode(), headers={"content-type": "application/json"})
t = time.time()
out = json.load(urllib.request.urlopen(req, timeout=120))
print(model, "%.0f ms" % ((time.time() - t) * 1000), json.dumps(out)[:600])
assert "answers" in out and "action" in out["answers"], out
PY
docker cp /tmp/ask.py laya:/tmp/ask.py
ok=0
for i in $(seq 1 120); do
if docker exec laya python -c "import socket; socket.create_connection(('127.0.0.1', 8080), 2)" 2>/dev/null; then ok=1; break; fi
sleep 3
done
if [ "$ok" != 1 ]; then echo "laya did not open its port"; docker logs laya | tail -60; exit 1; fi
for m in english typed-decisions; do docker exec laya python /tmp/ask.py "$m"; done
docker exec laya id
docker rm -f laya >/dev/null
echo SMOKE OK
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and publish
uses: docker/build-push-action@v6
with:
context: infrastructure/apps/commander-lab/laya
push: true
tags: |
${{ env.IMAGE }}:${{ env.IMAGE_TAG }}
${{ env.IMAGE }}:${{ github.sha }}
labels: |
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.revision=${{ github.sha }}
-93
View File
@@ -1,93 +0,0 @@
# Laya, a CPU decision model (laya/Dockerfile), staged for the simulator. Reached only by the app, over the cluster network, on 8080.
# No internet, no volume (weights are in the image), no service-account token.
apiVersion: apps/v1
kind: Deployment
metadata:
name: laya
namespace: commander-lab
labels: {app: laya}
spec:
# 0 since 2026-10-26: both checkpoints scored BELOW the always-guess baseline against the LLM's recorded decisions (English 16.1%, typed-decisions
# 18.6%, baseline 27.5%, 149 states), and ~2 GB of the node's memory was needed for the card-search index build. Set to 1 to bring it back
# (image, service and policy stay in place); it is only worth running once it is fine-tuned on this game's decisions (README).
replicas: 0
selector:
matchLabels: {app: laya}
template:
metadata:
labels: {app: laya}
spec:
automountServiceAccountToken: false
# Kubernetes injects LAYA_PORT=tcp://<ip>:8080 for a Service named laya, and laya-serve reads LAYA_PORT as its own port setting
# ("invalid LAYA_PORT 'tcp://...'", crash loop). Service-link variables are not wanted here at all.
enableServiceLinks: false
# NOT on talos-gmw: that node runs the Kubernetes API server, and Laya's first placement there (two checkpoints, 3.6 GB) took it from
# 68% to 92% memory on 2026-10-26.
nodeSelector: {kubernetes.io/hostname: talos-noy-0r4}
imagePullSecrets:
- name: ghcr-pull
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
seccompProfile: {type: RuntimeDefault}
containers:
- name: laya
image: ghcr.io/fez5587/farmhouse-laya:v1
ports:
- {name: http, containerPort: 8080}
env:
- {name: LAYA_THREADS, value: "4"}
- {name: LAYA_PORT, value: "8080"}
# One checkpoint only (about 1.9 GB): the English base scored below the always-guess baseline against the LLM; typed-decisions is the
# fine-tuned one still being measured.
- {name: LAYA_MODELS, value: "typed-decisions"}
- {name: LAYA_DEFAULT_MODEL, value: "typed-decisions"}
- {name: LAYA_MAX_LOADED, value: "1"}
securityContext:
allowPrivilegeEscalation: false
capabilities: {drop: [ALL]}
resources:
requests: {cpu: "500m", memory: 2500Mi}
limits: {cpu: "4", memory: 3Gi}
# Loading two checkpoints takes a while; the port opens when the server is up.
startupProbe:
tcpSocket: {port: http}
periodSeconds: 5
failureThreshold: 90
readinessProbe:
tcpSocket: {port: http}
periodSeconds: 10
livenessProbe:
tcpSocket: {port: http}
periodSeconds: 30
failureThreshold: 6
---
apiVersion: v1
kind: Service
metadata:
name: laya
namespace: commander-lab
spec:
type: ClusterIP
selector: {app: laya}
ports:
- {name: http, port: 8080, targetPort: http}
---
# IN: only the app. OUT: nothing at all (the weights are in the image; it needs no DNS and calls no one).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: laya
namespace: commander-lab
spec:
podSelector:
matchLabels: {app: laya}
policyTypes: [Ingress, Egress]
ingress:
- from:
- podSelector:
matchLabels: {app: commander-lab}
ports:
- {protocol: TCP, port: 8080}
egress: []
-61
View File
@@ -1,61 +0,0 @@
# phase-sim: rules-accurate four-player Commander games with phase-rs's headless AI (github.com/phase-rs/phase), behind a small HTTP service.
#
# phase is a Rust rules engine (stack, priority, combat, layers, triggers, replacement effects), dual licensed Apache-2.0 / MIT, with card
# data from MTGJSON (MIT). Pinned to release v0.118.0 (commit ad0de6a) and to the card database that release was published with
# (`card-data-5e541a38c99b97f0.json`, named in data.phase-rs.dev/card-data-meta.json for that commit); the file's SHA-256 is checked, so a
# changed file fails the build instead of silently changing results. Nothing is fetched at run time, and the pod has no network.
#
# Built: the `ai-commander` binary (4-player Commander, batch mode) and `ai-duel` with the repo's `server-release` profile (unwinding
# panics, so one game's panic cannot kill a batch). The toolchain is whatever rust-toolchain.toml pins (a dated nightly).
FROM rust:slim-bookworm AS build
ARG PHASE_REPO=https://github.com/phase-rs/phase.git
ARG PHASE_TAG=v0.118.0
ARG PHASE_SHA=ad0de6adf00153a6e6eb89604f6670be5b1d5168
ARG CARD_DATA_URL=https://data.phase-rs.dev/card-data-5e541a38c99b97f0.json
ARG CARD_DATA_SHA256=5e541a38c99b97f0ef12c81f7b249e7cd253f38b32bd5c156cf19608cb6f1218
RUN apt-get update \
&& apt-get install -y --no-install-recommends git ca-certificates curl build-essential pkg-config python3 \
&& rm -rf /var/lib/apt/lists/*
RUN set -eux; \
mkdir /phase; cd /phase; \
git init -q; \
git remote add origin "$PHASE_REPO"; \
git fetch -q --depth 1 origin "$PHASE_SHA"; \
git checkout -q FETCH_HEAD; \
test "$(git rev-parse HEAD)" = "$PHASE_SHA"
WORKDIR /phase
# phase's server-release profile uses thin LTO and 16 code-generation units; compiling its big engine crate that way ran a 7 GB CI machine
# out of memory ("cannot allocate memory", 2026-10-27). LTO off and two parallel jobs trade some build time (and a few percent of run
# speed) for a build that fits; the optimisation level and panic=unwind (which batch isolation needs) are unchanged.
ENV CARGO_BUILD_JOBS=2 \
CARGO_PROFILE_SERVER_RELEASE_LTO=off \
CARGO_PROFILE_SERVER_RELEASE_CODEGEN_UNITS=8
RUN cargo build --profile server-release -p phase-ai --bin ai-commander --bin ai-duel
RUN set -eux; \
curl -fsSL --retry 3 -o /card-data.json "$CARD_DATA_URL"; \
echo "$CARD_DATA_SHA256 /card-data.json" | sha256sum -c -; \
cp /phase/client/public/feeds/mtggoldfish-commander.json /sample-feed.json
FROM python:3.12-slim-bookworm
ARG PHASE_TAG=v0.118.0
RUN groupadd -g 10001 phase && useradd -u 10001 -g 10001 -d /tmp -s /usr/sbin/nologin phase
COPY --from=build /phase/target/server-release/ai-commander /opt/phase/ai-commander
COPY --from=build /phase/target/server-release/ai-duel /opt/phase/ai-duel
COPY --from=build /card-data.json /opt/phase/data/card-data.json
COPY --from=build /sample-feed.json /opt/phase/sample-feed.json
COPY phase_sim.py phase_smoke.py /opt/phase/
ENV PHASE_ENGINE_VERSION="phase-rs ${PHASE_TAG}" \
PHASE_AI_COMMANDER=/opt/phase/ai-commander \
PHASE_CARD_DATA=/opt/phase/data/card-data.json \
PYTHONUNBUFFERED=1 PORT=8090
USER 10001
WORKDIR /tmp
EXPOSE 8090
CMD ["python", "/opt/phase/phase_sim.py"]
-72
View File
@@ -1,72 +0,0 @@
# phase-sim: rules-accurate four-player Commander games with phase-rs's headless AI (github.com/phase-rs/phase), behind a small HTTP service.
#
# phase is a Rust rules engine (stack, priority, combat, layers, triggers, replacement effects), dual licensed Apache-2.0 / MIT, with card
# data from MTGJSON (MIT). Pinned to release v0.118.0 (commit ad0de6a) and to the card database that release was published with
# (`card-data-5e541a38c99b97f0.json`, named in data.phase-rs.dev/card-data-meta.json for that commit); the file's SHA-256 is checked, so a
# changed file fails the build instead of silently changing results. Nothing is fetched at run time, and the pod has no network.
#
# Built: the `ai-commander` binary (4-player Commander, batch mode) and `ai-duel` with the repo's `server-release` profile (unwinding
# panics, so one game's panic cannot kill a batch). The toolchain is whatever rust-toolchain.toml pins (a dated nightly).
FROM rust:slim-bookworm AS build
ARG PHASE_REPO=https://github.com/phase-rs/phase.git
ARG PHASE_TAG=v0.118.0
ARG PHASE_SHA=ad0de6adf00153a6e6eb89604f6670be5b1d5168
ARG CARD_DATA_URL=https://data.phase-rs.dev/card-data-5e541a38c99b97f0.json
ARG CARD_DATA_SHA256=5e541a38c99b97f0ef12c81f7b249e7cd253f38b32bd5c156cf19608cb6f1218
RUN apt-get update \
&& apt-get install -y --no-install-recommends git ca-certificates curl build-essential pkg-config python3 \
&& rm -rf /var/lib/apt/lists/*
RUN set -eux; \
mkdir /phase; cd /phase; \
git init -q; \
git remote add origin "$PHASE_REPO"; \
git fetch -q --depth 1 origin "$PHASE_SHA"; \
git checkout -q FETCH_HEAD; \
test "$(git rev-parse HEAD)" = "$PHASE_SHA"
WORKDIR /phase
# phase's server-release profile uses thin LTO and 16 code-generation units; compiling its big engine crate that way ran a 7 GB CI machine
# out of memory ("cannot allocate memory", 2026-10-27). LTO off and two parallel jobs trade some build time (and a few percent of run
# speed) for a build that fits; the optimisation level and panic=unwind (which batch isolation needs) are unchanged.
ENV CARGO_BUILD_JOBS=2 \
CARGO_PROFILE_SERVER_RELEASE_LTO=off \
CARGO_PROFILE_SERVER_RELEASE_CODEGEN_UNITS=8
RUN cargo build --profile server-release -p phase-ai --bin ai-commander --bin ai-duel
# ---- model seats (this Dockerfile only) -------------------------------------------------------------------------------------------
# Everything above is identical to Dockerfile, so the long compile above comes from the build cache. These steps add `ai-commander-llm`: the
# same runner with a hook that lets a language model or a decision model (Laya / Kev) choose for named seats among the engine's OWN legal
# options. Two anchored edits to phase's source (apply_phase_patches.py: the build stops if phase moved either line) and one new crate.
# phase-llm depends on phase-ai, so the hook cannot live in phase-ai's binary; the new crate depends on both and includes the runner.
COPY llm-seat /llm-seat
RUN python3 /llm-seat/apply_phase_patches.py /phase /llm-seat
RUN cargo build --profile server-release -p farmhouse-llm-seat --bin ai-commander-llm
RUN set -eux; \
curl -fsSL --retry 3 -o /card-data.json "$CARD_DATA_URL"; \
echo "$CARD_DATA_SHA256 /card-data.json" | sha256sum -c -; \
cp /phase/client/public/feeds/mtggoldfish-commander.json /sample-feed.json
FROM python:3.12-slim-bookworm
ARG PHASE_TAG=v0.118.0
RUN groupadd -g 10001 phase && useradd -u 10001 -g 10001 -d /tmp -s /usr/sbin/nologin phase
COPY --from=build /phase/target/server-release/ai-commander /opt/phase/ai-commander
COPY --from=build /phase/target/server-release/ai-duel /opt/phase/ai-duel
COPY --from=build /phase/target/server-release/ai-commander-llm /opt/phase/ai-commander-llm
COPY --from=build /card-data.json /opt/phase/data/card-data.json
COPY --from=build /sample-feed.json /opt/phase/sample-feed.json
COPY phase_sim.py phase_smoke.py /opt/phase/
ENV PHASE_ENGINE_VERSION="phase-rs ${PHASE_TAG}" \
PHASE_AI_COMMANDER=/opt/phase/ai-commander \
PHASE_AI_COMMANDER_LLM=/opt/phase/ai-commander-llm \
PHASE_CARD_DATA=/opt/phase/data/card-data.json \
PYTHONUNBUFFERED=1 PORT=8090
USER 10001
WORKDIR /tmp
EXPOSE 8090
CMD ["python", "/opt/phase/phase_sim.py"]
-36
View File
@@ -1,36 +0,0 @@
# phase-sim: rules-accurate Commander games with phase-rs
Reference copies of what runs in the cluster (source of truth: `infrastructure/apps/commander-lab/` in the farmhouse-os repo). Background and the assessment
that led here: `docs/PHASE-AND-PLAYTESTER.md`.
| File | What |
|---|---|
| `phase_sim.py` | the service: stdlib HTTP, one job at a time. `POST /run` four decks -> `GET /job/<id>` per-game results, wins by seat, 95% interval, warnings. Optional model seats and two loopback-only relays (`/llm/v1/chat/completions`, `/jev/systemone`) |
| `Dockerfile` | builds phase-rs `v0.118.0` (`ai-commander`, `ai-duel`) and takes the card database that release was published with (SHA-256 checked) |
| `Dockerfile.llm` | the same plus `ai-commander-llm`: model-driven seats |
| `llm-seat/` | the Rust crate and the two anchored edits to phase's source that make model seats possible |
| `phase_smoke.py`, `test_phase_sim.py` | CI: real games through the service; 49 offline checks against a stub engine |
| `deployment-phase.yaml` | Deployment, Service and a NetworkPolicy (in: the app only; out: DNS, Olla and Laya only) |
The app side is `routes/farmhouse_phase.py` (four saved decks -> the service) and `ui/phase-sim.html`; both are real source in this repository, registered by
`lab_api.py` and linked from the home page.
## Model seats: how they work and why they are safe
phase's headless runner has no model support; the model seats exist only in phase's browser client. `phase-llm` (the crate) deliberately does no networking:
it renders the engine's option list into a prompt, builds the HTTP request, and parses the reply, and the host performs the call. `llm-seat/` is that host
for the headless runner:
1. `apply_phase_patches.py` adds a process-wide `ACTION_OVERRIDE` hook in `phase-ai/src/auto_play.rs` (asked before the built-in AI chooses) and makes the runner's `main` `pub`.
2. The crate `farmhouse-llm-seat` includes the runner's source as a module (`#[path]`) and installs the hook. `phase-llm` depends on `phase-ai`, so the hook cannot
live inside phase-ai's own binary.
3. For each decision on a model seat: the engine issues its option list (`AiDecisionContract`); phase-llm builds the prompt (a forced move with one option is never asked);
this crate makes the HTTP call (blocking, no TLS, 20 s limit); phase-llm turns the reply into one of the engine's options; the choice is checked against the contract
here and again by `run_ai_action`. **Any** problem returns "no opinion" and phase's own AI plays the move. A cap on model calls per run (default 300) bounds the cost.
4. The service supplies the endpoints through its own loopback-only relays: the chat relay switches the model's thinking off (twin-turbo otherwise thinks for tens of
seconds a move) and caps the answer; the decision relay unwraps phase's `Jev` envelope and forwards the System One request to Laya or Kev.
The model never authors an action and never sees hidden cards beyond what phase-llm renders for that seat.
## Status
Written 2026-10-27. The service logic is tested offline; the Rust crate has not compiled outside CI when this was written (no Rust toolchain on the workstation), so
its first CI run is the first real test. Check `.github/workflows/build-farmhouse-phase-sim.yml` results in the farmhouse-os repo.
-111
View File
@@ -1,111 +0,0 @@
# phase-sim (phase/Dockerfile): rules-accurate four-player Commander games over a small HTTP API. Only the app may call it; it has no
# network and no volume (engine and card data are in the image). One game at a time, CPU heavy.
apiVersion: apps/v1
kind: Deployment
metadata:
name: phase-sim
namespace: commander-lab
labels: {app: phase-sim}
spec:
replicas: 1
selector:
matchLabels: {app: phase-sim}
template:
metadata:
labels: {app: phase-sim}
spec:
automountServiceAccountToken: false
# A Service named like the app injects PHASE_SIM_* variables into the pod; nothing here wants them (the same kind of collision
# crash-looped Laya on LAYA_PORT).
enableServiceLinks: false
imagePullSecrets:
- name: ghcr-pull
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
seccompProfile: {type: RuntimeDefault}
containers:
- name: phase-sim
image: ghcr.io/fez5587/farmhouse-phase-sim:v1-llm # -llm = the baseline plus ai-commander-llm (model seats)
ports:
- {name: http, containerPort: 8090}
env:
- {name: PORT, value: "8090"}
- {name: PHASE_SIM_MAX_GAMES, value: "50"}
- {name: PHASE_SIM_TIMEOUT, value: "3600"}
# Model seats. The engine talks to THIS service's loopback-only relays, which forward to these (see phase_sim.py): chat = an
# OpenAI-style endpoint (Olla -> twin-turbo; the relay switches thinking off and caps the answer), decision = a System One server
# (Laya / Kev; the deployment is scaled to 0 until it is fine-tuned, so a decision-seat run answers 502 and falls back to phase's AI).
- {name: PHASE_LLM_CHAT_URL, value: "http://olla.ai-system.svc.cluster.local:40114/olla/openai/v1"}
- {name: PHASE_LLM_DECISION_URL, value: "http://laya.commander-lab.svc.cluster.local:8080/v1/systemone"}
- {name: PHASE_LLM_REASONING, value: "none"}
- {name: PHASE_LLM_MAX_TOKENS_CAP, value: "256"}
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities: {drop: [ALL]}
volumeMounts:
- {name: tmp, mountPath: /tmp}
resources:
requests: {cpu: "500m", memory: 1Gi}
limits: {cpu: "3", memory: 3Gi}
readinessProbe:
httpGet: {path: /health, port: http}
periodSeconds: 10
livenessProbe:
httpGet: {path: /health, port: http}
periodSeconds: 30
failureThreshold: 6
volumes:
- name: tmp
emptyDir: {sizeLimit: 512Mi}
---
apiVersion: v1
kind: Service
metadata:
name: phase-sim
namespace: commander-lab
spec:
type: ClusterIP
selector: {app: phase-sim}
ports:
- {name: http, port: 8090, targetPort: http}
---
# IN: only the app. OUT: DNS and the two model endpoints the relays use (Olla for the chat model, Laya for the decision model); nothing else.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: phase-sim
namespace: commander-lab
spec:
podSelector:
matchLabels: {app: phase-sim}
policyTypes: [Ingress, Egress]
ingress:
- from:
- podSelector:
matchLabels: {app: commander-lab}
ports:
- {protocol: TCP, port: 8090}
egress:
- to:
- namespaceSelector:
matchLabels: {kubernetes.io/metadata.name: kube-system}
podSelector:
matchLabels: {k8s-app: kube-dns}
ports:
- {protocol: UDP, port: 53}
- {protocol: TCP, port: 53}
- to:
- namespaceSelector:
matchLabels: {kubernetes.io/metadata.name: ai-system}
podSelector:
matchLabels: {app.kubernetes.io/name: olla}
ports:
- {protocol: TCP, port: 40114}
- to:
- podSelector:
matchLabels: {app: laya}
ports:
- {protocol: TCP, port: 8080}
-26
View File
@@ -1,26 +0,0 @@
[package]
name = "farmhouse-llm-seat"
version.workspace = true
edition = "2021"
license.workspace = true
publish = false
# FarmHouse: phase's headless four-player Commander runner (`ai-commander`) with MODEL-DRIVEN SEATS. The runner's own source is included
# as a module (src/main.rs, #[path]); this crate adds only the network transport phase-llm deliberately leaves to the host. phase-llm
# depends on phase-ai, so the hook cannot live inside phase-ai's own binary: a new crate that depends on both is the way round that.
[[bin]]
name = "ai-commander-llm"
path = "src/main.rs"
[dependencies]
engine = { path = "../engine", package = "phase-engine" }
phase-ai = { path = "../phase-ai" }
phase-llm = { path = "../phase-llm" }
serde = { workspace = true }
serde_json = "1"
rand = "0.9"
tracing = "0.1"
mimalloc = "0.1"
# Blocking HTTP, no TLS: the model endpoints are cluster-internal http:// relays (phase-sim's own /llm and /jev routes).
ureq = { version = "2", default-features = false }
@@ -1,74 +0,0 @@
"""Apply the FarmHouse edits to a phase-rs checkout (run in the Docker build, from the repository root).
python apply_phase_patches.py <phase-checkout> <llm-seat-crate-dir>
1. crates/phase-ai/src/auto_play.rs: a process-wide ACTION_OVERRIDE hook, asked before the built-in AI chooses. It returns Option<GameAction>;
None (the default, and what every failure returns) leaves phase's own choice untouched. The chosen action still goes through the same
contract check (`contract.permits`) as before.
2. crates/phase-ai/src/bin/ai_commander.rs: `fn main` becomes `pub fn main` so the new crate can include and call it.
3. The new crate is copied into crates/farmhouse-llm-seat (the workspace takes every crates/* member).
Every anchor must match exactly once or the build stops, so a phase update that moves a line is reported here, not in a compile error."""
import os
import shutil
import sys
root, crate = sys.argv[1], sys.argv[2]
def edit(rel, edits):
path = os.path.join(root, rel)
text = open(path, encoding="utf-8", newline="").read()
for old, new in edits:
n = text.count(old)
if n != 1:
raise SystemExit("%s: anchor found %d times (need 1): %r" % (rel, n, old[:80]))
text = text.replace(old, new)
open(path, "w", encoding="utf-8", newline="").write(text)
print("patched", rel)
HOOK = '''use crate::search::choose_action_with_session;
/// FarmHouse: an optional process-wide override, asked BEFORE the built-in AI chooses for a seat. A host (see crates/farmhouse-llm-seat)
/// installs one to let a model pick among the engine's own options. It returns None to leave the choice to the built-in AI, which is also
/// what it must return on any failure; whatever it returns still has to pass the same decision-contract check below.
pub type ActionOverride = Box<
dyn Fn(
&engine::types::game_state::GameState,
&engine::ai_support::AiDecisionContract,
engine::types::player::PlayerId,
engine::types::player::PlayerId,
) -> Option<engine::types::actions::GameAction>
+ Send
+ Sync,
>;
static ACTION_OVERRIDE: std::sync::OnceLock<ActionOverride> = std::sync::OnceLock::new();
/// Install the override. Returns false if one is already installed (it can be set once per process).
pub fn install_action_override(hook: ActionOverride) -> bool {
ACTION_OVERRIDE.set(hook).is_ok()
}
'''
edit("crates/phase-ai/src/auto_play.rs", [
("use crate::search::choose_action_with_session;\n", HOOK),
(" let action = match choose_action_with_session(state, semantic_owner, config, rng, session) {\n Some(action) => action,\n None => {\n tracing::warn!(player = ?actor, \"choose_action returned None",
" // The override's pick must be one the engine will really APPLY, not only one it lists: a model chose both modes of a modal spell whose\n"
" // entwine cost it could not pay, the contract listed the option, apply refused it, and the whole game stalled (2026-10-27). Try it on a\n"
" // copy of the game first; anything the engine refuses is dropped and the built-in AI plays the move. (Stack-pass rechecks have their\n"
" // own verified path and are left alone.)\n"
" let farmhouse_choice = ACTION_OVERRIDE\n .get()\n .and_then(|hook| hook(&*state, &contract, semantic_owner, actor))\n"
" .filter(|candidate| {\n"
" verified_ai_stack_pass_player(&*state, candidate).is_some()\n"
" || apply_interaction(&mut (*state).clone(), actor, semantic_owner, candidate.clone()).is_ok()\n"
" });\n"
" let action = match farmhouse_choice\n .or_else(|| choose_action_with_session(state, semantic_owner, config, rng, session))\n {\n Some(action) => action,\n None => {\n tracing::warn!(player = ?actor, \"choose_action returned None"),
])
edit("crates/phase-ai/src/bin/ai_commander.rs", [("\nfn main() {\n", "\npub fn main() {\n")])
dest = os.path.join(root, "crates", "farmhouse-llm-seat")
os.makedirs(os.path.join(dest, "src"), exist_ok=True)
shutil.copy(os.path.join(crate, "Cargo.toml"), os.path.join(dest, "Cargo.toml"))
shutil.copy(os.path.join(crate, "src", "main.rs"), os.path.join(dest, "src", "main.rs"))
print("added crates/farmhouse-llm-seat")
-237
View File
@@ -1,237 +0,0 @@
//! ai-commander with model-driven seats (FarmHouse).
//!
//! phase's headless runner plays four-player Commander games with the built-in AI on every seat. This binary is that same runner (its
//! source is included below, unchanged but for `fn main` being `pub`) plus a hook, installed before the games start, that asks a
//! language model or a decision model (Laya / Kev, over the System One protocol) to choose for the seats named in `PHASE_LLM_SEATS`.
//!
//! The model never authors an action. For each decision the engine issues its own option list (`AiDecisionContract`), phase-llm renders
//! it and builds the HTTP request, this file performs the HTTP call (the one thing phase-llm leaves to the host), and phase-llm turns the
//! reply into one of the engine's options. The pick is then checked against the contract a second time here, and again by
//! `run_ai_action`. ANY problem (forced move, timeout, an unreadable or stale answer, the call cap) returns `None` and phase's own AI
//! plays the move, so a model that is down, slow or wrong cannot stall or corrupt a game.
//!
//! Settings (environment): PHASE_LLM_SEATS "1,3" (seats 0-3; empty = none, the plain runner), PHASE_LLM_PROVIDER (OpenAiCompatible | Jev),
//! PHASE_LLM_BASE_URL, PHASE_LLM_MODEL, PHASE_LLM_API_KEY (leave empty for http:// endpoints), PHASE_LLM_MAX_TOKENS (256),
//! PHASE_LLM_TEMPERATURE (0.2), PHASE_LLM_TIMEOUT_S (20), PHASE_LLM_MAX_CALLS (total model calls for the whole process, default 300),
//! PHASE_LLM_DIFFICULTY (Medium: the strength hint in the prompt), PHASE_LLM_MAX_FAILS (4: model failures IN A ROW before every model seat
//! switches itself off for the rest of the process).
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::OnceLock;
use std::time::{Duration, Instant};
use engine::ai_support::AiDecisionContract;
use engine::database::CardDatabase;
use engine::types::actions::GameAction;
use engine::types::game_state::GameState;
use engine::types::player::PlayerId;
use phase_ai::auto_play::install_action_override;
use phase_ai::config::AiDifficulty;
use phase_llm::{LlmEndpointConfig, LlmProvider, LlmReply};
// The unchanged runner, with `fn main` made `pub` by apply_phase_patches.py.
#[path = "../../phase-ai/src/bin/ai_commander.rs"]
#[allow(dead_code, unused_imports, unused_variables)]
mod commander;
struct Seats {
seats: HashSet<u8>,
endpoint: LlmEndpointConfig,
difficulty: AiDifficulty,
agent: ureq::Agent,
cards_path: PathBuf,
db: OnceLock<Option<CardDatabase>>,
max_calls: u64,
asked: [AtomicU64; 4],
used: [AtomicU64; 4],
fell_back: [AtomicU64; 4],
total: AtomicU64,
// Cost visibility and the circuit-breaker. A late-game prompt is thousands of tokens and a big-model server needs longer than the
// per-call limit to read it; every such call used to burn the whole limit (a 9-minute game, 25 questions, 1 answer used). After
// `max_fails` failures IN A ROW the model seats switch themselves off for the rest of the process and phase's AI plays on.
timeouts: AtomicU64,
consecutive_fails: AtomicU64,
max_fails: u64,
disabled: AtomicBool,
millis: AtomicU64,
answered: AtomicU64,
prompt_chars: AtomicU64,
}
impl Seats {
fn database(&self) -> Option<&CardDatabase> {
self.db
.get_or_init(|| CardDatabase::from_export(&self.cards_path.join("card-data.json")).ok())
.as_ref()
}
/// The model's pick for `actor`, or None to let phase's AI play. Never panics on a bad answer.
/// One failed model call (timeout, error status, unusable answer). Returns None so callers can `return self.failed(..)`.
fn failed(&self, timeout: bool) -> Option<GameAction> {
if timeout {
self.timeouts.fetch_add(1, Ordering::Relaxed);
}
let in_a_row = self.consecutive_fails.fetch_add(1, Ordering::Relaxed) + 1;
if in_a_row >= self.max_fails && !self.disabled.swap(true, Ordering::Relaxed) {
println!(
"LLM-SEAT-DISABLED after {in_a_row} consecutive failures ({} timeouts of {} questions): phase's own AI plays the rest",
self.timeouts.load(Ordering::Relaxed),
self.total.load(Ordering::Relaxed)
);
}
None
}
fn decide(&self, state: &GameState, contract: &AiDecisionContract, actor: PlayerId) -> Option<GameAction> {
if self.disabled.load(Ordering::Relaxed) {
return None;
}
let seat = (actor.0 as usize).min(3);
// A forced move (one legal option) is never put to a model: build_game_decision_prompt refuses it.
let request = phase_llm::build_game_decision_prompt(
state,
contract,
self.difficulty,
self.database(),
&Vec::new(),
)
.ok()?;
if self.total.fetch_add(1, Ordering::Relaxed) >= self.max_calls {
return None; // the call cap: every later decision is phase's AI
}
self.asked[seat].fetch_add(1, Ordering::Relaxed);
self.prompt_chars.fetch_add(request.prompt.char_count() as u64, Ordering::Relaxed);
let http = phase_llm::build_chat_request(&self.endpoint, &request.prompt).ok()?;
let mut call = self.agent.request(http.method, &http.url);
for header in &http.headers {
call = call.set(&header.name, &header.value);
}
let started = Instant::now();
let (status, body) = match call.send_string(&http.body) {
Ok(response) => {
let status = response.status();
match response.into_string() {
Ok(text) => (status, text),
Err(_) => return self.failed(true),
}
}
// A 4xx/5xx still carries a body phase-llm knows how to classify.
Err(ureq::Error::Status(code, response)) => (code, response.into_string().unwrap_or_default()),
Err(_) => return self.failed(true), // transport error: a timeout, or the endpoint is down
};
self.millis.fetch_add(started.elapsed().as_millis() as u64, Ordering::Relaxed);
self.answered.fetch_add(1, Ordering::Relaxed);
let selection = match phase_llm::select_action_from_response(
state,
contract,
&request.fingerprint,
LlmReply { provider: self.endpoint.provider, status, body: &body },
) {
Ok(selection) => selection,
Err(_) => return self.failed(false),
};
if !contract.contains_action(state, &selection.action) {
return self.failed(false);
}
self.consecutive_fails.store(0, Ordering::Relaxed);
self.used[seat].fetch_add(1, Ordering::Relaxed);
Some(selection.action)
}
fn report(&self, seat: usize) {
let asked = self.asked[seat].load(Ordering::Relaxed);
if asked > 0 && asked % 25 == 0 {
let answered = self.answered.load(Ordering::Relaxed).max(1);
let questions = self.total.load(Ordering::Relaxed).max(1);
println!(
"LLM-SEAT seat={seat} asked={asked} used={} total_calls={} timeouts={} avg_ms={} avg_prompt_chars={}",
self.used[seat].load(Ordering::Relaxed),
self.total.load(Ordering::Relaxed),
self.timeouts.load(Ordering::Relaxed),
self.millis.load(Ordering::Relaxed) / answered,
self.prompt_chars.load(Ordering::Relaxed) / questions
);
}
}
}
fn env_or(name: &str, default: &str) -> String {
std::env::var(name).ok().filter(|v| !v.trim().is_empty()).unwrap_or_else(|| default.to_string())
}
fn install_model_seats() {
let seats: HashSet<u8> = env_or("PHASE_LLM_SEATS", "")
.split(',')
.filter_map(|s| s.trim().parse::<u8>().ok())
.filter(|s| *s < 4)
.collect();
if seats.is_empty() {
println!("LLM seats: none (plain ai-commander)");
return;
}
let provider = LlmProvider::from_label(&env_or("PHASE_LLM_PROVIDER", "OpenAiCompatible"));
let endpoint = LlmEndpointConfig {
provider,
base_url: std::env::var("PHASE_LLM_BASE_URL").ok().filter(|v| !v.trim().is_empty()),
api_key: env_or("PHASE_LLM_API_KEY", ""),
model: env_or("PHASE_LLM_MODEL", "model"),
max_output_tokens: env_or("PHASE_LLM_MAX_TOKENS", "256").parse().ok(),
temperature: env_or("PHASE_LLM_TEMPERATURE", "0.2").parse().ok(),
};
let timeout = env_or("PHASE_LLM_TIMEOUT_S", "20").parse::<u64>().unwrap_or(20);
// The runner's first positional argument is the data folder (card-data.json lives there).
let cards_path = PathBuf::from(std::env::args().nth(1).unwrap_or_else(|| ".".to_string()));
let state = Seats {
seats: seats.clone(),
endpoint,
difficulty: AiDifficulty::from_label(&env_or("PHASE_LLM_DIFFICULTY", "Medium")),
agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(timeout)).redirects(0).build(),
cards_path,
db: OnceLock::new(),
max_calls: env_or("PHASE_LLM_MAX_CALLS", "300").parse().unwrap_or(300),
asked: Default::default(),
used: Default::default(),
fell_back: Default::default(),
total: AtomicU64::new(0),
timeouts: AtomicU64::new(0),
consecutive_fails: AtomicU64::new(0),
max_fails: env_or("PHASE_LLM_MAX_FAILS", "4").parse().unwrap_or(4),
disabled: AtomicBool::new(false),
millis: AtomicU64::new(0),
answered: AtomicU64::new(0),
prompt_chars: AtomicU64::new(0),
};
println!(
"LLM seats: {:?} provider={} model={} max_calls={}",
{
let mut v: Vec<u8> = seats.iter().copied().collect();
v.sort();
v
},
provider.label(),
state.endpoint.model,
state.max_calls
);
let installed = install_action_override(Box::new(move |game, contract, _owner, actor| {
if !state.seats.contains(&actor.0) {
return None;
}
let seat = (actor.0 as usize).min(3);
let pick = state.decide(game, contract, actor);
if pick.is_none() {
state.fell_back[seat].fetch_add(1, Ordering::Relaxed);
}
state.report(seat);
pick
}));
if !installed {
eprintln!("LLM seats: an action override was already installed; model seats are off");
}
}
fn main() {
install_model_seats();
commander::main();
}
-501
View File
@@ -1,501 +0,0 @@
"""phase-sim: run rules-accurate four-player Commander games with phase-rs's headless `ai-commander` and report what happened.
Standard library only. One job runs at a time (a game is CPU-heavy); more wait in a queue. The service never touches the network.
GET /health {"ok": true, "engine": ..., "queued": n, "running": id|null}
POST /run {"decks": [4 x {"name", "commander": ["Card"], "main": [{"name","count"}, ...]}],
"games": 1..MAX_GAMES, "seed": int, "difficulty": "Medium", "seat_difficulty": {"2": "Hard"}, "action_cap": int}
-> {"job": id}
GET /job/<id> status queued|running|done|error, games finished, and when done: per-game rows, wins by seat and by deck,
win rate with a 95% interval, the cards the engine could not resolve, and the tail of the engine's output
Seat i is the i-th deck in the request (P0 = first). The engine treats every seat as AI; difficulty is per seat if given.
A game that stalls, hits the action cap, or panics is reported as such and is NEVER counted as a win or a draw.
Model seats (optional, needs the image's ai-commander-llm binary): "llm_seats": [1, 3] and "llm": {"kind": "chat" | "decision", "model": "...",
"max_calls": 300}. Those seats ask a model to pick among the ENGINE'S OWN legal options (phase-llm builds the prompt and checks the answer;
anything wrong or slow falls back to phase's AI). kind "chat" goes to PHASE_LLM_CHAT_URL (an OpenAI-style endpoint, e.g. Olla) through this
service's /llm relay, which switches the model's thinking off and caps its answer; kind "decision" goes to PHASE_LLM_DECISION_URL (a System One
server: Laya or Kev) through /jev/systemone. Both relays accept connections from this machine only.
"""
import json
import math
import os
import re
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.request
import uuid
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
BIN = os.environ.get("PHASE_AI_COMMANDER", "/opt/phase/ai-commander")
CARD_DATA = os.environ.get("PHASE_CARD_DATA", "/opt/phase/data/card-data.json")
ENGINE = os.environ.get("PHASE_ENGINE_VERSION", "phase-rs (version unknown)")
MAX_GAMES = int(os.environ.get("PHASE_SIM_MAX_GAMES", "50"))
JOB_TIMEOUT = int(os.environ.get("PHASE_SIM_TIMEOUT", "3600"))
PORT = int(os.environ.get("PORT", "8090"))
DIFFICULTIES = ("VeryEasy", "Easy", "Medium", "Hard", "VeryHard")
BIN_LLM = os.environ.get("PHASE_AI_COMMANDER_LLM", "/opt/phase/ai-commander-llm")
CHAT_URL = os.environ.get("PHASE_LLM_CHAT_URL", "").rstrip("/") # e.g. http://olla...:40114/olla/openai/v1
DECISION_URL = os.environ.get("PHASE_LLM_DECISION_URL", "") # e.g. http://laya...:8080/v1/systemone
DECISION_KEY = os.environ.get("PHASE_LLM_DECISION_KEY", "")
CHAT_REASONING = os.environ.get("PHASE_LLM_REASONING", "none")
CHAT_MAX_TOKENS = int(os.environ.get("PHASE_LLM_MAX_TOKENS_CAP", "256"))
MAX_LLM_CALLS = int(os.environ.get("PHASE_LLM_MAX_CALLS", "600"))
LOCAL_ONLY = ("127.0.0.1", "::1")
# A late-game prompt is thousands of tokens; reading it takes a 27B model on a V100 20-30 s. The engine waits MODEL_TIMEOUT per question and the
# relay a little less, and the engine switches the model seats off after PHASE_LLM_MAX_FAILS failures in a row, so a dead model costs a few minutes at most.
RELAY_TIMEOUT = float(os.environ.get("PHASE_LLM_RELAY_TIMEOUT", "55"))
MODEL_TIMEOUT = os.environ.get("PHASE_LLM_TIMEOUT_S", "60")
MAX_DECK_ENTRIES = 400
_jobs = {}
_queue = deque()
_cv = threading.Condition()
_running = {"id": None}
# ---------- request -> engine inputs ------------------------------------------------------------------------------------------
class BadRequest(ValueError):
pass
def validate(req):
decks = req.get("decks")
if not isinstance(decks, list) or len(decks) != 4:
raise BadRequest("decks must be a list of exactly 4 decks (one per seat)")
feed = []
for i, d in enumerate(decks):
if not isinstance(d, dict) or not str(d.get("name") or "").strip():
raise BadRequest("deck %d needs a name" % i)
cmd = d.get("commander")
if isinstance(cmd, str):
cmd = [cmd]
if not isinstance(cmd, list) or not cmd or not all(isinstance(c, str) and c.strip() for c in cmd):
raise BadRequest("deck %d needs commander: [\"Card Name\"]" % i)
main = d.get("main")
if main is None and isinstance(d.get("cards"), list):
counts = {}
for n in d["cards"]:
counts[str(n)] = counts.get(str(n), 0) + 1
main = [{"name": k, "count": v} for k, v in counts.items()]
if not isinstance(main, list) or not main or len(main) > MAX_DECK_ENTRIES:
raise BadRequest("deck %d needs a non-empty main list (at most %d entries)" % (i, MAX_DECK_ENTRIES))
rows = []
for e in main:
try:
name, count = str(e["name"]), int(e["count"])
except (KeyError, TypeError, ValueError):
raise BadRequest("deck %d has a bad main entry: %r" % (i, e))
if not name.strip() or not 1 <= count <= 99:
raise BadRequest("deck %d has a bad main entry: %r" % (i, e))
rows.append({"name": name, "count": count})
feed.append({"name": str(d["name"]), "commander": [c.strip() for c in cmd], "main": rows})
try:
games = int(req.get("games", 1))
seed = int(req.get("seed", 1))
except (TypeError, ValueError):
raise BadRequest("games and seed must be integers")
if not 1 <= games <= MAX_GAMES:
raise BadRequest("games must be 1 to %d" % MAX_GAMES)
difficulty = req.get("difficulty", "Medium")
if difficulty not in DIFFICULTIES:
raise BadRequest("difficulty must be one of %s" % ", ".join(DIFFICULTIES))
seat_diff = {}
for k, v in (req.get("seat_difficulty") or {}).items():
if str(k) not in ("0", "1", "2", "3") or v not in DIFFICULTIES:
raise BadRequest("seat_difficulty keys are seats 0-3, values one of %s" % ", ".join(DIFFICULTIES))
seat_diff[int(k)] = v
cap = req.get("action_cap")
if cap is not None:
try:
cap = int(cap)
except (TypeError, ValueError):
raise BadRequest("action_cap must be an integer")
if not 100 <= cap <= 200000:
raise BadRequest("action_cap must be 100 to 200000")
llm = None
seats = req.get("llm_seats") or []
if seats:
if not isinstance(seats, list) or not all(isinstance(x, int) and 0 <= x <= 3 for x in seats):
raise BadRequest("llm_seats must be a list of seats 0-3")
cfg = req.get("llm") or {}
kind = cfg.get("kind", "chat")
if kind not in ("chat", "decision"):
raise BadRequest("llm.kind must be chat or decision")
if (kind == "chat" and not CHAT_URL) or (kind == "decision" and not DECISION_URL):
raise BadRequest("this service has no %s model endpoint configured" % kind)
if not os.path.isfile(BIN_LLM) and not os.environ.get("PHASE_SIM_ALLOW_MISSING_LLM_BIN"):
raise BadRequest("this image has no model-seat engine (ai-commander-llm)")
model = str(cfg.get("model") or "").strip()
if kind == "chat" and not model:
raise BadRequest("llm.model is required for a chat model")
try:
max_calls = int(cfg.get("max_calls", 300))
except (TypeError, ValueError):
raise BadRequest("llm.max_calls must be an integer")
if not 1 <= max_calls <= MAX_LLM_CALLS:
raise BadRequest("llm.max_calls must be 1 to %d" % MAX_LLM_CALLS)
llm = {"seats": sorted(set(seats)), "kind": kind, "model": model or "decision-model", "max_calls": max_calls}
return {"feed": feed, "games": games, "seed": seed, "difficulty": difficulty, "seat_difficulty": seat_diff, "action_cap": cap, "llm": llm}
def engine_env(spec):
"""The environment for the engine process: model-seat settings, or None (inherit) for the plain runner."""
llm = spec.get("llm")
if not llm:
return None
env = dict(os.environ)
local = "http://127.0.0.1:%d" % PORT
env.update(PHASE_LLM_SEATS=",".join(str(x) for x in llm["seats"]), PHASE_LLM_MODEL=llm["model"], PHASE_LLM_API_KEY="",
PHASE_LLM_MAX_CALLS=str(llm["max_calls"]), PHASE_LLM_DIFFICULTY=spec["difficulty"], PHASE_LLM_TIMEOUT_S=MODEL_TIMEOUT)
if llm["kind"] == "chat":
env.update(PHASE_LLM_PROVIDER="OpenAiCompatible", PHASE_LLM_BASE_URL=local + "/llm/v1")
else:
env.update(PHASE_LLM_PROVIDER="Jev", PHASE_LLM_BASE_URL=local)
return env
def command(spec, root):
cmd = [BIN_LLM if spec.get("llm") else BIN, root, "--feed", "feed.json", "--games-file", os.path.join(root, "games.txt")]
for seat, level in sorted(spec["seat_difficulty"].items()):
cmd += ["--difficulty-p%d" % seat, level]
if spec["action_cap"]:
cmd += ["--action-cap", str(spec["action_cap"])]
return cmd
# ---------- engine output -> results ------------------------------------------------------------------------------------------
GAME_HEAD = re.compile(r"^--- GAME\b(.*)$")
WINNER = re.compile(r"Game ended cleanly\. Winner: (draw|P(\d))")
TURNS = re.compile(r"^Turns played: (\d+)")
ELIM = re.compile(r"^ELIMINATED: P(\d)\s+turn=(\d+)")
RESOLVED = re.compile(r"^\s+P(\d)\s+main=\s*(\d+)\s+commander=(\d+)")
LLM_STAT = re.compile(r"^LLM-SEAT seat=(\d) asked=(\d+) used=(\d+)(?: total_calls=(\d+))?(?: timeouts=(\d+))?(?: avg_ms=(\d+))?(?: avg_prompt_chars=(\d+))?")
LLM_OFF = re.compile(r"^LLM-SEAT-DISABLED after (\d+) consecutive failures")
SKIP = re.compile(r"^\s+SKIP (.+?): commander '(.+)' not in card db")
PRE = re.compile(r"^\s+(.+?)\s+\|\s+commander: (.+?)\s+\|\s+main: (\d+) cards")
def parse(output):
"""Per-game rows and the deck-resolution facts from the engine's stdout. Games that did not finish are kept, labelled, never counted."""
lines = output.splitlines()
pre, resolved, skipped, games, cur = [], {}, [], [], None
def finish():
if cur is not None:
games.append(cur)
def new_game(label=""):
return {"label": label, "status": "unfinished", "winner_seat": None, "turns": None, "eliminated": []}
result_line = re.compile(r"Game ended cleanly|^Turns played|^ELIMINATED:|^STALL:|ABORT: hit action cap|PANICKED")
for ln in lines:
if cur is None and not games: # the preamble: decks listed, then their resolved sizes
m = PRE.match(ln)
if m:
pre.append({"deck": m.group(1), "commander": m.group(2), "listed": int(m.group(3))})
continue
m = SKIP.match(ln)
if m:
skipped.append({"deck": m.group(1), "commander": m.group(2)})
continue
m = RESOLVED.match(ln)
if m and int(m.group(1)) not in resolved:
resolved[int(m.group(1))] = {"main": int(m.group(2)), "commanders": int(m.group(3))}
continue
if GAME_HEAD.match(ln):
finish()
cur = new_game(GAME_HEAD.match(ln).group(1).strip(" -"))
continue
if cur is None:
if not result_line.search(ln):
continue # banner and preamble lines are not a game
cur = new_game() # a single-game run prints no "--- GAME" header
m = WINNER.search(ln)
if m:
cur["status"] = "draw" if m.group(1) == "draw" else "won"
cur["winner_seat"] = None if m.group(2) is None else int(m.group(2))
continue
m = TURNS.match(ln)
if m:
cur["turns"] = int(m.group(1))
continue
m = ELIM.match(ln)
if m:
cur["eliminated"].append({"seat": int(m.group(1)), "turn": int(m.group(2))})
continue
if ln.startswith("STALL:"):
cur["status"] = "stalled"
cur.setdefault("detail", ln)
elif "ABORT: hit action cap" in ln:
cur["status"] = "action_cap"
elif re.search(r"GAME .* PANICKED", ln):
cur["status"] = "panicked"
cur["detail"] = ln[:300]
finish()
games = [g for g in games if g["status"] != "unfinished" or g["turns"] is not None or g["eliminated"] or g["label"]]
return {"pre": pre, "resolved": resolved, "skipped": skipped, "games": games}
def llm_summary(llm, lines):
"""The model seats' own counters (the engine prints one every 25th question), last value per seat, plus the breaker and the cost."""
per_seat, extra, disabled = {}, {}, None
for ln in lines:
m = LLM_STAT.match(ln)
if m:
per_seat[int(m.group(1))] = {"asked": int(m.group(2)), "used": int(m.group(3))}
for key, grp in (("timeouts", 5), ("avg_ms", 6), ("avg_prompt_chars", 7)):
if m.group(grp) is not None:
extra[key] = int(m.group(grp))
continue
m = LLM_OFF.match(ln)
if m:
disabled = int(m.group(1))
out = {"seats": llm["seats"], "kind": llm["kind"], "model": llm["model"], "max_calls": llm["max_calls"], "per_seat": per_seat,
"note": "counters are printed every 25th question, so the last few may be missing"}
out.update(extra)
if disabled is not None:
out["switched_off_after_failures_in_a_row"] = disabled
return out
def wilson(wins, n, z=1.96):
if n == 0:
return [0.0, 0.0]
p = wins / n
d = 1 + z * z / n
c = p + z * z / (2 * n)
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
return [round(max(0.0, (c - h) / d), 4), round(min(1.0, (c + h) / d), 4)]
def summarize(spec, parsed, seeds):
decks = [d["name"] for d in spec["feed"]]
finished = [g for g in parsed["games"] if g["status"] in ("won", "draw")]
won = [g for g in finished if g["status"] == "won"]
by_seat = [sum(1 for g in won if g["winner_seat"] == i) for i in range(4)]
n = len(finished)
warnings = []
for s in parsed["skipped"]:
warnings.append("deck %r was skipped: commander %r is not in the engine's card database" % (s["deck"], s["commander"]))
for i, pre in enumerate(parsed["pre"][:4]):
got = (parsed["resolved"].get(i) or {}).get("main")
if got is not None and got < pre["listed"]:
warnings.append("seat %d (%s): %d of %d cards were not recognised by the engine and were left out" % (
i, pre["deck"], pre["listed"] - got, pre["listed"]))
bad = [g for g in parsed["games"] if g["status"] not in ("won", "draw")]
if bad:
warnings.append("%d game(s) did not finish (%s): not counted as wins or draws" % (
len(bad), ", ".join(sorted({g["status"] for g in bad}))))
for i, g in enumerate(parsed["games"]):
if i < len(seeds):
g["seed"] = seeds[i]
return {"games_requested": spec["games"], "games_finished": n, "games_not_finished": len(bad), "draws": n - len(won),
"wins_by_seat": by_seat,
"decks": [{"seat": i, "name": decks[i], "wins": by_seat[i], "win_rate": round(by_seat[i] / n, 4) if n else None,
"win_rate_95": wilson(by_seat[i], n)} for i in range(4)],
"avg_turns": round(sum(g["turns"] or 0 for g in finished) / n, 1) if n else None,
"warnings": warnings, "games": parsed["games"]}
# ---------- jobs ----------------------------------------------------------------------------------------------------------------
def run_job(job):
spec = job["spec"]
root = tempfile.mkdtemp(prefix="phase-sim-")
out_lines = []
try:
os.symlink(CARD_DATA, os.path.join(root, "card-data.json"))
with open(os.path.join(root, "feed.json"), "w", encoding="utf-8") as f:
json.dump({"decks": spec["feed"]}, f)
seeds = [spec["seed"] + i for i in range(spec["games"])]
with open(os.path.join(root, "games.txt"), "w", encoding="utf-8") as f:
f.write("".join("%d,%s\n" % (s, spec["difficulty"]) for s in seeds))
job["status"], job["started"] = "running", time.time()
proc = subprocess.Popen(command(spec, root), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace", cwd=root,
env=engine_env(spec))
timer = threading.Timer(JOB_TIMEOUT, proc.kill)
timer.start()
try:
for ln in proc.stdout:
out_lines.append(ln.rstrip("\n"))
if GAME_HEAD.match(ln):
job["games_started"] += 1
if WINNER.search(ln) or "GAME" in ln and "PANICKED" in ln or ln.startswith("STALL:") or "ABORT: hit action cap" in ln:
job["games_done"] += 1
code = proc.wait()
finally:
timer.cancel()
text = "\n".join(out_lines)
parsed = parse(text)
job["result"] = summarize(spec, parsed, seeds)
if spec.get("llm"):
job["result"]["llm"] = llm_summary(spec["llm"], out_lines)
if "switched_off_after_failures_in_a_row" in job["result"]["llm"]:
job["result"]["warnings"].append(
"the model seats switched themselves off after %d failures in a row (usually timeouts: late-game prompts are thousands of tokens "
"and the model server could not read them in time); phase's own AI played the rest of the run, so the later moves are NOT the model's"
% job["result"]["llm"]["switched_off_after_failures_in_a_row"])
job["result"]["warnings"].append(
"model seats %s: the model is asked about each non-forced decision, up to %d calls for the whole run; an answer the engine "
"cannot use, a timeout, or any decision after the cap is played by phase's own AI instead" % (spec["llm"]["seats"], spec["llm"]["max_calls"]))
job["engine_exit_code"] = code
job["output_tail"] = out_lines[-40:]
job["status"] = "done" if parsed["games"] else "error"
if not parsed["games"]:
job["error"] = "the engine produced no game results (exit code %s); see output_tail" % code
except Exception as exc: # the job fails, the service does not
job["status"], job["error"] = "error", "%s: %s" % (type(exc).__name__, exc)
job["output_tail"] = out_lines[-40:]
finally:
job["finished"] = time.time()
try:
for name in os.listdir(root):
os.unlink(os.path.join(root, name))
os.rmdir(root)
except OSError:
pass
def worker():
while True:
with _cv:
while not _queue:
_cv.wait()
job = _queue.popleft()
_running["id"] = job["id"]
run_job(job)
with _cv:
_running["id"] = None
def submit(req):
spec = validate(req)
job = {"id": uuid.uuid4().hex[:12], "status": "queued", "created": time.time(), "spec": spec, "games_started": 0, "games_done": 0}
with _cv:
_jobs[job["id"]] = job
_queue.append(job)
for old in sorted(_jobs.values(), key=lambda j: j["created"])[:-50]: # remember the last 50
if old["status"] in ("done", "error"):
_jobs.pop(old["id"], None)
_cv.notify()
return job["id"]
def public(job):
out = {k: job[k] for k in ("id", "status", "games_started", "games_done") if k in job}
out["games_requested"] = job["spec"]["games"]
for k in ("result", "error", "output_tail", "engine_exit_code"):
if k in job:
out[k] = job[k]
if "started" in job:
out["seconds"] = round((job.get("finished") or time.time()) - job["started"], 1)
return out
def forward(url, data, headers):
req = urllib.request.Request(url, data=data, headers=dict({"content-type": "application/json"}, **headers))
try:
with urllib.request.urlopen(req, timeout=RELAY_TIMEOUT) as r:
return r.status, json.loads(r.read() or b"{}")
except urllib.error.HTTPError as exc:
try:
return exc.code, json.loads(exc.read() or b"{}")
except ValueError:
return exc.code, {"error": "upstream error"}
except (urllib.error.URLError, OSError, ValueError):
return 502, {"error": "the model endpoint is not reachable"}
def relay_chat(body, remote):
"""POST /llm/v1/chat/completions -> the OpenAI-style endpoint, with the model's thinking off and its answer capped."""
if remote not in LOCAL_ONLY or not CHAT_URL:
return 403, {"error": "not available"}
try:
req = json.loads(body)
req["max_tokens"] = min(int(req.get("max_tokens") or CHAT_MAX_TOKENS), CHAT_MAX_TOKENS)
req["stream"] = False
if CHAT_REASONING:
req["reasoning_effort"] = CHAT_REASONING
data = json.dumps(req).encode()
except (ValueError, TypeError):
return 400, {"error": "bad chat request"}
return forward(CHAT_URL + "/chat/completions", data, {})
def relay_decision(body, remote):
"""POST /jev/systemone: phase's Jev envelope {"apiKey", "request": {...}} -> a System One server (Laya / Kev); the key comes from the environment."""
if remote not in LOCAL_ONLY or not DECISION_URL:
return 403, {"error": "not available"}
try:
data = json.dumps(json.loads(body)["request"]).encode()
except (ValueError, KeyError, TypeError):
return 400, {"error": "bad decision request"}
return forward(DECISION_URL, data, {"authorization": "Bearer " + DECISION_KEY} if DECISION_KEY else {})
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
server_version = "phase-sim/1"
def log_message(self, fmt, *args):
if os.environ.get("PHASE_SIM_LOG") == "1":
sys.stderr.write("%s\n" % (fmt % args))
def _send(self, code, obj):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/health":
with _cv:
return self._send(200, {"ok": os.path.isfile(BIN) and os.path.isfile(CARD_DATA), "engine": ENGINE,
"queued": len(_queue), "running": _running["id"], "max_games": MAX_GAMES})
m = re.match(r"^/job/([0-9a-f]+)$", self.path)
if m:
with _cv:
job = _jobs.get(m.group(1))
return self._send(200, public(job)) if job else self._send(404, {"error": "no such job"})
self._send(404, {"error": "not found"})
def do_POST(self):
if self.path in ("/llm/v1/chat/completions", "/jev/systemone"):
n = int(self.headers.get("Content-Length") or 0)
if n > 4_000_000:
return self._send(413, {"error": "request too large"})
fn = relay_chat if self.path.startswith("/llm") else relay_decision
code, obj = fn(self.rfile.read(n), self.client_address[0])
return self._send(code, obj)
if self.path != "/run":
return self._send(404, {"error": "not found"})
try:
n = int(self.headers.get("Content-Length") or 0)
if n > 2_000_000:
return self._send(413, {"error": "request too large"})
req = json.loads(self.rfile.read(n) or b"{}")
if not isinstance(req, dict):
raise BadRequest("the body must be a JSON object")
self._send(202, {"job": submit(req)})
except (BadRequest, json.JSONDecodeError) as exc:
self._send(400, {"error": str(exc)})
def main():
threading.Thread(target=worker, daemon=True).start()
ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
if __name__ == "__main__":
main()
-108
View File
@@ -1,108 +0,0 @@
"""Smoke test, run INSIDE the image (CI and by hand): four real decks from phase's own sample feed play real games through the service.
python /opt/phase/phase_smoke.py [games] [difficulty] plain engine
python /opt/phase/phase_smoke.py --llm model seats against a stub model inside this process
Exits non-zero unless at least one game finished with a winner or a draw. Prints what the engine reported, including any cards it did
not recognise, so a bad data/engine pairing shows up here and not in a result someone trusts.
--llm starts a stub OpenAI-style model on 127.0.0.1:9099 (the service must have been started with PHASE_LLM_CHAT_URL=http://127.0.0.1:9099/v1),
puts seats 1 and 3 on it, and passes when the engine's own counters show the model was asked AND its answers were used by the engine: that
proves the Rust hook, the relay and phase's answer check end to end without any outside service. The stub always answers option 0, so the
game itself may not finish (it can hit the action cap); that is not what is being tested.
"""
import json
import sys
import threading
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer
BASE = "http://127.0.0.1:8090"
LLM = "--llm" in sys.argv
args = [a for a in sys.argv[1:] if not a.startswith("--")]
games = int(args[0]) if args else (1 if LLM else 2)
difficulty = args[1] if len(args) > 1 else "VeryEasy"
ASKED = []
class StubModel(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)))
ASKED.append(body)
out = json.dumps({"choices": [{"index": 0, "message": {"role": "assistant", "content": "{\"choice\": 0, \"reason\": \"stub\"}"}, "finish_reason": "stop"}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}).encode()
self.send_response(200)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(out)))
self.end_headers()
self.wfile.write(out)
if LLM:
threading.Thread(target=HTTPServer(("127.0.0.1", 9099), StubModel).serve_forever, daemon=True).start()
def call(path, body=None):
req = urllib.request.Request(BASE + path, data=None if body is None else json.dumps(body).encode(), headers={"content-type": "application/json"})
with urllib.request.urlopen(req, timeout=60) as r:
return json.load(r)
for _ in range(60):
try:
h = call("/health")
break
except Exception:
time.sleep(1)
else:
sys.exit("the service did not come up")
print("health:", h)
assert h["ok"], "binary or card data missing"
feed = json.load(open("/opt/phase/sample-feed.json", encoding="utf-8"))["decks"]
decks = []
for d in feed:
cmd = d.get("commander") or [d["name"]]
decks.append({"name": d["name"], "commander": cmd, "main": d["main"]})
if len(decks) == 4:
break
request = {"decks": decks, "games": games, "seed": 7, "difficulty": difficulty, "action_cap": 60000}
if LLM:
request.update(action_cap=6000, llm_seats=[1, 3], llm={"kind": "chat", "model": "stub-model", "max_calls": 60})
job = call("/run", request)["job"]
t0 = time.time()
while True:
j = call("/job/" + job)
if j["status"] in ("done", "error"):
break
if time.time() - t0 > 1500:
sys.exit("timed out; last: %s" % json.dumps(j)[:300])
time.sleep(3)
print("job: %s in %.0f s" % (j["status"], time.time() - t0))
res = j.get("result") or {}
print(json.dumps({k: res.get(k) for k in ("games_requested", "games_finished", "games_not_finished", "draws", "wins_by_seat", "avg_turns", "warnings")}, indent=1))
for g in res.get("games", []):
print(" game seed=%s %s winner=%s turns=%s eliminated=%s" % (g.get("seed"), g["status"], g.get("winner_seat"), g.get("turns"), g.get("eliminated")))
if LLM:
llm = res.get("llm") or {}
print("model seats:", json.dumps(llm), "| requests the stub model received:", len(ASKED))
print("\n".join((j.get("output_tail") or [])[-15:]))
seats = llm.get("per_seat") or {}
asked = sum(v["asked"] for v in seats.values())
used = sum(v["used"] for v in seats.values())
reasoned = [a for a in ASKED if a.get("reasoning_effort") == "none"]
if not ASKED or not asked or not used:
sys.exit("the model seats were not exercised: stub got %d requests, engine counters asked=%d used=%d" % (len(ASKED), asked, used))
if len(reasoned) != len(ASKED):
sys.exit("the relay did not switch the model's thinking off on every request")
print("PHASE LLM SMOKE OK (asked %d, engine used %d, stub saw %d requests, all with thinking off)" % (asked, used, len(ASKED)))
sys.exit(0)
if j["status"] != "done" or res.get("games_finished", 0) < 1:
print("\n".join(j.get("output_tail") or []))
sys.exit("no game finished")
print("PHASE SMOKE OK")
-272
View File
@@ -1,272 +0,0 @@
"""Run: python -I -X utf8 test_phase_sim.py (offline: a stub engine prints output in the format phase's ai-commander prints)"""
import json
import os
import sys
import tempfile
import threading
import time
import urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import phase_sim as P # noqa: E402
FAILS = 0
def ck(name, cond, detail=""):
global FAILS
print(" %s %s%s" % ("ok " if cond else "FAIL", name, (" -- " + str(detail)[:260]) if detail and not cond else ""))
if not cond:
FAILS += 1
def deck(name, cmd, n=3):
return {"name": name, "commander": [cmd], "main": [{"name": "Sol Ring", "count": 1}, {"name": "Forest", "count": n}]}
GOOD = {"decks": [deck("A", "Cmd A"), deck("B", "Cmd B"), deck("C", "Cmd C"), deck("D", "Cmd D")], "games": 3, "seed": 10}
# --- validation
def bad(mut, why):
req = json.loads(json.dumps(GOOD))
mut(req)
try:
P.validate(req)
ck("rejects " + why, False)
except P.BadRequest as exc:
ck("rejects " + why, True, exc)
ck("a good request validates", P.validate(GOOD)["games"] == 3)
bad(lambda r: r["decks"].pop(), "three decks")
bad(lambda r: r["decks"][0].pop("commander"), "a deck with no commander")
bad(lambda r: r["decks"][1].update(main=[]), "an empty main list")
bad(lambda r: r["decks"][2]["main"].append({"name": "X", "count": 0}), "a zero count")
bad(lambda r: r.update(games=P.MAX_GAMES + 1), "too many games")
bad(lambda r: r.update(difficulty="Impossible"), "an unknown difficulty")
bad(lambda r: r.update(seat_difficulty={"7": "Easy"}), "a seat outside 0-3")
bad(lambda r: r.update(action_cap=5), "a tiny action cap")
v = P.validate(dict(GOOD, decks=[dict(deck("A", "Cmd A"), commander="Cmd A", main=None, cards=["Forest", "Forest", "Sol Ring"])] + GOOD["decks"][1:]))
ck("a plain card list becomes counted rows and a commander string becomes a list",
v["feed"][0]["commander"] == ["Cmd A"] and {"name": "Forest", "count": 2} in v["feed"][0]["main"], v["feed"][0])
# --- parsing the engine's output
OUT = """=== 4-player Commander AI test ===
Feed: feed.json
Batch mode: 5 games from games.txt
A | commander: Cmd A | main: 99 cards
B | commander: Cmd B | main: 99 cards
SKIP C: commander 'Cmd C' not in card db
D | commander: Cmd D | main: 99 cards
Resolved deck sizes (post name-resolution, 0-indexed by seat):
P0 main= 99 commander=1
P1 main= 97 commander=1
P2 main= 99 commander=1
P3 main= 99 commander=1
ExecutionMode: measurement
--- GAME seed=10 difficulty=Medium ---
Game started. 4 players.
ELIMINATED: P1 turn=9 actions= 400 elapsed=3.1s
ELIMINATED: P3 turn=12 actions= 600 elapsed=5.0s
=== RESULT ===
Elapsed: 8.0s
Turns played: 14
Game ended cleanly. Winner: P2
--- GAME seed=11 difficulty=Medium ---
Game started. 4 players.
=== RESULT ===
Turns played: 40
Game ended cleanly. Winner: draw
--- GAME seed=12 difficulty=Medium ---
=== RESULT ===
Turns played: 7
STALL: waiting_for=ChooseTarget turn=7 active=P0 priority=P0 pending_cast=none
Game did NOT reach GameOver. waiting_for = ChooseTarget
--- GAME seed=13 difficulty=Medium ---
ABORT: hit action cap=50000
=== RESULT ===
Turns played: 31
Game did NOT reach GameOver. waiting_for = Priority
--- GAME seed=14 difficulty=Medium ---
GAME 14 PANICKED: index out of bounds
"""
parsed = P.parse(OUT)
st = [g["status"] for g in parsed["games"]]
ck("five games found with their outcomes in order", st == ["won", "draw", "stalled", "action_cap", "panicked"], st)
g0 = parsed["games"][0]
ck("winner seat, turns and elimination order are read", g0["winner_seat"] == 2 and g0["turns"] == 14
and [e["seat"] for e in g0["eliminated"]] == [1, 3], g0)
ck("a draw has no winner seat", parsed["games"][1]["winner_seat"] is None)
ck("pre-resolution and resolved deck sizes and the skipped deck are read", len(parsed["pre"]) == 3 and parsed["resolved"][1]["main"] == 97
and parsed["skipped"] == [{"deck": "C", "commander": "Cmd C"}], (parsed["pre"], parsed["resolved"], parsed["skipped"]))
spec = P.validate(dict(GOOD, games=5))
res = P.summarize(spec, parsed, [10, 11, 12, 13, 14])
ck("only finished games are counted", res["games_finished"] == 2 and res["games_not_finished"] == 3 and res["draws"] == 1, res)
ck("wins by seat and per-deck win rate", res["wins_by_seat"] == [0, 0, 1, 0] and res["decks"][2]["win_rate"] == 0.5 and res["decks"][0]["win_rate"] == 0.0)
lo, hi = res["decks"][2]["win_rate_95"]
ck("a 95% interval wraps the rate and stays in 0..1", 0 <= lo < 0.5 < hi <= 1)
w = " | ".join(res["warnings"])
ck("warnings: a skipped deck, unrecognised cards, and unfinished games (never counted)",
"was skipped" in w and "2 of 99" in w and "not counted as wins or draws" in w and "stalled" in w, w)
ck("each game carries its seed", [g["seed"] for g in res["games"]] == [10, 11, 12, 13, 14])
ck("interval of nothing is zeros, of a sweep is high", P.wilson(0, 0) == [0.0, 0.0] and P.wilson(10, 10)[0] > 0.7)
# --- a whole job through the real worker path with a stub engine
STUB = os.path.join(tempfile.mkdtemp(), "stub_engine.py")
with open(STUB, "w", encoding="utf-8") as f:
f.write('''import sys, os
root = sys.argv[1]
seeds = [l.split(",")[0] for l in open(os.path.join(root, "games.txt")) if l.strip()]
feed = __import__("json").load(open(os.path.join(root, "feed.json")))
assert os.path.exists(os.path.join(root, "card-data.json")) and len(feed["decks"]) == 4
for d in feed["decks"]:
print(" %s | commander: %s | main: %d cards" % (d["name"], d["commander"][0], sum(e["count"] for e in d["main"])))
print("Resolved deck sizes (post name-resolution, 0-indexed by seat):")
for i, d in enumerate(feed["decks"]):
print(" P%d main=%3d commander=1" % (i, sum(e["count"] for e in d["main"])))
for k, s in enumerate(seeds):
print("--- GAME seed=%s ---" % s)
print("Turns played: %d" % (10 + k))
print("Game ended cleanly. Winner: P%d" % (k % 4))
''')
CD = os.path.join(os.path.dirname(STUB), "card-data.json")
open(CD, "w").write("{}")
P.CARD_DATA = CD
ORIG_COMMAND = P.command
P.command = lambda spec, root: [sys.executable, STUB, root]
job_id = P.submit(dict(GOOD, games=4))
threading.Thread(target=P.worker, daemon=True).start()
for _ in range(100):
j = P._jobs[job_id]
if j["status"] in ("done", "error"):
break
time.sleep(0.1)
pub = P.public(P._jobs[job_id])
ck("a queued job runs to done with four finished games, one win each", pub["status"] == "done" and pub["result"]["games_finished"] == 4
and pub["result"]["wins_by_seat"] == [1, 1, 1, 1] and pub["games_done"] == 4, pub)
ck("no warnings when every card resolved", pub["result"]["warnings"] == [], pub["result"]["warnings"])
ck("the temp folder is cleaned up", not [d for d in os.listdir(tempfile.gettempdir()) if d.startswith("phase-sim-")])
# --- the HTTP surface
srv = P.ThreadingHTTPServer(("127.0.0.1", 0), P.Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
base = "http://127.0.0.1:%d" % srv.server_port
def call(path, body=None):
req = urllib.request.Request(base + path, data=None if body is None else json.dumps(body).encode(), headers={"content-type": "application/json"})
try:
r = urllib.request.urlopen(req, timeout=10)
return r.status, json.load(r)
except urllib.error.HTTPError as e:
return e.code, json.load(e)
code, h = call("/health")
ck("/health answers (ok is false only because the real binary is not here)", code == 200 and "engine" in h and h["max_games"] == P.MAX_GAMES, h)
code, r = call("/run", dict(GOOD, games=1))
ck("POST /run is accepted with a job id", code == 202 and len(r["job"]) == 12, r)
for _ in range(100):
code, j = call("/job/" + r["job"])
if j["status"] in ("done", "error"):
break
time.sleep(0.1)
ck("GET /job/<id> returns the result", code == 200 and j["status"] == "done" and j["result"]["games_finished"] == 1, j)
ck("a bad request is a 400 with a reason", call("/run", {"decks": []})[0] == 400)
ck("an unknown job is a 404", call("/job/deadbeef")[0] == 404)
ck("an unknown path is a 404", call("/nope")[0] == 404)
# --- model seats: validation, environment, relays
from http.server import BaseHTTPRequestHandler, HTTPServer
UP = []
class Upstream(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)))
UP.append((self.path, body, self.headers.get("authorization")))
out = json.dumps({"echo": True, "path": self.path}).encode()
self.send_response(200)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(out)))
self.end_headers()
self.wfile.write(out)
up = HTTPServer(("127.0.0.1", 0), Upstream)
threading.Thread(target=up.serve_forever, daemon=True).start()
UPBASE = "http://127.0.0.1:%d" % up.server_port
os.environ["PHASE_SIM_ALLOW_MISSING_LLM_BIN"] = "1"
LLMREQ = dict(GOOD, llm_seats=[1, 3], llm={"kind": "chat", "model": "twin-turbo", "max_calls": 120})
P.CHAT_URL, P.DECISION_URL = "", ""
try:
P.validate(LLMREQ)
ck("model seats are refused when no model endpoint is configured", False)
except P.BadRequest as exc:
ck("model seats are refused when no model endpoint is configured", "no chat model endpoint" in str(exc), exc)
P.CHAT_URL, P.DECISION_URL, P.DECISION_KEY = UPBASE + "/v1", UPBASE + "/v1/systemone", "sekret"
v = P.validate(LLMREQ)
ck("a chat model seat request validates", v["llm"] == {"seats": [1, 3], "kind": "chat", "model": "twin-turbo", "max_calls": 120}, v["llm"])
ck("a request with no model seats has no llm settings", P.validate(GOOD)["llm"] is None)
for mut, why in ((lambda r: r.update(llm_seats=[4]), "a seat outside 0-3"),
(lambda r: r["llm"].pop("model"), "a chat model with no name"),
(lambda r: r["llm"].update(max_calls=P.MAX_LLM_CALLS + 1), "too many model calls"),
(lambda r: r["llm"].update(kind="telepathy"), "an unknown kind")):
req = json.loads(json.dumps(LLMREQ))
mut(req)
try:
P.validate(req)
ck("rejects " + why, False)
except P.BadRequest:
ck("rejects " + why, True)
dv = P.validate(dict(GOOD, llm_seats=[0], llm={"kind": "decision"}))
ck("a decision-model seat needs no model name", dv["llm"]["kind"] == "decision" and dv["llm"]["model"] == "decision-model")
env = P.engine_env(v)
ck("chat seats: the engine is pointed at this service's /llm relay as an OpenAI-compatible endpoint with no key",
env["PHASE_LLM_SEATS"] == "1,3" and env["PHASE_LLM_PROVIDER"] == "OpenAiCompatible" and env["PHASE_LLM_BASE_URL"].endswith("/llm/v1")
and env["PHASE_LLM_MODEL"] == "twin-turbo" and env["PHASE_LLM_API_KEY"] == "" and env["PHASE_LLM_MAX_CALLS"] == "120", env)
denv = P.engine_env(dv)
ck("decision seats: provider Jev, base is this service (the engine adds /jev/systemone)", denv["PHASE_LLM_PROVIDER"] == "Jev"
and denv["PHASE_LLM_BASE_URL"] == "http://127.0.0.1:%d" % P.PORT)
ck("no model seats: no special environment, the plain engine", P.engine_env(P.validate(GOOD)) is None
and ORIG_COMMAND(P.validate(GOOD), "/r")[0] == P.BIN and ORIG_COMMAND(v, "/r")[0] == P.BIN_LLM)
code, out = P.relay_chat(json.dumps({"model": "twin-turbo", "messages": [{"role": "user", "content": "x"}], "max_tokens": 4000, "stream": True}).encode(), "127.0.0.1")
path, body, auth = UP[-1]
ck("the chat relay forwards to /chat/completions with thinking off, the answer capped and streaming off",
code == 200 and path == "/v1/chat/completions" and body["reasoning_effort"] == "none" and body["max_tokens"] == P.CHAT_MAX_TOKENS
and body["stream"] is False and body["model"] == "twin-turbo", (code, path, body))
ck("a request without max_tokens gets the cap", (P.relay_chat(b'{"model": "m", "messages": []}', "127.0.0.1"), UP[-1][1]["max_tokens"] == P.CHAT_MAX_TOKENS)[1])
ck("the relays refuse anyone but this machine", P.relay_chat(b"{}", "10.1.2.3")[0] == 403 and P.relay_decision(b"{}", "10.1.2.3")[0] == 403)
ck("a malformed chat body is a 400, not an exception", P.relay_chat(b"not json", "127.0.0.1")[0] == 400)
envelope = {"apiKey": "ignored-by-us", "request": {"state": {"body": "t"}, "questions": {"pick": {"type": "choice"}}}}
code, out = P.relay_decision(json.dumps(envelope).encode(), "127.0.0.1")
path, body, auth = UP[-1]
ck("the decision relay unwraps phase's envelope and sends only the request, with OUR key", code == 200 and path == "/v1/systemone"
and body == envelope["request"] and auth == "Bearer sekret", (code, path, body, auth))
ck("a decision body with no request is a 400", P.relay_decision(b'{"apiKey": "k"}', "127.0.0.1")[0] == 400)
P.CHAT_URL = "http://127.0.0.1:1/v1"
ck("an unreachable model endpoint is a 502", P.relay_chat(b'{"model": "m", "messages": []}', "127.0.0.1")[0] == 502)
P.CHAT_URL = UPBASE + "/v1"
summ = P.llm_summary({"seats": [1], "kind": "chat", "model": "m", "max_calls": 9},
["LLM-SEAT seat=1 asked=25 used=20 total_calls=25", "noise", "LLM-SEAT seat=1 asked=50 used=41 total_calls=50"])
ck("the model seats' counters are read from the engine's output (last value wins)", summ["per_seat"] == {1: {"asked": 50, "used": 41}}, summ)
summ2 = P.llm_summary({"seats": [1], "kind": "chat", "model": "m", "max_calls": 9},
["LLM-SEAT seat=1 asked=25 used=1 total_calls=25 timeouts=20 avg_ms=1800 avg_prompt_chars=31000",
"LLM-SEAT-DISABLED after 4 consecutive failures (20 timeouts of 25 questions): phase's own AI plays the rest"])
ck("cost counters and the circuit-breaker are read from the engine's output", summ2["timeouts"] == 20 and summ2["avg_ms"] == 1800
and summ2["avg_prompt_chars"] == 31000 and summ2["switched_off_after_failures_in_a_row"] == 4 and summ2["per_seat"] == {1: {"asked": 25, "used": 1}}, summ2)
ck("old three-field counter lines still parse", P.llm_summary({"seats": [1], "kind": "chat", "model": "m", "max_calls": 9},
["LLM-SEAT seat=2 asked=25 used=24 total_calls=25"])["per_seat"] == {2: {"asked": 25, "used": 24}})
code, r = call("/llm/v1/chat/completions", {"model": "m", "messages": []})
ck("over HTTP from this machine the chat relay answers", code == 200 and r["echo"] is True, (code, r))
print("\nFAILURES: %d" % FAILS)
sys.exit(1 if FAILS else 0)
-42
View File
@@ -1,42 +0,0 @@
with open('ml/eval/forge_evaluator.py', 'rb') as f:
data = f.read()
# Fix 1: absolute JAR path in subprocess call
data = data.replace(
b'"--forge-jar", self.cfg.forge_jar,',
b'"--forge-jar", str(Path(self.cfg.forge_jar).resolve()),'
)
# Fix 2: resolve forge_work_dir to absolute path too
data = data.replace(
b'"--forge-dir", self.cfg.forge_work_dir,',
b'"--forge-dir", str(Path(self.cfg.forge_work_dir).resolve()),'
)
# Fix 3: change default forge_work_dir
data = data.replace(
b'forge_work_dir: str = "forge"',
b'forge_work_dir: str = "D:/ForgeCommander/forge-repo/forge-gui"'
)
with open('ml/eval/forge_evaluator.py', 'wb') as f:
f.write(data)
import py_compile
py_compile.compile('ml/eval/forge_evaluator.py', doraise=True)
print('forge_evaluator.py - Syntax OK')
# Fix eval_policy.py too
with open('scripts/eval_policy.py', 'rb') as f:
data = f.read()
data = data.replace(
b'"--forge-dir", default="forge"',
b'"--forge-dir", default="D:/ForgeCommander/forge-repo/forge-gui"'
)
with open('scripts/eval_policy.py', 'wb') as f:
f.write(data)
py_compile.compile('scripts/eval_policy.py', doraise=True)
print('eval_policy.py - Syntax OK')
+24
View File
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
+73
View File
@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>commander-ai-lab-ui</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
{
"name": "commander-ai-lab-ui",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@tailwindcss/vite": "^4.2.1",
"lucide-react": "^0.577.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-router-dom": "^7.13.1",
"recharts": "^3.8.0",
"tailwindcss": "^4.2.1"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@types/node": "^24.10.1",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.48.0",
"vite": "^7.3.1"
}
}
+27
View File
@@ -0,0 +1,27 @@
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { PageLayout } from './components/layout/PageLayout'
import { BatchSimPage } from './pages/BatchSimPage'
import { CollectionPage } from './pages/CollectionPage'
import { DecksPage } from './pages/DecksPage'
import { AutoGenPage } from './pages/AutoGenPage'
import { SimulatorPage } from './pages/SimulatorPage'
import { CoachPage } from './pages/CoachPage'
import { TrainingPage } from './pages/TrainingPage'
export default function App() {
return (
<BrowserRouter>
<PageLayout>
<Routes>
<Route path="/" element={<BatchSimPage />} />
<Route path="/collection" element={<CollectionPage />} />
<Route path="/decks" element={<DecksPage />} />
<Route path="/autogen" element={<AutoGenPage />} />
<Route path="/simulator" element={<SimulatorPage />} />
<Route path="/coach" element={<CoachPage />} />
<Route path="/training" element={<TrainingPage />} />
</Routes>
</PageLayout>
</BrowserRouter>
)
}
@@ -0,0 +1,82 @@
// ═══════════════════════════════════════════════════════════
// Base API client — all fetch calls go through here
// ═══════════════════════════════════════════════════════════
const BASE = '' // same origin; Vite proxy handles /api in dev
export class ApiError extends Error {
status: number
constructor(status: number, message: string) {
super(message)
this.name = 'ApiError'
this.status = status
}
}
async function handleResponse<T>(res: Response): Promise<T> {
if (!res.ok) {
const body = await res.text()
let message = `HTTP ${res.status}`
try {
const json = JSON.parse(body)
message = json.detail || json.error || message
} catch {
if (body) message = body
}
throw new ApiError(res.status, message)
}
// Handle 204 No Content
if (res.status === 204) return undefined as T
return res.json()
}
export async function get<T>(path: string, params?: Record<string, string | number | boolean | undefined>): Promise<T> {
const url = new URL(BASE + path, window.location.origin)
if (params) {
Object.entries(params).forEach(([k, v]) => {
if (v !== undefined && v !== '') url.searchParams.set(k, String(v))
})
}
const res = await fetch(url.toString())
return handleResponse<T>(res)
}
export async function post<T>(path: string, body?: unknown): Promise<T> {
const res = await fetch(BASE + path, {
method: 'POST',
headers: body ? { 'Content-Type': 'application/json' } : {},
body: body ? JSON.stringify(body) : undefined,
})
return handleResponse<T>(res)
}
export async function postForm<T>(path: string, formData: FormData): Promise<T> {
const res = await fetch(BASE + path, {
method: 'POST',
body: formData,
})
return handleResponse<T>(res)
}
export async function put<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(BASE + path, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
return handleResponse<T>(res)
}
export async function patch<T>(path: string, body: unknown): Promise<T> {
const res = await fetch(BASE + path, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
return handleResponse<T>(res)
}
export async function del<T>(path: string): Promise<T> {
const res = await fetch(BASE + path, { method: 'DELETE' })
return handleResponse<T>(res)
}
@@ -0,0 +1,131 @@
import { get, post } from './client'
import type {
CoachStatus, CoachDeck, CoachSession, CoachSessionSummary,
CoachChatResponse, CoachApplyResult, CoachCardLikeResult
} from '../types'
export async function getCoachStatus() {
return get<CoachStatus>('/api/coach/status')
}
export async function getCoachDecks() {
return get<CoachDeck[]>('/api/coach/decks')
}
export async function getCoachDeckReport(deckId: string) {
return get<Record<string, unknown>>(`/api/coach/decks/${deckId}/report`)
}
export async function runCoachSession(deckId: string, goals?: Record<string, unknown>) {
return post<CoachSession>(`/api/coach/decks/${deckId}`, goals ? { goals } : undefined)
}
export async function getCoachSessions(deckId?: string) {
const params: Record<string, string> = {}
if (deckId) params.deck_id = deckId
return get<{ sessions: CoachSessionSummary[] }>('/api/coach/sessions', params)
}
export async function getCoachSession(sessionId: string) {
return get<CoachSession>(`/api/coach/sessions/${sessionId}`)
}
export async function downloadEmbeddings() {
return post<{ success: boolean; cards: number }>('/api/coach/embeddings/download')
}
export async function coachChat(
deckId: string,
messages: { role: string; content: string }[],
goals?: Record<string, unknown>
) {
return post<CoachChatResponse>('/api/coach/chat', {
deck_id: deckId,
messages,
goals,
stream: false,
})
}
export async function coachChatStream(
deckId: string,
messages: { role: string; content: string }[],
goals?: Record<string, unknown>,
onChunk?: (text: string) => void,
signal?: AbortSignal
): Promise<string> {
const res = await fetch('/api/coach/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
deck_id: deckId,
messages,
goals,
stream: true,
}),
signal,
})
if (!res.ok) {
const body = await res.text()
throw new Error(body || `HTTP ${res.status}`)
}
const reader = res.body?.getReader()
if (!reader) throw new Error('No response body')
const decoder = new TextDecoder()
let fullText = ''
let buffer = ''
while (true) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || ''
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6).trim()
if (data === '[DONE]') break
try {
const parsed = JSON.parse(data)
if (parsed.content) {
fullText += parsed.content
onChunk?.(fullText)
}
} catch { /* skip bad chunks */ }
}
}
}
return fullText
}
export async function applyCoachSuggestions(
sessionId: string,
deckId: number,
acceptedCuts: string[],
acceptedAdds: string[]
) {
return post<CoachApplyResult>('/api/coach/apply', {
session_id: sessionId,
deck_id: deckId,
accepted_cuts: acceptedCuts,
accepted_adds: acceptedAdds,
})
}
export async function searchCardsLike(card: string, colors?: string, topN = 10) {
const params: Record<string, string | number> = { card, top_n: topN }
if (colors) params.colors = colors
return get<{ query: string; results: CoachCardLikeResult[] }>('/api/coach/cards-like', params)
}
export async function generateReport(deckId?: number) {
return post<{ status: string; decksUpdated: string[]; count: number }>('/api/coach/reports/generate',
deckId ? { deck_id: deckId } : undefined
)
}
@@ -0,0 +1,86 @@
import { get, post, patch, postForm } from './client'
import type { CollectionCard, CollectionFilters, SetInfo, ScanResult } from '../types'
export async function searchCollection(filters: CollectionFilters) {
// Map frontend snake_case filter names to backend camelCase param names
const params: Record<string, string | number | boolean> = {}
if (filters.q) params.q = filters.q
if (filters.page) params.page = filters.page
if (filters.page_size) params.pageSize = filters.page_size
if (filters.sort_by) params.sortField = filters.sort_by
if (filters.sort_dir) params.sortDir = filters.sort_dir
if (filters.color) params.colors = filters.color
if (filters.type_line) params.types = filters.type_line
if (filters.rarity) params.rarity = filters.rarity
if (filters.set_code) params.setCode = filters.set_code
if (filters.cmc_min !== undefined) params.cmcMin = filters.cmc_min
if (filters.cmc_max !== undefined) params.cmcMax = filters.cmc_max
if (filters.price_min !== undefined) params.priceMin = filters.price_min
if (filters.price_max !== undefined) params.priceMax = filters.price_max
if (filters.owned_only !== undefined) params.owned_only = filters.owned_only
const res = await get<{ items?: CollectionCard[]; cards?: CollectionCard[]; total: number; page: number; pageSize?: number; page_size?: number }>(
'/api/collection', params
)
return {
cards: res.items || res.cards || [],
total: res.total || 0,
page: res.page || 1,
page_size: res.pageSize || res.page_size || 48,
}
}
export async function getCard(cardId: number) {
return get<CollectionCard>(`/api/collection/${cardId}`)
}
export async function updateCard(cardId: number, updates: Partial<CollectionCard>) {
return patch<CollectionCard>(`/api/collection/${cardId}`, updates)
}
export async function getSets() {
const res = await get<SetInfo[] | { sets: SetInfo[] }>('/api/collection/sets')
return Array.isArray(res) ? res : (res as { sets: SetInfo[] }).sets || []
}
export async function getKeywords() {
const res = await get<string[] | { keywords: string[] }>('/api/collection/keywords')
return Array.isArray(res) ? res : (res as { keywords: string[] }).keywords || []
}
export async function exportCollection(format: string = 'csv') {
const res = await fetch(`/api/collection/export?format=${format}`)
return res.blob()
}
export async function importCollection(file: File) {
const fd = new FormData()
fd.append('file', file)
return postForm<{ imported: number; errors: string[] }>('/api/collection/import', fd)
}
export async function scanCard(file: File) {
const fd = new FormData()
fd.append('image', file)
return postForm<ScanResult>('/api/collection/scan', fd)
}
export async function addScanResult(match: { name: string; set_code: string; scryfall_id: string; quantity?: number }) {
return post<{ success: boolean; card_id: number }>('/api/collection/scan/add', match)
}
export async function reEnrichCards() {
return post<{ updated: number }>('/api/collection/re-enrich')
}
export async function autoClassify(cardId: number) {
return post<{ classifications: string[] }>(`/api/collection/auto-classify`, { card_id: cardId })
}
export async function autoClassifyAll() {
return post<{ processed: number }>('/api/collection/auto-classify-all')
}
export async function getEdhrecData(cardId: number) {
return get<Record<string, unknown>>(`/api/collection/${cardId}/edhrec`)
}
@@ -0,0 +1,22 @@
import { get, post } from './client'
import type { DeckGenV3Request, DeckGenV3Status, DeckGenV3Result, CommanderSearchResult } from '../types'
export async function getV3Status() {
return get<DeckGenV3Status>('/api/deck/v3/status')
}
export async function searchCommanders(q: string) {
return get<CommanderSearchResult[]>('/api/deck-generator/commander-search', { q })
}
export async function generateDeckV3(req: DeckGenV3Request) {
return post<DeckGenV3Result>('/api/deck/v3/generate', req)
}
export async function commitDeckV3(req: DeckGenV3Request) {
return post<DeckGenV3Result & { deck_id: number; dck_path: string }>('/api/deck/v3/commit', req)
}
export async function exportDeckV3(format: 'csv' | 'dck' | 'moxfield' | 'shopping', req: DeckGenV3Request) {
return post<Record<string, unknown>>(`/api/deck/v3/export/${format}`, req)
}
@@ -0,0 +1,130 @@
import { get, post, put, del, patch } from './client'
import type { Deck, DeckCard, DeckAnalysis, EdhRecsResponse, CollectionRecsResponse, PplxStatus } from '../types'
export async function listDecks() {
const res = await get<{ decks: Record<string, unknown>[] } | Record<string, unknown>[]>('/api/decks')
const raw = Array.isArray(res) ? res : (res as { decks: Record<string, unknown>[] }).decks || []
return raw.map(d => ({
...d,
commander: d.commander || d.commander_name || '',
card_count: d.card_count ?? d.total_cards ?? 0,
total_price: d.total_price ?? 0,
color_identity: d.color_identity || [],
created_date: d.created_date || d.created_at || '',
updated_date: d.updated_date || d.updated_at || '',
})) as Deck[]
}
export async function getDeck(deckId: number) {
return get<Deck>(`/api/decks/${deckId}`)
}
export async function createDeck(deck: { name: string; commander?: string; format?: string }) {
return post<Deck>('/api/decks', deck)
}
export async function updateDeck(deckId: number, updates: Partial<Deck>) {
return put<Deck>(`/api/decks/${deckId}`, updates)
}
export async function deleteDeck(deckId: number) {
return del<void>(`/api/decks/${deckId}`)
}
export async function deleteAllDecks() {
return del<void>('/api/decks')
}
export async function getDeckCards(deckId: number) {
const res = await get<{ cards: Record<string, unknown>[]; total: number } | Record<string, unknown>[]>(`/api/decks/${deckId}/cards`)
const raw = Array.isArray(res) ? res : (res as { cards: Record<string, unknown>[] }).cards || []
return raw.map(c => ({
...c,
name: c.name || c.card_name || '',
category: c.category || c.role_tag || '',
})) as DeckCard[]
}
export async function addCardToDeck(deckId: number, card: { name: string; scryfall_id?: string; quantity?: number; category?: string }) {
return post<DeckCard>(`/api/decks/${deckId}/cards`, card)
}
export async function removeCardFromDeck(deckId: number, cardId: number) {
return del<void>(`/api/decks/${deckId}/cards/${cardId}`)
}
export async function updateDeckCard(deckId: number, cardId: number, updates: Partial<DeckCard>) {
return patch<DeckCard>(`/api/decks/${deckId}/cards/${cardId}`, updates)
}
export async function getDeckAnalysis(deckId: number) {
const raw = await get<Record<string, unknown>>(`/api/decks/${deckId}/analysis`)
// Backend returns: counts_by_type, targets, deltas, mana_curve, color_pips, total_cards, roles
// Frontend DeckAnalysis expects: card_count, land_count, creature_count, noncreature_count, avg_cmc, mana_curve, color_distribution, type_distribution, total_price, owned_count, missing_count
const counts = (raw.counts_by_type || {}) as Record<string, number>
const totalCards = (raw.total_cards as number) || 0
const landCount = counts['Land'] || 0
const creatureCount = counts['Creature'] || 0
const manaCurve = (raw.mana_curve || {}) as Record<string | number, number>
const colorPips = (raw.color_pips || {}) as Record<string, number>
// Compute avg CMC from mana curve
let totalMana = 0, nonLandCards = 0
for (const [cmc, count] of Object.entries(manaCurve)) {
const cmcNum = cmc === '6+' ? 6 : Number(cmc)
totalMana += cmcNum * count
nonLandCards += count
}
return {
card_count: totalCards,
land_count: landCount,
creature_count: creatureCount,
noncreature_count: totalCards - landCount - creatureCount,
avg_cmc: nonLandCards > 0 ? totalMana / nonLandCards : 0,
mana_curve: manaCurve as Record<number, number>,
color_distribution: colorPips,
type_distribution: counts,
total_price: 0,
owned_count: totalCards,
missing_count: 0,
} as DeckAnalysis
}
export async function getCollectionRecs(deckId: number) {
return get<CollectionRecsResponse>(`/api/decks/${deckId}/recommended-from-collection`)
}
export async function getEdhRecs(deckId: number, onlyOwned = false, maxResults = 30) {
return get<EdhRecsResponse>(`/api/decks/${deckId}/edh-recs?only_owned=${onlyOwned}&max_results=${maxResults}`)
}
export async function bulkAddCards(deckId: number, cards: { name: string; quantity?: number }[]) {
return post<{ added: number }>(`/api/decks/${deckId}/bulk-add`, { cards })
}
export async function bulkAddRecommended(deckId: number, cards: string[]) {
return post<{ added: number }>(`/api/decks/${deckId}/bulk-add-recommended`, { card_names: cards })
}
export async function exportDeckToSim(deckId: number) {
return post<{ path: string }>(`/api/decks/${deckId}/export-to-sim`)
}
export async function importDeckToDeck(deckId: number, data: { text?: string; url?: string }) {
return post<{ imported: number }>(`/api/decks/${deckId}/import`, data)
}
export async function importNewDeck(data: { text?: string; url?: string; name?: string }) {
return post<Deck>('/api/decks/import-new', data)
}
export async function getPplxStatus() {
return get<PplxStatus>('/api/pplx/status')
}
export async function deckResearch(payload: { commander: string; strategy?: string }) {
return post<{ research: string }>('/api/deck-research', payload)
}
export async function deckGenerate(payload: { commander: string; strategy?: string; bracket?: number }) {
return post<{ cards: Array<{ name: string; quantity: number; category: string }> }>('/api/deck-generate', payload)
}
@@ -0,0 +1,7 @@
export * as collectionApi from './collection'
export * as decksApi from './decks'
export * as deckgenApi from './deckgen'
export * as labApi from './lab'
export * as simApi from './sim'
export * as coachApi from './coach'
export * as trainingApi from './training'
@@ -0,0 +1,65 @@
import { get, post } from './client'
import type { LabDeck, LabStatus, LabResult, LabHistoryEntry, PreconDeck } from '../types'
export async function getLabDecks() {
const res = await get<{ decks: LabDeck[] } | LabDeck[]>('/api/lab/decks')
return Array.isArray(res) ? res : (res as { decks: LabDeck[] }).decks || []
}
export async function startBatchSim(config: { decks: string[]; games: number; threads?: number; use_deepseek?: boolean; deepseek_deck?: string }) {
return post<{ run_id: string }>('/api/lab/start', config)
}
export async function startDeepSeekSim(config: { decks: string[]; games: number; deepseek_deck: string }) {
return post<{ run_id: string }>('/api/lab/start-deepseek', config)
}
export async function getLabStatus() {
return get<LabStatus>('/api/lab/status')
}
export async function getLabResult() {
return get<LabResult>('/api/lab/result')
}
export async function getLabHistory() {
const res = await get<{ results: LabHistoryEntry[] } | LabHistoryEntry[]>('/api/lab/history')
return Array.isArray(res) ? res : (res as { results: LabHistoryEntry[] }).results || []
}
export async function getPrecons() {
const res = await get<{ precons: PreconDeck[] } | PreconDeck[]>('/api/lab/precons')
return Array.isArray(res) ? res : (res as { precons: PreconDeck[] }).precons || []
}
export async function installPrecon(name: string) {
return post<{ installed: boolean }>('/api/lab/precons/install', { name })
}
export async function installPreconBatch(names: string[]) {
return post<{ installed: number }>('/api/lab/precons/install-batch', { names })
}
export async function getMetaCommanders() {
return get<Array<{ name: string; color_identity: string[] }>>('/api/lab/meta/commanders')
}
export async function searchMetaCommanders(q: string) {
return get<Array<{ name: string; color_identity: string[]; source: string }>>('/api/lab/meta/search', { q })
}
export async function fetchMetaDeck(commander: string) {
return post<{ deck_name: string; cards: Array<{ name: string; quantity: number }> }>('/api/lab/meta/fetch', { commander })
}
export async function importDeckFromUrl(url: string) {
return post<{ deck_name: string }>('/api/lab/import/url', { url })
}
export async function importDeckFromText(text: string, name?: string) {
return post<{ deck_name: string }>('/api/lab/import/text', { text, name })
}
export async function getLabLog() {
return get<{ log: string }>('/api/lab/log')
}
@@ -0,0 +1,38 @@
import { get, post } from './client'
import type { SimStatus, SimResult, DeepSeekStatus } from '../types'
export async function runSim(config: { deck_a: string; deck_b: string; games: number }) {
return post<{ sim_id: string }>('/api/sim/run', config)
}
export async function runSimFromDeck(deckId: number, config: { opponent?: string; games?: number }) {
return post<{ sim_id: string }>('/api/sim/run-from-deck', { deck_id: deckId, ...config })
}
export async function runDeepSeekSim(config: { deck_a: string; deck_b: string; games: number; deepseek_deck: string }) {
return post<{ sim_id: string }>('/api/sim/run-deepseek', config)
}
export async function getSimStatus(simId: string) {
return get<SimStatus>('/api/sim/status', { simId })
}
export async function getSimResult(simId: string) {
return get<SimResult>('/api/sim/result', { simId })
}
export async function connectDeepSeek() {
return post<DeepSeekStatus>('/api/deepseek/connect')
}
export async function getDeepSeekStatus() {
return get<DeepSeekStatus>('/api/deepseek/status')
}
export async function configureDeepSeek(config: { model?: string; base_url?: string }) {
return post<DeepSeekStatus>('/api/deepseek/configure', config)
}
export async function getDeepSeekLogs() {
return get<Array<{ filename: string; size: number; modified: string }>>('/api/deepseek/logs')
}
@@ -0,0 +1,92 @@
import { get, post } from './client'
import type {
MLStatus, MLDataStatus, MLTrainStatus, PPOTrainStatus,
TournamentStatus, TournamentResults, MLModelInfo
} from '../types'
// ── ML Status & Toggle ──────────────────────────────────────
export async function getMLStatus() {
return get<MLStatus>('/api/ml/status')
}
export async function toggleML(enable = true) {
return post<{ ml_logging_enabled: boolean; message: string }>(`/api/ml/toggle?enable=${enable}`)
}
// ── Data & Model Info ───────────────────────────────────────
export async function getDataStatus() {
return get<MLDataStatus>('/api/ml/data/status')
}
export async function getModelInfo() {
return get<MLModelInfo>('/api/ml/model')
}
export async function reloadModel(checkpoint?: string) {
return post<{ success: boolean; status: MLModelInfo }>('/api/ml/reload', checkpoint ? { checkpoint } : undefined)
}
// ── Supervised Training ─────────────────────────────────────
export async function startTraining(config: {
epochs?: number
lr?: number
batchSize?: number
patience?: number
rebuildDataset?: boolean
}) {
return post<{ status: string; config: Record<string, unknown> }>('/api/ml/train', config)
}
export async function getTrainStatus() {
return get<MLTrainStatus>('/api/ml/train/status')
}
// ── PPO Training ────────────────────────────────────────────
export async function startPPOTraining(config: {
iterations?: number
episodesPerIter?: number
ppoEpochs?: number
batchSize?: number
lr?: number
clipEpsilon?: number
entropyCoeff?: number
opponent?: string
playstyle?: string
loadSupervised?: string
}) {
return post<{ status: string; iterations: number }>('/api/ml/train/ppo', config)
}
export async function getPPOStatus() {
return get<PPOTrainStatus>('/api/ml/train/ppo/status')
}
// ── Tournament ──────────────────────────────────────────────
export async function startTournament(config: {
episodes?: number
playstyle?: string
}) {
return post<{ status: string; episodes: number }>('/api/ml/tournament', config)
}
export async function getTournamentStatus() {
return get<TournamentStatus>('/api/ml/tournament/status')
}
export async function getTournamentResults() {
return get<TournamentResults>('/api/ml/tournament/results')
}
// ── Decision Files ──────────────────────────────────────────
export async function getDecisionFile(filename: string, limit = 100, offset = 0) {
return get<{ file: string; offset: number; limit: number; count: number; decisions: Record<string, unknown>[] }>(
`/api/ml/decisions/${filename}?limit=${limit}&offset=${offset}`
)
}
// ── Prediction ──────────────────────────────────────────────
export async function predict(state: Record<string, unknown>) {
return post<{ action: string; action_index: number; confidence: number; probabilities: Record<string, number>; inference_ms: number }>(
'/api/ml/predict', state
)
}
@@ -0,0 +1,49 @@
import { useState } from 'react'
interface CardImageProps {
src: string
alt: string
size?: 'sm' | 'md' | 'lg' | 'xl'
className?: string
onClick?: () => void
}
const SIZES = {
sm: 'w-16 h-[22px]', // tiny inline
md: 'w-[146px] h-[204px]', // grid thumbnail
lg: 'w-[244px] h-[340px]', // detail view
xl: 'w-[336px] h-[468px]', // full size
}
export function CardImage({ src, alt, size = 'md', className = '', onClick }: CardImageProps) {
const [loaded, setLoaded] = useState(false)
const [error, setError] = useState(false)
// Build Scryfall URL if needed — ensure we get the right size
const imgUrl = src || ''
return (
<div
className={`relative overflow-hidden rounded-lg bg-bg-tertiary ${SIZES[size]} ${onClick ? 'cursor-pointer hover:ring-2 hover:ring-accent-blue/50 transition-all' : ''} ${className}`}
onClick={onClick}
>
{!error ? (
<img
src={imgUrl}
alt={alt}
className={`w-full h-full object-cover transition-opacity duration-200 ${loaded ? 'opacity-100' : 'opacity-0'}`}
onLoad={() => setLoaded(true)}
onError={() => setError(true)}
loading="lazy"
/>
) : (
<div className="flex items-center justify-center w-full h-full text-text-tertiary text-xs text-center p-2">
{alt}
</div>
)}
{!loaded && !error && (
<div className="absolute inset-0 bg-bg-tertiary animate-pulse" />
)}
</div>
)
}
@@ -0,0 +1,19 @@
import type { LucideIcon } from 'lucide-react'
interface EmptyStateProps {
icon: LucideIcon
title: string
description?: string
action?: React.ReactNode
}
export function EmptyState({ icon: Icon, title, description, action }: EmptyStateProps) {
return (
<div className="flex flex-col items-center justify-center py-16 text-center">
<Icon className="w-12 h-12 text-text-tertiary mb-4" strokeWidth={1.5} />
<h3 className="text-lg font-semibold text-text-primary mb-1">{title}</h3>
{description && <p className="text-sm text-text-secondary max-w-md mb-4">{description}</p>}
{action}
</div>
)
}
@@ -0,0 +1,69 @@
// Parse MTG mana cost strings like "{2}{W}{U}" into colored symbols
const MANA_COLORS: Record<string, string> = {
W: 'bg-mana-white text-black',
U: 'bg-mana-blue text-white',
B: 'bg-mana-black text-white',
R: 'bg-mana-red text-white',
G: 'bg-mana-green text-white',
C: 'bg-mana-colorless text-white',
}
interface ManaSymbolsProps {
cost: string
size?: 'sm' | 'md'
}
export function ManaSymbols({ cost, size = 'sm' }: ManaSymbolsProps) {
if (!cost) return null
const symbols = cost.match(/\{([^}]+)\}/g)
if (!symbols) return <span className="text-text-tertiary">{cost}</span>
const sz = size === 'sm' ? 'w-5 h-5 text-[10px]' : 'w-6 h-6 text-xs'
return (
<span className="inline-flex items-center gap-0.5">
{symbols.map((s, i) => {
const val = s.replace(/[{}]/g, '')
const colorClass = MANA_COLORS[val] || 'bg-mana-colorless text-white'
return (
<span
key={i}
className={`${sz} inline-flex items-center justify-center rounded-full font-bold ${colorClass}`}
>
{val}
</span>
)
})}
</span>
)
}
// Color identity dots
interface ColorDotsProps {
colors: string[]
size?: 'sm' | 'md'
}
export function ColorDots({ colors, size = 'sm' }: ColorDotsProps) {
if (!colors || colors.length === 0) return <span className="text-text-tertiary text-xs">Colorless</span>
const sz = size === 'sm' ? 'w-3 h-3' : 'w-4 h-4'
const DOT_COLORS: Record<string, string> = {
W: 'bg-mana-white',
U: 'bg-mana-blue',
B: 'bg-mana-black border border-border-secondary',
R: 'bg-mana-red',
G: 'bg-mana-green',
}
return (
<span className="inline-flex items-center gap-0.5">
{colors.map(c => (
<span key={c} className={`${sz} rounded-full ${DOT_COLORS[c] || 'bg-mana-colorless'}`} />
))}
</span>
)
}
@@ -0,0 +1,38 @@
interface SpinnerProps {
size?: 'sm' | 'md' | 'lg'
className?: string
}
const SIZES = { sm: 'w-4 h-4', md: 'w-6 h-6', lg: 'w-8 h-8' }
export function Spinner({ size = 'md', className = '' }: SpinnerProps) {
return (
<svg
className={`animate-spin ${SIZES[size]} ${className}`}
viewBox="0 0 24 24"
fill="none"
>
<circle
cx="12" cy="12" r="10"
stroke="currentColor"
strokeWidth="3"
strokeLinecap="round"
className="opacity-20"
/>
<path
d="M12 2a10 10 0 0 1 10 10"
stroke="currentColor"
strokeWidth="3"
strokeLinecap="round"
/>
</svg>
)
}
export function PageSpinner() {
return (
<div className="flex items-center justify-center h-64">
<Spinner size="lg" className="text-accent-blue" />
</div>
)
}
@@ -0,0 +1,35 @@
import { CheckCircle, XCircle, AlertTriangle, Info } from 'lucide-react'
type Variant = 'success' | 'error' | 'warning' | 'info' | 'neutral'
interface StatusBadgeProps {
variant: Variant
label: string
className?: string
}
const STYLES: Record<Variant, string> = {
success: 'bg-status-success/15 text-status-success border-status-success/30',
error: 'bg-status-error/15 text-status-error border-status-error/30',
warning: 'bg-status-warning/15 text-status-warning border-status-warning/30',
info: 'bg-status-info/15 text-status-info border-status-info/30',
neutral: 'bg-bg-tertiary text-text-secondary border-border-primary',
}
const ICONS: Record<Variant, typeof CheckCircle> = {
success: CheckCircle,
error: XCircle,
warning: AlertTriangle,
info: Info,
neutral: Info,
}
export function StatusBadge({ variant, label, className = '' }: StatusBadgeProps) {
const Icon = ICONS[variant]
return (
<span className={`inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-md border ${STYLES[variant]} ${className}`}>
<Icon className="w-3.5 h-3.5" />
{label}
</span>
)
}
@@ -0,0 +1,5 @@
export { Spinner, PageSpinner } from './Spinner'
export { StatusBadge } from './StatusBadge'
export { CardImage } from './CardImage'
export { ManaSymbols, ColorDots } from './ManaSymbols'
export { EmptyState } from './EmptyState'
@@ -0,0 +1,16 @@
import { Sidebar } from './Sidebar'
interface PageLayoutProps {
children: React.ReactNode
}
export function PageLayout({ children }: PageLayoutProps) {
return (
<div className="min-h-screen bg-bg-primary">
<Sidebar />
<main className="ml-56 min-h-screen">
{children}
</main>
</div>
)
}
@@ -0,0 +1,51 @@
import { NavLink } from 'react-router-dom'
const NAV_ITEMS = [
{ to: '/', label: 'Batch Sim', icon: '⚗️' },
{ to: '/collection', label: 'Collection', icon: '📦' },
{ to: '/decks', label: 'Decks', icon: '🃏' },
{ to: '/autogen', label: 'Auto Gen', icon: '⚡' },
{ to: '/simulator', label: 'Simulator', icon: '🎮' },
{ to: '/coach', label: 'Coach', icon: '🧠' },
{ to: '/training', label: 'Training', icon: '📈' },
]
export function Sidebar() {
return (
<aside className="fixed left-0 top-0 bottom-0 w-56 bg-bg-secondary border-r border-border-primary flex flex-col z-30">
{/* Logo */}
<div className="px-5 py-5 border-b border-border-primary">
<h1 className="text-base font-bold text-text-primary tracking-tight">
Commander AI Lab
</h1>
<p className="text-xs text-text-tertiary mt-0.5">MTG Intelligence Platform</p>
</div>
{/* Nav */}
<nav className="flex-1 py-3 overflow-y-auto">
{NAV_ITEMS.map(item => (
<NavLink
key={item.to}
to={item.to}
end={item.to === '/'}
className={({ isActive }) =>
`flex items-center gap-3 px-5 py-2.5 text-sm transition-colors duration-150 ${
isActive
? 'bg-accent-blue/10 text-accent-blue border-r-2 border-accent-blue'
: 'text-text-secondary hover:text-text-primary hover:bg-bg-hover'
}`
}
>
<span className="text-base">{item.icon}</span>
<span>{item.label}</span>
</NavLink>
))}
</nav>
{/* Footer */}
<div className="px-5 py-4 border-t border-border-primary">
<p className="text-xs text-text-tertiary">v4.0 — React + TypeScript</p>
</div>
</aside>
)
}
@@ -0,0 +1,13 @@
import { useEffect, useRef } from 'react'
/** Polls a function at the given interval while `enabled` is true */
export function usePolling(fn: () => void, intervalMs: number, enabled: boolean) {
const savedFn = useRef(fn)
savedFn.current = fn
useEffect(() => {
if (!enabled) return
const id = setInterval(() => savedFn.current(), intervalMs)
return () => clearInterval(id)
}, [intervalMs, enabled])
}
+114
View File
@@ -0,0 +1,114 @@
@import "tailwindcss";
/* ═══════════════════════════════════════════════════════════
Commander AI Lab — Design Tokens (Tailwind v4 CSS Theme)
Fresh dark theme with MTG-inspired accents
═══════════════════════════════════════════════════════════ */
@theme {
/* ── Backgrounds ── */
--color-bg-primary: #0f1117;
--color-bg-secondary: #161921;
--color-bg-tertiary: #1c2030;
--color-bg-elevated: #222738;
--color-bg-hover: #2a3048;
/* ── Borders ── */
--color-border-primary: #2a2f42;
--color-border-secondary: #363c54;
--color-border-accent: #4f6ef7;
/* ── Text ── */
--color-text-primary: #e8eaf0;
--color-text-secondary: #9ba1b8;
--color-text-tertiary: #6b7190;
--color-text-inverse: #0f1117;
/* ── Accents ── */
--color-accent-blue: #4f6ef7;
--color-accent-blue-hover: #6b84ff;
--color-accent-teal: #2dd4bf;
--color-accent-teal-hover: #5eead4;
--color-accent-purple: #a78bfa;
--color-accent-amber: #fbbf24;
--color-accent-red: #f87171;
--color-accent-green: #4ade80;
/* ── MTG Mana Colors ── */
--color-mana-white: #f9faf4;
--color-mana-blue: #0e67ab;
--color-mana-black: #2b2424;
--color-mana-red: #d3202a;
--color-mana-green: #00733e;
--color-mana-colorless: #706f6f;
/* ── Status ── */
--color-status-success: #4ade80;
--color-status-warning: #fbbf24;
--color-status-error: #f87171;
--color-status-info: #60a5fa;
/* ── Radius ── */
--radius-sm: 0.375rem;
--radius-md: 0.5rem;
--radius-lg: 0.75rem;
--radius-xl: 1rem;
/* ── Shadows ── */
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3);
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.4);
--shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.5);
--shadow-glow-blue: 0 0 20px rgba(79, 110, 247, 0.15);
--shadow-glow-teal: 0 0 20px rgba(45, 212, 191, 0.15);
}
/* ── Base Styles ── */
html {
background-color: var(--color-bg-primary);
color: var(--color-text-primary);
}
body {
font-family: 'Inter', system-ui, -apple-system, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* ── Scrollbar ── */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--color-bg-secondary);
}
::-webkit-scrollbar-thumb {
background: var(--color-border-secondary);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--color-text-tertiary);
}
/* ── Utility animations ── */
@keyframes fade-in {
from { opacity: 0; transform: translateY(4px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes pulse-glow {
0%, 100% { box-shadow: 0 0 0 0 rgba(79, 110, 247, 0.2); }
50% { box-shadow: 0 0 16px 4px rgba(79, 110, 247, 0.15); }
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.animate-fade-in {
animation: fade-in 0.2s ease-out;
}
.animate-pulse-glow {
animation: pulse-glow 2s infinite;
}
.animate-spin {
animation: spin 1s linear infinite;
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
@@ -0,0 +1,436 @@
import { useState, useEffect, useRef } from 'react'
import {
Search, Wand2, Save, AlertCircle,
ChevronDown, Sparkles, RefreshCw, Check
} from 'lucide-react'
import { Spinner, StatusBadge, ManaSymbols, CardImage, ColorDots } from '../components/common'
import { deckgenApi } from '../api'
import type { DeckGenV3Status, DeckGenV3Result, DeckGenV3Card, CommanderSearchResult } from '../types'
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from 'recharts'
// ── Commander Search ──────────────────────────────────────────
function CommanderSearch({ onSelect }: { onSelect: (c: CommanderSearchResult) => void }) {
const [query, setQuery] = useState('')
const [results, setResults] = useState<CommanderSearchResult[]>([])
const [searching, setSearching] = useState(false)
const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined)
function handleSearch(q: string) {
setQuery(q)
clearTimeout(debounceRef.current)
if (q.length < 2) { setResults([]); return }
debounceRef.current = setTimeout(async () => {
setSearching(true)
try {
const r = await deckgenApi.searchCommanders(q)
setResults(r)
} catch { setResults([]) }
setSearching(false)
}, 300)
}
return (
<div className="relative">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-tertiary" />
<input
type="text"
placeholder="Search for a commander..."
value={query}
onChange={e => handleSearch(e.target.value)}
className="w-full pl-10 pr-4 py-3 bg-bg-secondary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue/50 focus:ring-1 focus:ring-accent-blue/30 transition-all"
/>
{searching && <Spinner size="sm" className="absolute right-3 top-1/2 -translate-y-1/2 text-accent-blue" />}
</div>
{results.length > 0 && (
<div className="absolute z-20 top-full mt-1 w-full bg-bg-elevated border border-border-primary rounded-xl shadow-lg max-h-80 overflow-y-auto">
{results.map(c => (
<button
key={c.scryfall_id}
onClick={() => { onSelect(c); setQuery(c.name); setResults([]) }}
className="w-full flex items-center gap-3 px-4 py-3 hover:bg-bg-hover text-left transition-colors"
>
<CardImage src={c.image_url} alt={c.name} size="sm" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-text-primary truncate">{c.name}</p>
<p className="text-xs text-text-secondary truncate">{c.type_line}</p>
</div>
<ColorDots colors={c.color_identity} />
{c.in_collection && (
<span className="text-[10px] px-1.5 py-0.5 bg-accent-green/15 text-accent-green rounded">Owned</span>
)}
</button>
))}
</div>
)}
</div>
)
}
// ── Generated Deck View ───────────────────────────────────────
function GeneratedDeckView({ result, onCommit }: { result: DeckGenV3Result; onCommit: () => void }) {
const [view, setView] = useState<'visual' | 'list'>('visual')
const [committing, setCommitting] = useState(false)
const [selectedCard, setSelectedCard] = useState<DeckGenV3Card | null>(null)
// Group by category
const grouped = result.cards.reduce<Record<string, DeckGenV3Card[]>>((acc, c) => {
const cat = c.category || 'Other'
if (!acc[cat]) acc[cat] = []
acc[cat].push(c)
return acc
}, {})
const curveData = Object.entries(result.stats.mana_curve)
.map(([cmc, count]) => ({ cmc: cmc === '7' ? '7+' : cmc, count }))
.sort((a, b) => Number(a.cmc) - Number(b.cmc))
async function handleCommit() {
setCommitting(true)
try { onCommit() } catch { /* ignore */ }
setCommitting(false)
}
return (
<div className="space-y-5 animate-fade-in">
{/* Commander header */}
<div className="flex gap-5 bg-bg-secondary rounded-xl border border-border-primary p-5">
<CardImage src={result.commander.image_url} alt={result.commander.name} size="lg" />
<div className="flex-1 space-y-3">
<div>
<h2 className="text-xl font-bold text-text-primary">{result.commander.name}</h2>
<p className="text-sm text-text-secondary">{result.commander.type_line}</p>
<div className="flex items-center gap-3 mt-2">
<ManaSymbols cost={result.commander.mana_cost} size="md" />
<ColorDots colors={result.commander.color_identity} size="md" />
</div>
</div>
<p className="text-sm text-text-primary whitespace-pre-wrap">{result.commander.oracle_text}</p>
<div className="flex items-center gap-4 text-xs text-text-secondary">
<span>Strategy: <span className="text-accent-blue font-medium">{result.strategy}</span></span>
<span>Bracket: <span className="text-accent-amber font-medium">{result.bracket}</span></span>
<span>Model: <span className="text-accent-purple font-medium">{result.model}</span></span>
</div>
{result.substitution && (
<div className="flex items-center gap-3 text-xs">
<span className="text-accent-green">{result.substitution.owned} owned</span>
<span className="text-accent-amber">{result.substitution.substituted} substituted</span>
<span className="text-accent-red">{result.substitution.missing} missing</span>
</div>
)}
</div>
</div>
{/* Actions */}
<div className="flex items-center gap-3">
<button onClick={handleCommit} disabled={committing}
className="flex items-center gap-2 px-4 py-2.5 bg-accent-green/15 text-accent-green text-sm font-medium rounded-lg hover:bg-accent-green/25 border border-accent-green/30 transition-colors disabled:opacity-50">
{committing ? <Spinner size="sm" /> : <Save className="w-4 h-4" />}
Save to Decks
</button>
<div className="flex items-center gap-1 bg-bg-secondary rounded-lg border border-border-primary p-0.5">
<button onClick={() => setView('visual')}
className={`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${view === 'visual' ? 'bg-bg-hover text-text-primary' : 'text-text-tertiary hover:text-text-secondary'}`}>
Visual
</button>
<button onClick={() => setView('list')}
className={`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${view === 'list' ? 'bg-bg-hover text-text-primary' : 'text-text-tertiary hover:text-text-secondary'}`}>
List
</button>
</div>
{/* Stats summary */}
<div className="flex-1" />
<span className="text-xs text-text-tertiary">{result.stats.card_count} cards</span>
<span className="text-xs text-accent-teal font-medium">${result.stats.total_price.toFixed(2)}</span>
</div>
{/* Mana curve mini */}
<div className="bg-bg-secondary rounded-xl border border-border-primary p-4">
<h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider mb-2">Mana Curve</h4>
<div className="h-28">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={curveData} barSize={20}>
<XAxis dataKey="cmc" axisLine={false} tickLine={false} tick={{ fill: '#6b7190', fontSize: 10 }} />
<YAxis hide />
<Tooltip contentStyle={{ backgroundColor: '#1c2030', border: '1px solid #2a2f42', borderRadius: 8, fontSize: 11 }} />
<Bar dataKey="count" radius={[3, 3, 0, 0]}>
{curveData.map((_, i) => <Cell key={i} fill="#4f6ef7" fillOpacity={0.8} />)}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
</div>
{/* Card grid/list */}
{view === 'visual' ? (
<div className="space-y-5">
{Object.entries(grouped).map(([cat, cards]) => (
<div key={cat}>
<h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider mb-3">{cat} ({cards.length})</h4>
<div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-8 gap-2">
{cards.map(card => (
<div key={card.name} className="group cursor-pointer relative" onClick={() => setSelectedCard(card)}>
<CardImage src={card.image_url} alt={card.name} size="md" className="w-full h-auto aspect-[5/7]" />
{card.is_substitute && (
<div className="absolute top-1 right-1 w-4 h-4 bg-accent-amber rounded-full flex items-center justify-center">
<RefreshCw className="w-2.5 h-2.5 text-bg-primary" />
</div>
)}
{card.owned && (
<div className="absolute top-1 left-1 w-4 h-4 bg-accent-green rounded-full flex items-center justify-center">
<Check className="w-2.5 h-2.5 text-bg-primary" />
</div>
)}
</div>
))}
</div>
</div>
))}
</div>
) : (
<div className="bg-bg-secondary rounded-xl border border-border-primary overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border-primary text-left">
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider">Card</th>
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider">Category</th>
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider">Role</th>
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider">Mana</th>
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider text-right">Price</th>
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider">Status</th>
</tr>
</thead>
<tbody className="divide-y divide-border-primary">
{result.cards.map(card => (
<tr key={card.name} className="hover:bg-bg-hover transition-colors">
<td className="px-4 py-2.5">
<span className="font-medium text-text-primary">{card.quantity}x {card.name}</span>
{card.is_substitute && (
<span className="ml-2 text-[10px] text-accent-amber">sub for {card.original_name}</span>
)}
</td>
<td className="px-4 py-2.5 text-xs text-text-secondary">{card.category}</td>
<td className="px-4 py-2.5 text-xs text-text-secondary">{card.role}</td>
<td className="px-4 py-2.5"><ManaSymbols cost={card.mana_cost} /></td>
<td className="px-4 py-2.5 text-right text-accent-teal text-xs">{card.tcg_price != null ? `$${card.tcg_price.toFixed(2)}` : '—'}</td>
<td className="px-4 py-2.5">
<span className={`text-[10px] px-2 py-0.5 rounded ${card.owned ? 'bg-accent-green/15 text-accent-green' : 'bg-bg-tertiary text-text-tertiary'}`}>
{card.owned ? `Owned (${card.owned_qty})` : 'Missing'}
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{/* Card detail popup */}
{selectedCard && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm" onClick={() => setSelectedCard(null)}>
<div className="bg-bg-secondary rounded-xl border border-border-primary shadow-lg max-w-2xl w-full mx-4 p-6 animate-fade-in" onClick={e => e.stopPropagation()}>
<div className="flex gap-5">
<CardImage src={selectedCard.image_url} alt={selectedCard.name} size="lg" />
<div className="flex-1 space-y-3">
<h3 className="text-lg font-bold text-text-primary">{selectedCard.name}</h3>
<p className="text-sm text-text-secondary">{selectedCard.type_line}</p>
<ManaSymbols cost={selectedCard.mana_cost} size="md" />
<p className="text-sm text-text-primary whitespace-pre-wrap">{selectedCard.reason}</p>
<div className="flex items-center gap-3 text-xs">
<span className="text-text-tertiary">Role: <span className="text-accent-blue">{selectedCard.role}</span></span>
{selectedCard.is_substitute && (
<span className="text-accent-amber">Substituted for {selectedCard.original_name} ({(selectedCard.similarity_score ?? 0 * 100).toFixed(0)}%)</span>
)}
</div>
</div>
</div>
</div>
</div>
)}
</div>
)
}
// ── Main Auto Gen Page ────────────────────────────────────────
export function AutoGenPage() {
const [status, setStatus] = useState<DeckGenV3Status | null>(null)
const [loading, setLoading] = useState(true)
const [generating, setGenerating] = useState(false)
const [result, setResult] = useState<DeckGenV3Result | null>(null)
const [commander, setCommander] = useState<CommanderSearchResult | null>(null)
const [strategy, setStrategy] = useState('')
const [bracket, setBracket] = useState(3)
const [budget, setBudget] = useState<string>('')
const [useCollection, setUseCollection] = useState(true)
const [runSub, setRunSub] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
deckgenApi.getV3Status().then(s => { setStatus(s); setLoading(false) }).catch(() => setLoading(false))
}, [])
async function handleGenerate() {
if (!commander) return
setGenerating(true)
setError(null)
setResult(null)
try {
const res = await deckgenApi.generateDeckV3({
commander_name: commander.name,
strategy: strategy || undefined,
target_bracket: bracket,
budget_usd: budget ? Number(budget) : undefined,
use_collection: useCollection,
run_substitution: runSub,
})
setResult(res)
} catch (e) {
setError(e instanceof Error ? e.message : 'Generation failed')
}
setGenerating(false)
}
async function handleCommit() {
if (!commander || !result) return
try {
await deckgenApi.commitDeckV3({
commander_name: commander.name,
strategy: strategy || undefined,
target_bracket: bracket,
budget_usd: budget ? Number(budget) : undefined,
use_collection: useCollection,
run_substitution: runSub,
})
} catch { /* ignore */ }
}
if (loading) {
return <div className="p-6 flex items-center justify-center h-64"><Spinner size="lg" className="text-accent-blue" /></div>
}
return (
<div className="p-6 space-y-5">
<div>
<h1 className="text-2xl font-bold text-text-primary flex items-center gap-3">
<Sparkles className="w-6 h-6 text-accent-purple" />
Auto Gen V3
</h1>
<p className="text-sm text-text-secondary mt-0.5">AI-powered deck generation with Perplexity</p>
</div>
{/* Status bar */}
<div className="flex items-center gap-3">
<StatusBadge
variant={status?.initialized ? 'success' : 'error'}
label={status?.initialized ? 'Ready' : 'Not Initialized'}
/>
<StatusBadge
variant={status?.pplx_configured ? 'success' : 'warning'}
label={status?.pplx_configured ? 'Perplexity Connected' : 'Perplexity Not Set'}
/>
{status?.embeddings_loaded && (
<StatusBadge variant="info" label={`${status.embedding_cards.toLocaleString()} embeddings`} />
)}
</div>
{!result ? (
/* Config form */
<div className="max-w-2xl space-y-5">
<div>
<label className="text-sm font-medium text-text-primary block mb-2">Commander</label>
<CommanderSearch onSelect={setCommander} />
{commander && (
<div className="mt-2 flex items-center gap-3 p-3 bg-bg-secondary rounded-lg border border-border-primary">
<CardImage src={commander.image_url} alt={commander.name} size="sm" />
<div>
<p className="text-sm font-medium text-text-primary">{commander.name}</p>
<p className="text-xs text-text-secondary">{commander.type_line}</p>
</div>
<ColorDots colors={commander.color_identity} />
</div>
)}
</div>
<div>
<label className="text-sm font-medium text-text-primary block mb-2">Strategy (optional)</label>
<input
type="text"
placeholder="e.g. Voltron, Aristocrats, Storm..."
value={strategy}
onChange={e => setStrategy(e.target.value)}
className="w-full px-4 py-3 bg-bg-secondary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue/50 transition-all"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-sm font-medium text-text-primary block mb-2">Target Bracket</label>
<select
value={bracket}
onChange={e => setBracket(Number(e.target.value))}
className="w-full px-4 py-3 bg-bg-secondary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all"
>
<option value={1}>1 — Casual</option>
<option value={2}>2 — Low Power</option>
<option value={3}>3 — Mid Power</option>
<option value={4}>4 — High Power</option>
</select>
</div>
<div>
<label className="text-sm font-medium text-text-primary block mb-2">Budget (USD, optional)</label>
<input
type="number"
placeholder="No limit"
value={budget}
onChange={e => setBudget(e.target.value)}
className="w-full px-4 py-3 bg-bg-secondary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue/50 transition-all"
/>
</div>
</div>
<div className="flex items-center gap-6">
<label className="flex items-center gap-2 cursor-pointer">
<input type="checkbox" checked={useCollection} onChange={e => setUseCollection(e.target.checked)}
className="w-4 h-4 rounded border-border-primary bg-bg-tertiary text-accent-blue focus:ring-accent-blue/30" />
<span className="text-sm text-text-secondary">Use collection cards</span>
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input type="checkbox" checked={runSub} onChange={e => setRunSub(e.target.checked)}
className="w-4 h-4 rounded border-border-primary bg-bg-tertiary text-accent-blue focus:ring-accent-blue/30" />
<span className="text-sm text-text-secondary">Run substitution pass</span>
</label>
</div>
{error && (
<div className="flex items-center gap-2 px-4 py-3 bg-status-error/10 border border-status-error/30 rounded-lg text-sm text-status-error">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
{error}
</div>
)}
<button
onClick={handleGenerate}
disabled={!commander || generating || !status?.initialized}
className="flex items-center gap-2 px-6 py-3 bg-accent-blue text-white text-sm font-semibold rounded-lg hover:bg-accent-blue-hover shadow-glow-blue transition-all disabled:opacity-50 disabled:shadow-none"
>
{generating ? (
<><Spinner size="sm" /> Generating...</>
) : (
<><Wand2 className="w-4 h-4" /> Generate Deck</>
)}
</button>
</div>
) : (
/* Results */
<div>
<button onClick={() => setResult(null)}
className="flex items-center gap-2 mb-4 text-sm text-text-secondary hover:text-text-primary transition-colors">
<ChevronDown className="w-4 h-4 rotate-90" />
Back to Config
</button>
<GeneratedDeckView result={result} onCommit={handleCommit} />
</div>
)}
</div>
)
}
@@ -0,0 +1,415 @@
import { useState, useEffect } from 'react'
import {
FlaskConical, Play, Clock, Trophy,
Upload, Link, FileText, History, ChevronRight, AlertCircle,
Check
} from 'lucide-react'
import { Spinner } from '../components/common'
import { labApi } from '../api'
import { usePolling } from '../hooks/usePolling'
import type { LabDeck, LabStatus, LabResult, LabHistoryEntry, PreconDeck } from '../types'
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from 'recharts'
// ── Results Chart ─────────────────────────────────────────────
function ResultsChart({ result }: { result: LabResult }) {
const data = result.decks
.sort((a, b) => b.win_rate - a.win_rate)
.map(d => ({
name: d.name.length > 20 ? d.name.slice(0, 18) + '...' : d.name,
win_rate: Math.round(d.win_rate * 100),
fullName: d.name,
}))
return (
<div className="h-64">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} layout="vertical" barSize={20} margin={{ left: 10, right: 20 }}>
<XAxis type="number" domain={[0, 100]} tick={{ fill: '#6b7190', fontSize: 11 }} axisLine={false} tickLine={false} />
<YAxis type="category" dataKey="name" width={150} tick={{ fill: '#9ba1b8', fontSize: 11 }} axisLine={false} tickLine={false} />
<Tooltip
contentStyle={{ backgroundColor: '#1c2030', border: '1px solid #2a2f42', borderRadius: 8, fontSize: 12 }}
formatter={(value: unknown) => [`${value}%`, 'Win Rate']}
labelFormatter={(label: unknown) => data.find(d => d.name === String(label))?.fullName || String(label)}
/>
<Bar dataKey="win_rate" radius={[0, 4, 4, 0]}>
{data.map((_, i) => (
<Cell key={i} fill={i === 0 ? '#4ade80' : i === 1 ? '#4f6ef7' : '#363c54'} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
)
}
// ── Deck Selector ─────────────────────────────────────────────
function DeckSelector({
decks,
selected,
onToggle,
precons,
onInstallPrecon,
}: {
decks: LabDeck[]
selected: Set<string>
onToggle: (name: string) => void
precons: PreconDeck[]
onInstallPrecon: (name: string) => void
}) {
const [showPrecons, setShowPrecons] = useState(false)
const [installing, setInstalling] = useState<string | null>(null)
async function handleInstall(name: string) {
setInstalling(name)
await onInstallPrecon(name)
setInstalling(null)
}
return (
<div className="space-y-3">
<h3 className="text-sm font-semibold text-text-primary">Available Decks</h3>
{decks.length === 0 ? (
<p className="text-xs text-text-tertiary">No decks available. Import or install precons.</p>
) : (
<div className="space-y-1 max-h-64 overflow-y-auto">
{decks.map(d => (
<label key={d.name} className="flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-bg-hover cursor-pointer transition-colors">
<input
type="checkbox"
checked={selected.has(d.name)}
onChange={() => onToggle(d.name)}
className="w-4 h-4 rounded border-border-primary bg-bg-tertiary text-accent-blue focus:ring-accent-blue/30"
/>
<div className="flex-1 min-w-0">
<span className="text-sm text-text-primary truncate block">{d.name}</span>
<span className="text-[10px] text-text-tertiary">{d.source} · {d.card_count} cards</span>
</div>
</label>
))}
</div>
)}
<button
onClick={() => setShowPrecons(!showPrecons)}
className="w-full flex items-center justify-between px-3 py-2 text-xs font-medium bg-bg-tertiary rounded-lg text-text-secondary hover:bg-bg-hover border border-border-primary transition-colors"
>
Precon Decks
<ChevronRight className={`w-3.5 h-3.5 transition-transform ${showPrecons ? 'rotate-90' : ''}`} />
</button>
{showPrecons && (
<div className="space-y-1 max-h-48 overflow-y-auto animate-fade-in">
{precons.map(p => (
<div key={p.name} className="flex items-center gap-3 px-3 py-2 rounded-lg bg-bg-tertiary">
<span className="flex-1 text-xs text-text-secondary truncate">{p.name}</span>
{p.installed ? (
<span className="text-[10px] text-accent-green flex items-center gap-1"><Check className="w-3 h-3" /> Installed</span>
) : (
<button
onClick={() => handleInstall(p.name)}
disabled={installing === p.name}
className="text-[10px] text-accent-blue hover:text-accent-blue-hover transition-colors"
>
{installing === p.name ? <Spinner size="sm" /> : 'Install'}
</button>
)}
</div>
))}
</div>
)}
</div>
)
}
// ── Import Panel ──────────────────────────────────────────────
function ImportPanel({ onImported }: { onImported: () => void }) {
const [importUrl, setImportUrl] = useState('')
const [importText, setImportText] = useState('')
const [importName, setImportName] = useState('')
const [importing, setImporting] = useState(false)
const [importMode, setImportMode] = useState<'url' | 'text'>('url')
async function handleImport() {
setImporting(true)
try {
if (importMode === 'url' && importUrl.trim()) {
await labApi.importDeckFromUrl(importUrl.trim())
} else if (importMode === 'text' && importText.trim()) {
await labApi.importDeckFromText(importText.trim(), importName || undefined)
}
setImportUrl('')
setImportText('')
setImportName('')
onImported()
} catch { /* ignore */ }
setImporting(false)
}
return (
<div className="bg-bg-secondary rounded-xl border border-border-primary p-4 space-y-3">
<h3 className="text-sm font-semibold text-text-primary flex items-center gap-2">
<Upload className="w-4 h-4 text-accent-blue" />
Import Deck
</h3>
<div className="flex gap-1">
<button onClick={() => setImportMode('url')}
className={`flex-1 px-3 py-1.5 text-xs font-medium rounded-lg transition-colors ${importMode === 'url' ? 'bg-accent-blue/15 text-accent-blue' : 'bg-bg-tertiary text-text-tertiary'}`}>
<Link className="w-3 h-3 inline mr-1" />URL
</button>
<button onClick={() => setImportMode('text')}
className={`flex-1 px-3 py-1.5 text-xs font-medium rounded-lg transition-colors ${importMode === 'text' ? 'bg-accent-blue/15 text-accent-blue' : 'bg-bg-tertiary text-text-tertiary'}`}>
<FileText className="w-3 h-3 inline mr-1" />Text
</button>
</div>
{importMode === 'url' ? (
<input
type="text"
placeholder="Moxfield, Archidekt, or deck URL..."
value={importUrl}
onChange={e => setImportUrl(e.target.value)}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue/50 transition-all"
/>
) : (
<>
<input
type="text"
placeholder="Deck name"
value={importName}
onChange={e => setImportName(e.target.value)}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue/50 transition-all"
/>
<textarea
placeholder={"1x Sol Ring\n1x Command Tower\n..."}
value={importText}
onChange={e => setImportText(e.target.value)}
rows={5}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary font-mono focus:outline-none focus:border-accent-blue/50 transition-all resize-none"
/>
</>
)}
<button onClick={handleImport} disabled={importing}
className="w-full px-4 py-2 bg-accent-blue text-white text-sm font-medium rounded-lg hover:bg-accent-blue-hover transition-colors disabled:opacity-50">
{importing ? <Spinner size="sm" /> : 'Import'}
</button>
</div>
)
}
// ── Main Batch Sim Page ───────────────────────────────────────
export function BatchSimPage() {
const [decks, setDecks] = useState<LabDeck[]>([])
const [precons, setPrecons] = useState<PreconDeck[]>([])
const [selected, setSelected] = useState<Set<string>>(new Set())
const [games, setGames] = useState(100)
const [status, setStatus] = useState<LabStatus | null>(null)
const [result, setResult] = useState<LabResult | null>(null)
const [history, setHistory] = useState<LabHistoryEntry[]>([])
const [loading, setLoading] = useState(true)
const [starting, setStarting] = useState(false)
const [error, setError] = useState<string | null>(null)
const [showHistory, setShowHistory] = useState(false)
async function fetchDecks() {
try {
const [d, p] = await Promise.all([labApi.getLabDecks(), labApi.getPrecons()])
setDecks(d)
setPrecons(p)
} catch { /* ignore */ }
setLoading(false)
}
useEffect(() => {
fetchDecks()
labApi.getLabStatus().then(setStatus).catch(() => {})
labApi.getLabHistory().then(setHistory).catch(() => {})
}, [])
// Poll while running
usePolling(async () => {
try {
const s = await labApi.getLabStatus()
setStatus(s)
if (!s.running && s.run_id) {
const r = await labApi.getLabResult()
setResult(r)
labApi.getLabHistory().then(setHistory).catch(() => {})
}
} catch { /* ignore */ }
}, 2000, status?.running || false)
function toggleDeck(name: string) {
setSelected(prev => {
const next = new Set(prev)
if (next.has(name)) next.delete(name)
else next.add(name)
return next
})
}
async function handleStart() {
if (selected.size < 2) { setError('Select at least 2 decks'); return }
setStarting(true)
setError(null)
setResult(null)
try {
await labApi.startBatchSim({ decks: [...selected], games })
const s = await labApi.getLabStatus()
setStatus(s)
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to start')
}
setStarting(false)
}
async function handleInstallPrecon(name: string) {
try {
await labApi.installPrecon(name)
fetchDecks()
} catch { /* ignore */ }
}
return (
<div className="p-6 space-y-5">
<div>
<h1 className="text-2xl font-bold text-text-primary flex items-center gap-3">
<FlaskConical className="w-6 h-6 text-accent-teal" />
Batch Simulator
</h1>
<p className="text-sm text-text-secondary mt-0.5">Run mass simulations between decks</p>
</div>
<div className="flex gap-5">
{/* Left sidebar: deck selection + import */}
<div className="w-72 flex-shrink-0 space-y-4">
{loading ? (
<div className="flex items-center justify-center h-32"><Spinner size="md" className="text-accent-blue" /></div>
) : (
<DeckSelector
decks={decks}
selected={selected}
onToggle={toggleDeck}
precons={precons}
onInstallPrecon={handleInstallPrecon}
/>
)}
<ImportPanel onImported={fetchDecks} />
</div>
{/* Main content */}
<div className="flex-1 space-y-5">
{/* Config + Start */}
<div className="bg-bg-secondary rounded-xl border border-border-primary p-5">
<div className="flex items-center gap-4">
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Games</label>
<input
type="number"
min={10}
max={10000}
step={10}
value={games}
onChange={e => setGames(Number(e.target.value))}
className="mt-1 w-28 px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all"
/>
</div>
<div className="flex-1">
<p className="text-xs text-text-tertiary">Selected: {selected.size} decks</p>
</div>
{status?.running ? (
<div className="flex items-center gap-3">
<div className="flex items-center gap-2">
<Spinner size="sm" className="text-accent-blue" />
<span className="text-sm text-text-secondary">
{status.games_completed} / {status.total_games} games
</span>
</div>
<div className="w-48 h-2 bg-bg-tertiary rounded-full overflow-hidden">
<div
className="h-full bg-accent-blue rounded-full transition-all"
style={{ width: `${status.total_games ? (status.games_completed / status.total_games) * 100 : 0}%` }}
/>
</div>
</div>
) : (
<button onClick={handleStart} disabled={starting || selected.size < 2}
className="flex items-center gap-2 px-5 py-2.5 bg-accent-teal/15 text-accent-teal text-sm font-semibold rounded-lg hover:bg-accent-teal/25 border border-accent-teal/30 transition-colors disabled:opacity-50">
{starting ? <Spinner size="sm" /> : <Play className="w-4 h-4" />}
Start Simulation
</button>
)}
</div>
{error && (
<div className="mt-3 flex items-center gap-2 px-4 py-2 bg-status-error/10 border border-status-error/30 rounded-lg text-sm text-status-error">
<AlertCircle className="w-4 h-4" />{error}
</div>
)}
</div>
{/* Results */}
{result && (
<div className="bg-bg-secondary rounded-xl border border-border-primary p-5 space-y-4 animate-fade-in">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-text-primary flex items-center gap-2">
<Trophy className="w-4 h-4 text-accent-amber" />
Results
</h3>
<span className="text-xs text-text-tertiary">{result.total_games} games · {new Date(result.timestamp).toLocaleString()}</span>
</div>
<ResultsChart result={result} />
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border-primary">
<th className="px-3 py-2 text-left text-xs text-text-tertiary font-medium uppercase tracking-wider">Deck</th>
<th className="px-3 py-2 text-right text-xs text-text-tertiary font-medium uppercase tracking-wider">Wins</th>
<th className="px-3 py-2 text-right text-xs text-text-tertiary font-medium uppercase tracking-wider">Games</th>
<th className="px-3 py-2 text-right text-xs text-text-tertiary font-medium uppercase tracking-wider">Win Rate</th>
<th className="px-3 py-2 text-right text-xs text-text-tertiary font-medium uppercase tracking-wider">Avg Turns</th>
</tr>
</thead>
<tbody className="divide-y divide-border-primary">
{result.decks.sort((a, b) => b.win_rate - a.win_rate).map((d, i) => (
<tr key={d.name} className="hover:bg-bg-hover transition-colors">
<td className="px-3 py-2.5 flex items-center gap-2">
{i === 0 && <Trophy className="w-3.5 h-3.5 text-accent-amber" />}
<span className="font-medium text-text-primary">{d.name}</span>
</td>
<td className="px-3 py-2.5 text-right text-text-secondary">{d.wins}</td>
<td className="px-3 py-2.5 text-right text-text-secondary">{d.games}</td>
<td className="px-3 py-2.5 text-right font-semibold text-accent-blue">{(d.win_rate * 100).toFixed(1)}%</td>
<td className="px-3 py-2.5 text-right text-text-secondary">{d.avg_turns.toFixed(1)}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* History */}
<div>
<button onClick={() => setShowHistory(!showHistory)}
className="flex items-center gap-2 text-sm text-text-secondary hover:text-text-primary transition-colors">
<History className="w-4 h-4" />
Run History ({history.length})
<ChevronRight className={`w-3.5 h-3.5 transition-transform ${showHistory ? 'rotate-90' : ''}`} />
</button>
{showHistory && history.length > 0 && (
<div className="mt-3 space-y-2 animate-fade-in">
{history.map(h => (
<div key={h.run_id} className="flex items-center gap-4 px-4 py-3 bg-bg-secondary rounded-lg border border-border-primary">
<Clock className="w-4 h-4 text-text-tertiary" />
<div className="flex-1">
<p className="text-sm text-text-primary">{h.decks.join(' vs ')}</p>
<p className="text-xs text-text-tertiary">{new Date(h.timestamp).toLocaleString()} · {h.total_games} games</p>
</div>
</div>
))}
</div>
)}
</div>
</div>
</div>
</div>
)
}
@@ -0,0 +1,949 @@
import { useState, useEffect, useRef, useCallback } from 'react'
import {
GraduationCap, MessageSquare, Send, Sparkles, AlertCircle, X, Check,
ChevronRight, ChevronDown, Download, Settings2, Search, Zap,
Minus, Plus, History, ArrowRightLeft, Lightbulb, DollarSign, Loader2,
ClipboardList, Brain, BarChart3
} from 'lucide-react'
import { Spinner, StatusBadge, EmptyState } from '../components/common'
import { coachApi } from '../api'
import type {
CoachStatus, CoachDeck, CoachSession, CoachSessionSummary,
CoachMessage, CoachGoals, CoachApplyResult, CoachCardLikeResult
} from '../types'
// ════════════════════════════════════════════════════════════
// Goals Config Panel
// ════════════════════════════════════════════════════════════
function GoalsPanel({
goals, onChange, collapsed, onToggle
}: {
goals: CoachGoals
onChange: (g: CoachGoals) => void
collapsed: boolean
onToggle: () => void
}) {
const strategies = ['aggro', 'control', 'combo', 'midrange', 'stax', 'voltron', 'aristocrats', 'tokens']
const budgets = [
{ value: 'budget', label: 'Budget', desc: 'Under $5/card' },
{ value: 'medium', label: 'Medium', desc: 'Under $20/card' },
{ value: 'no-limit', label: 'No Limit', desc: 'Any price' },
]
const focusOptions = ['ramp', 'card draw', 'removal', 'protection', 'threats', 'mana base', 'combos', 'synergy']
return (
<div className="bg-bg-secondary rounded-xl border border-border-primary">
<button
onClick={onToggle}
className="w-full flex items-center gap-2 px-4 py-3 text-left hover:bg-bg-hover transition-colors rounded-xl"
>
<Settings2 className="w-4 h-4 text-accent-teal" />
<span className="text-sm font-medium text-text-primary flex-1">Coaching Goals</span>
{collapsed ? <ChevronRight className="w-4 h-4 text-text-tertiary" /> : <ChevronDown className="w-4 h-4 text-text-tertiary" />}
</button>
{!collapsed && (
<div className="px-4 pb-4 space-y-4 border-t border-border-primary pt-3">
{/* Power Level Slider */}
<div>
<label className="text-xs font-medium text-text-secondary mb-1 block">
Power Level: {goals.targetPowerLevel ?? 'Any'}
</label>
<input
type="range" min={1} max={10}
value={goals.targetPowerLevel ?? 5}
onChange={e => onChange({ ...goals, targetPowerLevel: parseInt(e.target.value) })}
className="w-full accent-accent-teal"
/>
<div className="flex justify-between text-[10px] text-text-tertiary">
<span>Casual</span><span>Focused</span><span>cEDH</span>
</div>
</div>
{/* Strategy */}
<div>
<label className="text-xs font-medium text-text-secondary mb-1.5 block">Strategy Focus</label>
<div className="flex flex-wrap gap-1.5">
{strategies.map(s => (
<button
key={s}
onClick={() => onChange({ ...goals, metaFocus: goals.metaFocus === s ? null : s })}
className={`px-2.5 py-1 text-xs rounded-full border transition-colors ${
goals.metaFocus === s
? 'bg-accent-teal/20 border-accent-teal/40 text-accent-teal'
: 'border-border-primary text-text-tertiary hover:border-border-secondary'
}`}
>
{s}
</button>
))}
</div>
</div>
{/* Budget */}
<div>
<label className="text-xs font-medium text-text-secondary mb-1.5 block">Budget</label>
<div className="grid grid-cols-3 gap-2">
{budgets.map(b => (
<button
key={b.value}
onClick={() => onChange({ ...goals, budget: goals.budget === b.value ? null : b.value })}
className={`px-3 py-2 text-xs rounded-lg border transition-colors ${
goals.budget === b.value
? 'bg-accent-teal/20 border-accent-teal/40 text-accent-teal'
: 'border-border-primary text-text-tertiary hover:border-border-secondary'
}`}
>
<div className="font-medium">{b.label}</div>
<div className="text-[10px] opacity-60">{b.desc}</div>
</button>
))}
</div>
</div>
{/* Focus Areas */}
<div>
<label className="text-xs font-medium text-text-secondary mb-1.5 block">Focus Areas</label>
<div className="flex flex-wrap gap-1.5">
{focusOptions.map(f => {
const active = (goals.focusAreas || []).includes(f)
return (
<button
key={f}
onClick={() => {
const areas = goals.focusAreas || []
onChange({
...goals,
focusAreas: active ? areas.filter(a => a !== f) : [...areas, f]
})
}}
className={`px-2.5 py-1 text-xs rounded-full border transition-colors ${
active
? 'bg-accent-blue/20 border-accent-blue/40 text-accent-blue'
: 'border-border-primary text-text-tertiary hover:border-border-secondary'
}`}
>
{f}
</button>
)
})}
</div>
</div>
</div>
)}
</div>
)
}
// ════════════════════════════════════════════════════════════
// Session View — Shows coaching results with apply functionality
// ════════════════════════════════════════════════════════════
function SessionView({
session, deckId, onClose, onApplied
}: {
session: CoachSession
deckId: number
onClose: () => void
onApplied?: () => void
}) {
const [selectedCuts, setSelectedCuts] = useState<Set<string>>(new Set())
const [selectedAdds, setSelectedAdds] = useState<Set<string>>(new Set())
const [applying, setApplying] = useState(false)
const [applyResult, setApplyResult] = useState<CoachApplyResult | null>(null)
const toggleCut = (name: string) => {
const s = new Set(selectedCuts)
s.has(name) ? s.delete(name) : s.add(name)
setSelectedCuts(s)
}
const toggleAdd = (name: string) => {
const s = new Set(selectedAdds)
s.has(name) ? s.delete(name) : s.add(name)
setSelectedAdds(s)
}
const handleApply = async () => {
if (selectedCuts.size === 0 && selectedAdds.size === 0) return
setApplying(true)
try {
const result = await coachApi.applyCoachSuggestions(
session.sessionId, deckId,
[...selectedCuts], [...selectedAdds]
)
setApplyResult(result)
onApplied?.()
} catch (e) {
console.error('Apply failed:', e)
}
setApplying(false)
}
return (
<div className="space-y-5">
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-semibold text-text-primary">Coaching Session</h3>
<p className="text-xs text-text-tertiary">
{new Date(session.timestamp).toLocaleString()} · {session.modelUsed}
{session.promptTokens > 0 && ` · ${session.promptTokens + session.completionTokens} tokens`}
</p>
</div>
<button onClick={onClose} className="p-1.5 rounded-lg hover:bg-bg-hover text-text-tertiary">
<X className="w-4 h-4" />
</button>
</div>
{/* Summary */}
{session.summary && (
<div className="bg-bg-secondary rounded-xl border border-border-primary p-4">
<h4 className="text-xs font-medium text-text-secondary mb-2 flex items-center gap-1.5">
<Brain className="w-3.5 h-3.5" /> Summary
</h4>
<p className="text-sm text-text-primary leading-relaxed">{session.summary}</p>
</div>
)}
{/* Heuristic Hints */}
{session.heuristicHints?.length > 0 && (
<div className="bg-accent-amber/5 rounded-xl border border-accent-amber/20 p-4">
<h4 className="text-xs font-medium text-accent-amber mb-2 flex items-center gap-1.5">
<Lightbulb className="w-3.5 h-3.5" /> Strategic Tips
</h4>
<ul className="space-y-1.5">
{session.heuristicHints.map((h, i) => (
<li key={i} className="text-sm text-text-primary flex items-start gap-2">
<span className="text-accent-amber mt-0.5">•</span> {h}
</li>
))}
</ul>
</div>
)}
{/* Mana Base Advice */}
{session.manaBaseAdvice && (
<div className="bg-accent-blue/5 rounded-xl border border-accent-blue/20 p-4">
<h4 className="text-xs font-medium text-accent-blue mb-2 flex items-center gap-1.5">
<BarChart3 className="w-3.5 h-3.5" /> Mana Base
</h4>
<p className="text-sm text-text-primary">{session.manaBaseAdvice}</p>
</div>
)}
{/* Suggested Cuts */}
{session.suggestedCuts?.length > 0 && (
<div>
<h4 className="text-sm font-medium text-status-error mb-2 flex items-center gap-1.5">
<Minus className="w-4 h-4" /> Suggested Cuts ({session.suggestedCuts.length})
</h4>
<div className="space-y-2">
{session.suggestedCuts.map((cut, i) => (
<div
key={i}
onClick={() => toggleCut(cut.cardName)}
className={`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${
selectedCuts.has(cut.cardName)
? 'bg-status-error/10 border-status-error/30'
: 'bg-bg-secondary border-border-primary hover:border-border-secondary'
}`}
>
<div className={`mt-0.5 w-4 h-4 rounded border flex items-center justify-center flex-shrink-0 ${
selectedCuts.has(cut.cardName)
? 'bg-status-error border-status-error text-white'
: 'border-border-secondary'
}`}>
{selectedCuts.has(cut.cardName) && <Check className="w-3 h-3" />}
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-text-primary">{cut.cardName}</p>
<p className="text-xs text-text-secondary mt-0.5">{cut.reason}</p>
{cut.replacementOptions?.length > 0 && (
<p className="text-[10px] text-text-tertiary mt-1">
Replace with: {cut.replacementOptions.join(', ')}
</p>
)}
</div>
</div>
))}
</div>
</div>
)}
{/* Suggested Adds */}
{session.suggestedAdds?.length > 0 && (
<div>
<h4 className="text-sm font-medium text-status-success mb-2 flex items-center gap-1.5">
<Plus className="w-4 h-4" /> Suggested Adds ({session.suggestedAdds.length})
</h4>
<div className="space-y-2">
{session.suggestedAdds.map((add, i) => (
<div
key={i}
onClick={() => toggleAdd(add.cardName)}
className={`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${
selectedAdds.has(add.cardName)
? 'bg-status-success/10 border-status-success/30'
: 'bg-bg-secondary border-border-primary hover:border-border-secondary'
}`}
>
<div className={`mt-0.5 w-4 h-4 rounded border flex items-center justify-center flex-shrink-0 ${
selectedAdds.has(add.cardName)
? 'bg-status-success border-status-success text-white'
: 'border-border-secondary'
}`}>
{selectedAdds.has(add.cardName) && <Check className="w-3 h-3" />}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="text-sm font-medium text-text-primary">{add.cardName}</p>
{add.role && (
<span className="px-1.5 py-0.5 text-[10px] bg-accent-blue/15 text-accent-blue rounded">
{add.role}
</span>
)}
</div>
<p className="text-xs text-text-secondary mt-0.5">{add.reason}</p>
{add.synergyWith?.length > 0 && (
<p className="text-[10px] text-text-tertiary mt-1">
Synergy: {add.synergyWith.join(', ')}
</p>
)}
</div>
</div>
))}
</div>
</div>
)}
{/* Apply Button */}
{!applyResult && (selectedCuts.size > 0 || selectedAdds.size > 0) && (
<div className="sticky bottom-0 bg-bg-primary/95 backdrop-blur-sm border-t border-border-primary py-3 -mx-6 px-6">
<button
onClick={handleApply}
disabled={applying}
className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-accent-blue text-white text-sm font-medium rounded-lg hover:bg-accent-blue-hover transition-colors disabled:opacity-50"
>
{applying ? <Spinner size="sm" /> : <ArrowRightLeft className="w-4 h-4" />}
Apply {selectedCuts.size > 0 && `${selectedCuts.size} cuts`}
{selectedCuts.size > 0 && selectedAdds.size > 0 && ' + '}
{selectedAdds.size > 0 && `${selectedAdds.size} adds`} to Deck
</button>
</div>
)}
{/* Apply Results */}
{applyResult && (
<div className="bg-status-success/5 rounded-xl border border-status-success/20 p-4">
<h4 className="text-sm font-medium text-status-success mb-2 flex items-center gap-1.5">
<Check className="w-4 h-4" /> Changes Applied
</h4>
<p className="text-sm text-text-primary">
{applyResult.total_cuts > 0 && `Removed ${applyResult.total_cuts} card(s). `}
{applyResult.total_adds > 0 && `Added ${applyResult.total_adds} card(s). `}
{applyResult.errors.length > 0 && `${applyResult.errors.length} error(s).`}
</p>
{applyResult.errors.length > 0 && (
<ul className="mt-2 text-xs text-status-error">
{applyResult.errors.map((e, i) => (
<li key={i}>{e.name}: {e.error}</li>
))}
</ul>
)}
</div>
)}
{/* Raw Explanation */}
{session.rawTextExplanation && (
<details className="group">
<summary className="text-xs text-text-tertiary cursor-pointer hover:text-text-secondary">
Full analysis...
</summary>
<p className="mt-2 text-sm text-text-secondary whitespace-pre-wrap leading-relaxed bg-bg-secondary rounded-lg p-4 border border-border-primary">
{session.rawTextExplanation}
</p>
</details>
)}
</div>
)
}
// ════════════════════════════════════════════════════════════
// Cards Like Search
// ════════════════════════════════════════════════════════════
function CardsLikePanel() {
const [query, setQuery] = useState('')
const [results, setResults] = useState<CoachCardLikeResult[]>([])
const [searching, setSearching] = useState(false)
const handleSearch = async () => {
if (!query.trim()) return
setSearching(true)
try {
const data = await coachApi.searchCardsLike(query.trim(), undefined, 12)
setResults(data.results)
} catch { /* ignore */ }
setSearching(false)
}
return (
<div className="space-y-4">
<div className="flex gap-2">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-tertiary" />
<input
value={query}
onChange={e => setQuery(e.target.value)}
onKeyDown={e => e.key === 'Enter' && handleSearch()}
placeholder="Enter a card name..."
className="w-full pl-9 pr-3 py-2 bg-bg-secondary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue"
/>
</div>
<button
onClick={handleSearch}
disabled={searching || !query.trim()}
className="px-4 py-2 bg-accent-teal/15 text-accent-teal text-sm font-medium rounded-lg hover:bg-accent-teal/25 border border-accent-teal/30 transition-colors disabled:opacity-50"
>
{searching ? <Spinner size="sm" /> : 'Search'}
</button>
</div>
{results.length > 0 && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-2">
{results.map((card, i) => (
<div key={i} className="flex items-start gap-3 p-3 bg-bg-secondary rounded-lg border border-border-primary">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="text-sm font-medium text-text-primary truncate">{card.name}</p>
<span className="text-[10px] text-text-tertiary whitespace-nowrap">
{(card.similarity * 100).toFixed(0)}%
</span>
</div>
<p className="text-[11px] text-text-secondary mt-0.5">{card.types}</p>
{card.text && (
<p className="text-[10px] text-text-tertiary mt-1 line-clamp-2">{card.text}</p>
)}
<div className="flex items-center gap-3 mt-1.5 text-[10px]">
{card.tcg_price != null && (
<span className="text-accent-amber flex items-center gap-0.5">
<DollarSign className="w-2.5 h-2.5" />{card.tcg_price.toFixed(2)}
</span>
)}
{card.owned_qty > 0 && (
<span className="text-status-success">Owned: {card.owned_qty}</span>
)}
<span className="text-text-tertiary">MV: {card.mana_value}</span>
</div>
</div>
{card.image_url && (
<img src={card.image_url} alt={card.name} className="w-14 h-auto rounded" />
)}
</div>
))}
</div>
)}
</div>
)
}
// ════════════════════════════════════════════════════════════
// Live Chat View
// ════════════════════════════════════════════════════════════
function LiveChat({
deckId, deckName, goals, onClose
}: {
deckId: string
deckName: string
goals: CoachGoals
onClose: () => void
}) {
const [messages, setMessages] = useState<CoachMessage[]>([])
const [input, setInput] = useState('')
const [streaming, setStreaming] = useState(false)
const [streamText, setStreamText] = useState('')
const messagesEndRef = useRef<HTMLDivElement>(null)
const abortRef = useRef<AbortController | null>(null)
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
}, [messages, streamText])
const sendMessage = async () => {
if (!input.trim() || streaming) return
const userMsg: CoachMessage = { role: 'user', content: input.trim() }
const allMessages = [...messages, userMsg]
setMessages(allMessages)
setInput('')
setStreaming(true)
setStreamText('')
const goalsDict = goals.targetPowerLevel || goals.metaFocus || goals.budget || (goals.focusAreas || []).length > 0
? {
targetPowerLevel: goals.targetPowerLevel,
metaFocus: goals.metaFocus,
budget: goals.budget,
focusAreas: goals.focusAreas,
}
: undefined
try {
abortRef.current = new AbortController()
const fullText = await coachApi.coachChatStream(
deckId,
allMessages.map(m => ({ role: m.role, content: m.content })),
goalsDict,
(text) => setStreamText(text),
abortRef.current.signal
)
setMessages(prev => [...prev, { role: 'assistant', content: fullText }])
setStreamText('')
} catch (e) {
if ((e as Error).name !== 'AbortError') {
// Fallback to non-streaming
try {
const resp = await coachApi.coachChat(
deckId,
allMessages.map(m => ({ role: m.role, content: m.content })),
goalsDict
)
setMessages(prev => [...prev, { role: 'assistant', content: resp.content }])
} catch (e2) {
setMessages(prev => [...prev, {
role: 'assistant',
content: `Error: ${(e2 as Error).message || 'Failed to get response'}`
}])
}
}
setStreamText('')
}
setStreaming(false)
}
return (
<div className="flex flex-col h-[calc(100vh-180px)]">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-border-primary">
<div>
<h3 className="text-sm font-semibold text-text-primary flex items-center gap-2">
<MessageSquare className="w-4 h-4 text-accent-blue" />
Chat: {deckName}
</h3>
<p className="text-[10px] text-text-tertiary">
{goals.metaFocus && `${goals.metaFocus} · `}
{goals.targetPowerLevel && `Power ${goals.targetPowerLevel} · `}
{goals.budget && `${goals.budget}`}
</p>
</div>
<button onClick={onClose} className="p-1.5 rounded-lg hover:bg-bg-hover text-text-tertiary">
<X className="w-4 h-4" />
</button>
</div>
{/* Messages */}
<div className="flex-1 overflow-y-auto p-4 space-y-3">
{messages.length === 0 && !streaming && (
<div className="text-center py-12">
<GraduationCap className="w-10 h-10 text-text-tertiary mx-auto mb-3" />
<p className="text-sm text-text-secondary">Ask your coach anything about this deck.</p>
<div className="mt-4 flex flex-wrap gap-2 justify-center">
{[
'What should I cut?',
'How is my mana curve?',
'Suggest win conditions',
'Rate my removal suite',
].map(q => (
<button
key={q}
onClick={() => { setInput(q); }}
className="px-3 py-1.5 text-xs bg-bg-secondary border border-border-primary rounded-full text-text-secondary hover:text-text-primary hover:border-border-secondary transition-colors"
>
{q}
</button>
))}
</div>
</div>
)}
{messages.map((msg, i) => (
<div key={i} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>
<div className={`max-w-[85%] px-4 py-3 rounded-xl text-sm whitespace-pre-wrap leading-relaxed ${
msg.role === 'user'
? 'bg-accent-blue/15 text-text-primary border border-accent-blue/20'
: 'bg-bg-secondary text-text-primary border border-border-primary'
}`}>
{msg.content}
</div>
</div>
))}
{/* Streaming indicator */}
{streaming && (
<div className="flex justify-start">
<div className="max-w-[85%] px-4 py-3 rounded-xl text-sm whitespace-pre-wrap leading-relaxed bg-bg-secondary text-text-primary border border-border-primary">
{streamText || (
<span className="flex items-center gap-2 text-text-tertiary">
<Loader2 className="w-3.5 h-3.5 animate-spin" />
Thinking...
</span>
)}
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
{/* Input */}
<div className="border-t border-border-primary p-3">
<div className="flex gap-2">
<input
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={e => e.key === 'Enter' && !e.shiftKey && sendMessage()}
placeholder="Ask the coach..."
disabled={streaming}
className="flex-1 px-3 py-2 bg-bg-secondary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue disabled:opacity-50"
/>
<button
onClick={sendMessage}
disabled={streaming || !input.trim()}
className="px-3 py-2 bg-accent-blue text-white rounded-lg hover:bg-accent-blue-hover transition-colors disabled:opacity-50"
>
<Send className="w-4 h-4" />
</button>
</div>
</div>
</div>
)
}
// ════════════════════════════════════════════════════════════
// Main Coach Page
// ════════════════════════════════════════════════════════════
type Tab = 'decks' | 'chat' | 'session' | 'history' | 'search'
export function CoachPage() {
const [status, setStatus] = useState<CoachStatus | null>(null)
const [decks, setDecks] = useState<CoachDeck[]>([])
const [sessions, setSessions] = useState<CoachSessionSummary[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
// UI state
const [tab, setTab] = useState<Tab>('decks')
const [selectedDeck, setSelectedDeck] = useState<CoachDeck | null>(null)
const [selectedSession, setSelectedSession] = useState<CoachSession | null>(null)
const [goals, setGoals] = useState<CoachGoals>({})
const [goalsCollapsed, setGoalsCollapsed] = useState(true)
const [generatingReport, setGeneratingReport] = useState(false)
const [runningSession, setRunningSession] = useState<number | null>(null)
const [downloadingEmbeddings, setDownloadingEmbeddings] = useState(false)
const loadData = useCallback(async () => {
try {
const [s, d, sess] = await Promise.all([
coachApi.getCoachStatus(),
coachApi.getCoachDecks().catch(() => []),
coachApi.getCoachSessions().catch(() => ({ sessions: [] })),
])
setStatus(s)
setDecks(Array.isArray(d) ? d : [])
setSessions(Array.isArray(sess) ? sess : (sess as { sessions: CoachSessionSummary[] }).sessions || [])
} catch { /* ignore */ }
setLoading(false)
}, [])
useEffect(() => { loadData() }, [loadData])
const handleDownloadEmbeddings = async () => {
setDownloadingEmbeddings(true)
try {
await coachApi.downloadEmbeddings()
const s = await coachApi.getCoachStatus()
setStatus(s)
} catch { /* ignore */ }
setDownloadingEmbeddings(false)
}
const handleGenerateReports = async () => {
setGeneratingReport(true)
setError(null)
try {
await coachApi.generateReport()
await loadData()
} catch (e) {
setError(e instanceof Error ? e.message : 'Report generation failed')
}
setGeneratingReport(false)
}
const handleRunSession = async (deck: CoachDeck) => {
setRunningSession(deck.deck_id)
setError(null)
try {
const deckSlug = deck.deck_name.toLowerCase().replace(/\s+/g, '-')
const goalsDict = goals.targetPowerLevel || goals.metaFocus || goals.budget || (goals.focusAreas || []).length > 0
? goals : undefined
const session = await coachApi.runCoachSession(deckSlug, goalsDict as Record<string, unknown>)
setSelectedSession(session)
setSelectedDeck(deck)
setTab('session')
await loadData()
} catch (e) {
setError(e instanceof Error ? e.message : 'Session failed')
}
setRunningSession(null)
}
const handleOpenChat = (deck: CoachDeck) => {
setSelectedDeck(deck)
setTab('chat')
}
const handleViewSession = async (sessionId: string) => {
try {
const s = await coachApi.getCoachSession(sessionId)
setSelectedSession(s)
// Find the matching deck
const matchDeck = decks.find(d =>
d.deck_name.toLowerCase().replace(/\s+/g, '-') === s.deckId.toLowerCase() ||
d.deck_name.toLowerCase() === s.deckId.toLowerCase()
)
if (matchDeck) setSelectedDeck(matchDeck)
setTab('session')
} catch { /* ignore */ }
}
if (loading) {
return (
<div className="p-6 flex items-center justify-center h-64">
<Spinner size="lg" className="text-accent-blue" />
</div>
)
}
return (
<div className="p-6 space-y-5">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-text-primary flex items-center gap-3">
<GraduationCap className="w-6 h-6 text-accent-amber" />
Deck Coach
</h1>
<p className="text-sm text-text-secondary mt-0.5">
AI-powered deck analysis, coaching, and live chat
</p>
</div>
</div>
{/* Status Bar */}
<div className="flex items-center gap-3 flex-wrap">
<StatusBadge
variant={status?.llmConnected ? 'success' : 'warning'}
label={status?.llmConnected ? `LLM: ${status.llmModel || 'Connected'}` : 'LLM: Disconnected'}
/>
<StatusBadge
variant={status?.embeddingsLoaded ? 'success' : 'neutral'}
label={status?.embeddingsLoaded ? `${(status.embeddingCards || 0).toLocaleString()} embeddings` : 'No embeddings'}
/>
{status?.deckReportsAvailable != null && status.deckReportsAvailable > 0 && (
<StatusBadge variant="success" label={`${status.deckReportsAvailable} reports`} />
)}
{!status?.embeddingsLoaded && (
<button onClick={handleDownloadEmbeddings} disabled={downloadingEmbeddings}
className="flex items-center gap-1.5 text-xs text-accent-blue hover:text-accent-blue-hover transition-colors disabled:opacity-50">
{downloadingEmbeddings ? <Spinner size="sm" /> : <Download className="w-3 h-3" />}
Download Embeddings
</button>
)}
</div>
{error && (
<div className="flex items-center gap-2 px-4 py-2 bg-status-error/10 border border-status-error/30 rounded-lg text-sm text-status-error">
<AlertCircle className="w-4 h-4 flex-shrink-0" />{error}
<button onClick={() => setError(null)} className="ml-auto"><X className="w-3 h-3" /></button>
</div>
)}
{/* Tab Nav */}
<div className="flex gap-1 bg-bg-secondary rounded-lg p-1 border border-border-primary">
{([
{ id: 'decks', label: 'Decks', icon: ClipboardList },
{ id: 'history', label: 'Sessions', icon: History },
{ id: 'search', label: 'Cards Like', icon: Search },
] as { id: Tab; label: string; icon: typeof ClipboardList }[]).map(t => (
<button
key={t.id}
onClick={() => setTab(t.id)}
className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${
tab === t.id
? 'bg-bg-primary text-text-primary shadow-sm'
: 'text-text-tertiary hover:text-text-secondary'
}`}
>
<t.icon className="w-3.5 h-3.5" />
{t.label}
{t.id === 'history' && sessions.length > 0 && (
<span className="text-[10px] bg-bg-tertiary px-1.5 rounded-full">{sessions.length}</span>
)}
</button>
))}
{tab === 'chat' && selectedDeck && (
<div className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md bg-bg-primary text-accent-blue shadow-sm">
<MessageSquare className="w-3.5 h-3.5" />
Chat
</div>
)}
{tab === 'session' && selectedSession && (
<div className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md bg-bg-primary text-accent-amber shadow-sm">
<Sparkles className="w-3.5 h-3.5" />
Results
</div>
)}
</div>
{/* Goals Panel (shown when on decks tab) */}
{tab === 'decks' && (
<GoalsPanel
goals={goals}
onChange={setGoals}
collapsed={goalsCollapsed}
onToggle={() => setGoalsCollapsed(!goalsCollapsed)}
/>
)}
{/* ── Decks Tab ─────────────────────────────────────── */}
{tab === 'decks' && (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold text-text-primary">Your Decks</h2>
<button
onClick={handleGenerateReports}
disabled={generatingReport}
className="flex items-center gap-1.5 text-xs text-accent-amber hover:text-accent-amber transition-colors disabled:opacity-50"
>
{generatingReport ? <Spinner size="sm" /> : <Zap className="w-3 h-3" />}
Generate Reports
</button>
</div>
{decks.length === 0 ? (
<EmptyState
icon={GraduationCap}
title="No decks available"
description="Create decks in the Deck Builder to start coaching."
/>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
{decks.map(deck => (
<div key={deck.deck_id} className="bg-bg-secondary rounded-xl border border-border-primary p-4 space-y-3">
<div>
<h3 className="text-sm font-semibold text-text-primary">{deck.deck_name}</h3>
<p className="text-xs text-text-secondary">{deck.commander}</p>
</div>
<div className="flex items-center gap-3 text-[10px] text-text-tertiary">
<span>{deck.card_count} cards</span>
{deck.has_report && (
<span className="flex items-center gap-1 text-status-success">
<Check className="w-2.5 h-2.5" /> Report
</span>
)}
</div>
<div className="flex items-center gap-2">
<button
onClick={() => handleRunSession(deck)}
disabled={runningSession === deck.deck_id || !status?.llmConnected}
className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 bg-accent-amber/15 text-accent-amber text-xs font-medium rounded-lg hover:bg-accent-amber/25 border border-accent-amber/30 transition-colors disabled:opacity-50"
>
{runningSession === deck.deck_id ? <Spinner size="sm" /> : <Sparkles className="w-3 h-3" />}
Analyze
</button>
<button
onClick={() => handleOpenChat(deck)}
disabled={!status?.llmConnected}
className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 bg-accent-blue/15 text-accent-blue text-xs font-medium rounded-lg hover:bg-accent-blue/25 border border-accent-blue/30 transition-colors disabled:opacity-50"
>
<MessageSquare className="w-3 h-3" />
Chat
</button>
</div>
</div>
))}
</div>
)}
</div>
)}
{/* ── Chat Tab ──────────────────────────────────────── */}
{tab === 'chat' && selectedDeck && (
<LiveChat
deckId={selectedDeck.deck_name.toLowerCase().replace(/\s+/g, '-')}
deckName={selectedDeck.deck_name}
goals={goals}
onClose={() => setTab('decks')}
/>
)}
{/* ── Session Results Tab ───────────────────────────── */}
{tab === 'session' && selectedSession && selectedDeck && (
<SessionView
session={selectedSession}
deckId={selectedDeck.deck_id}
onClose={() => setTab('decks')}
onApplied={() => loadData()}
/>
)}
{/* ── History Tab ───────────────────────────────────── */}
{tab === 'history' && (
<div className="space-y-3">
<h2 className="text-sm font-semibold text-text-primary">Coaching Sessions</h2>
{sessions.length === 0 ? (
<EmptyState
icon={History}
title="No sessions yet"
description="Run an analysis on a deck to create your first coaching session."
/>
) : (
<div className="space-y-2">
{sessions.map(s => (
<button
key={s.sessionId}
onClick={() => handleViewSession(s.sessionId)}
className="w-full flex items-center gap-4 px-4 py-3 bg-bg-secondary rounded-lg border border-border-primary hover:border-border-secondary text-left transition-colors"
>
<Sparkles className="w-4 h-4 text-accent-amber flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="text-sm font-medium text-text-primary">{s.deckId}</p>
<span className="text-[10px] text-text-tertiary">
{s.cutsCount > 0 && `${s.cutsCount} cuts`}
{s.cutsCount > 0 && s.addsCount > 0 && ' · '}
{s.addsCount > 0 && `${s.addsCount} adds`}
</span>
</div>
<p className="text-xs text-text-tertiary mt-0.5 truncate">{s.summary || 'No summary'}</p>
<p className="text-[10px] text-text-tertiary mt-0.5">{new Date(s.timestamp).toLocaleString()}</p>
</div>
<ChevronRight className="w-4 h-4 text-text-tertiary flex-shrink-0" />
</button>
))}
</div>
)}
</div>
)}
{/* ── Cards Like Tab ────────────────────────────────── */}
{tab === 'search' && (
<div className="space-y-4">
<div>
<h2 className="text-sm font-semibold text-text-primary mb-1">Cards Like This</h2>
<p className="text-xs text-text-secondary">
Find similar cards using AI embeddings. Search by card name to discover alternatives.
</p>
</div>
<CardsLikePanel />
</div>
)}
</div>
)
}
@@ -0,0 +1,484 @@
import { useState, useEffect, useCallback, useRef } from 'react'
import {
Search, Filter, Upload, Download, Camera, RefreshCw,
ChevronLeft, ChevronRight, X, Package, SlidersHorizontal,
Plus, Grid3x3, List
} from 'lucide-react'
import { Spinner, EmptyState, ManaSymbols, CardImage } from '../components/common'
import { collectionApi } from '../api'
import type { CollectionCard, CollectionFilters, SetInfo } from '../types'
// ── Card Detail Modal ─────────────────────────────────────────
function CardDetailModal({ card, onClose }: { card: CollectionCard; onClose: () => void }) {
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm" onClick={onClose}>
<div
className="bg-bg-secondary rounded-xl border border-border-primary shadow-lg max-w-4xl w-full mx-4 max-h-[90vh] overflow-y-auto animate-fade-in"
onClick={e => e.stopPropagation()}
>
<div className="flex items-start justify-between p-5 border-b border-border-primary">
<div>
<h2 className="text-xl font-bold text-text-primary">{card.name}</h2>
<p className="text-sm text-text-secondary mt-0.5">{card.type_line}</p>
</div>
<button onClick={onClose} className="p-1 rounded hover:bg-bg-hover text-text-tertiary">
<X className="w-5 h-5" />
</button>
</div>
<div className="flex flex-col md:flex-row gap-6 p-5">
{/* Large card image */}
<div className="flex-shrink-0">
<CardImage src={card.image_url} alt={card.name} size="xl" />
</div>
{/* Card info */}
<div className="flex-1 space-y-4">
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Mana Cost</label>
<div className="mt-1"><ManaSymbols cost={card.mana_cost} size="md" /></div>
</div>
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Oracle Text</label>
<p className="mt-1 text-sm text-text-primary whitespace-pre-wrap leading-relaxed">{card.oracle_text}</p>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Set</label>
<p className="mt-1 text-sm text-text-primary">{card.set_name} ({card.set_code.toUpperCase()})</p>
</div>
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Rarity</label>
<p className={`mt-1 text-sm font-medium capitalize ${
card.rarity === 'mythic' ? 'text-accent-amber' :
card.rarity === 'rare' ? 'text-accent-amber/80' :
card.rarity === 'uncommon' ? 'text-accent-teal' : 'text-text-secondary'
}`}>{card.rarity}</p>
</div>
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">CMC</label>
<p className="mt-1 text-sm text-text-primary">{card.cmc}</p>
</div>
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">EDHREC Rank</label>
<p className="mt-1 text-sm text-text-primary">{card.edhrec_rank ?? 'N/A'}</p>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Quantity</label>
<p className="mt-1 text-sm text-text-primary">{card.quantity} (+ {card.foil_quantity} foil)</p>
</div>
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Price</label>
<p className="mt-1 text-sm text-accent-teal font-semibold">
${card.tcg_price?.toFixed(2) ?? '—'}
{card.foil_price ? <span className="text-text-tertiary ml-2">Foil: ${card.foil_price.toFixed(2)}</span> : null}
</p>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
// ── Scanner Panel ─────────────────────────────────────────────
function ScannerPanel({ onCardAdded }: { onCardAdded: () => void }) {
const [scanning, setScanning] = useState(false)
const [results, setResults] = useState<import('../types').ScanMatch[]>([])
const [adding, setAdding] = useState<string | null>(null)
const fileRef = useRef<HTMLInputElement>(null)
async function handleScan(file: File) {
setScanning(true)
setResults([])
try {
const res = await collectionApi.scanCard(file)
setResults(res.matches || [])
} catch {
setResults([])
}
setScanning(false)
}
async function handleAdd(match: import('../types').ScanMatch) {
setAdding(match.scryfall_id)
try {
await collectionApi.addScanResult({
name: match.name,
set_code: match.set_code,
scryfall_id: match.scryfall_id,
})
onCardAdded()
} catch { /* ignore */ }
setAdding(null)
}
return (
<div className="bg-bg-secondary rounded-xl border border-border-primary p-5">
<h3 className="text-sm font-semibold text-text-primary flex items-center gap-2 mb-3">
<Camera className="w-4 h-4 text-accent-blue" />
Card Scanner
</h3>
<input
ref={fileRef}
type="file"
accept="image/*"
className="hidden"
onChange={e => e.target.files?.[0] && handleScan(e.target.files[0])}
/>
<button
onClick={() => fileRef.current?.click()}
disabled={scanning}
className="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-accent-blue/10 text-accent-blue border border-accent-blue/30 rounded-lg text-sm font-medium hover:bg-accent-blue/20 transition-colors disabled:opacity-50"
>
{scanning ? <Spinner size="sm" /> : <Camera className="w-4 h-4" />}
{scanning ? 'Scanning...' : 'Scan a Card'}
</button>
{results.length > 0 && (
<div className="mt-3 space-y-2 max-h-60 overflow-y-auto">
{results.map(m => (
<div key={m.scryfall_id} className="flex items-center gap-3 p-2 rounded-lg bg-bg-tertiary">
<CardImage src={m.image_url} alt={m.name} size="sm" />
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-text-primary truncate">{m.name}</p>
<p className="text-xs text-text-tertiary">{m.set_name} — {(m.confidence * 100).toFixed(0)}%</p>
</div>
<button
onClick={() => handleAdd(m)}
disabled={adding === m.scryfall_id}
className="p-1.5 rounded-lg bg-accent-green/15 text-accent-green hover:bg-accent-green/25 transition-colors"
>
{adding === m.scryfall_id ? <Spinner size="sm" /> : <Plus className="w-4 h-4" />}
</button>
</div>
))}
</div>
)}
</div>
)
}
// ── Main Collection Page ──────────────────────────────────────
export function CollectionPage() {
const [cards, setCards] = useState<CollectionCard[]>([])
const [total, setTotal] = useState(0)
const [loading, setLoading] = useState(true)
const [sets, setSets] = useState<SetInfo[]>([])
const [selectedCard, setSelectedCard] = useState<CollectionCard | null>(null)
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid')
const [showFilters, setShowFilters] = useState(false)
const [importing, setImporting] = useState(false)
const [enriching, setEnriching] = useState(false)
const importRef = useRef<HTMLInputElement>(null)
const [filters, setFilters] = useState<CollectionFilters>({
q: '',
page: 1,
page_size: 48,
sort_by: 'name',
sort_dir: 'asc',
})
const fetchCards = useCallback(async () => {
setLoading(true)
try {
const res = await collectionApi.searchCollection(filters)
setCards(res.cards)
setTotal(res.total)
} catch { /* ignore */ }
setLoading(false)
}, [filters])
useEffect(() => { fetchCards() }, [fetchCards])
useEffect(() => {
collectionApi.getSets().then(setSets).catch(() => {})
}, [])
const totalPages = Math.ceil(total / (filters.page_size || 48))
function updateFilter(key: keyof CollectionFilters, value: string | number | boolean | undefined) {
setFilters(prev => ({ ...prev, [key]: value, page: 1 }))
}
async function handleExport() {
const blob = await collectionApi.exportCollection('csv')
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'collection.csv'
a.click()
URL.revokeObjectURL(url)
}
async function handleImport(file: File) {
setImporting(true)
try {
await collectionApi.importCollection(file)
fetchCards()
} catch { /* ignore */ }
setImporting(false)
}
async function handleReEnrich() {
setEnriching(true)
try {
await collectionApi.reEnrichCards()
fetchCards()
} catch { /* ignore */ }
setEnriching(false)
}
return (
<div className="p-6 space-y-5">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-text-primary">Collection</h1>
<p className="text-sm text-text-secondary mt-0.5">{total.toLocaleString()} cards in your collection</p>
</div>
<div className="flex items-center gap-2">
<button onClick={handleReEnrich} disabled={enriching}
className="flex items-center gap-2 px-3 py-2 text-xs font-medium bg-bg-tertiary text-text-secondary rounded-lg hover:bg-bg-hover border border-border-primary transition-colors disabled:opacity-50">
{enriching ? <Spinner size="sm" /> : <RefreshCw className="w-3.5 h-3.5" />}
Re-Enrich
</button>
<input ref={importRef} type="file" accept=".csv,.txt" className="hidden"
onChange={e => e.target.files?.[0] && handleImport(e.target.files[0])} />
<button onClick={() => importRef.current?.click()} disabled={importing}
className="flex items-center gap-2 px-3 py-2 text-xs font-medium bg-bg-tertiary text-text-secondary rounded-lg hover:bg-bg-hover border border-border-primary transition-colors disabled:opacity-50">
{importing ? <Spinner size="sm" /> : <Upload className="w-3.5 h-3.5" />}
Import
</button>
<button onClick={handleExport}
className="flex items-center gap-2 px-3 py-2 text-xs font-medium bg-bg-tertiary text-text-secondary rounded-lg hover:bg-bg-hover border border-border-primary transition-colors">
<Download className="w-3.5 h-3.5" />
Export
</button>
</div>
</div>
<div className="flex gap-5">
{/* Left sidebar: search + filters + scanner */}
<div className="w-72 flex-shrink-0 space-y-4">
{/* Search */}
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-tertiary" />
<input
type="text"
placeholder="Search cards..."
value={filters.q || ''}
onChange={e => updateFilter('q', e.target.value)}
className="w-full pl-10 pr-4 py-2.5 bg-bg-secondary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue/50 focus:ring-1 focus:ring-accent-blue/30 transition-all"
/>
</div>
{/* Filter toggle */}
<button
onClick={() => setShowFilters(!showFilters)}
className="w-full flex items-center justify-between px-4 py-2.5 bg-bg-secondary border border-border-primary rounded-lg text-sm text-text-secondary hover:bg-bg-hover transition-colors"
>
<span className="flex items-center gap-2">
<SlidersHorizontal className="w-4 h-4" />
Filters
</span>
<Filter className={`w-3.5 h-3.5 transition-transform ${showFilters ? 'rotate-180' : ''}`} />
</button>
{showFilters && (
<div className="bg-bg-secondary rounded-xl border border-border-primary p-4 space-y-3 animate-fade-in">
{/* Rarity */}
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Rarity</label>
<select
value={filters.rarity || ''}
onChange={e => updateFilter('rarity', e.target.value || undefined)}
className="mt-1 w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50"
>
<option value="">All</option>
<option value="common">Common</option>
<option value="uncommon">Uncommon</option>
<option value="rare">Rare</option>
<option value="mythic">Mythic</option>
</select>
</div>
{/* Color */}
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Color</label>
<select
value={filters.color || ''}
onChange={e => updateFilter('color', e.target.value || undefined)}
className="mt-1 w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50"
>
<option value="">All</option>
<option value="W">White</option>
<option value="U">Blue</option>
<option value="B">Black</option>
<option value="R">Red</option>
<option value="G">Green</option>
<option value="C">Colorless</option>
</select>
</div>
{/* Set */}
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Set</label>
<select
value={filters.set_code || ''}
onChange={e => updateFilter('set_code', e.target.value || undefined)}
className="mt-1 w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50"
>
<option value="">All Sets</option>
{sets.map(s => (
<option key={s.code} value={s.code}>{s.name} ({s.card_count})</option>
))}
</select>
</div>
{/* CMC Range */}
<div className="grid grid-cols-2 gap-2">
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">CMC Min</label>
<input type="number" min="0" max="20"
value={filters.cmc_min ?? ''}
onChange={e => updateFilter('cmc_min', e.target.value ? Number(e.target.value) : undefined)}
className="mt-1 w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50"
/>
</div>
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">CMC Max</label>
<input type="number" min="0" max="20"
value={filters.cmc_max ?? ''}
onChange={e => updateFilter('cmc_max', e.target.value ? Number(e.target.value) : undefined)}
className="mt-1 w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50"
/>
</div>
</div>
{/* Sort */}
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Sort By</label>
<select
value={filters.sort_by || 'name'}
onChange={e => updateFilter('sort_by', e.target.value)}
className="mt-1 w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50"
>
<option value="name">Name</option>
<option value="cmc">CMC</option>
<option value="tcg_price">Price</option>
<option value="rarity">Rarity</option>
<option value="set_code">Set</option>
<option value="added_date">Date Added</option>
</select>
</div>
</div>
)}
{/* Scanner */}
<ScannerPanel onCardAdded={fetchCards} />
</div>
{/* Main content: card grid/list */}
<div className="flex-1 min-w-0">
{/* View toggle + pagination */}
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-1 bg-bg-secondary rounded-lg border border-border-primary p-0.5">
<button
onClick={() => setViewMode('grid')}
className={`p-1.5 rounded-md transition-colors ${viewMode === 'grid' ? 'bg-bg-hover text-text-primary' : 'text-text-tertiary hover:text-text-secondary'}`}
>
<Grid3x3 className="w-4 h-4" />
</button>
<button
onClick={() => setViewMode('list')}
className={`p-1.5 rounded-md transition-colors ${viewMode === 'list' ? 'bg-bg-hover text-text-primary' : 'text-text-tertiary hover:text-text-secondary'}`}
>
<List className="w-4 h-4" />
</button>
</div>
<div className="flex items-center gap-2 text-sm text-text-secondary">
<span>Page {filters.page} of {totalPages || 1}</span>
<button
onClick={() => setFilters(p => ({ ...p, page: Math.max(1, (p.page || 1) - 1) }))}
disabled={!filters.page || filters.page <= 1}
className="p-1 rounded hover:bg-bg-hover disabled:opacity-30"
>
<ChevronLeft className="w-4 h-4" />
</button>
<button
onClick={() => setFilters(p => ({ ...p, page: Math.min(totalPages, (p.page || 1) + 1) }))}
disabled={(filters.page || 1) >= totalPages}
className="p-1 rounded hover:bg-bg-hover disabled:opacity-30"
>
<ChevronRight className="w-4 h-4" />
</button>
</div>
</div>
{loading ? (
<div className="flex items-center justify-center h-64">
<Spinner size="lg" className="text-accent-blue" />
</div>
) : cards.length === 0 ? (
<EmptyState
icon={Package}
title="No cards found"
description="Try adjusting your search or filters, or import a collection."
/>
) : viewMode === 'grid' ? (
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3">
{cards.map(card => (
<div
key={card.id}
className="group cursor-pointer"
onClick={() => setSelectedCard(card)}
>
<CardImage src={card.image_url} alt={card.name} size="md" className="w-full h-auto aspect-[5/7]" />
<div className="mt-1.5 px-0.5">
<p className="text-xs font-medium text-text-primary truncate group-hover:text-accent-blue transition-colors">{card.name}</p>
<div className="flex items-center justify-between">
<span className="text-[10px] text-text-tertiary">{card.set_code.toUpperCase()}</span>
{card.tcg_price != null && (
<span className="text-[10px] text-accent-teal font-medium">${card.tcg_price.toFixed(2)}</span>
)}
</div>
</div>
</div>
))}
</div>
) : (
<div className="bg-bg-secondary rounded-xl border border-border-primary overflow-hidden">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border-primary text-left">
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider">Card</th>
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider">Type</th>
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider">Mana</th>
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider">Set</th>
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider">Qty</th>
<th className="px-4 py-3 text-xs text-text-tertiary font-medium uppercase tracking-wider text-right">Price</th>
</tr>
</thead>
<tbody className="divide-y divide-border-primary">
{cards.map(card => (
<tr key={card.id} className="hover:bg-bg-hover cursor-pointer transition-colors" onClick={() => setSelectedCard(card)}>
<td className="px-4 py-2.5">
<span className="font-medium text-text-primary">{card.name}</span>
</td>
<td className="px-4 py-2.5 text-text-secondary text-xs">{card.type_line}</td>
<td className="px-4 py-2.5"><ManaSymbols cost={card.mana_cost} /></td>
<td className="px-4 py-2.5 text-text-secondary text-xs">{card.set_code.toUpperCase()}</td>
<td className="px-4 py-2.5 text-text-secondary">{card.quantity}</td>
<td className="px-4 py-2.5 text-right text-accent-teal font-medium">{card.tcg_price != null ? `$${card.tcg_price.toFixed(2)}` : '—'}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
</div>
{/* Card detail modal */}
{selectedCard && <CardDetailModal card={selectedCard} onClose={() => setSelectedCard(null)} />}
</div>
)
}
@@ -0,0 +1,967 @@
import { useState, useEffect } from 'react'
import {
Plus, Trash2, Download, ChevronRight,
BarChart3, Lightbulb, Layers, X, Library,
Globe, XCircle, ShoppingCart,
ChevronDown, ChevronUp, Sparkles
} from 'lucide-react'
import { Spinner, EmptyState, ManaSymbols, ColorDots } from '../components/common'
import { decksApi } from '../api'
import type {
Deck, DeckCard, DeckAnalysis,
EdhRecCard, EdhRecsResponse,
CollectionRecsResponse
} from '../types'
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from 'recharts'
// ── Role Badge ──────────────────────────────────────────────
const ROLE_COLORS: Record<string, string> = {
Ramp: 'bg-green-500/15 text-green-400 border-green-500/25',
Draw: 'bg-blue-500/15 text-blue-400 border-blue-500/25',
Removal: 'bg-red-500/15 text-red-400 border-red-500/25',
BoardWipe: 'bg-orange-500/15 text-orange-400 border-orange-500/25',
Tutor: 'bg-purple-500/15 text-purple-400 border-purple-500/25',
Protection: 'bg-cyan-500/15 text-cyan-400 border-cyan-500/25',
Finisher: 'bg-yellow-500/15 text-yellow-400 border-yellow-500/25',
Recursion: 'bg-emerald-500/15 text-emerald-400 border-emerald-500/25',
Other: 'bg-slate-500/15 text-slate-400 border-slate-500/25',
}
function RoleBadge({ role }: { role: string }) {
const colors = ROLE_COLORS[role] || ROLE_COLORS.Other
return (
<span className={'text-[10px] font-medium px-1.5 py-0.5 rounded border ' + colors}>
{role}
</span>
)
}
// ── Deck Card List ────────────────────────────────────────────
function DeckCardList({ deckId, cards, onUpdate }: { deckId: number; cards: DeckCard[]; onUpdate: () => void }) {
const [removing, setRemoving] = useState<number | null>(null)
// Group cards by category
const grouped = cards.reduce<Record<string, DeckCard[]>>((acc, c) => {
const cat = c.category || 'Other'
if (!acc[cat]) acc[cat] = []
acc[cat].push(c)
return acc
}, {})
const categoryOrder = ['Commander', 'Creature', 'Instant', 'Sorcery', 'Artifact', 'Enchantment', 'Planeswalker', 'Land', 'Other']
const sortedCategories = Object.keys(grouped).sort((a, b) => {
const ia = categoryOrder.indexOf(a)
const ib = categoryOrder.indexOf(b)
return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib)
})
async function handleRemove(cardId: number) {
setRemoving(cardId)
try {
await decksApi.removeCardFromDeck(deckId, cardId)
onUpdate()
} catch { /* ignore */ }
setRemoving(null)
}
return (
<div className="space-y-4">
{sortedCategories.map(cat => (
<div key={cat}>
<h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider mb-2">
{cat} ({grouped[cat].length})
</h4>
<div className="space-y-1">
{grouped[cat].map(card => (
<div key={card.id} className="flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-bg-hover group transition-colors">
<span className="text-xs text-text-tertiary w-5 text-right">{card.quantity}x</span>
<ManaSymbols cost={card.mana_cost} />
<span className="flex-1 text-sm text-text-primary truncate">{card.name}</span>
{card.tcg_price != null && (
<span className="text-xs text-accent-teal">${card.tcg_price.toFixed(2)}</span>
)}
{!card.is_commander && (
<button
onClick={() => handleRemove(card.id)}
className="opacity-0 group-hover:opacity-100 p-1 text-text-tertiary hover:text-accent-red transition-all"
>
{removing === card.id ? <Spinner size="sm" /> : <Trash2 className="w-3.5 h-3.5" />}
</button>
)}
</div>
))}
</div>
</div>
))}
</div>
)
}
// ── Mana Curve Chart ──────────────────────────────────────────
function ManaCurveChart({ analysis }: { analysis: DeckAnalysis }) {
const data = Object.entries(analysis.mana_curve)
.map(([cmc, count]) => ({ cmc: cmc === '7' ? '7+' : cmc, count }))
.sort((a, b) => Number(a.cmc) - Number(b.cmc))
return (
<div className="h-40">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} barSize={24}>
<XAxis dataKey="cmc" axisLine={false} tickLine={false} tick={{ fill: '#6b7190', fontSize: 11 }} />
<YAxis hide />
<Tooltip
contentStyle={{ backgroundColor: '#1c2030', border: '1px solid #2a2f42', borderRadius: 8, fontSize: 12 }}
labelStyle={{ color: '#9ba1b8' }}
itemStyle={{ color: '#e8eaf0' }}
/>
<Bar dataKey="count" radius={[4, 4, 0, 0]}>
{data.map((_, i) => (
<Cell key={i} fill="#4f6ef7" fillOpacity={0.8} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
)
}
// ── EDHREC Recommendations Sub-tab ──────────────────────────
function EdhRecTab({ deckId, onAddedCards }: { deckId: number; onAddedCards: () => void }) {
const [data, setData] = useState<EdhRecsResponse | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [onlyOwned, setOnlyOwned] = useState(false)
const [selectedCards, setSelectedCards] = useState<Set<string>>(new Set())
const [addingCards, setAddingCards] = useState<Set<string>>(new Set())
const [bulkAdding, setBulkAdding] = useState(false)
const [hoveredCard, setHoveredCard] = useState<EdhRecCard | null>(null)
const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(new Set())
async function fetchRecs() {
setLoading(true)
setError(null)
try {
const result = await decksApi.getEdhRecs(deckId, onlyOwned)
setData(result)
} catch (e: any) {
setError(e?.message || 'Failed to load EDHREC recommendations')
}
setLoading(false)
}
useEffect(() => { fetchRecs() }, [deckId, onlyOwned])
function toggleSelect(name: string) {
setSelectedCards(prev => {
const next = new Set(prev)
if (next.has(name)) next.delete(name)
else next.add(name)
return next
})
}
function selectAll() {
if (!data) return
setSelectedCards(new Set(data.recommendations.map(r => r.name)))
}
function selectNone() { setSelectedCards(new Set()) }
function selectOwned() {
if (!data) return
setSelectedCards(new Set(data.recommendations.filter(r => r.owned).map(r => r.name)))
}
async function handleAddSingle(name: string) {
setAddingCards(prev => new Set(prev).add(name))
try {
await decksApi.bulkAddRecommended(deckId, [name])
onAddedCards()
// Remove from list
if (data) {
setData({
...data,
recommendations: data.recommendations.filter(r => r.name !== name),
total: data.total - 1,
})
}
selectedCards.delete(name)
setSelectedCards(new Set(selectedCards))
} catch { /* ignore */ }
setAddingCards(prev => { const n = new Set(prev); n.delete(name); return n })
}
async function handleBulkAdd() {
if (selectedCards.size === 0) return
setBulkAdding(true)
try {
await decksApi.bulkAddRecommended(deckId, Array.from(selectedCards))
onAddedCards()
if (data) {
setData({
...data,
recommendations: data.recommendations.filter(r => !selectedCards.has(r.name)),
total: data.total - selectedCards.size,
})
}
setSelectedCards(new Set())
} catch { /* ignore */ }
setBulkAdding(false)
}
function toggleGroup(groupName: string) {
setCollapsedGroups(prev => {
const next = new Set(prev)
if (next.has(groupName)) next.delete(groupName)
else next.add(groupName)
return next
})
}
// Group recommendations by role
function groupByRole(recs: EdhRecCard[]): Record<string, EdhRecCard[]> {
const groups: Record<string, EdhRecCard[]> = {}
for (const rec of recs) {
const role = rec.role || 'Other'
if (!groups[role]) groups[role] = []
groups[role].push(rec)
}
return groups
}
if (loading) {
return <div className="flex items-center justify-center h-40"><Spinner size="lg" className="text-accent-blue" /></div>
}
if (error) {
return (
<div className="bg-accent-red/10 border border-accent-red/20 rounded-xl p-5 text-center">
<XCircle className="w-6 h-6 text-accent-red mx-auto mb-2" />
<p className="text-sm text-accent-red font-medium">{error}</p>
<button onClick={fetchRecs} className="mt-3 px-4 py-2 text-xs font-medium bg-bg-tertiary text-text-secondary rounded-lg hover:bg-bg-hover border border-border-primary transition-colors">
Retry
</button>
</div>
)
}
if (!data || data.recommendations.length === 0) {
return <EmptyState icon={Globe} title="No EDHREC data" description="No recommendations found for this commander on EDHREC." />
}
const grouped = groupByRole(data.recommendations)
const roleOrder = ['Ramp', 'Draw', 'Removal', 'BoardWipe', 'Tutor', 'Protection', 'Finisher', 'Recursion', 'Other']
const sortedRoles = Object.keys(grouped).sort((a, b) => {
const ia = roleOrder.indexOf(a)
const ib = roleOrder.indexOf(b)
return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib)
})
const ownedCount = data.recommendations.filter(r => r.owned).length
const missingCount = data.recommendations.length - ownedCount
return (
<div className="space-y-4">
{/* Header bar */}
<div className="flex items-center justify-between flex-wrap gap-3">
<div className="flex items-center gap-3">
<div className="flex items-center gap-2 text-sm">
<Sparkles className="w-4 h-4 text-accent-blue" />
<span className="text-text-primary font-medium">{data.commander}</span>
<span className="text-text-tertiary">via {data.source}</span>
</div>
<span className="text-xs px-2 py-0.5 rounded bg-accent-green/15 text-accent-green">{ownedCount} owned</span>
<span className="text-xs px-2 py-0.5 rounded bg-bg-tertiary text-text-tertiary">{missingCount} missing</span>
</div>
<label className="flex items-center gap-2 text-xs text-text-secondary cursor-pointer select-none">
<input
type="checkbox"
checked={onlyOwned}
onChange={e => setOnlyOwned(e.target.checked)}
className="rounded border-border-primary bg-bg-tertiary text-accent-blue focus:ring-accent-blue/30 w-3.5 h-3.5"
/>
Show only owned
</label>
</div>
{/* Selection toolbar */}
<div className="flex items-center justify-between bg-bg-secondary rounded-xl border border-border-primary px-4 py-3">
<div className="flex items-center gap-2">
<span className="text-xs text-text-tertiary">Select:</span>
<button onClick={selectAll} className="text-xs text-accent-blue hover:underline">All</button>
<span className="text-text-tertiary">/</span>
<button onClick={selectNone} className="text-xs text-accent-blue hover:underline">None</button>
<span className="text-text-tertiary">/</span>
<button onClick={selectOwned} className="text-xs text-accent-blue hover:underline">Owned</button>
{selectedCards.size > 0 && (
<span className="text-xs text-text-secondary ml-2">({selectedCards.size} selected)</span>
)}
</div>
<button
onClick={handleBulkAdd}
disabled={selectedCards.size === 0 || bulkAdding}
className="flex items-center gap-2 px-3 py-1.5 text-xs font-medium bg-accent-blue text-white rounded-lg hover:bg-accent-blue-hover transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
>
{bulkAdding ? <Spinner size="sm" /> : <ShoppingCart className="w-3.5 h-3.5" />}
Add {selectedCards.size > 0 ? selectedCards.size : ''} to Deck
</button>
</div>
{/* Grouped cards */}
{sortedRoles.map(role => {
const cards = grouped[role]
const isCollapsed = collapsedGroups.has(role)
return (
<div key={role} className="bg-bg-secondary rounded-xl border border-border-primary overflow-hidden">
{/* Group header */}
<button
onClick={() => toggleGroup(role)}
className="w-full flex items-center justify-between px-4 py-3 hover:bg-bg-hover transition-colors"
>
<div className="flex items-center gap-2">
<RoleBadge role={role} />
<span className="text-xs text-text-tertiary">({cards.length})</span>
</div>
{isCollapsed ? <ChevronDown className="w-4 h-4 text-text-tertiary" /> : <ChevronUp className="w-4 h-4 text-text-tertiary" />}
</button>
{/* Card list */}
{!isCollapsed && (
<div className="border-t border-border-primary divide-y divide-border-primary">
{cards.map(rec => (
<div
key={rec.name}
className="flex items-center gap-3 px-4 py-2.5 hover:bg-bg-hover transition-colors group relative"
onMouseEnter={() => setHoveredCard(rec)}
onMouseLeave={() => setHoveredCard(null)}
>
{/* Checkbox */}
<input
type="checkbox"
checked={selectedCards.has(rec.name)}
onChange={() => toggleSelect(rec.name)}
className="rounded border-border-primary bg-bg-tertiary text-accent-blue focus:ring-accent-blue/30 w-3.5 h-3.5 flex-shrink-0"
/>
{/* Card image mini */}
{rec.image_url && (
<div className="w-8 h-11 rounded overflow-hidden bg-bg-tertiary flex-shrink-0">
<img src={rec.image_url} alt={rec.name} className="w-full h-full object-cover" loading="lazy" />
</div>
)}
{/* Card info */}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-text-primary truncate">{rec.name}</p>
<div className="flex items-center gap-1.5 mt-0.5">
<span className="text-[10px] text-text-tertiary truncate">{rec.type_line}</span>
{rec.roles.length > 0 && rec.roles.map(r => <RoleBadge key={r} role={r} />)}
</div>
</div>
{/* Owned badge */}
<span className={'text-xs px-2 py-0.5 rounded flex-shrink-0 ' + (rec.owned ? 'bg-accent-green/15 text-accent-green' : 'bg-bg-tertiary text-text-tertiary')}>
{rec.owned ? (rec.owned_qty + 'x owned') : 'Missing'}
</span>
{/* Add button */}
<button
onClick={e => { e.stopPropagation(); handleAddSingle(rec.name) }}
disabled={addingCards.has(rec.name)}
className="opacity-0 group-hover:opacity-100 px-2.5 py-1 text-xs font-medium bg-accent-blue text-white rounded-lg hover:bg-accent-blue-hover transition-all disabled:opacity-50 flex-shrink-0"
>
{addingCards.has(rec.name) ? <Spinner size="sm" /> : '+ Add'}
</button>
</div>
))}
</div>
)}
</div>
)
})}
{/* Hover preview */}
{hoveredCard && hoveredCard.image_url && (
<div className="fixed top-20 right-8 z-50 pointer-events-none animate-fade-in">
<img
src={hoveredCard.image_url}
alt={hoveredCard.name}
className="w-[244px] rounded-xl shadow-2xl shadow-black/60 border border-border-primary"
/>
</div>
)}
</div>
)
}
// ── Collection Recommendations Sub-tab ──────────────────────
function CollectionRecTab({ deckId, onAddedCards }: { deckId: number; onAddedCards: () => void }) {
const [data, setData] = useState<CollectionRecsResponse | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [selectedCards, setSelectedCards] = useState<Set<string>>(new Set())
const [addingCards, setAddingCards] = useState<Set<string>>(new Set())
const [bulkAdding, setBulkAdding] = useState(false)
const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(new Set())
async function fetchRecs() {
setLoading(true)
setError(null)
try {
const result = await decksApi.getCollectionRecs(deckId)
setData(result)
} catch (e: any) {
setError(e?.message || 'Failed to load collection recommendations')
}
setLoading(false)
}
useEffect(() => { fetchRecs() }, [deckId])
function toggleSelect(name: string) {
setSelectedCards(prev => {
const next = new Set(prev)
if (next.has(name)) next.delete(name)
else next.add(name)
return next
})
}
function selectAll() {
if (!data) return
const all = new Set<string>()
Object.values(data.grouped).flat().forEach(c => all.add(c.name))
setSelectedCards(all)
}
function selectNone() { setSelectedCards(new Set()) }
async function handleAddSingle(name: string) {
setAddingCards(prev => new Set(prev).add(name))
try {
await decksApi.bulkAddRecommended(deckId, [name])
onAddedCards()
// Remove from groupings
if (data) {
const newGrouped = { ...data.grouped }
for (const key of Object.keys(newGrouped)) {
newGrouped[key] = newGrouped[key].filter(c => c.name !== name)
if (newGrouped[key].length === 0) delete newGrouped[key]
}
setData({ ...data, grouped: newGrouped, total: data.total - 1 })
}
selectedCards.delete(name)
setSelectedCards(new Set(selectedCards))
} catch { /* ignore */ }
setAddingCards(prev => { const n = new Set(prev); n.delete(name); return n })
}
async function handleBulkAdd() {
if (selectedCards.size === 0) return
setBulkAdding(true)
try {
await decksApi.bulkAddRecommended(deckId, Array.from(selectedCards))
onAddedCards()
if (data) {
const newGrouped = { ...data.grouped }
for (const key of Object.keys(newGrouped)) {
newGrouped[key] = newGrouped[key].filter(c => !selectedCards.has(c.name))
if (newGrouped[key].length === 0) delete newGrouped[key]
}
setData({ ...data, grouped: newGrouped, total: data.total - selectedCards.size })
}
setSelectedCards(new Set())
} catch { /* ignore */ }
setBulkAdding(false)
}
function toggleGroup(groupName: string) {
setCollapsedGroups(prev => {
const next = new Set(prev)
if (next.has(groupName)) next.delete(groupName)
else next.add(groupName)
return next
})
}
if (loading) {
return <div className="flex items-center justify-center h-40"><Spinner size="lg" className="text-accent-blue" /></div>
}
if (error) {
return (
<div className="bg-accent-red/10 border border-accent-red/20 rounded-xl p-5 text-center">
<XCircle className="w-6 h-6 text-accent-red mx-auto mb-2" />
<p className="text-sm text-accent-red font-medium">{error}</p>
<button onClick={fetchRecs} className="mt-3 px-4 py-2 text-xs font-medium bg-bg-tertiary text-text-secondary rounded-lg hover:bg-bg-hover border border-border-primary transition-colors">
Retry
</button>
</div>
)
}
if (!data || data.total === 0) {
return <EmptyState icon={Library} title="No collection matches" description="No cards in your collection match this deck's needs." />
}
const typeOrder = ['Creature', 'Instant', 'Sorcery', 'Artifact', 'Enchantment', 'Planeswalker', 'Land', 'Other']
const sortedTypes = Object.keys(data.grouped).sort((a, b) => {
const ia = typeOrder.indexOf(a)
const ib = typeOrder.indexOf(b)
return (ia === -1 ? 99 : ia) - (ib === -1 ? 99 : ib)
})
return (
<div className="space-y-4">
{/* Shortfall alert */}
{data.shortfall_types.length > 0 && (
<div className="flex items-start gap-3 bg-accent-blue/8 border border-accent-blue/20 rounded-xl px-4 py-3">
<Lightbulb className="w-4 h-4 text-accent-blue mt-0.5 flex-shrink-0" />
<div>
<p className="text-xs font-medium text-accent-blue">Deck needs more:</p>
<div className="flex flex-wrap gap-1.5 mt-1">
{data.shortfall_types.map(t => (
<span key={t} className="text-[10px] font-medium px-2 py-0.5 rounded bg-accent-blue/15 text-accent-blue border border-accent-blue/25">{t}</span>
))}
</div>
</div>
</div>
)}
{/* Selection toolbar */}
<div className="flex items-center justify-between bg-bg-secondary rounded-xl border border-border-primary px-4 py-3">
<div className="flex items-center gap-2">
<span className="text-xs text-text-tertiary">Select:</span>
<button onClick={selectAll} className="text-xs text-accent-blue hover:underline">All</button>
<span className="text-text-tertiary">/</span>
<button onClick={selectNone} className="text-xs text-accent-blue hover:underline">None</button>
{selectedCards.size > 0 && (
<span className="text-xs text-text-secondary ml-2">({selectedCards.size} selected)</span>
)}
</div>
<button
onClick={handleBulkAdd}
disabled={selectedCards.size === 0 || bulkAdding}
className="flex items-center gap-2 px-3 py-1.5 text-xs font-medium bg-accent-blue text-white rounded-lg hover:bg-accent-blue-hover transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
>
{bulkAdding ? <Spinner size="sm" /> : <ShoppingCart className="w-3.5 h-3.5" />}
Add {selectedCards.size > 0 ? selectedCards.size : ''} to Deck
</button>
</div>
{/* Grouped cards */}
{sortedTypes.map(type => {
const cards = data.grouped[type]
const isCollapsed = collapsedGroups.has(type)
const isShortfall = data.shortfall_types.includes(type)
return (
<div key={type} className={'bg-bg-secondary rounded-xl border overflow-hidden ' + (isShortfall ? 'border-accent-blue/30' : 'border-border-primary')}>
{/* Group header */}
<button
onClick={() => toggleGroup(type)}
className="w-full flex items-center justify-between px-4 py-3 hover:bg-bg-hover transition-colors"
>
<div className="flex items-center gap-2">
<span className="text-xs font-semibold text-text-primary uppercase tracking-wider">{type}</span>
<span className="text-xs text-text-tertiary">({cards.length})</span>
{isShortfall && <span className="text-[10px] font-medium px-1.5 py-0.5 rounded bg-accent-blue/15 text-accent-blue border border-accent-blue/25">Shortfall</span>}
</div>
{isCollapsed ? <ChevronDown className="w-4 h-4 text-text-tertiary" /> : <ChevronUp className="w-4 h-4 text-text-tertiary" />}
</button>
{/* Card list */}
{!isCollapsed && (
<div className="border-t border-border-primary divide-y divide-border-primary">
{cards.map(rec => (
<div key={rec.scryfall_id} className="flex items-center gap-3 px-4 py-2.5 hover:bg-bg-hover transition-colors group">
{/* Checkbox */}
<input
type="checkbox"
checked={selectedCards.has(rec.name)}
onChange={() => toggleSelect(rec.name)}
className="rounded border-border-primary bg-bg-tertiary text-accent-blue focus:ring-accent-blue/30 w-3.5 h-3.5 flex-shrink-0"
/>
{/* Card image mini */}
{rec.image_url && (
<div className="w-8 h-11 rounded overflow-hidden bg-bg-tertiary flex-shrink-0">
<img src={rec.image_url} alt={rec.name} className="w-full h-full object-cover" loading="lazy" />
</div>
)}
{/* Card info */}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-text-primary truncate">{rec.name}</p>
<div className="flex items-center gap-1.5 mt-0.5">
<span className="text-[10px] text-text-tertiary">{rec.cmc} CMC</span>
{rec.roles.length > 0 && rec.roles.map(r => <RoleBadge key={r} role={r} />)}
</div>
</div>
{/* Score */}
<span className="text-xs text-accent-teal font-medium flex-shrink-0">Score: {rec.score}</span>
{/* Owned qty */}
<span className="text-xs px-2 py-0.5 rounded bg-accent-green/15 text-accent-green flex-shrink-0">{rec.owned_qty}x</span>
{/* Add button */}
<button
onClick={e => { e.stopPropagation(); handleAddSingle(rec.name) }}
disabled={addingCards.has(rec.name)}
className="opacity-0 group-hover:opacity-100 px-2.5 py-1 text-xs font-medium bg-accent-blue text-white rounded-lg hover:bg-accent-blue-hover transition-all disabled:opacity-50 flex-shrink-0"
>
{addingCards.has(rec.name) ? <Spinner size="sm" /> : '+ Add'}
</button>
</div>
))}
</div>
)}
</div>
)
})}
</div>
)
}
// ── Deck Detail View ──────────────────────────────────────────
function DeckDetail({ deck, onBack }: { deck: Deck; onBack: () => void }) {
const [cards, setCards] = useState<DeckCard[]>([])
const [analysis, setAnalysis] = useState<DeckAnalysis | null>(null)
const [loading, setLoading] = useState(true)
const [tab, setTab] = useState<'cards' | 'analysis' | 'recs'>('cards')
const [recSource, setRecSource] = useState<'edhrec' | 'collection'>('edhrec')
const [addingCard, setAddingCard] = useState('')
const [bulkText, setBulkText] = useState('')
const [showBulk, setShowBulk] = useState(false)
async function fetchAll() {
setLoading(true)
try {
const [c, a] = await Promise.all([
decksApi.getDeckCards(deck.id),
decksApi.getDeckAnalysis(deck.id),
])
setCards(c)
setAnalysis(a)
} catch { /* ignore */ }
setLoading(false)
}
useEffect(() => { fetchAll() }, [deck.id])
async function handleAddCard() {
if (!addingCard.trim()) return
try {
await decksApi.addCardToDeck(deck.id, { name: addingCard.trim() })
setAddingCard('')
fetchAll()
} catch { /* ignore */ }
}
async function handleBulkAdd() {
if (!bulkText.trim()) return
const cardLines = bulkText.split('\n').filter(l => l.trim())
const cardParsed = cardLines.map(l => {
const match = l.match(/^(\d+)x?\s+(.+)$/)
return match ? { name: match[2].trim(), quantity: Number(match[1]) } : { name: l.trim() }
})
try {
await decksApi.bulkAddCards(deck.id, cardParsed)
setBulkText('')
setShowBulk(false)
fetchAll()
} catch { /* ignore */ }
}
async function handleExportToSim() {
try {
await decksApi.exportDeckToSim(deck.id)
} catch { /* ignore */ }
}
return (
<div className="space-y-5">
{/* Header */}
<div className="flex items-center gap-4">
<button onClick={onBack} className="p-2 rounded-lg hover:bg-bg-hover text-text-secondary transition-colors">
<ChevronRight className="w-5 h-5 rotate-180" />
</button>
<div className="flex-1">
<h2 className="text-xl font-bold text-text-primary">{deck.name}</h2>
<div className="flex items-center gap-3 mt-1">
<span className="text-sm text-text-secondary">{deck.commander}</span>
<ColorDots colors={deck.color_identity} />
<span className="text-xs text-text-tertiary">{deck.card_count} cards</span>
<span className="text-xs text-accent-teal">${deck.total_price.toFixed(2)}</span>
</div>
</div>
<button onClick={handleExportToSim}
className="flex items-center gap-2 px-3 py-2 text-xs font-medium bg-bg-tertiary text-text-secondary rounded-lg hover:bg-bg-hover border border-border-primary transition-colors">
<Download className="w-3.5 h-3.5" />
Export to Sim
</button>
</div>
{/* Tabs */}
<div className="flex gap-1 border-b border-border-primary">
{(['cards', 'analysis', 'recs'] as const).map(t => (
<button
key={t}
onClick={() => setTab(t)}
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors capitalize ${
tab === t
? 'border-accent-blue text-accent-blue'
: 'border-transparent text-text-tertiary hover:text-text-secondary'
}`}
>
{t === 'recs' ? 'Recommendations' : t}
</button>
))}
</div>
{loading ? (
<div className="flex items-center justify-center h-40"><Spinner size="lg" className="text-accent-blue" /></div>
) : tab === 'cards' ? (
<div className="space-y-4">
{/* Add card */}
<div className="flex items-center gap-2">
<input
type="text"
placeholder="Add card by name..."
value={addingCard}
onChange={e => setAddingCard(e.target.value)}
onKeyDown={e => e.key === 'Enter' && handleAddCard()}
className="flex-1 px-4 py-2.5 bg-bg-secondary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue/50 transition-all"
/>
<button onClick={handleAddCard}
className="px-4 py-2.5 bg-accent-blue text-white text-sm font-medium rounded-lg hover:bg-accent-blue-hover transition-colors">
Add
</button>
<button onClick={() => setShowBulk(!showBulk)}
className="px-3 py-2.5 bg-bg-tertiary text-text-secondary text-sm rounded-lg hover:bg-bg-hover border border-border-primary transition-colors">
<Layers className="w-4 h-4" />
</button>
</div>
{showBulk && (
<div className="bg-bg-secondary rounded-xl border border-border-primary p-4 animate-fade-in space-y-3">
<textarea
placeholder={"1x Sol Ring\n1x Command Tower\n2x Counterspell"}
value={bulkText}
onChange={e => setBulkText(e.target.value)}
rows={6}
className="w-full px-4 py-3 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary font-mono focus:outline-none focus:border-accent-blue/50 transition-all resize-none"
/>
<button onClick={handleBulkAdd}
className="px-4 py-2 bg-accent-blue text-white text-sm font-medium rounded-lg hover:bg-accent-blue-hover transition-colors">
Bulk Add
</button>
</div>
)}
<DeckCardList deckId={deck.id} cards={cards} onUpdate={fetchAll} />
</div>
) : tab === 'analysis' && analysis ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
{/* Stats */}
<div className="bg-bg-secondary rounded-xl border border-border-primary p-5 space-y-4">
<h3 className="text-sm font-semibold text-text-primary flex items-center gap-2">
<BarChart3 className="w-4 h-4 text-accent-blue" />
Deck Stats
</h3>
<div className="grid grid-cols-2 gap-3">
{[
{ label: 'Cards', value: analysis.card_count },
{ label: 'Lands', value: analysis.land_count },
{ label: 'Creatures', value: analysis.creature_count },
{ label: 'Non-Creature', value: analysis.noncreature_count },
{ label: 'Avg CMC', value: analysis.avg_cmc.toFixed(2) },
{ label: 'Owned', value: `${analysis.owned_count} / ${analysis.card_count}` },
].map(stat => (
<div key={stat.label} className="px-3 py-2 rounded-lg bg-bg-tertiary">
<p className="text-xs text-text-tertiary">{stat.label}</p>
<p className="text-lg font-bold text-text-primary">{stat.value}</p>
</div>
))}
</div>
</div>
{/* Mana Curve */}
<div className="bg-bg-secondary rounded-xl border border-border-primary p-5 space-y-4">
<h3 className="text-sm font-semibold text-text-primary">Mana Curve</h3>
<ManaCurveChart analysis={analysis} />
</div>
{/* Type Distribution */}
<div className="bg-bg-secondary rounded-xl border border-border-primary p-5 space-y-3 md:col-span-2">
<h3 className="text-sm font-semibold text-text-primary">Type Distribution</h3>
<div className="flex flex-wrap gap-2">
{Object.entries(analysis.type_distribution).map(([type, count]) => (
<span key={type} className="px-3 py-1.5 bg-bg-tertiary rounded-lg text-xs text-text-secondary">
{type}: <span className="font-semibold text-text-primary">{count}</span>
</span>
))}
</div>
</div>
</div>
) : tab === 'recs' ? (
<div className="space-y-4">
{/* Sub-tab toggle */}
<div className="flex items-center gap-1 bg-bg-tertiary rounded-lg p-1 w-fit">
<button
onClick={() => setRecSource('edhrec')}
className={'flex items-center gap-1.5 px-3.5 py-2 text-xs font-medium rounded-md transition-all ' +
(recSource === 'edhrec'
? 'bg-accent-blue text-white shadow-sm'
: 'text-text-tertiary hover:text-text-secondary')}
>
<Globe className="w-3.5 h-3.5" />
EDHREC
</button>
<button
onClick={() => setRecSource('collection')}
className={'flex items-center gap-1.5 px-3.5 py-2 text-xs font-medium rounded-md transition-all ' +
(recSource === 'collection'
? 'bg-accent-blue text-white shadow-sm'
: 'text-text-tertiary hover:text-text-secondary')}
>
<Library className="w-3.5 h-3.5" />
From Collection
</button>
</div>
{/* Sub-tab content */}
{recSource === 'edhrec' ? (
<EdhRecTab deckId={deck.id} onAddedCards={fetchAll} />
) : (
<CollectionRecTab deckId={deck.id} onAddedCards={fetchAll} />
)}
</div>
) : null}
</div>
)
}
// ── Main Decks Page ───────────────────────────────────────────
export function DecksPage() {
const [decks, setDecks] = useState<Deck[]>([])
const [loading, setLoading] = useState(true)
const [selectedDeck, setSelectedDeck] = useState<Deck | null>(null)
const [showCreate, setShowCreate] = useState(false)
const [newDeckName, setNewDeckName] = useState('')
const [newCommander, setNewCommander] = useState('')
const [creating, setCreating] = useState(false)
async function fetchDecks() {
setLoading(true)
try {
const d = await decksApi.listDecks()
setDecks(d)
} catch { /* ignore */ }
setLoading(false)
}
useEffect(() => { fetchDecks() }, [])
async function handleCreate() {
if (!newDeckName.trim()) return
setCreating(true)
try {
const deck = await decksApi.createDeck({ name: newDeckName.trim(), commander: newCommander.trim() || undefined })
setNewDeckName('')
setNewCommander('')
setShowCreate(false)
setSelectedDeck(deck)
fetchDecks()
} catch { /* ignore */ }
setCreating(false)
}
async function handleDelete(deckId: number) {
try {
await decksApi.deleteDeck(deckId)
fetchDecks()
} catch { /* ignore */ }
}
if (selectedDeck) {
return (
<div className="p-6">
<DeckDetail deck={selectedDeck} onBack={() => { setSelectedDeck(null); fetchDecks() }} />
</div>
)
}
return (
<div className="p-6 space-y-5">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-text-primary">Decks</h1>
<p className="text-sm text-text-secondary mt-0.5">{decks.length} deck{decks.length !== 1 ? 's' : ''}</p>
</div>
<button
onClick={() => setShowCreate(true)}
className="flex items-center gap-2 px-4 py-2.5 bg-accent-blue text-white text-sm font-medium rounded-lg hover:bg-accent-blue-hover transition-colors"
>
<Plus className="w-4 h-4" />
New Deck
</button>
</div>
{/* Create form */}
{showCreate && (
<div className="bg-bg-secondary rounded-xl border border-border-primary p-5 animate-fade-in space-y-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-text-primary">Create New Deck</h3>
<button onClick={() => setShowCreate(false)} className="text-text-tertiary hover:text-text-secondary">
<X className="w-4 h-4" />
</button>
</div>
<div className="grid grid-cols-2 gap-3">
<input
type="text"
placeholder="Deck name"
value={newDeckName}
onChange={e => setNewDeckName(e.target.value)}
className="px-4 py-2.5 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue/50 transition-all"
/>
<input
type="text"
placeholder="Commander (optional)"
value={newCommander}
onChange={e => setNewCommander(e.target.value)}
className="px-4 py-2.5 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue/50 transition-all"
/>
</div>
<button onClick={handleCreate} disabled={creating}
className="px-4 py-2 bg-accent-blue text-white text-sm font-medium rounded-lg hover:bg-accent-blue-hover transition-colors disabled:opacity-50">
{creating ? <Spinner size="sm" /> : 'Create'}
</button>
</div>
)}
{/* Deck list */}
{loading ? (
<div className="flex items-center justify-center h-40"><Spinner size="lg" className="text-accent-blue" /></div>
) : decks.length === 0 ? (
<EmptyState icon={Layers} title="No decks yet" description="Create your first deck to get started." />
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{decks.map(deck => (
<div
key={deck.id}
className="bg-bg-secondary rounded-xl border border-border-primary hover:border-border-secondary p-5 cursor-pointer transition-all group"
onClick={() => setSelectedDeck(deck)}
>
<div className="flex items-start justify-between mb-3">
<div className="min-w-0 flex-1">
<h3 className="text-base font-semibold text-text-primary truncate group-hover:text-accent-blue transition-colors">{deck.name}</h3>
<p className="text-sm text-text-secondary mt-0.5 truncate">{deck.commander}</p>
</div>
<button
onClick={e => { e.stopPropagation(); handleDelete(deck.id) }}
className="opacity-0 group-hover:opacity-100 p-1.5 text-text-tertiary hover:text-accent-red transition-all"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<ColorDots colors={deck.color_identity} />
<span className="text-xs text-text-tertiary">{deck.card_count} cards</span>
</div>
<span className="text-xs font-medium text-accent-teal">${deck.total_price.toFixed(2)}</span>
</div>
</div>
))}
</div>
)}
</div>
)
}
@@ -0,0 +1,284 @@
import { useState, useEffect } from 'react'
import {
Gamepad2, Play, Wifi, WifiOff, Settings,
AlertCircle, Trophy, Clock, Brain
} from 'lucide-react'
import { Spinner, StatusBadge } from '../components/common'
import { simApi, labApi } from '../api'
import { usePolling } from '../hooks/usePolling'
import type { SimStatus, SimResult, DeepSeekStatus, LabDeck } from '../types'
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from 'recharts'
export function SimulatorPage() {
const [decks, setDecks] = useState<LabDeck[]>([])
const [deckA, setDeckA] = useState('')
const [deckB, setDeckB] = useState('')
const [games, setGames] = useState(50)
const [useDeepSeek, setUseDeepSeek] = useState(false)
const [deepSeekDeck, setDeepSeekDeck] = useState('')
const [dsStatus, setDsStatus] = useState<DeepSeekStatus | null>(null)
const [running, setRunning] = useState(false)
const [simId, setSimId] = useState<string | null>(null)
const [simStatus, setSimStatus] = useState<SimStatus | null>(null)
const [result, setResult] = useState<SimResult | null>(null)
const [error, setError] = useState<string | null>(null)
const [starting, setStarting] = useState(false)
// DS config
const [showDsConfig, setShowDsConfig] = useState(false)
const [dsModel, setDsModel] = useState('')
const [dsUrl, setDsUrl] = useState('')
useEffect(() => {
labApi.getLabDecks().then(setDecks).catch(() => {})
simApi.getDeepSeekStatus().then(s => {
setDsStatus(s)
if (s.model) setDsModel(s.model)
if (s.base_url) setDsUrl(s.base_url)
}).catch(() => {})
}, [])
// Poll while running
usePolling(async () => {
if (!simId) return
try {
const s = await simApi.getSimStatus(simId)
setSimStatus(s)
if (!s.running) {
const r = await simApi.getSimResult(simId)
setResult(r)
setRunning(false)
}
} catch { /* ignore */ }
}, 2000, running)
async function handleStart() {
if (!deckA || !deckB) { setError('Select both decks'); return }
setStarting(true)
setError(null)
setResult(null)
try {
let res
if (useDeepSeek && deepSeekDeck) {
res = await simApi.runDeepSeekSim({ deck_a: deckA, deck_b: deckB, games, deepseek_deck: deepSeekDeck })
} else {
res = await simApi.runSim({ deck_a: deckA, deck_b: deckB, games })
}
setSimId(res.sim_id)
setRunning(true)
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to start')
}
setStarting(false)
}
async function handleDsConnect() {
try {
const s = await simApi.connectDeepSeek()
setDsStatus(s)
} catch { /* ignore */ }
}
async function handleDsConfigure() {
try {
const s = await simApi.configureDeepSeek({
model: dsModel || undefined,
base_url: dsUrl || undefined,
})
setDsStatus(s)
setShowDsConfig(false)
} catch { /* ignore */ }
}
return (
<div className="p-6 space-y-5">
<div>
<h1 className="text-2xl font-bold text-text-primary flex items-center gap-3">
<Gamepad2 className="w-6 h-6 text-accent-purple" />
Simulator
</h1>
<p className="text-sm text-text-secondary mt-0.5">Run head-to-head deck simulations</p>
</div>
{/* DeepSeek status */}
<div className="flex items-center gap-3">
<StatusBadge
variant={dsStatus?.connected ? 'success' : 'warning'}
label={dsStatus?.connected ? `DeepSeek: ${dsStatus.model}` : 'DeepSeek: Disconnected'}
/>
<button onClick={handleDsConnect}
className="flex items-center gap-1.5 text-xs text-text-tertiary hover:text-text-secondary transition-colors">
{dsStatus?.connected ? <Wifi className="w-3 h-3" /> : <WifiOff className="w-3 h-3" />}
{dsStatus?.connected ? 'Reconnect' : 'Connect'}
</button>
<button onClick={() => setShowDsConfig(!showDsConfig)}
className="flex items-center gap-1.5 text-xs text-text-tertiary hover:text-text-secondary transition-colors">
<Settings className="w-3 h-3" />
Configure
</button>
</div>
{showDsConfig && (
<div className="bg-bg-secondary rounded-xl border border-border-primary p-4 max-w-md animate-fade-in space-y-3">
<h3 className="text-sm font-semibold text-text-primary flex items-center gap-2">
<Brain className="w-4 h-4 text-accent-purple" />
DeepSeek Configuration
</h3>
<input
type="text"
placeholder="Model name"
value={dsModel}
onChange={e => setDsModel(e.target.value)}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue/50 transition-all"
/>
<input
type="text"
placeholder="Base URL (e.g. http://192.168.0.122:1234)"
value={dsUrl}
onChange={e => setDsUrl(e.target.value)}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary placeholder:text-text-tertiary focus:outline-none focus:border-accent-blue/50 transition-all"
/>
<button onClick={handleDsConfigure}
className="px-4 py-2 bg-accent-blue text-white text-sm font-medium rounded-lg hover:bg-accent-blue-hover transition-colors">
Save
</button>
</div>
)}
{/* Sim config */}
<div className="bg-bg-secondary rounded-xl border border-border-primary p-5 space-y-4 max-w-2xl">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Deck A</label>
<select
value={deckA}
onChange={e => setDeckA(e.target.value)}
className="mt-1 w-full px-3 py-2.5 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all"
>
<option value="">Select deck...</option>
{decks.map(d => <option key={d.name} value={d.name}>{d.name}</option>)}
</select>
</div>
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Deck B</label>
<select
value={deckB}
onChange={e => setDeckB(e.target.value)}
className="mt-1 w-full px-3 py-2.5 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all"
>
<option value="">Select deck...</option>
{decks.map(d => <option key={d.name} value={d.name}>{d.name}</option>)}
</select>
</div>
</div>
<div className="flex items-center gap-6">
<div>
<label className="text-xs text-text-tertiary uppercase tracking-wider">Games</label>
<input
type="number" min={1} max={1000}
value={games}
onChange={e => setGames(Number(e.target.value))}
className="mt-1 w-24 px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all"
/>
</div>
<label className="flex items-center gap-2 cursor-pointer mt-5">
<input type="checkbox" checked={useDeepSeek} onChange={e => setUseDeepSeek(e.target.checked)}
className="w-4 h-4 rounded border-border-primary bg-bg-tertiary text-accent-purple focus:ring-accent-purple/30" />
<span className="text-sm text-text-secondary">Use DeepSeek AI pilot</span>
</label>
{useDeepSeek && (
<div className="mt-5">
<select
value={deepSeekDeck}
onChange={e => setDeepSeekDeck(e.target.value)}
className="px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all"
>
<option value="">AI pilots which deck?</option>
{[deckA, deckB].filter(Boolean).map(d => <option key={d} value={d}>{d}</option>)}
</select>
</div>
)}
</div>
{error && (
<div className="flex items-center gap-2 px-4 py-2 bg-status-error/10 border border-status-error/30 rounded-lg text-sm text-status-error">
<AlertCircle className="w-4 h-4" />{error}
</div>
)}
{running ? (
<div className="flex items-center gap-3">
<Spinner size="md" className="text-accent-blue" />
<div>
<p className="text-sm text-text-primary">Simulation running...</p>
{simStatus && (
<p className="text-xs text-text-tertiary">
{simStatus.games_completed ?? 0} / {simStatus.total_games ?? games} games
</p>
)}
</div>
</div>
) : (
<button onClick={handleStart} disabled={starting || !deckA || !deckB}
className="flex items-center gap-2 px-5 py-2.5 bg-accent-purple/15 text-accent-purple text-sm font-semibold rounded-lg hover:bg-accent-purple/25 border border-accent-purple/30 transition-colors disabled:opacity-50">
{starting ? <Spinner size="sm" /> : <Play className="w-4 h-4" />}
Run Simulation
</button>
)}
</div>
{/* Results */}
{result && (
<div className="bg-bg-secondary rounded-xl border border-border-primary p-5 space-y-4 animate-fade-in">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-text-primary flex items-center gap-2">
<Trophy className="w-4 h-4 text-accent-amber" />
Results
</h3>
<span className="text-xs text-text-tertiary flex items-center gap-1.5">
<Clock className="w-3 h-3" />
{(result.duration_ms / 1000).toFixed(1)}s · {result.total_games} games
</span>
</div>
<div className="h-48">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={result.decks.map(d => ({ name: d.name, win_rate: Math.round(d.win_rate * 100) }))} barSize={40}>
<XAxis dataKey="name" tick={{ fill: '#9ba1b8', fontSize: 12 }} axisLine={false} tickLine={false} />
<YAxis domain={[0, 100]} tick={{ fill: '#6b7190', fontSize: 11 }} axisLine={false} tickLine={false} />
<Tooltip contentStyle={{ backgroundColor: '#1c2030', border: '1px solid #2a2f42', borderRadius: 8, fontSize: 12 }}
formatter={(value: unknown) => [`${value}%`, 'Win Rate']} />
<Bar dataKey="win_rate" radius={[4, 4, 0, 0]}>
{result.decks.map((d, i) => (
<Cell key={i} fill={d.win_rate === Math.max(...result.decks.map(x => x.win_rate)) ? '#4ade80' : '#4f6ef7'} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
<div className="grid grid-cols-2 gap-4">
{result.decks.map(d => (
<div key={d.name} className="px-4 py-3 rounded-lg bg-bg-tertiary">
<p className="text-sm font-semibold text-text-primary">{d.name}</p>
<div className="grid grid-cols-3 gap-2 mt-2">
<div>
<p className="text-[10px] text-text-tertiary uppercase">Wins</p>
<p className="text-lg font-bold text-accent-green">{d.wins}</p>
</div>
<div>
<p className="text-[10px] text-text-tertiary uppercase">Win Rate</p>
<p className="text-lg font-bold text-accent-blue">{(d.win_rate * 100).toFixed(1)}%</p>
</div>
<div>
<p className="text-[10px] text-text-tertiary uppercase">Avg Turn</p>
<p className="text-lg font-bold text-text-primary">{d.avg_turn.toFixed(1)}</p>
</div>
</div>
</div>
))}
</div>
</div>
)}
</div>
)
}
@@ -0,0 +1,822 @@
import { useState, useEffect, useCallback } from 'react'
import {
Brain, Play, RotateCw, Database, Trophy, AlertCircle,
Activity, Zap, Swords, FileText, Cpu, CheckCircle,
ChevronDown, ChevronUp, Settings
} from 'lucide-react'
import { Spinner, StatusBadge } from '../components/common'
import { trainingApi } from '../api'
import { usePolling } from '../hooks/usePolling'
import type {
MLStatus, MLDataStatus, MLTrainStatus, PPOTrainStatus,
TournamentStatus, MLModelInfo
} from '../types'
// ── Progress Bar ──────────────────────────────────────────────
function ProgressBar({ value, max, label, color = 'bg-accent-blue' }: { value: number; max: number; label: string; color?: string }) {
const pct = max > 0 ? Math.min((value / max) * 100, 100) : 0
return (
<div>
<div className="flex items-center justify-between text-xs mb-1">
<span className="text-text-secondary">{label}</span>
<span className="text-text-tertiary">{value} / {max} ({pct.toFixed(0)}%)</span>
</div>
<div className="w-full h-2 bg-bg-tertiary rounded-full overflow-hidden">
<div className={'h-full rounded-full transition-all duration-500 ' + color} style={{ width: `${pct}%` }} />
</div>
</div>
)
}
// ── Phase Badge ──────────────────────────────────────────────
const PHASE_STYLES: Record<string, string> = {
idle: 'bg-bg-tertiary text-text-tertiary',
starting: 'bg-accent-blue/15 text-accent-blue animate-pulse',
building: 'bg-accent-purple/15 text-accent-purple animate-pulse',
training: 'bg-accent-blue/15 text-accent-blue animate-pulse',
evaluating: 'bg-accent-teal/15 text-accent-teal animate-pulse',
running: 'bg-accent-amber/15 text-accent-amber animate-pulse',
done: 'bg-accent-green/15 text-accent-green',
error: 'bg-accent-red/15 text-accent-red',
}
function PhaseBadge({ phase }: { phase: string }) {
const cls = PHASE_STYLES[phase] || PHASE_STYLES.idle
return (
<span className={'text-[10px] font-semibold uppercase tracking-wider px-2 py-0.5 rounded ' + cls}>
{phase}
</span>
)
}
// ── Metric Card ──────────────────────────────────────────────
function MetricCard({ label, value, accent }: { label: string; value: string | number; accent?: string }) {
return (
<div className="px-3 py-2 bg-bg-tertiary rounded-lg">
<p className="text-[10px] text-text-tertiary">{label}</p>
<p className={'text-sm font-bold ' + (accent || 'text-text-primary')}>{value}</p>
</div>
)
}
// ── Collapsible Section ─────────────────────────────────────
function Section({ title, icon, children, defaultOpen = true, color = 'text-accent-blue' }: {
title: string; icon: React.ReactNode; children: React.ReactNode; defaultOpen?: boolean; color?: string
}) {
const [open, setOpen] = useState(defaultOpen)
return (
<div className="bg-bg-secondary rounded-xl border border-border-primary overflow-hidden">
<button
onClick={() => setOpen(!open)}
className="w-full flex items-center justify-between px-5 py-4 hover:bg-bg-hover transition-colors"
>
<h3 className="text-sm font-semibold text-text-primary flex items-center gap-2">
<span className={color}>{icon}</span>
{title}
</h3>
{open ? <ChevronUp className="w-4 h-4 text-text-tertiary" /> : <ChevronDown className="w-4 h-4 text-text-tertiary" />}
</button>
{open && <div className="px-5 pb-5 space-y-4 border-t border-border-primary pt-4">{children}</div>}
</div>
)
}
// ══════════════════════════════════════════════════════════════
// Main Training Page
// ══════════════════════════════════════════════════════════════
export function TrainingPage() {
// Status states
const [mlStatus, setMlStatus] = useState<MLStatus | null>(null)
const [dataStatus, setDataStatus] = useState<MLDataStatus | null>(null)
const [modelInfo, setModelInfo] = useState<MLModelInfo | null>(null)
const [trainStatus, setTrainStatus] = useState<MLTrainStatus | null>(null)
const [ppoStatus, setPpoStatus] = useState<PPOTrainStatus | null>(null)
const [tournStatus, setTournStatus] = useState<TournamentStatus | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
// Supervised training config
const [epochs, setEpochs] = useState(50)
const [lr, setLr] = useState(0.001)
const [batchSize, setBatchSize] = useState(256)
const [patience, setPatience] = useState(10)
const [rebuildDataset, setRebuildDataset] = useState(true)
// PPO config
const [ppoIterations, setPpoIterations] = useState(100)
const [ppoEpisodes, setPpoEpisodes] = useState(64)
const [ppoEpochs, setPpoEpochs] = useState(4)
const [ppoBatchSize, setPpoBatchSize] = useState(256)
const [ppoLr, setPpoLr] = useState(0.0003)
const [ppoClipEps, setPpoClipEps] = useState(0.2)
const [ppoEntropy, setPpoEntropy] = useState(0.01)
const [ppoOpponent, setPpoOpponent] = useState('heuristic')
const [ppoPlaystyle, _setPpoPlaystyle] = useState('midrange') // eslint-disable-line
// Tournament config
const [tournEpisodes, setTournEpisodes] = useState(50)
const [tournPlaystyle, setTournPlaystyle] = useState('midrange')
// Action states
const [startingTrain, setStartingTrain] = useState(false)
const [startingPpo, setStartingPpo] = useState(false)
const [startingTourn, setStartingTourn] = useState(false)
const [reloading, setReloading] = useState(false)
const [showSupAdvanced, setShowSupAdvanced] = useState(false)
const [showPpoAdvanced, setShowPpoAdvanced] = useState(false)
// ── Initial Load ──────────────────────────────────────────
const loadAll = useCallback(async () => {
try {
const [ml, data, model, train, ppo, tourn] = await Promise.all([
trainingApi.getMLStatus().catch(() => null),
trainingApi.getDataStatus().catch(() => null),
trainingApi.getModelInfo().catch(() => null),
trainingApi.getTrainStatus().catch(() => null),
trainingApi.getPPOStatus().catch(() => null),
trainingApi.getTournamentStatus().catch(() => null),
])
if (ml) setMlStatus(ml)
if (data) setDataStatus(data)
if (model) setModelInfo(model)
if (train) setTrainStatus(train)
if (ppo) setPpoStatus(ppo)
if (tourn) setTournStatus(tourn)
} catch { /* ignore */ }
setLoading(false)
}, [])
useEffect(() => { loadAll() }, [loadAll])
// ── Polling ───────────────────────────────────────────────
const isTraining = trainStatus?.running || false
const isPpo = ppoStatus?.running || false
const isTourn = tournStatus?.running || false
const anyRunning = isTraining || isPpo || isTourn
usePolling(async () => {
try {
const s = await trainingApi.getTrainStatus()
setTrainStatus(s)
if (!s.running && s.phase === 'done') {
// Refresh model info + data when training completes
const [model, data] = await Promise.all([
trainingApi.getModelInfo().catch(() => null),
trainingApi.getDataStatus().catch(() => null),
])
if (model) setModelInfo(model)
if (data) setDataStatus(data)
}
} catch { /* ignore */ }
}, 2000, isTraining)
usePolling(async () => {
try {
const s = await trainingApi.getPPOStatus()
setPpoStatus(s)
if (!s.running && s.phase === 'done') {
const [model, data] = await Promise.all([
trainingApi.getModelInfo().catch(() => null),
trainingApi.getDataStatus().catch(() => null),
])
if (model) setModelInfo(model)
if (data) setDataStatus(data)
}
} catch { /* ignore */ }
}, 2000, isPpo)
usePolling(async () => {
try {
const s = await trainingApi.getTournamentStatus()
setTournStatus(s)
} catch { /* ignore */ }
}, 2000, isTourn)
// ── Actions ───────────────────────────────────────────────
async function handleToggleLogging() {
try {
const newState = !(mlStatus?.ml_logging_enabled ?? false)
await trainingApi.toggleML(newState)
const ml = await trainingApi.getMLStatus()
setMlStatus(ml)
} catch { /* ignore */ }
}
async function handleReloadModel() {
setReloading(true)
try {
const res = await trainingApi.reloadModel()
setModelInfo(res.status)
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to reload model')
}
setReloading(false)
}
async function handleStartTrain() {
setStartingTrain(true)
setError(null)
try {
await trainingApi.startTraining({ epochs, lr, batchSize, patience, rebuildDataset })
const s = await trainingApi.getTrainStatus()
setTrainStatus(s)
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to start training')
}
setStartingTrain(false)
}
async function handleStartPpo() {
setStartingPpo(true)
setError(null)
try {
await trainingApi.startPPOTraining({
iterations: ppoIterations,
episodesPerIter: ppoEpisodes,
ppoEpochs,
batchSize: ppoBatchSize,
lr: ppoLr,
clipEpsilon: ppoClipEps,
entropyCoeff: ppoEntropy,
opponent: ppoOpponent,
playstyle: ppoPlaystyle,
})
const s = await trainingApi.getPPOStatus()
setPpoStatus(s)
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to start PPO training')
}
setStartingPpo(false)
}
async function handleStartTournament() {
setStartingTourn(true)
setError(null)
try {
await trainingApi.startTournament({ episodes: tournEpisodes, playstyle: tournPlaystyle })
const s = await trainingApi.getTournamentStatus()
setTournStatus(s)
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to start tournament')
}
setStartingTourn(false)
}
// ── Render ────────────────────────────────────────────────
if (loading) {
return <div className="p-6 flex items-center justify-center h-64"><Spinner size="lg" className="text-accent-blue" /></div>
}
const trainDataset = dataStatus?.datasets?.['train']
const hasDecisions = (mlStatus?.total_decisions ?? 0) > 0
const hasModel = modelInfo?.loaded === true
return (
<div className="p-6 space-y-5">
{/* Page Header */}
<div>
<h1 className="text-2xl font-bold text-text-primary flex items-center gap-3">
<Brain className="w-6 h-6 text-accent-green" />
ML Training Pipeline
</h1>
<p className="text-sm text-text-secondary mt-0.5">Collect data, train models, and evaluate performance</p>
</div>
{/* Error banner */}
{error && (
<div className="flex items-center gap-2 px-4 py-2 bg-accent-red/10 border border-accent-red/30 rounded-lg text-sm text-accent-red">
<AlertCircle className="w-4 h-4 flex-shrink-0" />
<span className="flex-1">{error}</span>
<button onClick={() => setError(null)} className="text-accent-red/60 hover:text-accent-red text-xs">dismiss</button>
</div>
)}
{/* Pipeline overview bar */}
<div className="flex flex-wrap items-center gap-3 bg-bg-secondary rounded-xl border border-border-primary px-5 py-3">
<div className="flex items-center gap-2">
<div className={'w-2 h-2 rounded-full ' + (mlStatus?.ml_logging_enabled ? 'bg-accent-green' : 'bg-text-tertiary')} />
<span className="text-xs text-text-secondary">Logging {mlStatus?.ml_logging_enabled ? 'On' : 'Off'}</span>
</div>
<span className="text-border-primary">|</span>
<span className="text-xs text-text-secondary">{mlStatus?.total_decisions ?? 0} decisions</span>
<span className="text-border-primary">|</span>
<span className="text-xs text-text-secondary">{trainDataset ? `${trainDataset.samples.toLocaleString()} training samples` : 'No dataset'}</span>
<span className="text-border-primary">|</span>
<span className="text-xs text-text-secondary">{(dataStatus?.checkpoints?.length ?? 0)} checkpoints</span>
<span className="text-border-primary">|</span>
<StatusBadge
variant={hasModel ? 'success' : 'neutral'}
label={hasModel ? `Model on ${modelInfo?.device ?? '?'}` : 'No model'}
/>
{anyRunning && (
<>
<span className="text-border-primary">|</span>
<span className="text-xs font-medium text-accent-blue animate-pulse">Pipeline running...</span>
</>
)}
</div>
{/* ═══ Phase 1: Data Collection ═══ */}
<Section title="Phase 1 — Data Collection" icon={<FileText className="w-4 h-4" />} color="text-accent-teal">
<div className="flex items-center justify-between">
<p className="text-xs text-text-secondary">
Run batch simulations with ML logging enabled to collect decision data.
</p>
<button
onClick={handleToggleLogging}
className={'flex items-center gap-2 px-3 py-1.5 text-xs font-medium rounded-lg border transition-colors ' +
(mlStatus?.ml_logging_enabled
? 'bg-accent-green/15 text-accent-green border-accent-green/30 hover:bg-accent-green/25'
: 'bg-bg-tertiary text-text-secondary border-border-primary hover:bg-bg-hover'
)}
>
<div className={'w-2 h-2 rounded-full ' + (mlStatus?.ml_logging_enabled ? 'bg-accent-green' : 'bg-text-tertiary')} />
{mlStatus?.ml_logging_enabled ? 'Logging Enabled' : 'Enable Logging'}
</button>
</div>
{/* Decision files */}
{(dataStatus?.decisionFiles?.length ?? 0) > 0 ? (
<div className="space-y-1">
<h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider">Decision Files</h4>
<div className="max-h-36 overflow-y-auto space-y-1">
{dataStatus!.decisionFiles.map(f => (
<div key={f.name} className="flex items-center justify-between px-3 py-1.5 bg-bg-tertiary rounded-lg text-xs">
<span className="text-text-secondary font-mono truncate">{f.name}</span>
<div className="flex items-center gap-3 text-text-tertiary">
<span>{f.decisions.toLocaleString()} decisions</span>
<span>{(f.size / 1024).toFixed(0)} KB</span>
</div>
</div>
))}
</div>
</div>
) : (
<div className="text-xs text-text-tertiary italic">No decision files yet. Run batch sims with logging enabled.</div>
)}
</Section>
{/* ═══ Phase 2: Dataset & Checkpoints ═══ */}
<Section title="Phase 2 — Dataset & Model Artifacts" icon={<Database className="w-4 h-4" />} color="text-accent-purple">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Dataset splits */}
<div className="space-y-2">
<h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider">Dataset Splits</h4>
{Object.keys(dataStatus?.datasets ?? {}).length > 0 ? (
<div className="grid grid-cols-3 gap-2">
{(['train', 'val', 'test'] as const).map(split => {
const ds = dataStatus?.datasets?.[split]
return (
<div key={split} className="px-3 py-2 bg-bg-tertiary rounded-lg">
<p className="text-[10px] text-text-tertiary uppercase">{split}</p>
{ds ? (
<>
<p className="text-sm font-bold text-text-primary">{ds.samples.toLocaleString()}</p>
<p className="text-[10px] text-text-tertiary">{ds.features} features</p>
</>
) : (
<p className="text-xs text-text-tertiary italic">Not built</p>
)}
</div>
)
})}
</div>
) : (
<p className="text-xs text-text-tertiary italic">No dataset built yet. Training will build it automatically.</p>
)}
</div>
{/* Checkpoints */}
<div className="space-y-2">
<h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider">Checkpoints</h4>
{(dataStatus?.checkpoints?.length ?? 0) > 0 ? (
<div className="max-h-28 overflow-y-auto space-y-1">
{dataStatus!.checkpoints.map(ckpt => (
<div key={ckpt.name} className="flex items-center justify-between px-3 py-1.5 bg-bg-tertiary rounded-lg text-xs">
<span className="text-text-secondary font-mono truncate">{ckpt.name}</span>
<span className="text-text-tertiary">{(ckpt.size / 1024 / 1024).toFixed(1)} MB</span>
</div>
))}
</div>
) : (
<p className="text-xs text-text-tertiary italic">No checkpoints yet. Train a model to generate them.</p>
)}
</div>
</div>
{/* Model info + reload */}
<div className="flex items-center justify-between pt-2 border-t border-border-primary">
<div className="flex items-center gap-3">
<Cpu className="w-4 h-4 text-text-tertiary" />
<div className="text-xs">
{hasModel ? (
<span className="text-accent-green font-medium">
Model loaded on {modelInfo?.device} | {modelInfo?.input_dim} features | {modelInfo?.num_actions} actions
</span>
) : (
<span className="text-text-tertiary">No model loaded{modelInfo?.error ? ` — ${modelInfo.error}` : ''}</span>
)}
</div>
</div>
<button
onClick={handleReloadModel}
disabled={reloading}
className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium bg-bg-tertiary text-text-secondary rounded-lg hover:bg-bg-hover border border-border-primary transition-colors disabled:opacity-50"
>
{reloading ? <Spinner size="sm" /> : <RotateCw className="w-3 h-3" />}
Reload Model
</button>
</div>
{/* Eval results */}
{dataStatus?.evalResults && (
<div className="pt-2 border-t border-border-primary space-y-2">
<h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider flex items-center gap-2">
<CheckCircle className="w-3.5 h-3.5 text-accent-green" />
Latest Evaluation
</h4>
<div className="grid grid-cols-2 md:grid-cols-4 gap-2">
{Object.entries(dataStatus.evalResults).map(([k, v]) => (
<MetricCard
key={k}
label={k.replace(/_/g, ' ')}
value={typeof v === 'number' ? (k.includes('accuracy') || k.includes('rate') ? `${(v * 100).toFixed(1)}%` : v.toFixed(4)) : String(v)}
accent={k.includes('accuracy') ? 'text-accent-green' : undefined}
/>
))}
</div>
</div>
)}
</Section>
{/* ═══ Phase 3: Supervised Training ═══ */}
<Section title="Phase 3 — Supervised Training" icon={<Activity className="w-4 h-4" />}>
{/* Config */}
<div className="space-y-3">
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs text-text-tertiary block mb-1">Epochs</label>
<input type="number" min={1} max={1000} value={epochs} onChange={e => setEpochs(Number(e.target.value))}
disabled={isTraining}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
<div>
<label className="text-xs text-text-tertiary block mb-1">Learning Rate</label>
<input type="number" min={0.00001} max={1} step={0.0001} value={lr} onChange={e => setLr(Number(e.target.value))}
disabled={isTraining}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
</div>
{/* Advanced toggle */}
<button onClick={() => setShowSupAdvanced(!showSupAdvanced)} className="flex items-center gap-1 text-xs text-text-tertiary hover:text-text-secondary transition-colors">
<Settings className="w-3 h-3" />
{showSupAdvanced ? 'Hide' : 'Show'} advanced options
</button>
{showSupAdvanced && (
<div className="grid grid-cols-3 gap-3 animate-fade-in">
<div>
<label className="text-xs text-text-tertiary block mb-1">Batch Size</label>
<input type="number" min={16} max={2048} value={batchSize} onChange={e => setBatchSize(Number(e.target.value))}
disabled={isTraining}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
<div>
<label className="text-xs text-text-tertiary block mb-1">Early Stop Patience</label>
<input type="number" min={1} max={100} value={patience} onChange={e => setPatience(Number(e.target.value))}
disabled={isTraining}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
<div className="flex items-end pb-1">
<label className="flex items-center gap-2 text-xs text-text-secondary cursor-pointer select-none">
<input type="checkbox" checked={rebuildDataset} onChange={e => setRebuildDataset(e.target.checked)}
disabled={isTraining}
className="rounded border-border-primary bg-bg-tertiary text-accent-blue focus:ring-accent-blue/30 w-3.5 h-3.5" />
Rebuild dataset
</label>
</div>
</div>
)}
</div>
{/* Training status / start button */}
{isTraining || (trainStatus?.phase && trainStatus.phase !== 'idle') ? (
<div className="space-y-3 bg-bg-tertiary/50 rounded-xl p-4 border border-border-primary">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<PhaseBadge phase={trainStatus!.phase} />
<span className="text-xs text-text-secondary">{trainStatus!.message}</span>
</div>
{trainStatus!.started_at && (
<span className="text-[10px] text-text-tertiary">Started: {new Date(trainStatus!.started_at).toLocaleTimeString()}</span>
)}
</div>
{/* Progress bar — only in training phase */}
{(trainStatus!.phase === 'training' || trainStatus!.phase === 'done') && trainStatus!.total_epochs > 0 && (
<ProgressBar
value={trainStatus!.current_epoch}
max={trainStatus!.total_epochs}
label="Epoch progress"
/>
)}
{/* Live metrics during training */}
{trainStatus!.metrics && (
<div className="grid grid-cols-2 md:grid-cols-4 gap-2">
{Object.entries(trainStatus!.metrics).map(([k, v]) => {
if (typeof v !== 'number') return null
const isAcc = k.includes('accuracy') || k.includes('acc')
const isLoss = k.includes('loss')
return (
<MetricCard
key={k}
label={k.replace(/_/g, ' ')}
value={isAcc ? `${(v * 100).toFixed(1)}%` : v.toFixed(4)}
accent={isAcc ? 'text-accent-green' : isLoss ? 'text-accent-amber' : undefined}
/>
)
})}
</div>
)}
{/* Final result */}
{trainStatus!.phase === 'done' && trainStatus!.result && (
<div className="pt-2 border-t border-border-primary space-y-2">
<h4 className="text-xs font-semibold text-accent-green flex items-center gap-1.5">
<CheckCircle className="w-3.5 h-3.5" /> Training Complete
</h4>
<div className="grid grid-cols-2 md:grid-cols-4 gap-2">
<MetricCard label="Device" value={trainStatus!.result.device} />
<MetricCard label="Checkpoint" value={trainStatus!.result.checkpoint.split('/').pop() || '—'} />
{trainStatus!.result.evaluation && Object.entries(trainStatus!.result.evaluation).map(([k, v]) => (
typeof v === 'number' ? (
<MetricCard key={k} label={k.replace(/_/g, ' ')}
value={k.includes('accuracy') ? `${(v * 100).toFixed(1)}%` : v.toFixed(4)}
accent={k.includes('accuracy') ? 'text-accent-green' : undefined} />
) : null
))}
</div>
</div>
)}
{/* Error state */}
{trainStatus!.phase === 'error' && trainStatus!.error && (
<div className="flex items-start gap-2 bg-accent-red/10 border border-accent-red/20 rounded-lg px-3 py-2">
<AlertCircle className="w-4 h-4 text-accent-red mt-0.5 flex-shrink-0" />
<span className="text-xs text-accent-red">{trainStatus!.error}</span>
</div>
)}
</div>
) : (
<div className="flex items-center gap-3">
<button
onClick={handleStartTrain}
disabled={startingTrain || !hasDecisions || isPpo}
className="flex items-center gap-2 px-4 py-2.5 bg-accent-blue/15 text-accent-blue text-sm font-medium rounded-lg hover:bg-accent-blue/25 border border-accent-blue/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
>
{startingTrain ? <Spinner size="sm" /> : <Play className="w-4 h-4" />}
Start Training
</button>
{!hasDecisions && (
<span className="text-xs text-text-tertiary italic">Enable logging and run batch sims first to generate decision data.</span>
)}
</div>
)}
</Section>
{/* ═══ Phase 4: PPO Reinforcement Learning ═══ */}
<Section title="Phase 4 — PPO Reinforcement Learning" icon={<Zap className="w-4 h-4" />} color="text-accent-purple" defaultOpen={false}>
<p className="text-xs text-text-secondary">
Fine-tune the supervised model using PPO self-play against an opponent policy.
</p>
{/* Config */}
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs text-text-tertiary block mb-1">Iterations</label>
<input type="number" min={1} max={1000} value={ppoIterations} onChange={e => setPpoIterations(Number(e.target.value))}
disabled={isPpo}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
<div>
<label className="text-xs text-text-tertiary block mb-1">Opponent</label>
<select value={ppoOpponent} onChange={e => setPpoOpponent(e.target.value)}
disabled={isPpo}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50">
<option value="heuristic">Heuristic</option>
<option value="random">Random</option>
<option value="self">Self-Play</option>
</select>
</div>
</div>
<button onClick={() => setShowPpoAdvanced(!showPpoAdvanced)} className="flex items-center gap-1 text-xs text-text-tertiary hover:text-text-secondary transition-colors">
<Settings className="w-3 h-3" />
{showPpoAdvanced ? 'Hide' : 'Show'} advanced options
</button>
{showPpoAdvanced && (
<div className="grid grid-cols-3 gap-3 animate-fade-in">
<div>
<label className="text-xs text-text-tertiary block mb-1">Episodes / Iter</label>
<input type="number" min={1} max={512} value={ppoEpisodes} onChange={e => setPpoEpisodes(Number(e.target.value))}
disabled={isPpo}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
<div>
<label className="text-xs text-text-tertiary block mb-1">PPO Epochs</label>
<input type="number" min={1} max={20} value={ppoEpochs} onChange={e => setPpoEpochs(Number(e.target.value))}
disabled={isPpo}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
<div>
<label className="text-xs text-text-tertiary block mb-1">Batch Size</label>
<input type="number" min={16} max={2048} value={ppoBatchSize} onChange={e => setPpoBatchSize(Number(e.target.value))}
disabled={isPpo}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
<div>
<label className="text-xs text-text-tertiary block mb-1">Learning Rate</label>
<input type="number" min={0.000001} max={0.01} step={0.0001} value={ppoLr} onChange={e => setPpoLr(Number(e.target.value))}
disabled={isPpo}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
<div>
<label className="text-xs text-text-tertiary block mb-1">Clip Epsilon</label>
<input type="number" min={0.05} max={0.5} step={0.05} value={ppoClipEps} onChange={e => setPpoClipEps(Number(e.target.value))}
disabled={isPpo}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
<div>
<label className="text-xs text-text-tertiary block mb-1">Entropy Coeff</label>
<input type="number" min={0} max={0.1} step={0.005} value={ppoEntropy} onChange={e => setPpoEntropy(Number(e.target.value))}
disabled={isPpo}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
</div>
)}
{/* PPO running status */}
{isPpo || (ppoStatus?.phase && ppoStatus.phase !== 'idle') ? (
<div className="space-y-3 bg-bg-tertiary/50 rounded-xl p-4 border border-border-primary">
<div className="flex items-center gap-2">
<PhaseBadge phase={ppoStatus!.phase} />
<span className="text-xs text-text-secondary">{ppoStatus!.message}</span>
</div>
{(ppoStatus!.phase === 'training' || ppoStatus!.phase === 'done') && ppoStatus!.total_iterations > 0 && (
<ProgressBar
value={ppoStatus!.iteration}
max={ppoStatus!.total_iterations}
label="PPO iteration"
color="bg-accent-purple"
/>
)}
{ppoStatus!.metrics && (
<div className="grid grid-cols-2 md:grid-cols-4 gap-2">
{ppoStatus!.metrics.win_rate != null && (
<MetricCard label="Win Rate" value={`${(ppoStatus!.metrics.win_rate * 100).toFixed(1)}%`} accent="text-accent-green" />
)}
{ppoStatus!.metrics.avg_reward != null && (
<MetricCard label="Avg Reward" value={ppoStatus!.metrics.avg_reward.toFixed(3)} accent="text-accent-amber" />
)}
{ppoStatus!.metrics.policy_loss != null && (
<MetricCard label="Policy Loss" value={ppoStatus!.metrics.policy_loss.toFixed(4)} />
)}
{ppoStatus!.metrics.entropy != null && (
<MetricCard label="Entropy" value={ppoStatus!.metrics.entropy.toFixed(4)} />
)}
</div>
)}
{ppoStatus!.phase === 'done' && ppoStatus!.result && (
<div className="flex items-center gap-2 pt-2 border-t border-border-primary">
<CheckCircle className="w-3.5 h-3.5 text-accent-green" />
<span className="text-xs text-accent-green font-medium">
PPO Training Complete — Best Win Rate: {
typeof ppoStatus!.result.best_win_rate === 'number'
? `${(ppoStatus!.result.best_win_rate as number * 100).toFixed(1)}%`
: '—'
}
</span>
</div>
)}
{ppoStatus!.phase === 'error' && ppoStatus!.error && (
<div className="flex items-start gap-2 bg-accent-red/10 border border-accent-red/20 rounded-lg px-3 py-2">
<AlertCircle className="w-4 h-4 text-accent-red mt-0.5 flex-shrink-0" />
<span className="text-xs text-accent-red">{ppoStatus!.error}</span>
</div>
)}
</div>
) : (
<button
onClick={handleStartPpo}
disabled={startingPpo || isTraining || !hasModel}
className="flex items-center gap-2 px-4 py-2.5 bg-accent-purple/15 text-accent-purple text-sm font-medium rounded-lg hover:bg-accent-purple/25 border border-accent-purple/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
>
{startingPpo ? <Spinner size="sm" /> : <Play className="w-4 h-4" />}
Start PPO Training
</button>
)}
{!hasModel && !(isPpo || (ppoStatus?.phase && ppoStatus.phase !== 'idle')) && (
<p className="text-xs text-text-tertiary italic">Train a supervised model first (Phase 3) before running PPO.</p>
)}
</Section>
{/* ═══ Phase 5: Tournament Evaluation ═══ */}
<Section title="Phase 5 — Tournament Evaluation" icon={<Swords className="w-4 h-4" />} color="text-accent-amber" defaultOpen={false}>
<p className="text-xs text-text-secondary">
Pit the trained model against heuristic, random, and other policy variants.
</p>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs text-text-tertiary block mb-1">Episodes per Matchup</label>
<input type="number" min={10} max={1000} value={tournEpisodes} onChange={e => setTournEpisodes(Number(e.target.value))}
disabled={isTourn}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50" />
</div>
<div>
<label className="text-xs text-text-tertiary block mb-1">Playstyle</label>
<select value={tournPlaystyle} onChange={e => setTournPlaystyle(e.target.value)}
disabled={isTourn}
className="w-full px-3 py-2 bg-bg-tertiary border border-border-primary rounded-lg text-sm text-text-primary focus:outline-none focus:border-accent-blue/50 transition-all disabled:opacity-50">
<option value="midrange">Midrange</option>
<option value="aggro">Aggro</option>
<option value="control">Control</option>
<option value="combo">Combo</option>
</select>
</div>
</div>
{/* Tournament status */}
{isTourn || (tournStatus?.phase && tournStatus.phase !== 'idle') ? (
<div className="space-y-3 bg-bg-tertiary/50 rounded-xl p-4 border border-border-primary">
<div className="flex items-center gap-2">
<PhaseBadge phase={tournStatus!.phase} />
<span className="text-xs text-text-secondary">{tournStatus!.message}</span>
</div>
{tournStatus!.phase === 'error' && tournStatus!.error && (
<div className="flex items-start gap-2 bg-accent-red/10 border border-accent-red/20 rounded-lg px-3 py-2">
<AlertCircle className="w-4 h-4 text-accent-red mt-0.5 flex-shrink-0" />
<span className="text-xs text-accent-red">{tournStatus!.error}</span>
</div>
)}
</div>
) : (
<button
onClick={handleStartTournament}
disabled={startingTourn || isTraining || isPpo}
className="flex items-center gap-2 px-4 py-2.5 bg-accent-amber/15 text-accent-amber text-sm font-medium rounded-lg hover:bg-accent-amber/25 border border-accent-amber/30 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
>
{startingTourn ? <Spinner size="sm" /> : <Trophy className="w-4 h-4" />}
Start Tournament
</button>
)}
{/* Tournament results */}
{(tournStatus?.result?.players?.length ?? 0) > 0 && (
<div className="pt-2 border-t border-border-primary space-y-2">
<h4 className="text-xs font-semibold text-text-tertiary uppercase tracking-wider flex items-center gap-2">
<Trophy className="w-3.5 h-3.5 text-accent-amber" />
Leaderboard
</h4>
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border-primary">
<th className="px-3 py-2 text-left text-xs text-text-tertiary font-medium w-8">#</th>
<th className="px-3 py-2 text-left text-xs text-text-tertiary font-medium">Policy</th>
<th className="px-3 py-2 text-right text-xs text-text-tertiary font-medium">Wins</th>
<th className="px-3 py-2 text-right text-xs text-text-tertiary font-medium">Games</th>
<th className="px-3 py-2 text-right text-xs text-text-tertiary font-medium">Win Rate</th>
</tr>
</thead>
<tbody className="divide-y divide-border-primary">
{tournStatus!.result!.players
.sort((a, b) => b.win_rate - a.win_rate)
.map((p, i) => (
<tr key={p.name} className="hover:bg-bg-hover transition-colors">
<td className="px-3 py-2 text-text-tertiary text-xs">
{i === 0 ? <Trophy className="w-3.5 h-3.5 text-accent-amber" /> : i + 1}
</td>
<td className="px-3 py-2">
<span className="text-text-primary font-medium capitalize">{p.name}</span>
</td>
<td className="px-3 py-2 text-right text-text-secondary">{p.wins}</td>
<td className="px-3 py-2 text-right text-text-secondary">{p.games}</td>
<td className={'px-3 py-2 text-right font-semibold ' + (i === 0 ? 'text-accent-green' : 'text-accent-blue')}>
{(p.win_rate * 100).toFixed(1)}%
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</Section>
</div>
)
}
@@ -0,0 +1,563 @@
// ═══════════════════════════════════════════════════════════
// Commander AI Lab — TypeScript Type Definitions
// Derived from the FastAPI backend's Pydantic models + SQLite schema
// ═══════════════════════════════════════════════════════════
// ── Cards & Collection ──────────────────────────────────────
export interface CollectionCard {
id: number
name: string
scryfall_id: string
set_code: string
set_name: string
collector_number: string
rarity: string
type_line: string
mana_cost: string
cmc: number
oracle_text: string
color_identity: string[]
quantity: number
foil_quantity: number
condition: string
tcg_price: number | null
foil_price: number | null
image_url: string
edhrec_rank: number | null
keywords: string
added_date: string
updated_date: string
}
export interface CollectionFilters {
q?: string
type_line?: string
color?: string
rarity?: string
set_code?: string
cmc_min?: number
cmc_max?: number
price_min?: number
price_max?: number
owned_only?: boolean
sort_by?: string
sort_dir?: 'asc' | 'desc'
page?: number
page_size?: number
}
export interface CollectionStats {
total_cards: number
total_unique: number
total_value: number
sets_count: number
}
export interface SetInfo {
code: string
name: string
card_count?: number
}
// ── Scan ─────────────────────────────────────────────────────
export interface ScanResult {
matches: ScanMatch[]
image_url?: string
}
export interface ScanMatch {
name: string
set_code: string
set_name: string
collector_number: string
scryfall_id: string
confidence: number
image_url: string
type_line: string
oracle_text: string
mana_cost: string
tcg_price: number | null
}
// ── Decks ────────────────────────────────────────────────────
export interface Deck {
id: number
name: string
commander: string
commander_scryfall_id?: string
commander_image_url?: string
color_identity: string[]
format: string
card_count: number
total_price: number
created_date: string
updated_date: string
}
export interface DeckCard {
id: number
deck_id: number
name: string
scryfall_id: string
quantity: number
is_commander: boolean
category: string
type_line: string
mana_cost: string
cmc: number
oracle_text: string
tcg_price: number | null
image_url: string
owned_qty: number
set_code: string
}
export interface DeckAnalysis {
card_count: number
land_count: number
creature_count: number
noncreature_count: number
avg_cmc: number
mana_curve: Record<number, number>
color_distribution: Record<string, number>
type_distribution: Record<string, number>
total_price: number
owned_count: number
missing_count: number
}
export interface DeckRecommendation {
name: string
scryfall_id: string
type_line: string
mana_cost: string
oracle_text: string
image_url: string
tcg_price: number | null
reason: string
score: number
owned: boolean
}
// ── EDHREC Recommendations ──────────────────────────────────
export interface EdhRecCard {
name: string
type_line: string
role: string
roles: string[]
inclusion_pct: number | null
synergy_score: number | null
owned: boolean
owned_qty: number
scryfall_id: string
image_url: string | null
}
export interface EdhRecsResponse {
commander: string
source: string
total: number
recommendations: EdhRecCard[]
}
// ── Collection Recommendations ──────────────────────────────
export interface CollectionRecCard {
id: number
scryfall_id: string
name: string
type_line: string
card_type: string
cmc: number
color_identity: string[]
owned_qty: number
roles: string[]
score: number
image_url: string | null
}
export interface CollectionRecsResponse {
shortfall_types: string[]
role_filter: string[]
grouped: Record<string, CollectionRecCard[]>
total: number
}
// ── V3 Deck Generator ────────────────────────────────────────
export interface DeckGenV3Request {
commander_name: string
strategy?: string
target_bracket: number
budget_usd?: number
budget_mode?: 'total' | 'per_card'
omit_cards?: string[]
use_collection?: boolean
run_substitution?: boolean
model?: string
deck_name?: string
}
export interface DeckGenV3Status {
initialized: boolean
pplx_configured: boolean
model: string | null
embeddings_loaded: boolean
embedding_cards: number
error: string | null
}
export interface DeckGenV3Card {
name: string
quantity: number
category: string
type_line: string
mana_cost: string
cmc: number
role: string
reason: string
tcg_price: number | null
image_url: string
owned: boolean
owned_qty: number
scryfall_id: string
is_substitute: boolean
original_name: string | null
substitution_reason: string | null
similarity_score: number | null
}
export interface DeckGenV3Result {
commander: {
name: string
image_url: string
type_line: string
color_identity: string[]
mana_cost: string
oracle_text: string
}
cards: DeckGenV3Card[]
stats: DeckAnalysis
strategy: string
bracket: number
model: string
substitution?: {
owned: number
substituted: number
missing: number
}
}
// ── Simulation ───────────────────────────────────────────────
export interface SimConfig {
deck_names: string[]
num_games: number
threads: number
use_deepseek?: boolean
}
export interface SimStatus {
running: boolean
sim_id: string
progress?: number
games_completed?: number
total_games?: number
}
export interface SimResult {
sim_id: string
decks: SimDeckResult[]
total_games: number
duration_ms: number
timestamp: string
}
export interface SimDeckResult {
name: string
wins: number
losses: number
win_rate: number
avg_turn: number
}
// ── Batch Sim (Lab) ──────────────────────────────────────────
export interface LabDeck {
name: string
source: string
path: string
card_count: number
}
export interface LabStartRequest {
decks: string[]
games: number
threads?: number
use_deepseek?: boolean
deepseek_deck?: string
}
export interface LabStatus {
running: boolean
run_id: string
games_completed: number
total_games: number
current_decks: string[]
error: string | null
}
export interface LabResult {
run_id: string
decks: LabDeckResult[]
total_games: number
timestamp: string
}
export interface LabDeckResult {
name: string
wins: number
games: number
win_rate: number
avg_turns: number
avg_life_remaining: number
}
export interface LabHistoryEntry {
run_id: string
timestamp: string
decks: string[]
total_games: number
}
export interface PreconDeck {
name: string
filename: string
release_date?: string
set_name?: string
installed: boolean
}
// ── Coach ────────────────────────────────────────────────────
export interface CoachStatus {
llmConnected: boolean
llmModel: string | null
llmModels: string[]
embeddingsLoaded: boolean
embeddingCards: number
deckReportsAvailable: number
error: string | null
}
export interface CoachDeck {
deck_id: number
deck_name: string
commander: string
card_count: number
has_report: boolean
report_count: number
last_report_date: string | null
}
export interface CoachGoals {
targetPowerLevel?: number | null
metaFocus?: string | null
budget?: string | null
focusAreas?: string[]
}
export interface CoachMessage {
role: 'user' | 'assistant'
content: string
}
export interface CoachChatResponse {
content: string
model: string
prompt_tokens: number
completion_tokens: number
}
export interface CoachSession {
sessionId: string
deckId: string
timestamp: string
summary: string
suggestedCuts: CoachSuggestedCut[]
suggestedAdds: CoachSuggestedAdd[]
heuristicHints: string[]
manaBaseAdvice: string | null
rawTextExplanation: string
modelUsed: string
promptTokens: number
completionTokens: number
goals: CoachGoals | null
}
export interface CoachSuggestedCut {
cardName: string
reason: string
replacementOptions: string[]
currentImpactScore: number
}
export interface CoachSuggestedAdd {
cardName: string
role: string
reason: string
synergyWith: string[]
estimatedManaValue: number | null
}
export interface CoachSessionSummary {
sessionId: string
deckId: string
timestamp: string
summary: string
cutsCount: number
addsCount: number
}
export interface CoachApplyResult {
cuts: { name: string; status: string }[]
adds: { name: string; scryfall_id?: string; status: string }[]
errors: { name: string; error: string }[]
total_cuts: number
total_adds: number
}
export interface CoachCardLikeResult {
name: string
similarity: number
types: string
mana_value: number
mana_cost: string
text: string
owned_qty: number
image_url: string | null
tcg_price: number | null
}
// ── ML Training ──────────────────────────────────────────────
/** GET /api/ml/status */
export interface MLStatus {
ml_logging_enabled: boolean
training_files: { file: string; decisions: number; size_kb: number }[]
total_decisions: number
total_files: number
}
/** GET /api/ml/data/status */
export interface MLDataStatus {
decisionFiles: { name: string; size: number; decisions: number }[]
totalDecisions: number
datasets: Record<string, { samples: number; features: number; size: number }>
checkpoints: { name: string; size: number; modified: string }[]
evalResults: Record<string, unknown> | null
policyLoaded: boolean
}
/** GET /api/ml/train/status */
export interface MLTrainStatus {
running: boolean
progress: number
total_epochs: number
current_epoch: number
phase: 'idle' | 'starting' | 'building' | 'training' | 'evaluating' | 'done' | 'error'
message: string
metrics: Record<string, unknown> | null
result: {
training: Record<string, unknown>
evaluation: Record<string, unknown> | null
checkpoint: string
device: string
} | null
error: string | null
started_at: string | null
}
/** GET /api/ml/train/ppo/status */
export interface PPOTrainStatus {
running: boolean
iteration: number
total_iterations: number
phase: 'idle' | 'starting' | 'training' | 'done' | 'error'
message: string
metrics: {
avg_reward?: number
win_rate?: number
policy_loss?: number
value_loss?: number
entropy?: number
[key: string]: unknown
} | null
result: Record<string, unknown> | null
error: string | null
}
/** GET /api/ml/tournament/status */
export interface TournamentStatus {
running: boolean
phase: 'idle' | 'starting' | 'running' | 'done' | 'error'
message: string
result: TournamentResults | null
error: string | null
}
export interface TournamentResults {
players: TournamentPlayer[]
total_matches: number
matchups?: Record<string, unknown>
}
export interface TournamentPlayer {
name: string
wins: number
games: number
win_rate: number
}
/** GET /api/ml/model */
export interface MLModelInfo {
loaded: boolean
device?: string
input_dim?: number
num_actions?: number
checkpoint_path?: string
error?: string
torch_available?: boolean
}
// ── DeepSeek ─────────────────────────────────────────────────
export interface DeepSeekStatus {
connected: boolean
model: string | null
base_url: string
}
// ── Commander Search ─────────────────────────────────────────
export interface CommanderSearchResult {
name: string
type_line: string
color_identity: string[]
mana_cost: string
image_url: string
oracle_text: string
scryfall_id: string
in_collection: boolean
}
// ── Perplexity ───────────────────────────────────────────────
export interface PplxStatus {
configured: boolean
key_prefix: string
}
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
@@ -0,0 +1,28 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [react(), tailwindcss()],
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
},
},
},
build: {
outDir: 'dist',
sourcemap: false,
rollupOptions: {
output: {
manualChunks: {
recharts: ['recharts'],
react: ['react', 'react-dom', 'react-router-dom'],
},
},
},
},
})
+1944 -163
View File
File diff suppressed because it is too large. Load diff
+8778 -305
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-34
View File
@@ -1,34 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Commander AI Lab — Collection</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="global.css" />
<link rel="stylesheet" href="collection.css" />
<style>
/* No nav bar when embedded in LAN client iframe */
:root { --nav-height: 0px; }
</style>
</head>
<body>
<!-- nav.js removed — collection is embedded via iframe in the LAN client -->
<div id="collection-container"></div>
<script>
window.LAB_API_BASE = window.LAB_API_BASE || '';
</script>
<script src="collection.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
Collection.init();
});
</script>
<!-- Card Preview Popup (hover tooltip) -->
<div id="coll-card-preview" style="display:none; position:fixed; pointer-events:none; z-index:9999;">
<img id="coll-card-preview-img" src="" alt="Card preview" style="width:220px; border-radius:8px; box-shadow:0 8px 24px rgba(0,0,0,0.7);" />
</div>
</body>
</html>
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-495
View File
@@ -1,495 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Commander AI Lab — Deck Builder</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="global.css" />
<link rel="stylesheet" href="deckbuilder.css" />
<style>
/* No nav bar when embedded in LAN client iframe */
:root { --nav-height: 0px; }
</style>
</head>
<body>
<!-- nav.js removed — deck builder is embedded via iframe in the LAN client -->
<div id="deck-builder-page">
<!-- TOP BAR -->
<header class="deck-topbar">
<div class="deck-topbar-commander">
<div class="deck-commander-portrait" id="deck-commander-portrait">
<span class="deck-commander-portrait-placeholder">⚔</span>
<img class="deck-commander-portrait-img" id="deck-commander-img" src="" alt="" style="display:none" />
</div>
<div class="deck-name-block">
<input
type="text"
class="deck-name-input"
id="deck-name-input"
placeholder="Untitled Deck"
value=""
/>
<div class="deck-commander-label" id="deck-commander-label">No commander selected</div>
</div>
<div class="deck-color-chips" id="deck-color-chips"></div>
</div>
<div class="deck-topbar-center">
<div class="deck-count-display">
<span class="deck-count-num" id="deck-total-count">0</span>
<span class="deck-count-sep">/</span>
<span class="deck-count-target">100</span>
<span class="deck-count-label">cards</span>
</div>
<button class="deck-btn deck-btn-ghost" id="deck-new-btn">+ New Deck</button>
<div class="deck-selector-wrap">
<select class="deck-selector" id="deck-selector">
<option value="">— Select Deck —</option>
</select>
</div>
<button class="deck-btn deck-btn-danger" id="deck-delete-btn" title="Delete this deck" style="display:none;">✕ Delete</button>
<button class="deck-btn deck-btn-danger-outline" id="deck-clear-all-btn" title="Delete all decks">Clear All</button>
</div>
<div class="deck-topbar-actions">
<button class="deck-btn deck-btn-import" id="deck-import-btn" title="Import a decklist">
<span>⬆</span> Import
</button>
<button class="deck-btn deck-btn-ghost" id="deck-export-btn" title="Export as .dck file">
<span>⬇</span> Export .dck
</button>
<button class="deck-btn deck-btn-ghost" id="deck-export-sim-btn" title="Export deck as .dck to Forge sim folder">
<span>&#x1F4E4;</span> Export to Sim
</button>
<button class="deck-btn deck-btn-ghost" id="deck-export-game-btn" title="Send deck to LAN game setup" style="border-color:rgba(91,141,217,0.4);color:rgba(91,141,217,0.9);">
<span>&#x1F3AE;</span> Use in Game
</button>
<button class="deck-btn deck-btn-sim" id="deck-sim-btn" title="Run quick simulation">
<span class="deck-btn-icon">▶</span> Run Simulation
</button>
</div>
</header>
<!-- MAIN 3-COLUMN LAYOUT -->
<main class="deck-main">
<!-- LEFT COLUMN: Collection Search -->
<aside class="deck-col-left">
<div class="deck-panel deck-panel-search">
<div class="deck-panel-header">
<span class="deck-panel-title">Collection Search</span>
<span class="deck-search-count" id="deck-search-count">0 results</span>
</div>
<div class="deck-search-bar-wrap">
<input
type="search"
class="deck-search-bar"
id="deck-search-bar"
placeholder="Search cards..."
autocomplete="off"
/>
<span class="deck-search-icon">🔍</span>
</div>
<div class="deck-filter-row">
<select class="deck-filter-select" id="deck-type-filter">
<option value="">All Types</option>
<option value="Land">Land</option>
<option value="Creature">Creature</option>
<option value="Instant">Instant</option>
<option value="Sorcery">Sorcery</option>
<option value="Artifact">Artifact</option>
<option value="Enchantment">Enchantment</option>
<option value="Planeswalker">Planeswalker</option>
</select>
<div class="deck-cmc-filter">
<input type="number" class="deck-cmc-input" id="deck-cmc-min" placeholder="0" min="0" max="20" />
<span class="deck-cmc-sep">–</span>
<input type="number" class="deck-cmc-input" id="deck-cmc-max" placeholder="∞" min="0" max="20" />
</div>
</div>
<div class="deck-color-filter-row" id="deck-color-filter">
<button class="deck-color-pip deck-color-W" data-color="W" title="White">W</button>
<button class="deck-color-pip deck-color-U" data-color="U" title="Blue">U</button>
<button class="deck-color-pip deck-color-B" data-color="B" title="Black">B</button>
<button class="deck-color-pip deck-color-R" data-color="R" title="Red">R</button>
<button class="deck-color-pip deck-color-G" data-color="G" title="Green">G</button>
<button class="deck-color-pip deck-color-C" data-color="C" title="Colorless">C</button>
</div>
<!-- Results list -->
<div class="deck-search-results" id="deck-search-results">
<div class="deck-empty-state">
<div class="deck-empty-icon">🃏</div>
<div class="deck-empty-text">Search your collection to add cards</div>
</div>
</div>
<div class="deck-search-footer">
<button class="deck-btn deck-btn-success deck-btn-full" id="deck-add-all-owned-btn" style="display:none">
Add All Matching (Owned)
</button>
</div>
</div>
</aside>
<!-- CENTER COLUMN: Deck Card List -->
<section class="deck-col-center">
<div class="deck-panel deck-panel-cards" id="deck-card-list-panel">
<div class="deck-panel-header deck-card-list-header">
<span class="deck-panel-title">Deck Contents</span>
<div class="deck-card-list-actions">
<span class="deck-card-list-meta" id="deck-card-list-meta">Select or create a deck</span>
</div>
</div>
<!-- Card groups by type -->
<div class="deck-card-groups" id="deck-card-groups">
<div class="deck-empty-state deck-empty-state-lg">
<div class="deck-empty-icon">⚔</div>
<div class="deck-empty-text">Create or select a deck to start building</div>
<button class="deck-btn deck-btn-accent" id="deck-empty-new-btn">+ New Deck</button>
</div>
</div>
<!-- Quick add by name -->
<div class="deck-quickadd-row" id="deck-quickadd-row" style="display:none">
<div class="deck-quickadd-wrap">
<input
type="text"
class="deck-quickadd-input"
id="deck-quickadd-input"
placeholder="Add card by name..."
autocomplete="off"
/>
<div class="deck-quickadd-dropdown" id="deck-quickadd-dropdown" style="display:none"></div>
</div>
<button class="deck-btn deck-btn-accent-sm" id="deck-quickadd-btn">Add</button>
</div>
<!-- Deck stats footer -->
<div class="deck-stats-footer" id="deck-stats-footer" style="display:none">
<div class="deck-stat-pill">
<span class="deck-stat-pill-num" id="deck-footer-total">0</span>
<span class="deck-stat-pill-label">total</span>
</div>
<div class="deck-stat-pill">
<span class="deck-stat-pill-num deck-stat-owned" id="deck-footer-owned">0</span>
<span class="deck-stat-pill-label">owned</span>
</div>
<div class="deck-stat-pill">
<span class="deck-stat-pill-num" id="deck-footer-avg-cmc">0.0</span>
<span class="deck-stat-pill-label">avg CMC</span>
</div>
</div>
</div>
</section>
<!-- RIGHT COLUMN: EDH Advisor -->
<aside class="deck-col-right">
<!-- Ratio Dashboard -->
<div class="deck-panel deck-panel-ratios" id="deck-ratio-panel">
<div class="deck-panel-header deck-panel-header-collapsible" data-target="deck-ratio-body">
<span class="deck-panel-title">📊 Ratio Dashboard</span>
<span class="deck-collapse-arrow">▼</span>
</div>
<div class="deck-panel-body" id="deck-ratio-body">
<div class="deck-ratio-bars" id="deck-ratio-bars">
<div class="deck-ratio-placeholder">Load a deck to see ratios</div>
</div>
</div>
</div>
<!-- Fix My Ratios -->
<div class="deck-panel deck-panel-fix" id="deck-fix-panel">
<div class="deck-panel-header deck-panel-header-collapsible" data-target="deck-fix-body">
<span class="deck-panel-title">🔧 Fix My Ratios</span>
<span class="deck-collapse-arrow">▼</span>
</div>
<div class="deck-panel-body" id="deck-fix-body">
<div class="deck-shortfalls" id="deck-shortfalls">
<div class="deck-ratio-placeholder">No analysis available</div>
</div>
<div class="deck-fix-actions" id="deck-fix-actions" style="display:none">
<button class="deck-btn deck-btn-ghost deck-btn-full" id="deck-autosuggest-btn">
⚡ Auto-suggest from Collection
</button>
</div>
<div class="deck-fix-suggestions" id="deck-fix-suggestions" style="display:none"></div>
</div>
</div>
<!-- EDHREC Recommendations -->
<div class="deck-panel deck-panel-edhrec" id="deck-edhrec-panel">
<div class="deck-panel-header deck-panel-header-collapsible" data-target="deck-edhrec-body">
<span class="deck-panel-title">✨ EDHREC Recs</span>
<span class="deck-collapse-arrow">▼</span>
</div>
<div class="deck-panel-body" id="deck-edhrec-body">
<div class="deck-edhrec-controls">
<label class="deck-toggle-label">
<input type="checkbox" class="deck-toggle-check" id="deck-edhrec-owned-only" />
<span class="deck-toggle-track"><span class="deck-toggle-thumb"></span></span>
Owned Only
</label>
<button class="deck-btn deck-btn-ghost deck-btn-sm" id="deck-edhrec-refresh-btn">
↺ Refresh
</button>
</div>
<div class="deck-edhrec-list" id="deck-edhrec-list">
<div class="deck-ratio-placeholder">Load a deck to see recommendations</div>
</div>
<div class="deck-edhrec-bulk" id="deck-edhrec-bulk" style="display:none">
<button class="deck-btn deck-btn-success deck-btn-full" id="deck-edhrec-bulk-owned-btn">
Add All Owned (respect ratios)
</button>
</div>
</div>
</div>
<!-- AI Research (Perplexity) — hidden until pplx status check -->
<div class="deck-panel deck-panel-ai" id="deck-ai-research-panel" style="display:none">
<div class="deck-panel-header deck-panel-header-collapsible" data-target="deck-ai-research-body">
<span class="deck-panel-title">🧠 AI Research</span>
<span class="deck-collapse-arrow">▼</span>
</div>
<div class="deck-panel-body" id="deck-ai-research-body">
<div class="deck-ai-controls">
<div class="deck-form-field deck-form-field-sm">
<label class="deck-form-label-sm">Analysis Goal</label>
<input type="text" class="deck-form-input deck-form-input-sm" id="ai-research-goal"
placeholder="Identify weaknesses and suggest upgrades" />
</div>
<div class="deck-ai-row">
<div class="deck-form-field deck-form-field-sm deck-form-field-half">
<label class="deck-form-label-sm">Budget ($)</label>
<input type="number" class="deck-form-input deck-form-input-sm" id="ai-research-budget"
placeholder="No limit" min="0" step="10" />
</div>
<label class="deck-toggle-label deck-toggle-label-sm">
<input type="checkbox" class="deck-toggle-check" id="ai-research-use-collection" checked />
<span class="deck-toggle-track"><span class="deck-toggle-thumb"></span></span>
Use Collection
</label>
</div>
<div class="deck-form-field deck-form-field-sm">
<label class="deck-form-label-sm">Omit Cards (comma-separated)</label>
<input type="text" class="deck-form-input deck-form-input-sm" id="ai-research-omit"
placeholder="Dockside Extortionist, Rhystic Study" />
</div>
<button class="deck-btn deck-btn-ai deck-btn-full" id="ai-research-btn" disabled>
🔍 Analyze Deck
</button>
</div>
<div class="deck-ai-loading" id="ai-research-loading" style="display:none">
<div class="deck-ai-spinner"></div>
<span>Analyzing with Claude Opus...</span>
</div>
<div class="deck-ai-results" id="ai-research-results" style="display:none"></div>
</div>
</div>
<!-- AI Deck Generate (Perplexity) — hidden until pplx status check -->
<div class="deck-panel deck-panel-ai" id="deck-ai-generate-panel" style="display:none">
<div class="deck-panel-header deck-panel-header-collapsible" data-target="deck-ai-generate-body">
<span class="deck-panel-title">✨ AI Generate Deck</span>
<span class="deck-collapse-arrow">▼</span>
</div>
<div class="deck-panel-body" id="deck-ai-generate-body">
<div class="deck-ai-controls">
<div class="deck-form-field deck-form-field-sm">
<label class="deck-form-label-sm">Commander</label>
<div class="deck-ai-commander-wrap">
<input type="text" class="deck-form-input deck-form-input-sm" id="ai-gen-commander"
placeholder="Search for a commander..." autocomplete="off" />
<div class="deck-ai-commander-dropdown" id="ai-gen-commander-dropdown" style="display:none"></div>
</div>
</div>
<div class="deck-ai-row">
<div class="deck-form-field deck-form-field-sm deck-form-field-half">
<label class="deck-form-label-sm">Budget ($)</label>
<input type="number" class="deck-form-input deck-form-input-sm" id="ai-gen-budget"
placeholder="No limit" min="0" step="10" />
</div>
<label class="deck-toggle-label deck-toggle-label-sm">
<input type="checkbox" class="deck-toggle-check" id="ai-gen-use-collection" checked />
<span class="deck-toggle-track"><span class="deck-toggle-thumb"></span></span>
Use Collection
</label>
</div>
<div class="deck-form-field deck-form-field-sm">
<label class="deck-form-label-sm">Omit Cards (comma-separated)</label>
<input type="text" class="deck-form-input deck-form-input-sm" id="ai-gen-omit"
placeholder="Rhystic Study, Cyclonic Rift" />
</div>
<button class="deck-btn deck-btn-ai deck-btn-full" id="ai-gen-btn">
✨ Generate Full Deck
</button>
</div>
<div class="deck-ai-loading" id="ai-gen-loading" style="display:none">
<div class="deck-ai-spinner"></div>
<span>Generating deck with Claude Opus...</span>
</div>
<div class="deck-ai-results" id="ai-gen-results" style="display:none"></div>
</div>
</div>
</aside>
</main>
<!-- CARD PREVIEW TOOLTIP -->
<div class="deck-card-preview" id="deck-card-preview" style="display:none">
<img class="deck-card-preview-img" id="deck-card-preview-img" src="" alt="" />
</div>
<!-- TOAST CONTAINER -->
<div class="deck-toast-container" id="deck-toast-container"></div>
<!-- CONFIRM MODAL -->
<div class="deck-modal-overlay" id="deck-confirm-modal" style="display:none">
<div class="deck-modal">
<div class="deck-modal-header">
<h3 class="deck-modal-title" id="deck-confirm-title">Confirm Action</h3>
<button class="deck-modal-close-btn" id="deck-confirm-close">✕</button>
</div>
<div class="deck-modal-body">
<p class="deck-confirm-message" id="deck-confirm-message"></p>
<div class="deck-confirm-changes" id="deck-confirm-changes"></div>
</div>
<div class="deck-modal-footer">
<button class="deck-btn deck-btn-ghost" id="deck-confirm-cancel">Cancel</button>
<button class="deck-btn deck-btn-accent" id="deck-confirm-ok">Confirm</button>
</div>
</div>
</div>
<!-- NEW DECK MODAL -->
<div class="deck-modal-overlay" id="deck-new-modal" style="display:none">
<div class="deck-modal">
<div class="deck-modal-header">
<h3 class="deck-modal-title">Create New Deck</h3>
<button class="deck-modal-close-btn" id="deck-new-modal-close">✕</button>
</div>
<div class="deck-modal-body">
<div class="deck-form-field">
<label class="deck-form-label">Deck Name</label>
<input type="text" class="deck-form-input" id="deck-new-name" placeholder="My Commander Deck" />
</div>
<div class="deck-form-field">
<label class="deck-form-label">Commander (optional)</label>
<div class="deck-commander-search-wrap">
<input
type="text"
class="deck-form-input"
id="deck-new-commander-search"
placeholder="Search Scryfall for commander..."
autocomplete="off"
/>
<div class="deck-commander-dropdown" id="deck-new-commander-dropdown" style="display:none"></div>
</div>
<div class="deck-new-commander-selected" id="deck-new-commander-selected" style="display:none">
<span class="deck-selected-commander-name" id="deck-new-commander-name"></span>
<button class="deck-clear-commander-btn" id="deck-clear-commander-btn">✕</button>
</div>
</div>
</div>
<div class="deck-modal-footer">
<button class="deck-btn deck-btn-ghost" id="deck-new-cancel">Cancel</button>
<button class="deck-btn deck-btn-accent" id="deck-new-create">Create Deck</button>
</div>
</div>
</div>
<!-- IMPORT MODAL -->
<div class="deck-modal-overlay" id="deck-import-modal" style="display:none">
<div class="deck-modal deck-modal-wide">
<div class="deck-modal-header">
<h3 class="deck-modal-title">Import Decklist</h3>
<button class="deck-modal-close-btn" id="deck-import-modal-close">✕</button>
</div>
<div class="deck-modal-body">
<div class="deck-import-tabs">
<button class="deck-import-tab active" data-tab="paste">Paste Text</button>
<button class="deck-import-tab" data-tab="file">Upload File</button>
</div>
<div id="deck-import-paste-panel" class="deck-import-panel">
<textarea id="deck-import-textarea" rows="14" placeholder="Paste your decklist here...
Supported formats:
[Commander]
1 Korvold, Fae-Cursed King
[Deck]
1 Sol Ring
1 Cultivate
37 Forest
Or plain list:
Sol Ring
Cultivate
Forest"></textarea>
</div>
<div id="deck-import-file-panel" class="deck-import-panel" style="display:none">
<div class="deck-import-dropzone" id="deck-import-dropzone">
<div class="deck-import-dropzone-label">Drop a .dck or .txt file here, or click to browse</div>
<input type="file" id="deck-import-file" accept=".dck,.txt,.dec,.mwDeck" style="display:none" />
</div>
<div class="deck-import-file-info" id="deck-import-file-name"></div>
</div>
<div class="deck-import-options">
<label class="deck-import-option-label">
<input type="radio" name="import-mode" value="new" checked /> Create new deck
</label>
<label class="deck-import-option-label">
<input type="radio" name="import-mode" value="add" /> Add to current deck
</label>
<label class="deck-import-option-label">
<input type="radio" name="import-mode" value="replace" /> Replace current deck cards
</label>
</div>
<div id="deck-import-new-name-row" class="deck-import-name-row">
<label>Deck name (optional):</label>
<input type="text" id="deck-import-name" placeholder="Auto-detected from commander" />
</div>
<div class="deck-import-progress-wrap" id="deck-import-progress" style="display:none">
<div class="deck-import-progress-label">Importing cards (Scryfall lookup)...</div>
<div class="deck-import-progress-track">
<div class="deck-import-progress-fill" id="deck-import-progress-bar"></div>
</div>
</div>
<div id="deck-import-result" style="display:none"></div>
</div>
<div class="deck-modal-footer">
<button class="deck-btn deck-btn-ghost" id="deck-import-cancel">Cancel</button>
<button class="deck-btn deck-btn-accent" id="deck-import-go">Import</button>
</div>
</div>
</div>
</div><!-- /#deck-builder-page -->
<script>
// Set API base URL — when served from a different host, override this value
window.LAB_API_BASE = window.LAB_API_BASE || '';
</script>
<script src="deckbuilder.js"></script>
<!-- Card Preview Popup (hover tooltip) -->
<div id="deck-card-preview" style="display:none; position:fixed; pointer-events:none; z-index:60;">
<img id="deck-card-preview-img" src="" alt="Card preview" style="width:220px; border-radius:8px; box-shadow:0 8px 24px rgba(0,0,0,0.7);" />
</div>
</body>
</html>
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-245
View File
@@ -1,245 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Commander AI Lab — Auto Deck Generator V3</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="global.css" />
<link rel="stylesheet" href="deckgenerator.css" />
<style>
/* No nav bar when embedded in LAN client iframe */
:root { --nav-height: 0px; }
</style>
</head>
<body>
<!-- nav.js removed — deck generator is embedded via iframe in the LAN client -->
<div id="deckgen-page">
<!-- MAIN LAYOUT -->
<main class="dg-main">
<!-- LEFT: Configuration -->
<section class="dg-col-config">
<!-- Commander Search -->
<div class="dg-panel dg-panel-commander">
<div class="dg-panel-header">
<span class="dg-panel-title">Commander</span>
</div>
<div class="dg-panel-body">
<div class="dg-commander-search-wrap">
<input
type="text"
class="dg-input"
id="dg-commander-input"
placeholder="Search for a legendary creature..."
autocomplete="off"
/>
<div class="dg-commander-dropdown" id="dg-commander-dropdown"></div>
</div>
<div class="dg-commander-selected" id="dg-commander-selected" style="display:none">
<div class="dg-commander-card">
<button class="dg-commander-clear" id="dg-commander-clear" title="Clear commander">&times;</button>
<img class="dg-commander-img" id="dg-commander-img" src="" alt="" />
<div class="dg-commander-info">
<div class="dg-commander-name" id="dg-commander-name"></div>
<div class="dg-commander-type" id="dg-commander-type"></div>
<div class="dg-commander-colors" id="dg-commander-colors"></div>
</div>
</div>
</div>
</div>
</div>
<!-- Strategy & Bracket -->
<div class="dg-panel">
<div class="dg-panel-header">
<span class="dg-panel-title">Strategy &amp; Power</span>
</div>
<div class="dg-panel-body">
<input
type="text"
class="dg-input"
id="dg-strategy"
placeholder="e.g. zombie tokens, voltron, spellslinger..."
title="Describe your deck strategy — the AI uses this to pick thematically aligned cards"
/>
<div class="dg-bracket-row">
<label class="dg-label">
Target Bracket
<span class="tip-icon" data-tip="B1 = precon-level casual. B2 = upgraded with synergies. B3 = high power with strong combos. B4 = cEDH with maximum optimization, fast mana, and instant-speed interaction.">?</span>
</label>
<div class="dg-bracket-btns" id="dg-bracket-btns">
<button class="dg-bracket-btn" data-bracket="1" title="Casual — precon level">B1</button>
<button class="dg-bracket-btn" data-bracket="2" title="Upgraded Casual">B2</button>
<button class="dg-bracket-btn dg-bracket-active" data-bracket="3" title="High Power">B3</button>
<button class="dg-bracket-btn" data-bracket="4" title="cEDH — maximum power">B4</button>
</div>
</div>
</div>
</div>
<!-- Deck Name -->
<div class="dg-panel">
<div class="dg-panel-header">
<span class="dg-panel-title">Deck Name</span>
</div>
<div class="dg-panel-body">
<input
type="text"
class="dg-input"
id="dg-deck-name"
placeholder="Auto-generated from commander name"
/>
</div>
</div>
<!-- Budget -->
<div class="dg-panel">
<div class="dg-panel-header">
<span class="dg-panel-title">Budget</span>
</div>
<div class="dg-panel-body">
<div class="dg-budget-row">
<input
type="number"
class="dg-input dg-input-narrow"
id="dg-budget"
placeholder="No limit"
min="0"
step="25"
/>
<select class="dg-select" id="dg-budget-mode" title="Total Deck: caps the combined price of all 100 cards. Per Card Max: caps each individual card price.">
<option value="total">Total Deck $</option>
<option value="per_card">Per Card Max $</option>
</select>
</div>
</div>
</div>
<!-- Options -->
<div class="dg-panel">
<div class="dg-panel-header">
<span class="dg-panel-title">Options</span>
</div>
<div class="dg-panel-body">
<label class="dg-toggle-row">
<span class="dg-toggle-label">
Use my collection
<span class="tip-icon" data-tip="Prioritizes cards you already own before pulling from the full card pool. Saves money and ensures the deck is ready to play. Requires an imported collection.">?</span>
</span>
<input type="checkbox" class="dg-toggle-check" id="dg-use-collection" checked />
<span class="dg-toggle-track"><span class="dg-toggle-thumb"></span></span>
</label>
<label class="dg-toggle-row">
<span class="dg-toggle-label">
Smart Substitution
<span class="tip-icon" data-tip="When a suggested card isn't in your collection, automatically finds the closest functional replacement you do own. Keeps the deck playable without buying extra cards.">?</span>
</span>
<input type="checkbox" class="dg-toggle-check" id="dg-substitution" checked />
<span class="dg-toggle-track"><span class="dg-toggle-thumb"></span></span>
</label>
<div class="dg-model-row">
<label class="dg-label">
AI Model
<span class="tip-icon" data-tip="Deck generation is powered by Claude Opus 4, Anthropic's most capable model.">?</span>
</label>
<input type="hidden" id="dg-model" value="claude-opus-4-20250514" />
<span style="font-size:0.8rem; color:var(--text-muted, #888);">claude-opus-4-20250514</span>
</div>
</div>
</div>
<!-- Omit Cards (chips input) -->
<div class="dg-panel">
<div class="dg-panel-header">
<span class="dg-panel-title">Omit Cards</span>
</div>
<div class="dg-panel-body">
<div class="dg-omit-wrap" id="dg-omit-wrap">
<div class="dg-omit-chips" id="dg-omit-chips"></div>
<input
type="text"
class="dg-input dg-omit-input"
id="dg-omit-input"
placeholder="Type a card name and press Enter…"
/>
</div>
<small class="dg-hint">Cards listed here will be excluded from the generated deck.</small>
</div>
</div>
<!-- Action Buttons -->
<div class="dg-actions">
<button class="dg-btn dg-btn-preview" id="dg-preview-btn" disabled>
<span class="dg-btn-icon">&#9889;</span> Generate Deck
</button>
</div>
<!-- Conversation Log -->
<div id="dg-conversation-log" class="dg-conversation-log">
<div class="dg-log-entry dg-log-info"><span class="dg-log-ts">[Ready]</span> Waiting for deck generation...</div>
</div>
</section>
<!-- RIGHT: Preview Results -->
<section class="dg-col-results">
<!-- Empty State -->
<div class="dg-empty-state" id="dg-empty-state">
<div class="dg-empty-icon">&#9889;</div>
<div class="dg-empty-title">V3 AI Deck Generator</div>
<div class="dg-empty-text">Select a commander, set your bracket and strategy, then click "Generate Deck" to build a complete 100-card deck using Claude Opus with structured output.</div>
</div>
<!-- Loading State -->
<div class="dg-loading" id="dg-loading" style="display:none">
<div class="dg-spinner"></div>
<div class="dg-loading-text" id="dg-loading-text">Generating deck via Claude Opus 4...</div>
</div>
<div class="dg-progress-wrap" id="dg-progress-wrap" style="display:none">
<div class="dg-progress-bar">
<div class="dg-progress-fill" id="dg-progress-fill"></div>
</div>
<div class="dg-progress-meta">
<span class="dg-progress-phase" id="dg-progress-phase"></span>
<span class="dg-progress-elapsed" id="dg-progress-elapsed">0s elapsed</span>
</div>
</div>
<!-- Results -->
<div class="dg-results" id="dg-results" style="display:none">
<div class="dg-results-header">
<div id="dg-strategy-bar"></div>
<div id="dg-stats-bar" class="dg-stats-bar"></div>
<div id="dg-sub-summary" style="display:none"></div>
<div class="dg-result-actions">
<button class="dg-btn dg-btn-secondary" id="dg-regenerate-btn">&#8635; Regenerate</button>
<button class="dg-btn dg-btn-primary" id="dg-save-btn">&#128190; Save to Deck Builder</button>
<button class="dg-btn dg-btn-ghost" id="dg-export-csv">CSV</button>
<button class="dg-btn dg-btn-ghost" id="dg-export-dck">Forge .dck</button>
<button class="dg-btn dg-btn-ghost" id="dg-export-moxfield">Moxfield</button>
<button class="dg-btn dg-btn-ghost" id="dg-export-shopping">&#128722; Shopping</button>
</div>
</div>
<div id="dg-card-groups" class="dg-card-groups"></div>
</div>
</section>
</main>
<!-- TOAST CONTAINER -->
<div class="dg-toast-container" id="dg-toast-container"></div>
</div>
<script>
window.LAB_API_BASE = window.LAB_API_BASE || '';
</script>
<script src="deckgenerator.js"></script>
</body>
</html>
Loaded 100 of 591 files, more files were not shown because too many files have changed in this diff. Show more