Commit Graph

192 Commits

Author SHA1 Message Date
Cal Corum
e058bc4a6c CLAUDE: RosterLink refactor for bench players with cached player data
- Add player_positions JSONB column to roster_links (migration 006)
- Add player_data JSONB column to cache name/image/headshot (migration 007)
- Add is_pitcher/is_batter computed properties for two-way player support
- Update lineup submission to populate RosterLink with all players + positions
- Update get_bench handler to use cached data (no runtime API calls)
- Add BenchPlayer type to frontend with proper filtering
- Add new Lineup components: InlineSubstitutionPanel, LineupSlotRow,
  PositionSelector, UnifiedLineupTab
- Add integration tests for get_bench_players

Bench players now load instantly without API dependency, and properly
filter batters vs pitchers (including CP closer position).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-17 22:15:12 -06:00
Cal Corum
64325d7163 CLAUDE: Fix game recovery to load team display info and add score text outline
Backend:
- Add game_metadata to load_game_state() return dict in DatabaseOperations
- Populate team display fields (name, color, thumbnail) in _rebuild_state_from_data()
  so recovered games show team colors/names

Frontend:
- Add text-outline CSS for score visibility on any background (light logos, gradients)
- Handle thumbnail 404 with @error event, show enhanced shadow when no thumbnail
- Apply consistent outline across mobile and desktop layouts

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-17 09:03:59 -06:00
Cal Corum
d60b7a2d60 CLAUDE: Store team display info in DB and fix lineup auto-start
Backend:
- Add game_metadata to create_game() and quick_create_game() endpoints
- Fetch team display info (lname, sname, abbrev, color, thumbnail) from
  SBA API at game creation time and store in DB
- Populate GameState with team display fields from game_metadata
- Fix submit_team_lineup to cache lineup in state_manager after DB write
  so auto-start correctly detects both teams ready

Frontend:
- Read team colors/names/thumbnails from gameState instead of useState
- Remove useState approach that failed across SSR navigation
- Fix create.vue redirect from legacy /games/lineup/[id] to /games/[id]
- Update game.vue header to show team names from gameState

Docs:
- Update CLAUDE.md to note dev mode has broken auth, always use prod

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-17 08:43:26 -06:00
Cal Corum
ff3f1746d6 CLAUDE: Add team color gradient to scoreboard and fix sticky tabs
- ScoreBoard: Dynamic gradient using team colors (away left, home right)
  with dark center blend and 20% overlay for text readability
- Fetch team colors from API using cached season from schedule state
- Fix sticky tabs by removing overflow-auto from game layout main
- Move play-by-play below gameplay panel on mobile layout

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 23:14:46 -06:00
Cal Corum
3a91a5d477 CLAUDE: Fix connection status indicator showing disconnected while playing
Use useWebSocket composable directly as source of truth for connection
status instead of gameStore.isConnected which could get out of sync.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 15:59:33 -06:00
Cal Corum
4cb8e3f6c4 CLAUDE: Auto-start game when both lineups submitted
- Broadcast game_state_update in game_engine.start_game() so frontend
  receives the active state immediately
- Add auto-start safeguard to /lineup-status endpoint for stuck pending
  games (both in-memory and database code paths)
- Fix None handling in state_manager._rebuild_state_from_data() for
  pending games with null inning/half values

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 14:56:35 -06:00
Cal Corum
1f5e290d8b CLAUDE: Add game page tabs with lineup persistence and per-team submission
- Refactor game page into tab container with Game, Lineups, Stats tabs
- Extract GamePlay, LineupBuilder, GameStats components from page
- Add manager-aware default tab logic (pending + manager → Lineups tab)
- Implement per-team lineup submission (each team submits independently)
- Add lineup-status endpoint with actual lineup data for recovery
- Fix lineup persistence across tab switches and page refreshes
- Query database directly for pending games (avoids GameState validation)
- Add userTeamIds to auth store for manager detection

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 14:08:39 -06:00
Cal Corum
5562d8de36 CLAUDE: Extend access token expiration to 24 hours
Changed ACCESS_TOKEN_MAX_AGE from 1 hour to 24 hours to reduce
frequency of re-authentication prompts.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 09:57:34 -06:00
Cal Corum
f8435a2fae CLAUDE: UI fixes - lineup builder layout and team order
- Lineup builder: Use layout: false to remove white border/padding
- Create game: Swap team order so Away Team appears above Home Team

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 14:59:03 -06:00
Cal Corum
2dd2b530f8 CLAUDE: Fix lineup builder bugs and improve player image display
Bug fixes:
- Fix pitcher filter to recognize SP, RP, CP positions (not just P)
- Fix validation to allow 9 players when pitcher bats (no DH games)
- Simplify position filters to All/Batters/Pitchers

