- Create frontend-sba/.env.example and frontend-pd/.env.example templates
- Fix hardcoded allowedHosts in nuxt.config.ts (now reads NUXT_ALLOWED_HOSTS)
- Add NUXT_ALLOWED_HOSTS support to frontend-pd/nuxt.config.ts
- Update docker-compose.yml with missing env vars:
- FRONTEND_URL, DISCORD_SERVER_REDIRECT_URI
- ALLOWED_DISCORD_IDS, WS_HEARTBEAT_INTERVAL, WS_CONNECTION_TIMEOUT
- NUXT_ALLOWED_HOSTS for both frontends
- Create docker-compose.prod.yml for production overrides
- Update root .env.example with new variables
- Add "Multi-Domain Deployment" section to README.md with checklist
- Update all CLAUDE.md files with environment configuration docs
- Remove obsolete 'version' attribute from docker-compose files
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Backend enhancements for real-time decision workflow:
**New Features**:
- decision_required event emission when game starts and after each decision
- Quick-create endpoint (/games/quick-create) for rapid testing with pre-configured lineups
- WebSocket connection manager integration in GameEngine
**Changes**:
- game_engine.py: Added _emit_decision_required() method and set_connection_manager()
- game_engine.py: Emit decision_required on game start with 5-minute timeout
- games.py: New /quick-create endpoint with Team 35 vs Team 38 lineups
- main.py: Wire connection manager to game_engine singleton
- state_manager.py: Enhanced state management for decision phases
- play_resolver.py: Improved play resolution logic
- handlers.py: Updated WebSocket handlers for new workflow
- backend/CLAUDE.md: Added WebSocket protocol spec reference
**Why**:
Eliminates polling - frontend now gets real-time notification when decisions are needed.
Quick-create saves 2 minutes of lineup setup during each test iteration.
**Testing**:
- Manual testing with terminal client
- WebSocket event flow verified with live frontend
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Removed outdated TODO comments and updated documentation to reflect
work completed in Phase 3E (Position Ratings and WebSocket Handlers).
Changes:
- Removed 2 stale WebSocket emission TODOs in game_engine.py (lines 319, 387)
These referenced Phase 3E-Final work completed on 2025-01-10
- Updated backend/CLAUDE.md Phase 3E status section
Marked defender retrieval as COMPLETE (Phase 3E-Main)
Clarified SPD test still pending (needs batter speed rating)
Marked runner advancement as COMPLETE (Phase 3D)
- Updated TODO_RESOLUTION_SUMMARY.md
Marked defender lookup TODO as resolved with implementation details
Documentation:
- Created TODO_AUDIT_2025-01-14.md - Complete TODO audit (53 items)
- Created TODO_VERIFICATION_RESULTS.md - Verification of resolved items
- Created TODO_SUMMARY.md - Quick reference priority matrix
- Created TODO_CLEANUP_COMPLETE.md - Cleanup work summary
Test Status:
- Backend: 9/9 PlayResolver tests passing
- No regressions introduced
Remaining Work:
- 41 legitimate TODOs properly categorized for future phases
- 8 Phase F6 TODOs (game page integration)
- 5 Quick win TODOs (optional polish)
- 28 Future phase TODOs (auth, AI, advanced features)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Test Fixes (609/609 passing):
- Fixed DiceSystem API to accept team_id/player_id parameters for audit trails
- Fixed dice roll history timing issue in test
- Fixed terminal client mock to match resolve_play signature (X-Check params)
- Fixed result chart test mocks with missing pitching fields
- Fixed flaky test by using groundball_a (exists in both batting/pitching)
Documentation Updates:
- Added Testing Policy section to backend/CLAUDE.md
- Added Testing Policy section to tests/CLAUDE.md
- Documented 100% unit test requirement before commits
- Added git hook setup instructions
Git Hook System:
- Created .git-hooks/pre-commit script (enforces 100% test pass)
- Created .git-hooks/install-hooks.sh (easy installation)
- Created .git-hooks/README.md (hook documentation)
- Hook automatically runs all unit tests before each commit
- Blocks commits if any test fails
All 609 unit tests now passing (100%)
Integration tests have known asyncpg connection issues (documented)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Updated terminal client REPL to work with refactored GameState structure
where current_batter/pitcher/catcher are now LineupPlayerState objects
instead of integer IDs. Also standardized all documentation to properly
show 'uv run' prefixes for Python commands.
REPL Updates:
- terminal_client/display.py: Access lineup_id from LineupPlayerState objects
- terminal_client/repl.py: Fix typos (self.current_game → self.current_game_id)
- tests/unit/terminal_client/test_commands.py: Create proper LineupPlayerState
objects in test fixtures (2 tests fixed, all 105 terminal client tests passing)
Documentation Updates (100+ command examples):
- CLAUDE.md: Updated pytest examples to use 'uv run' prefix
- terminal_client/CLAUDE.md: Updated ~40 command examples
- tests/CLAUDE.md: Updated all test commands (unit, integration, debugging)
- app/*/CLAUDE.md: Updated test and server startup commands (5 files)
All Python commands now consistently use 'uv run' prefix to align with
project's UV migration, improving developer experience and preventing
confusion about virtual environment activation.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Migrated from pip to UV (v0.9.7) for faster, more reliable package management.
## Changes
### Package Management
- Created `pyproject.toml` with project metadata and dependencies
- Generated `uv.lock` for reproducible builds (198KB)
- Migrated all dependencies from requirements.txt:
- Production: 20 packages (FastAPI, SQLAlchemy, Pydantic, etc.)
- Development: 6 packages (pytest, black, mypy, flake8)
- Virtual environment moved from `venv/` to `.venv/` (UV default)
### Dockerfile Updates
- Updated base image: python:3.11-slim → python:3.13-slim
- Added UV installation via official image copy
- Development stage: Uses `uv sync --frozen` for all deps
- Production stage: Uses `uv sync --frozen --no-dev` for prod only
- Commands now use `uv run` prefix for auto-activation
- Set UV environment variables:
- UV_LINK_MODE=copy (for Docker compatibility)
- UV_COMPILE_BYTECODE=1 (performance)
- UV_PYTHON_DOWNLOADS=never (use system Python)
### Code Fixes
- Fixed Pydantic model circular import in `app/models/game_models.py`
- Added runtime import of PositionRating at end of file
- Called `model_rebuild()` on LineupPlayerState and GameState
- Resolves "not fully defined" errors in tests
### Documentation
- Updated `backend/CLAUDE.md` with UV usage:
- Package management section with UV commands
- Updated all code examples to use `uv run`
- Daily development workflow now uses UV
- Added dependency management guide (add/remove/update)
- Updated virtual environment location (.venv/)
### Project Files
- Added `.python-version` (3.13) for UV Python version tracking
- Removed UV template files (main.py, README.md)
- Kept existing .gitignore (already includes venv/ and .venv/)
## Testing
- ✅ All imports work correctly
- ✅ 55/55 game model tests passing
- ✅ 500+ unit tests passing (same as before migration)
- ✅ Test failures are pre-existing (not UV-related)
## Benefits
- 10-100x faster dependency resolution
- 2-3x faster installation
- Better dependency conflict resolution
- Single tool for everything (replaces pip, pip-tools, virtualenv)
- Reproducible builds with uv.lock
## Migration Path for Team
```bash
# One-time: Install UV
curl -LsSf https://astral.sh/uv/install.sh | sh
# In project
cd backend
uv sync # Creates .venv and installs everything
# Daily usage
uv run python -m app.main
uv run pytest tests/ -v
```
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Updated NEXT_SESSION.md to reflect Phase 3E-Main completion:
- Marked Phase 3E-Main as 100% complete (position ratings integration)
- Overall Phase 3E progress now 90%
- Updated Phase 3 overall progress to ~95%
- Documented all accomplishments and live test results
- Outlined remaining Phase 3E-Final tasks (10%):
* WebSocket event handlers for X-Check UI
* Redis caching upgrade from in-memory
* Full defensive lineup evaluation
* Manual vs Auto mode workflows
Included comprehensive session handoff:
- Live API test results with player 8807 (7 positions)
- Performance metrics (16,601x cache speedup)
- All files created/modified
- Quick start guide for next session
- Technical architecture notes
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Added comprehensive Phase 3C documentation to CLAUDE.md:
- X-Check resolution logic implementation details
- Helper methods and integration points
- Key features and algorithms
- Placeholders for future phases
- Test coverage and verification results
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
This commit includes Week 6 player models implementation and critical
performance optimizations discovered during testing.
## Player Models (Week 6 - 50% Complete)
**New Files:**
- app/models/player_models.py (516 lines)
- BasePlayer abstract class with polymorphic interface
- SbaPlayer with API parsing factory method
- PdPlayer with batting/pitching scouting data support
- Supporting models: PdCardset, PdRarity, PdBattingCard, PdPitchingCard
- tests/unit/models/test_player_models.py (692 lines)
- 32 comprehensive unit tests, all passing
- Tests for BasePlayer, SbaPlayer, PdPlayer, polymorphism
**Architecture:**
- Simplified single-layer approach vs planned two-layer
- Factory methods handle API → Game transformation directly
- SbaPlayer.from_api_response(data) - parses SBA API inline
- PdPlayer.from_api_response(player_data, batting_data, pitching_data)
- Full Pydantic validation, type safety, and polymorphism
## Performance Optimizations
**Database Query Reduction (60% fewer queries per play):**
- Before: 5 queries per play (INSERT play, SELECT play with JOINs,
SELECT games, 2x SELECT lineups)
- After: 2 queries per play (INSERT play, UPDATE games conditionally)
Changes:
1. Lineup caching (game_engine.py:384-425)
- Check state_manager.get_lineup() cache before DB fetch
- Eliminates 2 SELECT queries per play
2. Remove unnecessary refresh (operations.py:281-302)
- Removed session.refresh(play) after INSERT
- Eliminates 1 SELECT with 3 expensive LEFT JOINs
3. Direct UPDATE statement (operations.py:109-165)
- Changed update_game_state() to use direct UPDATE
- No longer does SELECT + modify + commit
4. Conditional game state updates (game_engine.py:200-217)
- Only UPDATE games table when score/inning/status changes
- Captures state before/after and compares
- ~40-60% fewer updates (many plays don't score)
## Bug Fixes
1. Fixed outs_before tracking (game_engine.py:551)
- Was incorrectly calculating: state.outs - result.outs_recorded
- Now correctly captures: state.outs (before applying result)
- All play records now have accurate out counts
2. Fixed game recovery (state_manager.py:312-314)
- AttributeError when recovering: 'GameState' has no attribute 'runners'
- Changed to use state.get_all_runners() method
- Games can now be properly recovered from database
## Enhanced Terminal Client
**Status Display Improvements (terminal_client/display.py:75-97):**
- Added "⚠️ WAITING FOR ACTION" section when play is pending
- Shows specific guidance:
- "The defense needs to submit their decision" → Run defensive [OPTIONS]
- "The offense needs to submit their decision" → Run offensive [OPTIONS]
- "Ready to resolve play" → Run resolve
- Color-coded command hints for better UX
## Documentation Updates
**backend/CLAUDE.md:**
- Added comprehensive Player Models section (204 lines)
- Updated Current Phase status to Week 6 (~50% complete)
- Documented all optimizations and bug fixes
- Added integration examples and usage patterns
**New Files:**
- .claude/implementation/week6-status-assessment.md
- Comprehensive Week 6 progress review
- Architecture decision rationale (single-layer vs two-layer)
- Completion status and next priorities
- Updated roadmap for remaining Week 6 work
## Test Results
- Player models: 32/32 tests passing
- All existing tests continue to pass
- Performance improvements verified with terminal client
## Next Steps (Week 6 Remaining)
1. Configuration system (BaseConfig, SbaConfig, PdConfig)
2. Result charts & PD play resolution with ratings
3. API client for live roster data (deferred)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Replaced awkward "lookback" pattern with clean "prepare → execute → save"
orchestration that captures state snapshots BEFORE each play.
Key improvements:
- Added per-team batter indices (away_team_batter_idx, home_team_batter_idx)
- Added play snapshot fields (current_batter/pitcher/catcher_lineup_id)
- Added on_base_code bit field for efficient base situation queries
- Created _prepare_next_play() method for snapshot preparation
- Refactored start_game() with hard lineup validation requirement
- Refactored resolve_play() with explicit 6-step orchestration
- Updated _save_play_to_db() to use snapshots (no DB lookbacks)
- Enhanced state recovery to rebuild from last play (single query)
- Added defensive lineup position validator
Benefits:
- No special cases for first play
- Single source of truth in GameState
- Saves 18+ database queries per game
- Fast state recovery without replay
- Complete runner tracking (before/after positions)
- Explicit orchestration (easy to debug)
Testing:
- Added 3 new test functions (lineup validation, snapshot tracking, batting order)
- All 5 test suites passing (100%)
- Type checking cleaned up with targeted suppressions for SQLAlchemy
Documentation:
- Added comprehensive "Type Checking & Common False Positives" section to CLAUDE.md
- Created type-checking-guide.md and type-checking-summary.md
- Added mypy.ini configuration for SQLAlchemy/Pydantic
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Updated Lineup model to support both leagues using the same pattern as RosterLink:
- Made card_id nullable (PD league)
- Added player_id nullable (SBA league)
- Added XOR CHECK constraint to ensure exactly one ID is populated
- Created league-specific methods: add_pd_lineup_card() and add_sba_lineup_player()
- Replaced generic create_lineup_entry() with league-specific methods
Database migration applied to convert existing schema.
Bonus fix: Resolved Pendulum DateTime + asyncpg timezone compatibility issue
by using .naive() on all DateTime defaults in Game, Play, and GameSession models.
Updated tests to use league-specific lineup methods.
Archived migration docs and script to .claude/archive/ for reference.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Added league-agnostic roster tracking with single-table design:
Database Changes:
- Modified RosterLink model with surrogate primary key (id)
- Added nullable card_id (PD) and player_id (SBA) columns
- Added CHECK constraint ensuring exactly one ID populated (XOR logic)
- Added unique constraints for (game_id, card_id) and (game_id, player_id)
- Imported CheckConstraint and UniqueConstraint from SQLAlchemy
New Files:
- app/models/roster_models.py: Pydantic models for type safety
- BaseRosterLinkData: Abstract base class
- PdRosterLinkData: PD league card-based rosters
- SbaRosterLinkData: SBA league player-based rosters
- RosterLinkCreate: Request validation model
- tests/unit/models/test_roster_models.py: 24 unit tests (all passing)
- Tests for PD/SBA roster link creation and validation
- Tests for RosterLinkCreate XOR validation
- Tests for polymorphic behavior
Database Operations:
- add_pd_roster_card(): Add PD card to game roster
- add_sba_roster_player(): Add SBA player to game roster
- get_pd_roster(): Get PD cards with optional team filter
- get_sba_roster(): Get SBA players with optional team filter
- remove_roster_entry(): Remove roster entry by ID
Tests:
- Added 12 integration tests for roster operations
- Fixed setup_database fixture scope (module → function)
Documentation:
- Updated backend/CLAUDE.md with RosterLink documentation
- Added usage examples and design rationale
- Updated Game model relationship description
Design Pattern:
Single table with application-layer type safety rather than SQLAlchemy
polymorphic inheritance. Simpler queries, database-enforced integrity,
and Pydantic type safety at application layer.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Initialize both Nuxt 3 frontends (SBA and PD) with full configuration:
Frontend Setup:
- Initialized Nuxt 3 projects for both leagues (SBA and PD)
- Installed dependencies: Tailwind CSS, Pinia, Socket.io-client, Axios
- Configured league-specific settings in nuxt.config.ts
- Created WebSocket plugins for real-time communication
- Set up TypeScript with strict mode and type checking
- Configured Tailwind CSS for styling
Backend Updates:
- Updated database models documentation in backend/CLAUDE.md
- Enhanced db_models.py with additional relationship patterns
Documentation:
- Updated Phase 1 completion checklist (12/12 items - 100% complete)
- Marked all infrastructure objectives as complete
Running Services:
- Backend (FastAPI + Socket.io): http://localhost:8000
- Frontend SBA: http://localhost:3000
- Frontend PD: http://localhost:3001
- Redis: port 6379
- PostgreSQL: Connected to remote server
Phase 1 is now complete. Ready to proceed to Phase 2 (Game Engine Core).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented full FastAPI backend with WebSocket support, database models,
and comprehensive documentation for the Paper Dynasty game engine.
Backend Implementation:
- FastAPI application with Socket.io WebSocket server
- SQLAlchemy async database models (Game, Play, Lineup, GameSession)
- PostgreSQL connection to dev server (10.10.0.42:5432)
- Connection manager for WebSocket lifecycle
- JWT authentication utilities
- Health check and stub API endpoints
- Rotating file logger with Pendulum datetime handling
- Redis via Docker Compose for caching
Technical Details:
- Python 3.13 with updated package versions
- Pendulum 3.0 for all datetime operations
- Greenlet for SQLAlchemy async support
- Fixed SQLAlchemy reserved column names (metadata -> *_metadata)
- Pydantic Settings with JSON array format for lists
- Docker Compose V2 commands
Documentation:
- Updated backend/CLAUDE.md with environment-specific details
- Created .claude/ENVIRONMENT.md for gotchas and quirks
- Created QUICKSTART.md for developer onboarding
- Documented all critical learnings and troubleshooting steps
Database:
- Tables created: games, plays, lineups, game_sessions
- All indexes and foreign keys configured
- Successfully tested connection and health checks
Verified:
- Server starts at http://localhost:8000
- Health endpoints responding
- Database connection working
- WebSocket infrastructure functional
- Hot-reload working
🎯 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Add comprehensive project documentation and Docker infrastructure for
Paper Dynasty Real-Time Game Engine - a web-based multiplayer baseball
simulation platform replacing the legacy Google Sheets system.
Documentation Added:
- Complete PRD (Product Requirements Document)
- Project README with dual development workflows
- Implementation guide with 5-phase roadmap
- Architecture docs (backend, frontend, database, WebSocket)
- CLAUDE.md context files for each major directory
Infrastructure Added:
- Root docker-compose.yml for full stack orchestration
- Dockerfiles for backend and both frontends (multi-stage builds)
- .dockerignore files for optimal build context
- .env.example with all required configuration
- Updated .gitignore for Python, Node, Nuxt, and Docker
Project Structure:
- backend/ - FastAPI + Socket.io game engine (Python 3.11+)
- frontend-sba/ - SBA League Nuxt 3 frontend
- frontend-pd/ - PD League Nuxt 3 frontend
- .claude/implementation/ - Detailed implementation guides
Supports two development workflows:
1. Local dev (recommended): Services run natively with hot-reload
2. Full Docker: One-command stack orchestration for testing/demos
Next: Phase 1 implementation (backend/frontend foundations)