strat-gameplay-webapp/.claude/implementation/NEXT_SESSION.md
Claude 683954f6e4
CLAUDE: Update implementation notes to reflect Phase 2 completion
Updated documentation to accurately reflect all work completed in Phase 2:

**NEXT_SESSION.md Updates**:
- Updated last commit reference: 4cf349a313c2c8 (Phase 2 merge)
- Added "Additional Phase 2 Completions" section documenting:
  - 8,799 lines of comprehensive CLAUDE.md documentation
  - Flyball advancement system integration (21 new tests)
  - FLYOUT_BQ variant addition (4 flyball types total)
  - ManualOutcomeSubmission enum refactoring
  - State recovery fixes
- Updated test counts: ~540 total tests (all passing)
- Added branch information: implementation-phase-3
- Clarified status: Phase 2 COMPLETE → Phase 3 Ready to Begin

**00-index.md Updates**:
- Expanded implementation status table with Phase 2 completions:
  - Runner Advancement, Strategic Decisions, Result Charts
  - WebSocket Manual Mode, Terminal Client, Comprehensive Docs
- Updated test suite status: ~540 tests passing
- Added Phase 2 completion to decisions log (2025-10-31)
- Updated "Last Updated" section for 2025-11-03
- Changed phase status to "Ready to Begin" for Phase 3

These notes now accurately reflect all commits from 4cf349a through 313c2c8,
including the major flyball integration, documentation additions, and test
updates that happened after the initial Week 7 completion.
2025-11-03 13:18:01 +00:00

12 KiB

Next Session Plan - Week 8: Substitutions & Advanced Gameplay

Current Status: Phase 2 COMPLETE (100%) → Phase 3 Ready to Begin Last Commit: 313c2c8 - "Merge pull request #1 from calcorum/implement-phase-2" Date: 2025-10-31 Branch: implementation-phase-3 (newly created) Next Priority: Week 8 - Player substitutions, pitching changes, and game management features


🎉 Phase 2 Summary - COMPLETE!

All Week 7 tasks completed successfully, PLUS additional polish:

Task 1: Strategic Decision Integration

  • Async decision workflow with asyncio.Future
  • Defensive decision queue: alignment, infield/outfield depth, hold runners
  • Offensive decision queue: approach, steal attempts, bunting
  • Full integration with GameEngine

Task 2: Decision Validators (54 tests)

  • DefensiveDecision validation: positioning rules, depth requirements
  • OffensiveDecision validation: steal/bunt prerequisites
  • Lineup validation: complete defensive positioning
  • Game flow validation: inning/out state checks

Task 3: Result Charts + PD Auto Mode (21 tests)

  • ResultChart abstract base class
  • PdAutoResultChart for auto-generated outcomes
  • ManualResultChart for player submissions
  • calculate_hit_location() helper (pull rates, handedness)
  • ManualOutcomeSubmission validation model

Task 4: Runner Advancement Logic (30 tests)

  • RunnerAdvancement class with 13 result types
  • Infield Back chart (default positioning)
  • Infield In chart (runner on 3rd)
  • Corners In positioning (hybrid approach)
  • Full groundball outcome resolution

Task 5: Double Play Mechanics

  • Integrated into Task 4 RunnerAdvancement
  • Base probability: 45% with modifiers
  • Positioning: Infield In (-15%), Normal (0%)
  • Hit location: Middle infield (+10%), Corners (-10%)
  • Probabilistic execution (not deterministic)

Task 6: PlayResolver Integration (9 tests)

  • Outcome-first architecture - Manual mode is primary
  • resolve_outcome() core method - all game logic
  • resolve_manual_play() wrapper for player submissions
  • resolve_auto_play() wrapper for PD auto mode
  • RunnerAdvancement integrated for all groundballs
  • hit_location tracked in PlayResult
  • Removed obsolete SimplifiedResultChart and singleton

Task 7: WebSocket Manual Outcome Handlers (12 tests)

  • roll_dice event: Server rolls, broadcasts to players
  • submit_manual_outcome event: Players submit after reading cards
  • GameEngine.resolve_manual_play() orchestration
  • Terminal client commands: roll_dice, manual_outcome

Task 8: Terminal Client Enhancement

  • Manual outcome submission commands
  • Full REPL integration
  • Testing without frontend

Additional Phase 2 Completions (Post-Week 7)