Image display improvements:
- Use headshot > vanity_card priority (avoid card images in circles)
- Show player initials as fallback (e.g., "AV" for Alex Verdugo)
- Handle name suffixes (Jr, Sr, II, III, IV) correctly

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 13:58:02 -06:00
Cal Corum
d65ae19f5e CLAUDE: Add lineup builder polish - search, filters, player preview, visual improvements
Features:
- Player search box with filter by name
- Position filter tabs (All, Catchers, Infielders, Outfielders, Pitchers)
- Player preview modal on click (shows positions, wara rating)
- Clear lineup button with confirmation styling
- Progress bar showing lineup completion
- Player headshots in both roster list and lineup slots
- Skeleton loading state during data fetch
- Sticky navigation header with back button
- Improved visual styling throughout (pills, cards, badges)

TypeScript fixes:
- Added pitcherPlayer computed property for proper type narrowing
- Removed non-existent SbaPlayer stats (batting_average, home_runs, rbi)
- Fixed unused variable warnings

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 10:08:25 -06:00
Cal Corum
3dad6204e6 CLAUDE: Add production deployment documentation for Linode VPS
Documents deployment strategy using Docker Compose on existing Linode
infrastructure. Includes architecture diagram, step-by-step deployment
guide, NPM configuration, maintenance commands, and rollback procedures.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-15 09:51:41 -06:00
Cal Corum
9076ff6446
Merge pull request #6 from calcorum/implement-phase-3
Phase 3: Complete Real-Time Game Engine & Vue 3 Frontend
2026-01-15 09:45:12 -06:00
Cal Corum
a22513b053 CLAUDE: Add schedule_game_id linking for webapp games to external schedules
Enables precise tracking of which webapp games correspond to specific
scheduled matchups from SBA/PD league systems.

Backend:
- Add schedule_game_id column to games table with index
- Create Alembic migration for the new column
- Update QuickCreateRequest to accept schedule_game_id
- Update GameListItem response to include schedule_game_id
- Update DatabaseOperations.create_game() to store the link

Frontend:
- Pass schedule_game_id when creating game from "Play" button
- Add activeScheduleGameMap to track webapp games by schedule ID
- Show "In Progress" (green) link for active games
- Show "Resume" (green) link for pending games
- Show "Play" (blue) button for unstarted games

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 23:55:53 -06:00
Cal Corum
fbbb1cc5da CLAUDE: Add SBA schedule integration with weekly matchup display
Implements schedule viewing from SBA production API with week navigation
and game creation from scheduled matchups. Groups games by team matchup
horizontally with games stacked vertically for space efficiency.

Backend:
- Add schedule routes (/api/schedule/current, /api/schedule/games)
- Add SBA API client methods for schedule data
- Fix multi-worker state isolation (single worker for in-memory state)
- Add Redis migration TODO for future scalability
- Support custom team IDs in quick-create endpoint

Frontend:
- Add Schedule tab as default on home page
- Week navigation with prev/next and "Current Week" jump
- Horizontal group layout (2-6 columns responsive)
- Completed games show score + "Final" badge (no Play button)
- Incomplete games show "Play" button to create webapp game

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 23:39:31 -06:00
Cal Corum
403ba7c90f CLAUDE: Update project plan with HIGH-003 resolution phase fix
Added HIGH-003 task documenting the isMyTurn resolution phase bug
that was discovered and fixed during integration testing. All 6
production blockers now complete.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 23:55:50 -06:00
Cal Corum
38fb76c849 CLAUDE: Fix resolution phase control and add demo mode
Bug fix: During resolution phase (dice rolling), isMyTurn was false
for both players, preventing anyone from seeing the dice roller.
Now the batting team has control during resolution since they read
their card.

