Completed comprehensive planning for Phase 3.5 with focus on production readiness through materialized views approach for statistics. Planning Documents Created: - STAT_SYSTEM_ANALYSIS.md: Analysis of existing major-domo schema * Reviewed legacy BattingStat/PitchingStat tables (deprecated) * Analyzed existing /plays/batting and /plays/pitching endpoints * Evaluated 3 approaches (legacy port, modern, hybrid) - STAT_SYSTEM_MATERIALIZED_VIEWS.md: Recommended approach * PostgreSQL materialized views (following major-domo pattern) * Add stat fields to plays table (18 new columns) * 3 views: batting_game_stats, pitching_game_stats, game_stats * PlayStatCalculator service (~150 lines vs 400+ for StatTracker) * 80% less code, single source of truth, always consistent - phase-3.5-polish-stats.md: Complete implementation plan * Task 1: Game Statistics System (materialized views) * Task 2: Authorization Framework (WebSocket security) * Task 3: Uncapped Hit Decision Trees * Task 4: Code Cleanup (remove TODOs, integrate features) * Task 5: Integration Test Infrastructure * Estimated: 16-24 hours (2-3 days) NEXT_SESSION.md Updates: - Phase 3.5 ready to begin (0% → implementation phase) - Complete task breakdown with acceptance criteria - Materialized view approach detailed - Commit strategy for 3 separate commits - Files to review before starting Implementation Status Updates: - Phase 3: 100% Complete (688 tests passing) - Phase 3F: Substitution system fully tested - Phase 3.5: Planning complete, ready for implementation - Updated component status table with Phase 3 completion Key Decisions: - Use materialized views (not separate stat tables) - Add stat fields to plays table - Refresh views after game completion + on-demand - Use legacy field names (pa, ab, run, hit) for compatibility - Skip experimental fields (bphr, xba, etc.) for MVP Benefits of Materialized Views: - 80% less code (~400 lines → ~150 lines) - Single source of truth (plays table) - Always consistent (stats derived, not tracked) - Follows existing major-domo pattern - PostgreSQL optimized (indexed, cached) Next Steps: 1. Implement PlayStatCalculator (map PlayOutcome → stats) 2. Add stat fields to plays table (migration 004) 3. Create materialized views (migration 005) 4. Create BoxScoreService (query views) 5. Refresh logic after game completion 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
11 KiB
11 KiB
Paper Dynasty Real-Time Game Engine - Implementation Guide
Table of Contents
Architecture & Design
- Backend Architecture - FastAPI structure, game engine, state management
- Frontend Architecture - Vue/Nuxt structure, shared components, league-specific apps
- Database Design - Schema, indexes, operations, migration strategy
- WebSocket Protocol - Event specifications, connection lifecycle, error handling
Implementation Phases
Phase 1: Core Infrastructure (Weeks 1-3)
- 01 - Infrastructure Setup
- Backend foundation (FastAPI, PostgreSQL, Socket.io)
- Frontend foundation (Nuxt 3, TypeScript, Tailwind)
- Discord OAuth integration
- WebSocket connection management
- Basic session management
Phase 2: Game Engine Core (Weeks 4-6)
- 02 - Game Engine
- In-memory game state management
- Play resolution engine
- League configuration system
- Polymorphic player models
- Database persistence layer
- State recovery mechanism
Phase 3: Complete Game Features (Weeks 7-9) - ✅ COMPLETE
- 03 - Gameplay Features
- ✅ All strategic decision types
- ✅ Substitution system (SubstitutionRules, SubstitutionManager)
- ✅ Pitching changes (included in substitution system)
- ✅ Complete result charts (both leagues)
- ✅ X-Check system (position ratings, defense tables, Redis caching)
- ✅ GameState refactoring (consistent player references)
- 🔲 AI opponent integration (deferred to Phase 4+)
- 🔲 Async game mode support (deferred to Phase 4+)
Phase 3.5: Code Polish & Stat Tracking (2-3 days) - ⏳ IN PROGRESS
- phase-3.5-polish-stats
- Game statistics system (StatTracker, box scores)
- Authorization framework (AuthService, WebSocket auth)
- Uncapped hit decision trees
- Code cleanup (remove TODOs, integrate handedness, SPD test)
- Integration test infrastructure improvements
Phase 4: Spectator & Polish (Weeks 10-11)
- 04 - Spectator & Polish
- Spectator mode implementation
- UI/UX refinements
- Dice roll animations
- Mobile touch optimization
- Accessibility improvements
- Performance optimization
Phase 5: Testing & Launch (Weeks 12-13)
- 05 - Testing & Launch
- Comprehensive testing strategy
- Load testing procedures
- Security audit checklist
- Deployment procedures
- Monitoring setup
- Launch plan
Cross-Cutting Concerns
- Authentication & Authorization - Discord OAuth, session management, role-based access
- Testing Strategy - Unit, integration, e2e, load testing approaches
- Deployment Guide - Infrastructure setup, CI/CD, monitoring
- API Reference - REST endpoints, request/response formats
Implementation Status
| Component | Status | Phase | Notes |
|---|---|---|---|
| Backend Foundation | ✅ Complete | 1 | FastAPI, PostgreSQL, async session management |
| Frontend Foundation | 🔲 Not Started | 1 | Nuxt 3 apps pending |
| Discord OAuth | 🔲 Not Started | 1 | Auth system pending |
| WebSocket Server | ✅ Complete | 1-2 | Connection manager, manual outcome handlers |
| Game Engine Core | ✅ Complete | 2 | GameEngine with forward-looking snapshots |
| Database Schema | ✅ Complete | 2 | All tables created, polymorphic models working |
| Player Models | ✅ Complete | 2 | BasePlayer, SbaPlayer, PdPlayer with ratings |
| League Configs | ✅ Complete | 2 | SbaConfig, PdConfig with immutable settings |
| PlayOutcome Enum | ✅ Complete | 2 | Granular variants (SINGLE_1/2, GROUNDBALL_A/B/C, FLYOUT_A/B/BQ/C) |
| PlayResolver Integration | ✅ Complete | 2 | Universal PlayOutcome from app.config, metadata support |
| Dice System | ✅ Complete | 2 | chaos_d20 for WP/PB checks, resolution_d20 for outcomes |
| Runner Advancement | ✅ Complete | 2 | Unified system for groundballs AND flyballs |
| Strategic Decisions | ✅ Complete | 2 | DefensiveDecision, OffensiveDecision with validators |
| Result Charts | ✅ Complete | 2 | PdAutoResultChart, ManualResultChart |
| WebSocket Manual Mode | ✅ Complete | 2 | roll_dice, submit_manual_outcome events |
| Terminal Client | ✅ Complete | 2 | Full REPL with manual outcome testing |
| Comprehensive Docs | ✅ Complete | 2 | 8,799 lines of CLAUDE.md across all subdirectories |
| X-Check System | ✅ Complete | 3A-D | Position ratings, defense tables, error charts, Redis caching |
| GameState Refactoring | ✅ Complete | 3E | Consistent player references (all LineupPlayerState objects) |
| Substitutions | ✅ Complete | 3F | SubstitutionRules, SubstitutionManager, WebSocket events (688 tests) |
| Game Statistics | 🔲 Not Started | 3.5 | StatTracker, box scores, player/team stats |
| Authorization Framework | 🔲 Not Started | 3.5 | AuthService, WebSocket auth checks |
| Code Polish | 🔲 Not Started | 3.5 | Uncapped hits, cleanup TODOs |
| Pitching Changes | ✅ Complete | 3F | Included in substitution system |
| AI Opponent | 🟡 Stub | 4+ | Basic stub exists, needs implementation |
| Spectator Mode | 🔲 Not Started | 4 | - |
| UI Polish | 🔲 Not Started | 4 | - |
| Testing Suite | ✅ Complete | 3 | 688 tests passing (100% unit test coverage) |
| Deployment | 🔲 Not Started | 5 | - |
Quick Start
- Review Architecture Documents - Understand the system design before coding
- Follow Phase Order - Each phase builds on the previous
- Update Status - Keep the status table current as work progresses
- Reference PRD - Main PRD at
/prd-web-scorecard-1.1.mdfor detailed requirements
Key Decisions & Rationale
Why Hybrid State Management?
- In-Memory: Fast action processing, sub-500ms latency requirements
- PostgreSQL: Persistence, recovery, play history, async operations
- Best of Both: Performance without sacrificing reliability
Why Separate Frontends?
- League Branding: Each league maintains distinct identity
- Independent Deployment: Can update one league without affecting other
- Shared Components: 80%+ code reuse through component library
- Flexibility: League-specific features without codebase pollution
Why FastAPI + Socket.io?
- FastAPI: Modern async Python, automatic OpenAPI docs, Pydantic validation
- Socket.io: Mature WebSocket library, automatic reconnection, room support
- Python Ecosystem: Rich data processing libraries for game logic
Why Polymorphic Players?
- Type Safety: Each league's player structure validated at runtime
- Maintainability: League differences isolated in player classes
- Extensibility: Easy to add new leagues or modify existing ones
Critical Path Items
Must Have for MVP
- ✅ Game creation and lobby
- ✅ Complete turn-based gameplay
- ✅ Real-time WebSocket updates
- ✅ Game persistence and recovery
- ✅ Mobile-optimized UI
- ✅ Discord authentication
Nice to Have (Post-MVP)
- 🔲 Roster management
- 🔲 Marketplace
- 🔲 Tournament system
- 🔲 Advanced analytics
- 🔲 Discord bot notifications
Development Workflow
- Start Phase - Read phase markdown file thoroughly
- Create CLAUDE.md - Add subdirectory-specific context
- Implement - Follow TDD where appropriate
- Test - Unit tests as you go, integration tests per milestone
- Update Status - Mark components complete in index
- Review - Check against PRD requirements before moving on
Performance Budgets
| Metric | Target | Critical Threshold |
|---|---|---|
| Action Response | < 500ms | < 1000ms |
| WebSocket Delivery | < 200ms | < 500ms |
| DB Write (async) | < 100ms | < 250ms |
| State Recovery | < 2s | < 5s |
| Page Load (3G) | < 3s | < 5s |
Questions & Decisions Log
Track important decisions and open questions here as implementation progresses.
Open Questions
- Which VPS provider for deployment?
- Specific Discord OAuth scope requirements?
- AI opponent complexity level for MVP?
- Spectator chat feature in MVP or post-MVP?
Decisions Made
- 2025-10-21: Project initialized, implementation guide structure created
- 2025-10-22: Week 4 complete - State management and persistence working
- 2025-10-24: Week 5 complete - Game engine core with AbRoll dice system
- 2025-10-25: GameEngine refactored to forward-looking play tracking pattern
- 2025-10-28: Week 6 - 100% complete - Config system and PlayOutcome enum implemented
- Both SBA and PD use same card-based resolution mechanics
- Universal PlayOutcome enum with helper methods and granular variants
- Immutable league configs with singleton registry
- Renamed check_d20 → chaos_d20 for clarity
- Added play_metadata support for uncapped hits
- PlayResolver fully integrated with universal PlayOutcome
- 200/201 tests passing (1 pre-existing timing issue)
- 2025-10-29: Phase 3 planning - Ready to implement strategic decisions and result charts
- 2025-10-31: PHASE 2 COMPLETE - All Week 7 tasks + additional polish
- Strategic decision system fully integrated
- Runner advancement unified for groundballs AND flyballs
- FLYOUT_BQ variant added (4 flyball types total)
- Result charts complete (PdAutoResultChart, ManualResultChart)
- WebSocket manual outcome handlers implemented
- Terminal client with full REPL and manual testing
- 8,799 lines of comprehensive CLAUDE.md documentation
- ManualOutcomeSubmission refactored to use PlayOutcome enum
- All tests updated and passing (~540 total tests)
- Phase 2 merged to main via PR #1
- 2025-11-03: Created
implement-phase-3branch - Ready for Phase 3 - 2025-11-04: Phase 3A-E Complete - X-Check system + GameState refactoring
- Position ratings integration with PD API
- Redis caching (760x speedup: 0.274s → 0.000361s)
- Defense tables and error charts
- GameState refactoring (consistent LineupPlayerState references)
- Terminal client X-Check testing support
- 679 tests passing
- 2025-11-06: PHASE 3 COMPLETE - Substitution system fully tested
- SubstitutionRules validation (345 lines, 31 tests)
- SubstitutionManager orchestration (552 lines, 10 integration tests)
- WebSocket events (4 handlers: pinch hitter, defensive replacement, pitching change, get lineup)
- 688 tests passing (100% unit test coverage)
- All core gameplay features implemented
- 2025-11-06: PHASE 3.5 PLANNING - Code polish and stat tracking
- Identified 40+ TODO comments in codebase
- Stat tracking is natural next step (play resolution complete)
- Authorization framework needed for production
- Created comprehensive Phase 3.5 plan (5 major components)
Last Updated: 2025-11-06
Phase: Phase 3.5 - Code Polish & Stat Tracking (Ready to Begin)
Current Branch: implement-phase-3
Current Work: Planning complete for Phase 3.5
Next Session: Phase 3.5 Task 1 - Game Statistics System
Next Milestone: Phase 3.5 completion - Production-ready codebase with stats and security