Comprehensive Documentation

  • 8,799 lines of CLAUDE.md across all backend/app/ subdirectories
  • Complete architecture documentation for:
    • app/api/ - FastAPI routes and patterns (906 lines)
    • app/config/ - League configs and result charts (906 lines)
    • app/core/ - Game engine and state management (1,288 lines)
    • app/data/ - API clients and caching (937 lines)
    • app/database/ - Async operations and recovery (945 lines)
    • app/models/ - Polymorphic patterns and models (1,270 lines)
    • app/utils/ - Logging, JWT, security (959 lines)
    • app/websocket/ - Socket.io handlers (1,588 lines)
    • tests/ - Testing patterns (475 lines)

Flyball Advancement System Integration

  • FLYOUT_BQ variant added - 4 flyball types: A (deep), B (medium), BQ (medium-shallow), C (shallow)
  • RunnerAdvancement extended - Now handles both groundballs AND flyballs
  • PlayResolver refactored - Consolidated all 4 flyball outcomes (DRY principle)
  • State recovery fixed - Proper LineupPlayerState construction from database
  • 21 new flyball tests - Comprehensive coverage of all flyball mechanics
  • Type safety improvements - Fixed lineup_id access patterns throughout

Model Refinements

  • ManualOutcomeSubmission - Refactored to use PlayOutcome enum (better type safety)
  • Test suite updated - All tests match Phase 2 model changes
  • GameState.current_batter_lineup_id - Now non-optional (always set by _prepare_next_play)

Testing Summary

  • ~540 total tests - All passing (Phase 2 complete)
  • 147 new tests for Week 7 - Including 21 flyball tests
  • Manual testing: 8/8 scenarios verified
  • Test files updated: All aligned with Phase 2 models

🚀 Week 8: Substitutions & Advanced Gameplay

Focus: Player substitutions, pitching management, and advanced game features

Planned Tasks

Task 1: Substitution System

  • Pinch hitters - Replace batter mid-at-bat or in lineup
  • Pinch runners - Replace runner on base
  • Defensive replacements - Swap fielders
  • Database tracking: replacing_id, after_play, entered_inning
  • Validation: DH rules, position eligibility, one-way substitutions

Task 2: Pitching Changes

  • Relief pitcher - Bring in from bullpen
  • Pitching fatigue - Track pitch count and is_fatigued flag
  • Bullpen management - Available relievers, warmup status
  • Closer/setup roles - Strategic substitution timing

Task 3: Advanced Game Rules

  • Steal attempts - Use OffensiveDecision.steal_attempts
  • Caught stealing resolution - JumpRoll mechanics
  • Pick-off attempts - Pitcher vs runner
  • Balk detection - Using chaos_d20 rolls

Task 4: Game State Persistence

  • Save/load functionality - Store/restore game mid-play
  • Replay system - Rebuild state from play history
  • Recovery on crash - Automatic state reconstruction

Task 5: Enhanced Terminal Client

  • Substitution commands - pinch_hit, pinch_run, defensive_sub
  • Pitching commands - change_pitcher, bullpen_status
  • Better status display - Show fatigue, available subs

Quick Start for Next AI Agent

🎯 Where to Begin (Week 8)

  1. Read Week 8 plan (to be created): @.claude/implementation/WEEK_8_PLAN.md
  2. Review database models: @app/models/db_models.py
    • Check Lineup model: replacing_id, after_play, is_fatigued fields
    • These are already in place from Phase 1!
  3. Start with Task 1: Substitution system
    • Create SubstitutionManager class
    • Implement pinch hitter logic first (simplest case)
    • Add validation rules

📍 Current Architecture (Week 7 Complete)

Game Engine Flow:

# Manual mode (SBA + PD manual)
GameEngine.resolve_manual_play(
    game_id, ab_roll, outcome, hit_location
)  PlayResult

# Auto mode (PD only)
GameEngine.resolve_play(game_id)  PlayResult

Play Resolution:

PlayResolver(league_id, auto_mode)
  ├── resolve_manual_play(submission, state, ...)  PlayResult
  ├── resolve_auto_play(state, batter, pitcher, ...)  PlayResult
  └── resolve_outcome(outcome, hit_location, state, ...)  PlayResult (core)

Runner Advancement:

RunnerAdvancement.advance_runners(
    outcome, hit_location, state, defensive_decision
)  AdvancementResult

🔑 Key Files for Week 8

Substitution System:

  • app/models/db_models.py - Lineup model (already has substitution fields!)
  • app/core/substitution_manager.py (NEW) - Handle substitution logic
  • app/core/validators.py - Add substitution validation
  • tests/unit/core/test_substitution_manager.py (NEW)

Pitching Changes:

  • app/core/game_engine.py - Add change_pitcher() method
  • app/models/game_models.py - Add pitching state tracking
  • app/core/validators.py - Validate pitcher eligibility

Terminal Client:

  • terminal_client/commands.py - Add sub commands
  • terminal_client/repl.py - Add REPL integration

