strat-gameplay-webapp/.claude/implementation/NEXT_SESSION.md
Cal Corum 119f169474 CLAUDE: Prepare NEXT_SESSION.md for Week 8
Comprehensive update for next session:

Week 7 Summary (100% Complete):
- All 8 tasks completed with full descriptions
- 126 new tests (all passing)
- 180/181 core tests passing
- Manual testing verified (8/8 scenarios)

Week 8 Preview:
- Task 1: Substitution system (pinch hitters, runners, defensive)
- Task 2: Pitching changes (relief, fatigue, bullpen)
- Task 3: Advanced rules (steals, pickoffs, balks)
- Task 4: Game state persistence (save/load/replay)
- Task 5: Enhanced terminal client

Quick Start Guide:
- Clear entry point for next agent
- Key files and architecture diagrams
- Testing strategy
- Important patterns and conventions

Architectural Reference:
- Outcome-first PlayResolver design
- Auto mode configuration
- Hit location tracking
- Manual vs auto mode flows

Ready for Week 8 implementation!

🎯 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-31 08:37:59 -05:00

10 KiB

Next Session Plan - Week 8: Substitutions & Advanced Gameplay

Current Status: Phase 3 - Week 7 Complete (100%) → Starting Week 8 Last Commit: 4cf349a - "CLAUDE: Update NEXT_SESSION.md - Week 7 complete at 100%" Date: 2025-10-31 Next Priority: Week 8 - Player substitutions, pitching changes, and game management features


🎉 Week 7 Summary - COMPLETE!

All 8 tasks completed successfully:

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

Testing Summary

  • 180/181 core tests passing (1 pre-existing failure in dice history)
  • 126 new tests for Week 7 - all passing
  • Manual testing: 8/8 scenarios verified

🚀 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: ~519 tests

  • Config: 79/79 (58 base + 21 result charts)
  • Validators: 54/54
  • Runner Advancement: 30/30
  • PlayResolver: 9/9 (rewritten for new architecture)
  • WebSocket Handlers: 12/12
  • Dice: 34/35 (1 pre-existing failure in get_rolls_since)
  • Roll Types: 27/27
  • Player Models: 32/32
  • Game Models: ~150+
  • State Manager: ~80+

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