Demo mode: myTeamId now returns whichever team needs to act,
allowing single-player testing of both sides.

Changes:
- Add creator_discord_id to GameState (backend + frontend types)
- Add get_current_user_optional dependency for optional auth
- Update quick-create to capture creator's discord_id
- Fix isMyTurn to give batting team control during resolution
- Demo mode: myTeamId returns active team based on phase

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 23:47:21 -06:00
Cal Corum
581bc33f15 CLAUDE: Move games list to index page for better UX
SBA users are already league members - they don't need a marketing page.
Moving the games list to "/" reduces friction by eliminating a redirect.

Changes:
- pages/index.vue: Now shows games list (was marketing/dashboard)
- pages/games/index.vue: Redirects to / for backwards compatibility
- Updated all internal links from /games to /
- Auth callback redirects to / after login

User flow is now:
- Not logged in: / → auth middleware → Discord OAuth → /
- Logged in: / shows games list directly

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 20:59:34 -06:00
Cal Corum
39cea607dd CLAUDE: Mark HIGH-001 as complete in project plan
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 20:53:06 -06:00
Cal Corum
a9a3e9992d CLAUDE: Add error boundary UI for WebSocket failures (HIGH-001)
When WebSocket connection fails after max attempts (permanentlyFailed state):
- Show red error banner with "Connection Failed" message and "Try Again" button
- Loading modal distinguishes between connecting/reconnecting/failed states
- "Try Again" button uses manualRetry() to reset state and attempt fresh connection
- Yellow reconnecting banner only shows during active reconnection attempts

Uses permanentlyFailed state and manualRetry() from HIGH-002.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 20:52:34 -06:00
Cal Corum
ac7712d2cc CLAUDE: Mark HIGH-002 as complete in project plan
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 20:49:38 -06:00
Cal Corum
1a7e464990 CLAUDE: Fix infinite WebSocket reconnection loop (HIGH-002)
After max reconnection attempts (10), the stuck state detector was
continuing to retry forever. Now:

- Add permanentlyFailed state flag to track when we've given up
- Set flag and stop stuck state detector when max attempts reached
- Add manualRetry() method for UI to reset state and try again
- Expose permanentlyFailed in public API for error boundary (HIGH-001)

Also marks CRIT-002 and CRIT-002-BACKEND as completed in project plan.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 20:49:04 -06:00
Cal Corum
89a63af2a8 CLAUDE: Fix Nuxt 4 store import in game layout
Add explicit Pinia store imports to layouts/game.vue. Nuxt 4 requires
explicit imports for stores - auto-imports no longer work.

This fixes: ReferenceError: useAuthStore is not defined

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 20:41:04 -06:00
Cal Corum
c5869f5ba2 CLAUDE: Add team ownership to auth flow (CRIT-002)
Backend:
- Add get_teams_by_owner() to SBA API client
- Update /api/auth/me to return user's teams from SBA API
- Add sba_current_season config setting (default: 13)

Frontend:
- Replace hardcoded myTeamId with computed from auth store teams
- Fix isMyTurn logic to check actual team ownership
- Update REFACTORING_PLAN.json

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 20:28:08 -06:00
Cal Corum
f2ce91a239 CLAUDE: Add submitSubstitution unified wrapper for all substitution types
- Add submitSubstitution() method that routes to appropriate internal method
- Remove individual substitution methods from exports (now internal only)
- Add validation for defensive_replacement requiring position parameter
- Update tests to use unified wrapper, add test for validation error

Fixes CRIT-001: Game page called non-existent submitSubstitution method

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 20:00:22 -06:00
Cal Corum
e0c12467b0 CLAUDE: Improve UX with single-click OAuth, enhanced games list, and layout fix
Frontend UX improvements:
- Single-click Discord OAuth from home page (no intermediate /auth page)
- Auto-redirect authenticated users from home to /games
- Fixed Nuxt layout system - app.vue now wraps NuxtPage with NuxtLayout
- Games page now has proper card container with shadow/border styling
- Layout header includes working logout with API cookie clearing

Games list enhancements:
- Display team names (lname) instead of just team IDs
- Show current score for each team
- Show inning indicator (Top/Bot X) for active games
- Responsive header with wrapped buttons on mobile