🧪 Testing Strategy

# Run substitution tests
export PYTHONPATH=. && pytest tests/unit/core/test_substitution_manager.py -v

# Run all core tests (should still pass)
export PYTHONPATH=. && pytest tests/unit/core/ -v

# Manual testing in terminal client
python -m terminal_client
> new_game
> start_game
> pinch_hit 5 101  # Pinch hit for batting order 5 with lineup_id 101
> status

Week 7 Architectural Decisions (Reference)

1. Outcome-First PlayResolver Architecture

  • Manual mode is primary - Most games use this (all SBA + half of PD)
  • Core resolve_outcome() method - All game logic in one place
  • Thin wrappers - resolve_manual_play() and resolve_auto_play()
  • No hard-coded exceptions - Multi-step plays handled generically by GameEngine

2. Auto Mode Configuration

  • Stored per-game - GameState.auto_mode field
  • League validation - supports_auto_mode() in config
    • SBA: False (raises error if attempted)
    • PD: True (has digitized ratings)

3. Hit Location Tracking

  • Critical for advancement - Determines chart row and conditionals
  • Groundballs - Must specify location (1B, 2B, 3B, SS, P, C)
  • Flyouts - Track for future tag-up logic (LF, CF, RF)
  • Other outcomes - None (walks, strikeouts, etc.)

4. Manual vs Auto Mode

Manual Mode (primary):

1. Server rolls dice  AbRoll
2. Broadcasts dice to players via WebSocket
3. Players read physical cards
4. Players submit outcome + location
5. Server validates ManualOutcomeSubmission
6. Server resolves with RunnerAdvancement
7. Broadcasts result

Auto Mode (PD only, rare):

1. Server rolls dice  AbRoll
2. PdAutoResultChart.get_outcome(roll, batter, pitcher)  outcome + location
3. Server resolves with RunnerAdvancement
4. Broadcasts result

Important Patterns & Conventions

Testing

  • Always use venv: source venv/bin/activate
  • Set PYTHONPATH: export PYTHONPATH=.
  • Run tests after each change: pytest tests/unit/core/ -v

Git Commits

  • Prefix with "CLAUDE: ": All commits must start with this
  • Descriptive messages: Include what changed and why
  • Reference tasks: "Implement Week 8 Task 1 - Substitution System"

Code Style

  • Pydantic dataclasses - For models and validation
  • Async/await - All database operations
  • Frozen configs - Immutable league configurations
  • "Raise or Return" - No Optional unless required
  • Pendulum for dates - Never use Python's datetime

Documentation

  • Update NEXT_SESSION.md - After completing tasks
  • Add TODO comments - For future work
  • Docstrings - Google style for classes and public methods

Current Test Status

Total Tests: ~540 tests (All passing )

  • Config: 79/79 (58 base + 21 result charts)
  • Validators: 54/54
  • Runner Advancement: 30/30 (groundballs)
  • Flyball Advancement: 21/21 (NEW in Phase 2 final)
  • PlayResolver: 9/9 (rewritten for new architecture)
  • WebSocket Handlers: 12/12
  • Dice: 35/35
  • Roll Types: 27/27
  • Player Models: 32/32
  • Game Models: ~150+
  • State Manager: ~80+
  • Terminal Client: ~40+

Week 8 Target: Add ~50 new tests for substitutions and pitching


Database & Environment

Database: PostgreSQL @ 10.10.0.42:5432 (paperdynasty_dev) Python: 3.13.3 Virtual Env: backend/venv/ Branch: implement-phase-2

Key Commands:

# Activate venv
cd backend && source venv/bin/activate

# Run tests
export PYTHONPATH=. && pytest tests/unit/core/ -v

# Terminal client
python -m terminal_client

# Check git status
git status

What NOT to Do

  • Don't modify database schema without migrations
  • Don't use Python's datetime (use Pendulum)
  • Don't return Optional unless required
  • Don't disable type checking globally
  • Don't skip validation
  • Don't commit without "CLAUDE: " prefix
  • Don't forget export PYTHONPATH=. when running tests
  • Don't hard-code multi-step play logic (keep it generic)

References

  • Implementation Guide: @.claude/implementation/01-infrastructure.md
  • Backend Architecture: @.claude/implementation/backend-architecture.md
  • Week 7 Plan: @.claude/implementation/WEEK_7_PLAN.md
  • Database Design: @.claude/implementation/database-design.md
  • Full PRD: @prd-web-scorecard-1.1.md

Status: Week 7 Complete - Ready for Week 8! Priority: High - Substitutions are core gameplay feature Estimated Time: Week 8 should take 3-5 sessions Next Milestone: Complete substitution system and pitching management