Game Engine Improvements:
- State manager: Add game eviction with configurable max games, idle
timeout, and memory limits
- Game engine: Add resource cleanup on game completion
- Play resolver: Enhanced RunnerAdvancementData with lineup_id for
player name resolution in play-by-play
- Substitution manager: Minor improvements
Test Coverage:
- New test_game_eviction.py with 13 tests for eviction scenarios
- Updated state_manager tests for new functionality
- Updated play_resolver tests for lineup_id handling
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Add rate_limit.py middleware with per-client throttling and cleanup task
- Add pool_monitor.py for database connection pool health monitoring
- Add custom exceptions module (GameEngineError, DatabaseError, etc.)
- Add config settings for eviction intervals, session timeouts, memory limits
- Add unit tests for rate limiting and pool monitoring
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Changed cookie SameSite policy from Lax to None with Secure=true
for Safari ITP compatibility
- Fixed Nuxt composable context issue: moved useRuntimeConfig() from
connect() callback to composable setup phase (required in Nuxt 4)
- Added GET /logout endpoint for easy browser-based logout
- Improved loading overlay with clear status indicators and action
buttons (Retry, Re-Login, Dismiss)
- Added error handling with try-catch in WebSocket connect()
- Documented issue and fixes in .claude/SAFARI_WEBSOCKET_ISSUE.md
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Fixed missing PlayOutcome.HIT_BY_PITCH handling in resolve_outcome().
HBP was being submitted via WebSocket but rejected with error:
"Unhandled outcome: PlayOutcome.HIT_BY_PITCH"
Changes:
- Added HBP case to play_resolver.py (lines 430-446)
- HBP uses same forced runner advancement logic as WALK
- HBP is NOT classified as is_walk=True (correct for stats)
- Added 2 unit tests: test_hit_by_pitch, test_hit_by_pitch_bases_loaded
Test results: 981/981 passing (100%)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Added rollback_play WebSocket handler (handlers.py:1632)
- Accepts game_id and num_plays (default: 1)
- Validates game state and play count
- Broadcasts play_rolled_back and game_state_update events
- Full error handling with rate limiting
- Added undoLastPlay action to useGameActions composable
- Emits rollback_play event to backend
- Added Undo button to game page ([id].vue)
- Amber floating action button with undo arrow icon
- Positioned above substitutions button
- Only visible when game is active and has plays
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Resolved WebSocket connection issues and games list loading on iPad:
- cookies.py: Added is_secure_context() to set Secure flag when accessed
via HTTPS even in development mode (Safari requires this)
- useWebSocket.ts: Changed auto-connect from immediate watcher to
onMounted hook for safer SSR hydration
- games/index.vue: Replaced onMounted + fetchGames() with useAsyncData
for SSR data fetching with proper cookie forwarding
- Updated COOKIE_AUTH_IMPLEMENTATION.md with new issues and solutions
- Updated composables/CLAUDE.md with auto-connect pattern documentation
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Two related bug fixes for gameplay accuracy:
**Backend - play_resolver.py**:
- Fixed DOUBLE2 advancement: Runners now advance exactly 2 bases
* 1st → 3rd, 2nd → home, 3rd → home
* Was incorrectly advancing all runners to home
- Fixed DOUBLE3 advancement: Runners now advance exactly 3 bases
* All runners score (1st+3=4, 2nd+3=5→4, 3rd+3=6→4)
* Updated docstrings for clarity
**Frontend - ManualOutcomeEntry.vue**:
- Fixed hit location requirement logic
* Now requires hit location when runners on base (any outs)
* Was incorrectly restricting to only when outs < 2
* Hit location determines runner advancement regardless of outs
These fixes ensure accurate Strat-O-Matic gameplay simulation.
🤖 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>
This commit fixes two critical bugs in the game engine and updates tests
to match current webhook behavior:
1. State Recovery - Batter Advancement (operations.py:545-546)
- Added missing batting_order and outs_recorded fields to plays dictionary
- These fields exist in database but weren't loaded by load_game_state()
- Root cause: Batter index was correctly recovered but current_batter remained
at placeholder (batting_order=1) because recovery logic couldn't find the
actual batting_order from last play
- Fix enables proper batter advancement after backend restarts
2. Flyball Descriptions - 2 Outs Logic (runner_advancement.py)
- Made flyball descriptions dynamic based on outs and actual base runners
- FLYOUT_A (Deep): Lines 1352-1363
- FLYOUT_B (Medium): Lines 1438-1449
- FLYOUT_BQ (Medium-shallow): Lines 1521-1530
- With 2 outs: "3rd out, inning over" (no advancement possible)
- With 0-1 outs: Dynamic based on runners ("R3 scores" only if R3 exists)
- Game logic was already correct (runs_scored=0), only descriptions were wrong
- Fixed method signatures to include hit_location parameter for all flyball methods
- Updated X-check function calls to pass hit_location parameter
3. Test Updates
- Fixed test expectation in test_flyball_advancement.py to match corrected behavior
- Descriptions now only show runners that actually exist (no phantom "R2 DECIDE")
- Auto-fixed import ordering with Ruff
- Updated websocket tests to match current webhook behavior:
* test_submit_manual_outcome_success now expects 2 broadcasts (play_resolved + game_state_update)
* test_submit_manual_outcome_missing_required_location updated to reflect hit_location now optional
Testing:
- All 739 unit tests passing (100%)
- Verified batter advances correctly after state recovery
- Verified flyball with 2 outs shows correct description
- Verified dynamic descriptions only mention actual runners on base
- Verified websocket handler broadcasts work correctly
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Remove accidentally created backend/pages directory (Vue files belong in frontend).
Added pages/ to backend .gitignore to prevent future confusion.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Complete implementation of pre-game setup flow allowing players to create games
and submit lineups before gameplay starts.
Backend Changes:
- Extended games.py with create game, lineup submission, and game start endpoints
- Added teams.py roster endpoint with season filtering
- Enhanced SBA API client with player data fetching and caching
- Comprehensive validation for lineup submission (position conflicts, DH rules)
Frontend Changes:
- Redesigned create.vue with improved team selection and game options
- Enhanced index.vue with active/pending game filtering and navigation
- Added lineup/[id].vue for interactive lineup builder with drag-and-drop
- Implemented auth.client.ts plugin for client-side auth initialization
- Added comprehensive TypeScript types for API contracts
- Updated middleware for better auth handling
Key Features:
- Game creation with home/away team selection
- Full lineup builder with position assignment and batting order
- DH rule validation (pitcher can be excluded from batting order)
- Season-based roster filtering (Season 3)
- Auto-start game when both lineups submitted
- Real-time game list updates
Workflow:
1. Create game → select teams → set options
2. Submit home lineup → validate positions/order
3. Submit away lineup → validate positions/order
4. Game auto-starts → navigates to game page
5. WebSocket connection → loads game state
Ready for Phase F4 - connecting gameplay UI to complete the at-bat loop.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
## Authentication Implementation
### Backend
- Implemented complete Discord OAuth flow in auth.py:
* POST /api/auth/discord/callback - Exchange code for tokens
* POST /api/auth/refresh - Refresh JWT tokens
* GET /api/auth/me - Get authenticated user info
* GET /api/auth/verify - Verify auth status
- JWT token creation with 7-day expiration
- Refresh token support for session persistence
- Bearer token authentication for Discord API calls
### Frontend
- Created auth/login.vue - Discord OAuth initiation page
- Created auth/callback.vue - OAuth callback handler with states
- Integrated with existing auth store (already implemented)
- LocalStorage persistence for tokens and user data
- Full error handling and loading states
### Configuration
- Updated backend .env with Discord OAuth credentials
- Updated frontend .env with Discord Client ID
- Fixed redirect URI to port 3001
## SBA API Integration
### Backend
- Extended SbaApiClient with get_teams(season, active_only=True)
- Added bearer token auth support (_get_headers method)
- Created /api/teams route with TeamResponse model
- Registered teams router in main.py
- Filters out IL (Injured List) teams automatically
- Returns team data: id, abbrev, names, color, gmid, division
### Integration
- Connected to production SBA API: https://api.sba.manticorum.com
- Bearer token authentication working
- Successfully fetches ~16 active Season 3 teams
## Documentation
- Created SESSION_NOTES.md - Current session accomplishments
- Created NEXT_SESSION.md - Game creation implementation guide
- Updated implementation/NEXT_SESSION.md
## Testing
- ✅ Discord OAuth flow tested end-to-end
- ✅ User authentication and session persistence verified
- ✅ Teams API returns real data from production
- ✅ All services running and communicating
## What Works Now
- User can sign in with Discord
- Sessions persist across reloads
- Backend fetches real teams from SBA API
- Ready for game creation implementation
## Next Steps
See .claude/NEXT_SESSION.md for detailed game creation implementation plan.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Reviewed all remaining high-severity issues from code review:
Issues #6, #7 (Input validation): Already implemented in validators.py
- hold_runners validation: lines 71-77
- steal_attempts validation: lines 156-165
- Called from submit_defensive_decision and submit_offensive_decision
Issue #8 (Hardcoded inning limit): Deferred to next sprint
- Requires config system changes across validators.py and game_models.py
- Appropriate for technical debt phase
Issue #9 (Cleanup on abandon): Already fixed (part of Issue #3)
- _cleanup_game_resources() called in end_game() at line 1109
Issue #10 (Direct state mutation): Architectural acknowledgment
- Current pattern with debug logging throughout
- Consider immutable state pattern for v2 if auditability needed
Issue #11 (Logger singleton): Verified correct
- Module-level singleton at line 34, outside class
All high-priority issues now addressed or appropriately deferred.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Issue #5 from code review - resolve_play and resolve_manual_play shared
~70% of their code causing maintenance burden and divergent behavior risk.
Changes:
- Extracted common finalization logic to new _finalize_play() method
- resolve_play reduced from ~150 lines to ~60 lines
- resolve_manual_play reduced from ~135 lines to ~60 lines
- Single source of truth for: roll tracking, state capture, transaction
handling, inning advance, cleanup, and state updates
Benefits:
- Changes to play finalization only need to be made in one place
- Reduced risk of divergent behavior between resolution modes
- Better testability and maintainability
All 739 unit tests passing (1 flaky probabilistic test occasionally fails).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Issue #4 from code review - multi-step database operations were not
wrapped in transactions, risking partial state on failure.
Changes:
- Modified save_play() and update_game_state() in DatabaseOperations
to accept optional session parameter for transaction grouping
- Wrapped resolve_play() DB operations in single atomic transaction
- Wrapped resolve_manual_play() DB operations in single atomic transaction
- Transaction commits atomically or rolls back entirely on failure
Pattern: When session provided, use flush() for IDs without committing;
caller controls transaction. When no session, create internal transaction.
All 739 unit tests passing.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- test_game_data.py: Static lineup data based on real SBA Game 2519
- West Virginia Black Bears vs Columbus Hydra
- Complete lineup data with player info
- create_test_game.py: Script to end active games and create fresh test game
- Usage: uv run python scripts/create_test_game.py
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Backend fixes:
- state_manager: Properly recover current_pitcher and current_catcher from
fielding team during game state recovery (fixes pitcher badge not showing)
- handlers: Add headshot field to lineup data, use lineup_service for proper
player data loading on cache miss
- lineup_service: Minor adjustments for headshot support
Frontend fixes:
- player.ts: Update Lineup type to match WebSocket event format
- lineup_id (was 'id'), card_id fields
- player.headshot for UI circles
- Optional fields for event variations
- CurrentSituation.vue: Adapt to updated type structure
- Substitution selectors: Use updated Lineup type fields
This fixes the issue where pitcher badge wouldn't show after game recovery
because current_pitcher was being set from batting team instead of fielding team.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Created backend/.claude/DATABASE_SCHEMA.md with full table details
- Updated database/CLAUDE.md to reference the new schema doc
- Preserves valuable reference material while keeping CLAUDE.md concise
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Created centralized services for SBA player data fetching at lineup creation:
Backend - New Services:
- app/services/sba_api_client.py: REST client for SBA API (api.sba.manticorum.com)
with batch player fetching and caching support
- app/services/lineup_service.py: High-level service combining DB operations
with API calls for complete lineup entries with player data
Backend - Refactored Components:
- app/core/game_engine.py: Replaced raw API calls with LineupService,
reduced _prepare_next_play() from ~50 lines to ~15 lines
- app/core/substitution_manager.py: Updated pinch_hit(), defensive_replace(),
change_pitcher() to use lineup_service.get_sba_player_data()
- app/models/game_models.py: Added player_name/player_image to LineupPlayerState
- app/services/__init__.py: Exported new LineupService components
- app/websocket/handlers.py: Enhanced lineup state handling
Frontend - SBA League:
- components/Game/CurrentSituation.vue: Restored player images with fallback
badges (P/B letters) for both mobile and desktop layouts
- components/Game/GameBoard.vue: Enhanced game board visualization
- composables/useGameActions.ts: Updated game action handling
- composables/useWebSocket.ts: Improved WebSocket state management
- pages/games/[id].vue: Enhanced game page with better state handling
- types/game.ts: Updated type definitions
- types/websocket.ts: Added WebSocket type support
Architecture Improvement:
All SBA player data fetching now goes through LineupService:
- Lineup creation: add_sba_player_to_lineup()
- Lineup loading: load_team_lineup_with_player_data()
- Substitutions: get_sba_player_data()
All 739 unit tests pass.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Removed the incorrect restriction that squeeze bunt cannot be used with bases
loaded. The only requirements for squeeze bunt are:
- Runner on third base
- Not with 2 outs
Updated validator and test to reflect correct rule.
Test results: 739/739 passing (100%)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Removed the unused alignment field from DefensiveDecision model and all
related code across backend and frontend.
Backend changes:
- models/game_models.py: Removed alignment field and validator
- terminal_client/display.py: Removed alignment from display
- core/ai_opponent.py: Updated log message
- tests/unit/models/test_game_models.py: Removed alignment tests
- tests/unit/core/test_validators.py: Removed alignment validation test
Frontend changes:
- types/game.ts: Removed alignment from DefensiveDecision interface
- components/Decisions/DefensiveSetup.vue:
* Removed alignment section from template
* Removed alignment from localSetup initialization
* Removed alignmentOptions array
* Removed alignmentDisplay computed property
* Removed alignment from hasChanges comparison
* Removed alignment from visual preview (reorganized to col-span-2)
Rationale: Defensive alignment is not active in the game and will not be
used. Per Cal's decision, remove completely rather than keep as dead code.
Tests: All 728 backend unit tests passing (100%)
Session 1 Part 3 - Change #6 complete
Part of cleanup work from demo review
🤖 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>
Fixed failing test caught by pre-commit hook. The test was not properly
mocking dependencies in the resolve_play command.
Changes:
- Added mock for state_manager.get_state() to return valid state
- Added mock for random.choice() to return deterministic PlayOutcome
- Updated assertion to expect auto-generated outcome (SINGLE_1)
- Test now properly validates the auto-outcome behavior for terminal testing
Root cause: resolve_play() checks state_manager early and auto-generates
a random outcome for testing when no forced outcome is provided. Test was
not accounting for either behavior.
All 731 unit tests now passing (100%).
🤖 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 CLAUDE.md files to document recent changes including the GameState
refactoring and new X-Check testing capabilities in the terminal client.
Changes to app/models/CLAUDE.md:
- Updated GameState field documentation
- Replaced current_batter_lineup_id references with current_batter
- Documented LineupPlayerState requirement for current players
- Added comprehensive usage examples
- Added "Recent Updates" section documenting GameState refactoring
- Before/after code examples showing migration path
- Explanation of why the change was made
- Migration notes for developers
- List of all affected files (7 files updated)
Changes to terminal_client/CLAUDE.md:
- Added "2025-11-04: X-Check Testing & GameState Refactoring" section
- New feature: resolve_with x-check <position> command
- Complete X-Check resolution with defense tables and error charts
- Shows all resolution steps with audit trail
- Works with actual player ratings from PD API
- Documented 8 X-Check commands now in help system
- roll_jump / test_jump, roll_fielding / test_fielding
- test_location, rollback, force_wild_pitch, force_passed_ball
- Bug fixes documented
- GameState structure updates (display.py, repl.py)
- Game recovery fix (state_manager.py)
- DO3 advancement fix (play_resolver.py)
- Complete testing workflow examples
- List of 7 files updated
- Test coverage status (all passing)
- Updated footer: Last Updated 2025-11-04
These documentation updates provide clear migration guides for the GameState
refactoring and comprehensive examples for the new X-Check testing features.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Updated runner_advancement.py and its tests to use the new GameState
structure where current_batter is a LineupPlayerState object instead of
an integer ID.
Changes:
- runner_advancement.py: Replaced all 17 references to
state.current_batter_lineup_id with state.current_batter.lineup_id
- tests/unit/core/test_runner_advancement.py: Updated test fixtures
- Mock fixture: Added mock_batter object with lineup_id attribute
- GameState constructor calls: Create LineupPlayerState objects instead
of using current_batter_lineup_id parameter (9 tests fixed)
All 34 runner advancement tests now passing. This fixes the AttributeError
that was preventing X-Check resolution from completing in the terminal
client ("'GameState' object has no attribute 'current_batter_lineup_id'").
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Added ability to test X-Check defensive plays directly in the terminal
client using the resolve_with command. This allows testing the complete
X-Check resolution system (defense tables, error charts, runner advancement)
with actual player ratings.
Changes:
- repl.py: Updated do_resolve_with() to parse "x-check <position>" syntax
- Accepts "x-check", "xcheck", or "x_check" followed by position
- Validates position (P, C, 1B, 2B, 3B, SS, LF, CF, RF)
- Passes xcheck_position parameter through to commands
- commands.py: Updated resolve_play() to accept xcheck_position parameter
- Passes xcheck_position to game_engine.resolve_play()
- Shows "🎯 Forcing X-Check to: <position>" message
- game_engine.py: Updated resolve_play() to accept xcheck_position parameter
- For X_CHECK outcomes, uses xcheck_position as hit_location
- Enables full X-Check resolution with defense tables and error charts
- help_text.py: Updated resolve_with help documentation
- Added x-check usage syntax and examples
- Documented position parameter requirement
- Added note about using actual player ratings
Usage:
⚾ > defensive
⚾ > offensive
⚾ > resolve_with x-check SS # Test X-Check to shortstop
⚾ > resolve_with x-check LF # Test X-Check to left field
This integrates the existing play_resolver._resolve_x_check() logic,
providing a way to test the complete X-Check system including defense
range adjustments, table lookups, SPD tests, G2#/G3# conversion, error
charts, and runner advancement.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Added documentation for 8 X-Check testing and gameplay commands that
were implemented but missing from the help system:
X-Check Testing Commands:
- roll_jump: Roll jump dice for stolen base testing
- test_jump: Test jump roll distribution statistics
- roll_fielding: Roll fielding check dice for X-Check defensive plays
- test_fielding: Test fielding roll distribution
Testing & Development:
- test_location: Test hit location distribution
- rollback: Roll back the last N plays
Interrupt Plays:
- force_wild_pitch: Force a wild pitch interrupt play
- force_passed_ball: Force a passed ball interrupt play
Changes:
- help_text.py: Added new command categories to show_command_list()
- "X-Check Testing" section with 4 dice testing commands
- "Interrupt Plays" section with 2 force commands
- Moved test_location and rollback to "Testing & Development"
- help_text.py: Added detailed HELP_DATA entries for all 8 commands
- Complete usage, options, examples, and notes for each
- Includes dice component explanations and expected distributions
Users can now run 'help' to see all commands or 'help <command>' for
detailed information about X-Check testing features.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Fixed state_manager._rebuild_state_from_data to provide required
current_batter field when recovering games from database. The GameState
model now requires current_batter as a LineupPlayerState object, but
recovery was not populating this field, causing validation errors.
Changes:
- state_manager.py: Create placeholder current_batter during recovery
- Build LineupPlayerState from first active batter (batting_order=1)
- Fallback to first available lineup if no #1 batter found
- Raise error if no lineups exist (invalid game state)
- _prepare_next_play() will correct the batter after recovery
- Moved get_lineup_player helper to top of method (removed duplicate)
- tests/unit/core/test_state_manager.py: Update test to use new structure
- test_update_state_nonexistent_raises_error: Create LineupPlayerState
instead of using old current_batter_lineup_id field
All 26 state_manager unit tests passing. Game recovery now works
correctly in terminal client - fixes "current_batter Field required"
validation error when running status command on recovered games.
🤖 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>
Updated terminal_client/CLAUDE.md to use UV commands.
## Changes
- Updated REPL start command: uv run python -m terminal_client
- Updated standalone commands to use uv run prefix
- Added alternative manual activation option
- Consistent with all other project documentation
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Fixed Docker build issues to complete UV migration.
## Changes
### README.md
- Created backend README.md (required by hatchling build system)
- Simple quick start guide referencing CLAUDE.md
### Dockerfile
- Added `build-essential` for compiling native extensions (pendulum Rust code)
- Updated copy steps to include README.md in both dev and prod stages
- Dockerfile now successfully builds both development and production images
### .dockerignore
- Added exception `!README.md` to allow README.md through
- Keeps other *.md files excluded as intended
## Testing
- ✅ Development image builds successfully (paper-dynasty-backend:dev-uv)
- ✅ Production image builds successfully (paper-dynasty-backend:prod-uv)
- ✅ Container starts and UV installs dependencies correctly
- ✅ Application attempts to start (fails only on missing .env, as expected)
## Build Results
- Dev image: 73 packages installed (with dev deps)
- Prod image: 57 packages installed (no dev deps)
- Both stages use `uv sync --frozen` for reproducible builds
- Build time: ~1-2 minutes per stage
🤖 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>