Backend improvements:
- Added team caching to SbaApiClient (1-hour TTL)
- Enhanced GameListItem with team names, scores, inning data
- Games endpoint now enriches response with SBA API team data

Docker optimizations:
- Optimized Dockerfile using --chown flag on COPY (faster than chown -R)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-05 16:14:00 -06:00
Cal Corum
7d28eebd24 CLAUDE: Add multi-domain environment configuration support
- 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>
2025-12-03 13:58:42 -06:00
Cal Corum
db667965e6 CLAUDE: Add WebSocket troubleshooting documentation
Comprehensive guide documenting the investigation and resolution of
intermittent WebSocket connection failures:

- NPM configuration issues (HTTP/2, access lists, custom locations)
- Conflicting socket.io plugin (JWT vs cookie auth)
- SSR/hydration state corruption (primary root cause)
- Diagnostic commands and debugging tips
- SSR-safe patterns for WebSocket in Nuxt
- Cloudflare considerations

This document serves as future reference for similar WebSocket issues.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-29 15:32:30 -06:00
Cal Corum
751dcaf972 CLAUDE: Fix SSR/hydration issues in WebSocket composable
Refactored useWebSocket.ts to prevent SSR-related connection issues:

- Created ClientState interface to encapsulate all client-only state
- Added getClientState() function with lazy initialization on client only
- Added SSR guards (import.meta.client) to all connection functions
- Reset reactive state on client hydration to ensure clean slate
- Moved heartbeatInterval and stuckStateCheckInterval into ClientState
- Changed NodeJS.Timeout to ReturnType<typeof setTimeout/setInterval>
- Wrapped auth watcher in import.meta.client guard

Root cause: Module-level singleton state was being initialized during
SSR, then persisting in a potentially corrupted state during hydration.
This caused intermittent "Socket exists: no" issues where the browser
wouldn't even attempt WebSocket connections.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-29 15:29:24 -06:00
Cal Corum
b68e3ceacf CLAUDE: Improve service scripts and fix WebSocket plugin conflict
Service Scripts:
- start-services.sh: Add pre-flight checks, health monitoring, --dev/--prod modes,
  port options, dependency checks, and version logging
- stop-services.sh: Add port 3000 cleanup, verification, --quiet/--force flags
- status-services.sh: New script for monitoring service status with --watch mode

WebSocket:
- Remove conflicting socket.client.ts plugin that was interfering with
  useWebSocket.ts composable (used JWT auth vs cookie auth)
- Add debugging logs to useWebSocket.ts to diagnose intermittent connection issues

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-29 15:23:41 -06:00
Cal Corum
46cf1cc02b CLAUDE: Fix outs_before capturing AFTER value instead of BEFORE
The outs_before field in play records was incorrectly storing the
outs count AFTER _apply_play_result() modified state.outs, rather
than the value before the play resolved.

Fix: Capture state.outs before calling _apply_play_result() and
pass it explicitly to _save_play_to_db() as a required parameter.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-29 09:46:46 -06:00
Cal Corum
dc9f98ad88 CLAUDE: Fix batting order recovery after inning changes
When recovering game state after reconnect/refresh, the old code:
1. Only looked at the last play overall (regardless of team)
2. Used that play's batting order for the currently batting team
3. Reset the non-batting team's index to 0

This caused the wrong batter to appear after inning changes - e.g.,
batter #1 showing instead of #5 in top of 2nd after bottom of 1st ended.

Fix: Now recovers each team's batter index separately by filtering
plays by half ("top" = away team, "bottom" = home team) and finding
each team's last at-bat independently.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 23:38:54 -06:00
Cal Corum
4d2c905a1c CLAUDE: Fix RunnerAdvancementData tuple unpacking regression
After changing runners_advanced from list[tuple] to list[RunnerAdvancementData],
three locations were still trying to unpack as tuples causing "cannot unpack
non-iterable RunnerAdvancementData object" error on triples/doubles with runners.

Fixed locations:
- app/core/game_engine.py:772 - _apply_play_result() advancement map
- app/core/game_engine.py:1081 - _save_play() finals lookup
- terminal_client/display.py:150 - Runner movement display

Also renamed refactor_overview.md to game-engine-play-tracking-design.md
for clarity and updated the example code to use dataclass access pattern.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 23:11:26 -06:00
Cal Corum
450ef830dc CLAUDE: Fix batter not advancing after plays
Root cause: WebSocket handler had stale state reference after
resolve_manual_play() completed. The handler's state object still had
the old batter index, and calling state_manager.update_state()
overwrote the game engine's updated state.

Fix: Re-fetch state from state_manager AFTER resolve_manual_play()
returns, ensuring we get the state with the advanced batter index.

Also improved logging in _prepare_next_play() to show batting_order
for easier debugging.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 22:38:10 -06:00
Cal Corum
364c5149a4 CLAUDE: Fix Safari WebSocket connection issues
Frontend fixes for Safari/iPad WebSocket reliability:

1. Add Vite allowedHosts config (nuxt.config.ts)
   - Allow gameplay-demo.manticorum.com for external access
   - Fixes "Blocked request" error after Vite security update

2. Add connection timeout failsafe (useWebSocket.ts)
   - 10-second timeout resets stuck "isConnecting" state
   - Prevents Heisenbug where Safari connections hang indefinitely
   - Auto-schedules reconnection after timeout

3. Add visible debug info to connection modal (games/[id].vue)
   - Shows WS URL, socket status, and connection log
   - Helps diagnose Safari-specific issues without dev tools

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 22:37:53 -06:00
Cal Corum
acd080b437 CLAUDE: Fix Safari/iPad auth failure on game detail page
Root cause: Auth middleware was commented out on game detail page
([id].vue), causing SSR to render without checking authentication.
Safari's client-side auth check wasn't reaching the backend due to
caching behavior, resulting in "Auth: Failed" display.

Changes:
- Re-enabled middleware: ['auth'] in pages/games/[id].vue
- Added /api/auth/ws-token endpoint for Safari WebSocket fallback
- Added expires_minutes param to create_token() for short-lived tokens
- Added token query param support to WebSocket handlers
- Updated SAFARI_WEBSOCKET_ISSUE.md documentation

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 21:53:20 -06:00
Cal Corum
646878c572 CLAUDE: Optimize play history sync to O(1) with setPlayHistory
Replaced O(n²) deduplication check per play with O(1) array replacement:
- Added setPlayHistory() for game_state_sync (replaces entire array)
- Simplified addPlayToHistory() for live play_resolved events (just push)

This separates sync operations (replace) from live events (append),
eliminating the need for deduplication checks during gameplay.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 12:41:50 -06:00
Cal Corum
19b35f148b CLAUDE: Load play history on mid-game join via game_state_sync
Backend changes:
- Modified request_game_state handler to fetch plays from database
- Convert Play DB models to frontend-compatible PlayResult dicts
- Emit game_state_sync event with state + recent_plays array

Frontend changes:
- Added deduplication by play_number in addPlayToHistory()
- Prevents duplicate plays when game_state_sync is received

Field mapping from Play model:
- hit_type -> outcome
- result_description -> description
- batter_id -> batter_lineup_id
- batter_final -> batter_result

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 12:38:56 -06:00
Cal Corum
57121b62bd CLAUDE: Add tabbed Recent/Scoring views to PlayByPlay component
Enhanced PlayByPlay with a tabbed interface:
- "Recent" tab shows plays from current half inning only
- "Scoring" tab shows all plays where runs were scored
- Badge counts on each tab show number of matching plays
- Tab-aware empty states with contextual messaging
- Footer shows total game plays count

Removed unused showFilters prop and showAllPlays toggle.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 12:18:56 -06:00
Cal Corum
af598b3dee CLAUDE: Remove hit location requirement from lineout outcomes
Lineouts are simple outs with no runner advancement logic - the backend
doesn't use hit_location for them (unlike flyouts for sac flies or
groundballs for double plays). Updated OUTCOMES_REQUIRING_HIT_LOCATION
to exclude lineout and added documentation explaining the rationale.

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 12:14:50 -06:00
Cal Corum
27b502a7ad CLAUDE: Add exception tests and enhance stop-services script
New Tests:
- test_exceptions.py: Comprehensive tests for custom GameEngineError
  hierarchy including AuthorizationError, DatabaseError, etc.

Scripts:
- stop-services.sh: Enhanced to kill entire process trees and
  clean up orphan processes

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 12:10:59 -06:00
Cal Corum
9c90893b5d CLAUDE: Update documentation across codebase
Updated CLAUDE.md files with:
- Current test counts and status
- Session injection pattern documentation
- New module references and architecture notes
- Updated Phase status (3E-Final complete)
- Enhanced troubleshooting guides

Files updated:
- Root CLAUDE.md: Project overview and phase status
- backend/CLAUDE.md: Backend overview with test counts
- backend/README.md: Quick start and development guide
- backend/app/api/CLAUDE.md: API routes documentation
- backend/app/database/CLAUDE.md: Session injection docs
- backend/app/utils/CLAUDE.md: Utilities documentation
- backend/tests/CLAUDE.md: Testing patterns and policy
- frontend-sba/CLAUDE.md: Frontend overview
- frontend-sba/store/CLAUDE.md: Store patterns

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 12:10:10 -06:00
Cal Corum
891fb03c52 CLAUDE: Frontend enhancements for auth and game display
Auth Improvements:
- auth.ts: Enhanced authentication store with better error handling
- auth.ts middleware: Improved redirect logic
- login.vue: Better login flow and error display

Game Display:
- PlayByPlay.vue: Enhanced play-by-play feed with player name display
- game.ts types: Additional type definitions for runner advancement

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 12:09:39 -06:00
Cal Corum
9d0d29ef18 CLAUDE: Add Alembic migrations and database session injection
Database Infrastructure:
- Added Alembic migration system (alembic.ini, env.py)
- Migration 001: Initial schema
- Migration 004: Stat materialized views (enhanced)
- Migration 005: Composite indexes for performance
- operations.py: Session injection support for test isolation
- session.py: Enhanced session management

Application Updates:
- main.py: Integration with new database infrastructure
- health.py: Enhanced health checks with pool monitoring

Integration Tests:
- conftest.py: Session injection pattern for reliable tests
- test_operations.py: Database operations tests
- test_migrations.py: Migration verification tests

Session injection pattern enables:
- Production: Auto-commit per operation
- Testing: Shared session with automatic rollback
- Transactions: Multiple ops, single commit

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 12:09:09 -06:00
Cal Corum
4253b71db9 CLAUDE: Enhance WebSocket handlers with comprehensive test coverage
WebSocket Infrastructure:
- Connection manager: Improved connection/disconnection handling
- Handlers: Enhanced event handlers for game operations

Test Coverage (148 new tests):
- test_connection_handlers.py: Connection lifecycle tests
- test_connection_manager.py: Manager operations tests
- test_handler_locking.py: Concurrency/locking tests
- test_query_handlers.py: Game query handler tests
- test_rate_limiting.py: Rate limit enforcement tests
- test_substitution_handlers.py: Player substitution tests
- test_manual_outcome_handlers.py: Manual outcome workflow tests
- conftest.py: Shared WebSocket test fixtures

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 12:08:43 -06:00
Cal Corum
3623ad6978 CLAUDE: Add game state eviction and resource management
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>
2025-11-28 12:07:55 -06:00
Cal Corum
2a392b87f8 CLAUDE: Add rate limiting, pool monitoring, and exception infrastructure
- 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>
2025-11-28 12:06:10 -06:00
Cal Corum
ae4a92f0e0 CLAUDE: Fix Safari/iPad WebSocket connection issues
- 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>
2025-11-28 12:03:57 -06:00
Cal Corum
ee12f6210e CLAUDE: Fix WebSocket SSR hydration and add connection debugging
Problem: WebSocket wouldn't connect on page load because Pinia auth
state doesn't automatically transfer from SSR to client hydration.
The auth store showed isAuthenticated=false on client mount.

Solution:
- useWebSocket.onMounted now proactively calls checkAuth() if not authenticated
- This ensures auth state is initialized before attempting WebSocket connection
- Added forceReconnect() function to clear stale singleton connections

Debug UI (temporary):
- Added connection status debug info to loading overlay and banner
- Shows Auth/Connected/Connecting/Error states
- Retry button triggers auth check + reconnect

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-27 23:33:11 -06:00
Cal Corum
b12905a71b CLAUDE: Add HBP (Hit By Pitch) handler to PlayResolver
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>
2025-11-27 22:53:41 -06:00