Commit graph

490 commits

Author SHA1 Message Date
Chris Parsons
65478e1ef2 Add react-is as explicit dependency to fix production Docker build
recharts declares react-is as a peerDependency. With legacy-peer-deps=true,
npm no longer auto-installs peer deps, so react-is was missing from the
production image and recharts failed to load at runtime.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 22:29:13 -07:00
Chris Parsons
9a71a68ede
Copy .npmrc into production Docker stage so npm ci --omit=dev respects legacy-peer-deps (#325)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 22:17:35 -07:00
Chris Parsons
ba9bf64e37
Migrate authentication from Clerk to BetterAuth (#324)
* Migrate authentication from Clerk to BetterAuth (#322)

Replaces @clerk/react-router with self-hosted better-auth to eliminate
the external Clerk dependency and keep all user/session data in our own
PostgreSQL database.

**What changed**
- New: auth.server.ts (BetterAuth config w/ Drizzle adapter, bcrypt, Resend), auth-client.ts, api.auth.$.ts handler
- New: /login and /register pages with email+password and Google/Discord OAuth; open-redirect guard on redirectTo param
- New: UserMenu component replacing Clerk's UserButton
- Schema: sessions, accounts, verifications tables; emailVerified column; clerkId made nullable
- Migrations 0081 (BetterAuth tables) and 0082 (accounts extra columns for v1.6.9)
- All ~30 route files: getAuth → auth.api.getSession, isUserAdminByClerkId → isUserAdmin
- root.tsx: isAdmin read directly from session.user.isAdmin (no extra DB query)
- useDraftAuthRecovery: removed Clerk JWT refresh logic; replaced with cookie-session check
- models/user.ts: removed findUserByClerkId, findOrCreateUser, updateUserByClerkId (webhook pattern)
- Deleted: app/routes/api/webhooks/clerk.ts; uninstalled @clerk/react-router, @clerk/themes, svix
- scripts/migrate.mjs: extended with idempotent Clerk → BetterAuth data migration (FK conversion, email_verified, OAuth accounts)
- scripts/migrate-clerk-passwords.mjs: one-time script to import bcrypt hashes from Clerk CSV export
- BETTERAUTH_MIGRATION.md: dev and production runbooks
- All test mocks updated: vi.mock('~/lib/auth.server') instead of @clerk/react-router/server
- Test fixtures: added emailVerified field

**Follow-up (post-stable)**
- Rename actor_clerk_id column → actor_user_id in commissioner_audit_log
- Drop clerk_id column from users once migration confirmed

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Add .npmrc with legacy-peer-deps for better-auth/drizzle peer dep conflict

better-auth@1.6.9 declares peerOptional deps on drizzle-orm ^0.45.2 and
drizzle-kit >=0.31.4, but we run drizzle-orm ~0.36.3 / drizzle-kit ~0.28.1.
The adapter works correctly at runtime with our versions — the peer dep is
only for stricter type checking. This unblocks npm ci in CI without a risky
drizzle major-version upgrade.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 22:00:49 -07:00
Chris Parsons
e8e4981465
Add opencode oxlint plugin and UI refinements (#323)
* Add opencode oxlint plugin and UI refinements

- Add .opencode/plugins/oxlint.ts to run oxlint automatically on file edits
- Refactor RankingDisplay into shared StatHelpers component
- Add tied rank display support in home loader
- Update navbar with NavLink for active state styling
- Replace .reverse() with .toReversed() in RecentPicksFeed

* Remove unused RankChangeIndicator import in LeagueRow
2026-04-24 11:11:20 -07:00
Chris Parsons
3566a97a1e
feat: add projected pick dividers to draft participant list (fixes #82) (#322)
Show visual dividers in the available participants list indicating where
your future draft picks fall relative to the current pick position.
Dividers are suppressed when any filter is active (search, sport filter,
hide drafted, etc.) since positional references are meaningless in a
filtered view.

- Add getProjectedPicks() to draft-order.ts for computing future pick
  positions in a snake draft
- Interleave divider items into the virtualized list in
  AvailableParticipantsSection
- Extract ListItem type to module scope
- Add tests for getProjectedPicks, divider rendering, and filter
  suppression
2026-04-24 09:32:11 -07:00
Chris Parsons
01dacbce27
Add Storybook stories for new components from staged changes (#321) 2026-04-23 22:09:25 -07:00
Chris Parsons
41d45041c8 Fix more bad vite URLs. 2026-04-23 14:12:15 -07:00
Chris Parsons
72f33cef2a Url fix. 2026-04-23 14:01:05 -07:00
Chris Parsons
6926fb96bc
Cache-bust logos via Vite ?url import and extract shared stat helpers (#310)
Logo SVGs referenced by string path (/logo.svg) were cached by CDNs and
browsers after deployments. Import them with Vite's ?url suffix so the
build emits content-hashed filenames that force a refresh on change.

LeagueRow and StandingsPreview had duplicated StatColumn, StatDivider,
and rank-change indicator helpers. Extract them into a shared
StatHelpers module so both pages render rank and points identically
(#3 style with consistent rank-change arrows).
2026-04-23 13:52:34 -07:00
Chris Parsons
9ed0282fd0
New design (#309)
* Redesign home page with new layout and component system

- Two-column layout (My Leagues 2/3, Upcoming Events 1/3) with mobile stack
- LeagueRow: square avatar, gradient draft highlight, rank/points display, progress bar
- MyLeaguesCard, CreateLeagueCard with shared SectionCardHeader
- UpcomingEventsCard: vertical timeline with grouped multi-league events
- Shared gradient system: BracktGradients SVG defs, GradientIcon wrapper, brand.ts constants
- Button default variant updated to green→cyan gradient
- Navbar: plain nav links with gradient hover, support/admin icon buttons
- Accessibility fixes: semantic h2 headings, aria-label on LeagueAvatar and nav elements
- Storybook stories for all new components

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Responsive league row layout and mobile polish

- League rows stack avatar+name on top, stats full-width below on mobile
- Stats spread to right side on sm+ screens with border separator on mobile
- Tighter padding on mobile (px-3/py-3), full padding on sm+
- Card headers and content use px-3 sm:px-6 to reduce mobile gutters
- Two-column home layout deferred to lg breakpoint (tablet gets stacked)
- Active leagues sorted by completion percentage descending
- Default rank 1 / 0 points for active leagues with no scoring events yet
- Fix ordinal bug for 11th/12th/13th; add aria-labels to rank change indicators
- Remove dead StatDivider className prop

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Improve claude file.

* Add StandingsPreview card component with podium row styling

- New StandingsPreview component with gold/silver/bronze row tints for
  top 3, team avatar, and LeagueRow-style stat columns (Ranking + Points)
  with rank and 7-day point change indicators
- Fix GradientIcon in Storybook by adding BracktGradients decorator to
  preview.tsx (renamed from .ts to support JSX)
- Fix degenerate SVG gradient on horizontal strokes by switching
  BracktGradients to gradientUnits="userSpaceOnUse" with Lucide-space
  coordinates (0→24)
- Revert erroneous fill: url(#gradient) from GradientIcon; stroke-only
  fix was sufficient once gradientUnits was corrected

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Update components on league homepage.

* Finish up league page styling.

* Work on standings page.

* Add story for RecentScoresCard

* Update Point Progression Chart.

* Sort point progression legend by ranking and add team links to standings rows

* Fix standings discrepancy on change.

* Create draft cell component.

* Update draft board page

* Draft room improvements.

* Update some draft room styling.

* Fix context menu missing.

* Move tab navigation and autodraft to header row, narrow sidebar

* Virtualize available participants list, memoize draft room props

Adds @tanstack/react-virtual to replace separate mobile/desktop lists
with a single unified virtual scroll loop. Also memoizes miniDraftGrid
and availableParticipantsSectionProps, and switches pick lookup from
Array.find to a Map for O(1) access.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Update draft room UI.

* More draft room fixes.

* Draft room tweaks.

* Fix Rosters page.

* Queue Section fixes.

* Mobile Draft fixes.

* Fix draft board page.

* Create bracket look.

* Bracket work.

* Finish bracket page.

* Homepage initial styling

* homepage copy

* Add privacy policy. Fixes #88.

* how to play copy

* rules copy

* Fix brackets on homepage.

* Add footer to website.

* Glow on dots.

* Landing page copy.

* Fix sidebar.

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 13:14:55 -07:00
Chris Parsons
7fa88fc0ef
Add projected-wins input mode to admin Elo Ratings page (#306)
* Add projected-wins input mode to admin Elo Ratings page

Admins can now enter projected season win totals instead of raw Elo
numbers on the Elo Ratings page. Wins are auto-converted to Elo using
the inverse formula and stored as sourceElo, keeping the rest of the
simulation pipeline unchanged.

- Add `projectedWinsToElo` / `eloToProjectedWins` to probability-engine
- Add `simulator-config.ts` centralising per-sport season length, parity
  factor, and average opponent Elo (AFL, NFL, NBA, NHL, MLB, WNBA)
- Admin Elo Ratings page: toggle between Elo and Projected Wins input
  modes; bulk import parses wins format; existing sourceElo back-fills
  the wins field on load
- AFL simulator now reads sourceElo from participantExpectedValues first,
  falling back to hardcoded TEAMS_DATA then 1400

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix lint errors in simulator-config tests and probability-engine

- Replace non-null assertions (`!`) with optional chaining (`?.`) in simulator-config tests
- Remove redundant type annotations on default parameters in probability-engine

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-17 12:40:08 -07:00
Chris Parsons
e03bdd538f
Fix upcoming events grouping to separate individual bracket matches (#302)
Include playoffMatchId in the grouping key so that each match within a
scoring event (e.g. different Round of 32 matchups in snooker) appears
as its own calendar entry instead of being merged together.
2026-04-16 14:19:59 -07:00
Chris Parsons
13bc1e3b5f
Fix NBA play-in elimination display and consolidate bracket reprocessing (#299)
- Fix computeEliminatedByRound() to track participant1Id/participant2Id
  in addition to winnerId/loserId, so a 7v8 play-in loser placed in a
  PIR2 slot (incomplete match) is not shown as eliminated on the league page
- Replace separate Recalculate Floors and Reprocess Eliminations buttons
  with a single Reprocess Bracket action that replays all matches and
  re-marks non-bracket participants as eliminated
- Add NBA play-in test cases for the elimination computation logic
2026-04-15 14:56:33 -07:00
Chris Parsons
0eb486f8d3
Fix bracket scoring logic to prefer template over DB defaults (#298)
* Emit standings-updated socket event after recalculate-floors so league pages refresh automatically

When the admin runs "Recalculate Floors" on the bracket page, the league
sports-season homepage was showing stale elimination data because there was
no mechanism to notify it of the change.

Fix: after recalculate-floors updates participant_results, emit a
standings-updated socket event to all fantasy-season draft rooms linked to
the sports season. The sports-season page now joins its draft room and
revalidates its loader whenever it receives that event for the matching
sports season.

https://claude.ai/code/session_01D3NbnVQdaH82Fk7Jm8y3sB

* Fix recalculate-floors incorrectly eliminating play-in losers who still advance

The playoff_matches.isScoring column defaults to true in the database. Brackets
created before this column was added (or before the migration set correct values)
have isScoring=true on play-in rounds that should be false. When recalculate-floors
replayed those matches, it took the "scoring round" path; since "Play-In Round 1"
isn't in ROUND_CONFIG, config===null, and the loser was assigned finalPosition=0
regardless of loserAdvances — permanently eliminating teams like the Suns who had
a second play-in game remaining.

Fix: build a round→isScoring lookup from the bracket template before replaying
matches and use it as the source of truth, falling back to the DB field only when
the template doesn't define the round. This ensures non-scoring play-in rounds
are always processed with isScoring=false so the loserAdvances guard fires
correctly.

Also revert unrelated socket changes from the previous (wrong) commit.

https://claude.ai/code/session_01D3NbnVQdaH82Fk7Jm8y3sB

* Fix isScoring fallback and loserAdvances gaps across all match-processing paths

Three issues found in code review around the recalculate-floors fix:

1. set-winner and set-round-winners (bracket.server.ts) used `match.isScoring ?? true`
   just like recalculate-floors did. Both now derive isScoring from the bracket
   template as the source of truth, falling back to the DB field only when the round
   isn't defined in the template.

2. processPlayoffEvent (scoring-calculator.ts) used `matches[0]?.isScoring ?? true`
   with the same DB-default problem. Now uses BRACKET_TEMPLATES[bracketTemplateId]
   to look up the round's isScoring before falling back to the DB field.

3. doesLoserAdvance (playoff-match.ts) was missing the AFL afl_10 Qualifying Finals
   case: both losers advance to Semi-Finals. Without this, AFL QF losers would
   incorrectly receive finalPosition=0 when processed through the non-scoring path.

https://claude.ai/code/session_01D3NbnVQdaH82Fk7Jm8y3sB

* Fix no-non-null-assertion lint errors in isScoring Map lookups

Replace Map.has(key) ? Map.get(key)! : fallback pattern with
Map.get(key) ?? fallback to satisfy oxlint no-non-null-assertion rule.

https://claude.ai/code/session_01D3NbnVQdaH82Fk7Jm8y3sB

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-15 11:27:00 -07:00
Chris Parsons
f356bdce03
Fix NBA Play-In Round 1 loser advancement logic (#296)
* Fix NBA Play-In 7/8 loser incorrectly marked as eliminated

processPlayoffEvent (called by autoCompleteRoundIfDone when all round matches
finish) was marking every non-scoring round loser as eliminated without
checking doesLoserAdvance. This caused the 7v8 loser, who should advance to
Play-In Round 2, to get finalPosition=0 as soon as the full round completed.

Fixes:
- processPlayoffEvent now calls doesLoserAdvance per match before writing a
  0-pt elimination result, matching the guard already in processMatchResult
- recalculate-floors handler now passes loserAdvances to processMatchResult
  so a full reprocess also respects the loser-advances rule
- recalculateAffectedLeagues gains a skipDiscord option; recalculate-floors
  uses it so clicking the admin "Recalculate Floors" button corrects the bad
  data without re-announcing results on Discord
- Add two tests confirming 7v8 loser is not eliminated and 9v10 loser is

https://claude.ai/code/session_01QmvezscLYY38gN4GbvXZbA

* Address code review feedback on Play-In loserAdvances fix

- Use outer `round` variable instead of match.round in processPlayoffEvent
  (they're identical, but consistent with surrounding code)
- Add comment at recalculate-floors call site explaining skipDiscord intent
- Combine two redundant test cases into one covering all four assertions
- Add West conference matches (M3/M4) to test fixture — East-only was
  insufficient given doesLoserAdvance checks matchNumber 1 & 3
- Add guard test: when bracketTemplateId is null all losers are eliminated,
  catching any future refactor that drops the field from the DB query

https://claude.ai/code/session_01QmvezscLYY38gN4GbvXZbA

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-15 09:40:53 -07:00
Chris Parsons
d6a92c44ff
fix: NBA play-in 7v8 loser incorrectly marked as eliminated (#295)
The loser of NBA Play-In Round 1 matches 1 and 3 (East/West 7v8 games)
advances to Play-In Round 2 rather than being eliminated, but was being
assigned finalPosition=0 and appearing in Discord as knocked out.

- Add `loserAdvances` param to `processMatchResult` to skip recording an
  elimination result when the loser continues to another match
- Extract `doesLoserAdvance()` to `playoff-match.ts` as the single source
  of truth for which play-in matches have advancing losers (replaces
  duplicated hardcoded checks at both call sites in bracket.server.ts)
- Extract `isLoserNotifiable()` as a pure exported helper so Discord
  notification eligibility is testable; losers only appear when their
  team's score changed OR they have a finalized (non-partial) result,
  correctly suppressing advancing losers while still surfacing 0-pt
  eliminations that produce no score delta
- Add 14 new unit tests covering `doesLoserAdvance`, `isLoserNotifiable`,
  and the advancing-loser/eliminated-loser `processMatchResult` branches

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 22:16:57 -07:00
Chris Parsons
4a875e7628
fix: league settings sports swap and audit log detail improvements (#294)
- Fix sports seasons not updating when saving league settings. The form
  submits intent="update" but sports were only handled under the dead
  intent="update-sports" branch, which nothing called.

- Fix spurious audit log entries (scoring rules, draft settings) firing
  on every settings save. Change detection now compares submitted values
  against current DB values before adding to seasonUpdates.

- Add previousValues to scoring_rules_changed and draft_settings_changed
  audit log entries so the detail formatter can show old → new diffs
  (e.g. "Scoring updated: 1st: 100 → 105").

- Add sports_changed audit action (migration 0076) with sport names
  resolved at log time. Batch-fetch added sports in one query instead
  of N individual queries.

- Improve audit log display for all action types: field-level old→new
  diffs, readable labels, truncated sport lists (+N more).

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 21:41:05 -07:00
Chris Parsons
442b392461
Add audit logging for commissioner actions (#293)
Closes #144

* feat: add commissioner audit log for league transparency (issue #144)

Adds a complete audit log system so league members can verify that
settings, draft order, picks, and time banks have not been quietly
changed without their awareness.

Changes:
- database/schema.ts: new `audit_action` enum + `commissioner_audit_log`
  table (seasonId, leagueId, actorClerkId, actorDisplayName, action,
  affectedTeamIds[], details jsonb, createdAt)
- drizzle/0075: generated migration for the new table
- app/models/audit-log.ts: createAuditLogEntry, getAuditLogForSeason
  (paginated), logCommissionerAction (resolves display name automatically)
- app/lib/audit-log-display.ts: shared formatAuditDetail() helper used by
  both the league home widget and the full audit log page
- app/routes/leagues/$leagueId.audit-log.tsx: new read-only route at
  /leagues/:id/audit-log, accessible to all league members, with
  action-type filter and pagination
- app/routes.ts: registers the new route
- League home page ($leagueId.server.ts / $leagueId.tsx): "Recent Activity"
  summary card showing the last 5 entries with "View all" link
- Settings page ($leagueId.settings.tsx): "View Full Audit Log" link card;
  audit log calls added for league/draft settings changes, draft order
  set/randomized, and draft reset
- API routes: audit log calls added to draft.start, draft.pause,
  draft.resume, draft.rollback, draft.adjust-time-bank, draft.force-autopick,
  draft.force-manual-pick, draft.replace-pick
- Tests: 11 new unit tests for the audit-log model; mocks added to 3
  existing route test files to account for the new logCommissionerAction call

https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm

* fix: validate action filter URL param against known enum values

The action filter on the audit log route was cast directly from the URL
search param to AuditAction without validation. An invalid value would
be passed into the Drizzle inArray() call, potentially throwing a
PostgreSQL enum type error. Now validates against the actual enum values
before using the filter.

https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm

* Fix lint errors: use !== instead of != and toSorted instead of sort

https://claude.ai/code/session_01NdiwK2fbtKhAD3XuD58fTm

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-13 15:45:39 -07:00
Chris Parsons
66b0235678
fix: NBA play-in bracket advancement bugs (#292)
* fix: NBA play-in advancement writes E7/W7 to wrong participant slot

advanceNBAPlayInWinner was writing the PIR1 7v8 winner to participant1Id
of First Round M3/M7, but those slots already hold E2/W2 (seeded at
generation time). The "already filled" guard fired, silently swallowing
both the winner advancement and the loser's placement into Play-In
Round 2 — so the 7/8 loser never appeared in the second play-in game.

Fix: write the 7v8 winner to participant2Id (the correct null slot) and
update the guard, doc comment, and load-bearing comment accordingly.
Also swap the p2Override arguments in the simulator and test fixture to
match the corrected slot layout (FR M3: E2=p1, E7=p2).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: hasGroupStage check for templates without groupStage property

undefined !== null is true, so templates that omit groupStage (like
nba_20) were incorrectly treated as group-stage templates, triggering
the generate-groups action and the "Invalid template or template has
no group stage" error.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 22:25:32 -07:00
Chris Parsons
040c97137b
feat: NBA playoff bracket template and bracket-aware simulator (#291)
Adds the NBA_20 bracket template (20-team structure with play-in
tournament) and rewrites the NBA simulator to be bracket-aware like UCL.

- Add NBA_20 bracket template: PIR1 (4) → PIR2 (2) → First Round (8)
  → Conference Semifinals → Conference Finals → NBA Finals
- Add participantLabels (East/West 1–10) for admin bracket UI slot labels
- Add generateNBA20Bracket and advanceNBAPlayInWinner in playoff-match.ts
  with custom play-in advancement logic (PIR1 winners go to two different
  destinations)
- Rewrite NBASimulator with two auto-detected modes:
  - Bracket-aware (preferred): reads actual bracket state, simulates only
    remaining rounds forward using 50k Monte Carlo iterations
  - Season-projection (fallback): existing logic for pre-playoff use
- Guard resolveGame/resolveSeries against null participants (throws with
  match ID and slot info instead of silently using empty string)
- Document load-bearing First Round match ordering in generateNBA20Bracket
- Add 25 unit tests covering Elo math, team data, template structure,
  and all simulator integration paths

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 21:51:53 -07:00
Chris Parsons
cf91de941b Fix qualifying points league display. 2026-04-12 17:06:20 -07:00
Chris Parsons
1798020c74
feat: batch qualifying results entry (#290)
Fixes #289

* docs: add batch qualifying results entry design spec

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: add batch qualifying results entry implementation plan

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: ignore .worktrees directory

* feat: add qualifying results text parser with tests

* fix: handle no-space after dot separator, tighten T-prefix to uppercase only

* feat: add batch-add-results server intent with duplicate filtering

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: add create-participant intent for inline participant creation

* fix: trim sportsSeasonId validation in create-participant intent

* feat: fill 0-QP rows for unplaced participants on qualifying event finalize

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf: use bulk insert for 0-QP rows on qualifying event finalize

* feat: add BatchResultEntry component for paste-and-parse batch result import

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: disable add participant button while create request is in flight

* feat: render BatchResultEntry on qualifying event pages

Add BatchResultEntry component import and render it on event pages when
the event is a qualifying event, not a final_standings/playoff_game type,
and not yet complete.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address final review issues (sportsSeasonId authority, participant validation, CRLF, unused prop)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 14:52:22 -07:00
Chris Parsons
c68ff85429 Update AI memory for token usage. 2026-04-12 13:52:05 -07:00
Chris Parsons
fa16581f9b
feat: clone sports season (#282) (#288)
Adds a Clone Season button on the admin sports season detail page. The
clone form pre-fills all settings with the source season's data, bumping
the year by one and shifting all dates accordingly. On submit, the new
season is created in a single transaction that copies participants,
scoring events (with dates shifted), futures odds/Elo rating stubs
(zeroed-out probabilities so the simulator can re-run), and QP config
for qualifying_points seasons.

Fixes #282

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-11 22:03:37 -07:00
Chris Parsons
dc879e3033
feat: sort admin sports seasons by status, sport name, then year (#286)
Active seasons sort first, then upcoming, then completed. Within each
status group, seasons sort by sport name alphabetically then year
ascending. Fixes return type of findAllSportsSeasons to reflect the
included sport/participants relations, removing the cast in the loader.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 10:07:18 -04:00
Chris Parsons
68b2e070e6
fix: infer LLWS bracket side from name when externalId is null (#285)
Participants are created with externalId=null by default, causing the
LLWS simulator to crash at runtime. Fix in two parts:

1. Name-prefix inference: if externalId is null, participants whose
   name starts with "US " or equals "US" are assigned to the US side;
   all others are assigned to Intl. Pools are always randomized when
   inferred (no pool suffix).

2. Admin UI: add an inline-editable "Group" column to the Manage
   Participants page so admins can explicitly set externalId for any
   simulator that uses it (LLWS, and future cases like NHL conferences).

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 09:51:16 -04:00
Chris Parsons
a6bb1330e6
Fix darts simulator: bracket bug, ELO calibration, fallback Elo (#284)
* fix: lower darts ELO_DIVISOR to 400 and fallback Elo to 1400

ELO_DIVISOR 500 → 400: elite darts is more skill-dominated than the
previous setting implied. A 400-point gap now gives ~78% per-set win
probability (vs ~73% before).

fallbackElo 1600 → 1400: unseeded PDC World Championship entrants
(regional qualifiers, Q-School players) are materially weaker than
seeded tour professionals. 1400 better reflects that gap.

Combined effect: a dominant player (e.g. 2000 Elo vs 1400-1600 field)
now produces EV ≈ 65 instead of ≈ 30, which better matches expectations
for a top-ranked player in a 128-player bracket.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: lower darts ELO_DIVISOR to 200 for realistic EV distribution

With the actual PDC field (top players clustered 1800–1970 Elo, Littler at
~2080), ELO_DIVISOR=400 made the gap between world #1 and the top 8 too
soft — EV for Littler came out ~37 instead of the expected 65–70.

ELO_DIVISOR=200 calibrates correctly for this field: a 100-pt gap now
gives ~62% per-set win probability (vs ~56% at 400), sharply rewarding
the best players while still allowing upsets. Littler at 2084 produces
EV ≈ 65–70 against the real PDC tour roster.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: seed darts bracket by Elo instead of world ranking

World ranking (PDC Order of Merit) is prize-money-based and can diverge
from current skill — e.g. Kevin Doets (1818 Elo) was ranked 35th while
Joe Cullen (1667 Elo) held the 32nd seed. Seeding the weaker player and
leaving the stronger one unseeded contradicts the Elo-based match model.

Seeding by Elo descending ensures the 32 strongest players (by the same
metric used to compute match probabilities) get protected bracket positions.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* revert: restore world-ranking-based seeding for darts bracket

Seeding should follow the PDC Order of Merit (world ranking), not Elo.
Reverts the previous Elo-seeding commit.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: interleave seeded and unseeded R1 pairs in darts bracket

Previously, all 32 seeded-vs-unseeded matches were added to r1Pairs
first (indices 0–31) and all 32 unseeded-vs-unseeded matches last
(indices 32–63). Since R2 pairs adjacent R1 winners, this created two
completely separate sub-brackets that only converged at the Final:
  - Seeded sub-bracket: top players eliminating each other early
  - Unseeded sub-bracket: high-Elo unseeded players (e.g. Doets 1818,
    Zonneveld 1806) steamrolling weak opponents and making the Final
    ~20% of the time

Fix: interleave each seeded match with its adjacent unseeded-vs-unseeded
match. Seeded pair i is at r1Pairs[2i], unseeded pair i is at r1Pairs[2i+1].
From R2 onwards, winners from seeded and unseeded regions now merge
correctly as in a real single-elimination bracket.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 00:47:47 -04:00
Chris Parsons
d5aa8a3de4
fix: address VORP code review issues (#283)
* fix: address VORP code review issues

- Switch admin EV form to batchUpsertParticipantEVs to avoid N×N
  concurrent UPDATE storm (was calling upsertParticipantEV per
  participant, each triggering a full syncVorpForSeason)
- deleteParticipantEV now resets vorpValue to "0" and calls
  syncVorpForSeason so remaining participants' ranks stay correct
- syncVorpForSeason issues a single bulk CASE UPDATE instead of
  N individual UPDATE statements
- Add doc warning on recalculateEV that callers must sync VORP manually
- Extract REPLACEMENT_LEVEL_START/END_IDX constants; clarify comment
  that 12-14 is a fixed product decision, not derived from league size
- Include vorpValue in draft room participant select projection
- Update drizzle-orm mock to support sql.join; update test assertions
  to reflect single bulk-update call

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: resolve lint errors (toSorted, unused var)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 23:20:02 -04:00
Chris Parsons
8ee5a8008e feat: sort draft room and auto-pick by VORP instead of expected value
Update draft participant sorting to use vorpValue column instead of expectedValue
in draft room initialization and auto-pick selection for both single-sport and
multi-sport seasons.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 02:27:40 +00:00
Chris Parsons
3c740c50bf feat: add syncVorpForSeason and wire into EV update flow
Adds syncVorpForSeason to recalculate and persist VORP for all participants
in a season after any EV change. Wires it into upsertParticipantEV,
batchUpsertParticipantEVs, and recalculateAllEVsForSeason so VORP stays
current whenever EVs are updated.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 02:05:36 +00:00
Chris Parsons
22ec6381b8 feat: add calculateReplacementLevel and calculateVORP to ev-calculator 2026-04-09 01:59:46 +00:00
Chris Parsons
30903bec19 feat: add vorp_value column to participants table
Adds vorpValue decimal field to the participants schema to support
VORP (Value Over Replacement Player) calculation and caching.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 01:57:22 +00:00
Chris Parsons
9e5d1cda5f
Fix NHL simulator seeding bugs and code quality issues (#281)
* Fix NHL simulator dynamic seeding and code quality issues

- Replace hardcoded seeding probabilities with standings-based Monte Carlo
  projection: simulates remaining regular season games per team using Elo
  win probability vs. a league-average opponent, so mathematically eliminated
  teams naturally fall out of playoff contention
- Fix double-simulation bug in wildcard pool: all 16 conference teams are now
  projected exactly once via sortProjected([...divA, ...divB].map(projectTeam)),
  then filtered — wildcard pool no longer re-runs simulateProjectedPoints with
  fresh randomness independent of the division seeding
- Move ProjectedTeam interface, projectTeam(), and sortProjected() to module
  scope (defined once, not recreated on every buildConferenceBracket call)
- Replace conference-level participant count check (east < 8 || west < 8) with
  per-division checks (each division < 3) for a more actionable error message
- Add logger.warn when standings.length === 0 so admins know the sim is running
  without synced data
- Remove unused easternTeams/westernTeams variables
- Simplify test: replace Object.fromEntries pattern with a plain for..of loop

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix oxlint errors in NHL simulator and tests

- Replace non-null assertions (data!) with optional chaining (data?.x ?? "")
- Move makeEntry helper to module scope to avoid recreating on every call

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 21:33:33 -04:00
Chris Parsons
0da80bd2c0
Add LLWS bracket Monte Carlo simulator (#280)
* Add LLWS bracket Monte Carlo simulator

Simulates the 20-team Little League World Series: pool play round-robin
(5 teams/pool, top 2 advance) → 4-team double-elimination per side
(US and International) → consolation game → World Series final.

Uses championship futures odds as the sole win-probability signal.
Pool assignments are auto-detected from externalId: bare "US"/"Intl"
randomizes pools each simulation (pre-draw mode); "US:A"/"Intl:B" etc.
uses fixed assignments (post-draw mode). Sides can differ.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix oxlint violations in LLWS simulator

- Replace non-null assertions with null-safe access (! → ?? / optional chaining)
- Replace .sort() with .toSorted() per linting rules
- Promote bump() to simulate() scope and pass it into simulateSideBracket,
  removing the need to pass counts into that function

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 16:52:10 -04:00
Chris Parsons
4d5fea05ab
Add NCAA Football CFP simulator (12-team bracket) (#278)
Fixes #124

* Add NCAA Football CFP simulator (12-team bracket)

Implements a Monte Carlo simulator for the College Football Playoff using
the 2024-present 12-team format. Elo/FPI ratings are entered manually via
the existing admin Elo Ratings page; championship futures odds can
optionally be blended in (60% Elo / 40% odds).

- Add CFP_12 bracket template (First Round not scoring, QFs onward score)
- Add generateCFP12Bracket() with correct seeding: 5v12, 6v11, 7v10, 8v9
  in First Round; seeds 1–4 receive QF byes
- Add NCAAFootballSimulator: 50k Monte Carlo sims, seeds teams by blended
  Elo+odds strength, tracks champion/finalist/SF/QF placement tiers
- Register ncaa_football_bracket simulator type in registry and schema enum
- Add migration 0071: ALTER TYPE simulator_type ADD VALUE 'ncaa_football_bracket'
- Add tests: 30 tests covering bracket template structure and simulator
  probability distributions, seeding, edge cases, futures blending

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix lint errors in NCAA Football CFP simulator

Replace non-null assertions with optional chaining, change let to const,
use toSorted() instead of sort(), and add a bump() helper to avoid
repeated map lookups with non-null assertions in simulateBracket.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix TS2345 in NCAA football simulator test

Add ?? 0 fallback so optional-chained probFirst is number, not number | undefined.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-08 09:48:32 -04:00
Chris Parsons
ad49d6246d
Fix CS Major simulator bugs and accuracy issues (#276)
* Fix CS Major simulator bugs and accuracy issues (fixes #275)

- Fix crash when pool teams are missing Elo ratings by including all
  participants with FALLBACK_ELO, ensuring Champions Stage always gets
  exactly 8 teams
- Add AdvancedTeam type tracking losses-at-advancement; seed Champions
  Stage by stage performance (fewer losses = higher seed) instead of
  world rank alone
- Promote decisive Stage 2 matches (either team at ≥2W or ≥2L) to Bo3,
  matching the real Challengers Stage format
- Tie-split QP for QF losers (slots 5–8) and SF losers (slots 3–4)
  instead of assigning arbitrary individual placements
- Change stage-complete threshold from === 8 to >= 8 for robustness
- Validate even team count in simulateSwiss to prevent silent infinite loops
- Short-circuit Monte Carlo loop when all events are complete, returning
  deterministic 0/1 probabilities
- Parallelize stage results DB fetches with Promise.all
- Export calcStage3ExitQP and simulateOneMajor; add test coverage for
  both, plus new simulateSwiss and simulateChampionsStage edge cases

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Fix oxlint violations in CS Major simulator

- Replace non-null assertion (!) with null-safe guard in simulateOneMajor
- Replace non-null assertions in test expectations with nullish coalescing
- Move makeStage3QPConfig out of describe block (no captured variables)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 17:28:24 -04:00
Chris Parsons
102cb781ad
Add NFL season + playoffs Monte Carlo simulator (#272)
Implements a new `nfl_bracket` simulator that projects the NFL regular
season and full playoff bracket using nfelo Elo ratings.

- Simulates remaining regular season games (17 total) per team using
  Elo win probability vs an average opponent, then seeds both conferences
  (division winners = seeds 1–4, wildcards = 5–7) per simulation
- Simulates Wild Card, Divisional, Conference Championship, and Super
  Bowl rounds with correct NFL bracket structure (seed 1 bye)
- Applies +48 Elo home-field advantage (~57% win rate) for all rounds
  except the neutral-site Super Bowl
- Pre-season mode (no standings in DB): simulates all 17 games from
  scratch; falls back to futures odds → Elo conversion if no sourceElo
- Validates all 8 NFL divisions have Elo-rated teams before simulating,
  with a clear error listing missing divisions
- Registers as `nfl_bracket` simulator type in the registry and schema
- Adds migration to extend the `simulator_type` enum
- Also updates drizzle.config.ts to prefer DIRECT_DATABASE_URL when set

Fixes #129

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-07 09:39:34 -04:00
Chris Parsons
787b817fa7
Add PgBouncer connection pooling support for Vultr managed PostgreSQL (#271)
Disables prepared statements when PGBOUNCER=true (required for PgBouncer
transaction mode). Adds DATABASE_DIRECT_URL so migrations always use a
direct connection, bypassing the pool.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-06 17:15:18 -04:00
Chris Parsons
4bcadb0749 Remove extraneous drizzle file 2026-04-06 15:34:01 +00:00
Chris Parsons
b19445f2fe Fix idempotency on 0069 2026-04-06 15:32:39 +00:00
Chris Parsons
90127fe5bd
Fix migration 0068: add IF NOT EXISTS to enum ADD VALUE (#269)
The migration fails in production because the enum label
"cs2_major_qualifying_points" already exists. Adding IF NOT EXISTS
makes the statement idempotent so it won't error on re-run.

https://claude.ai/code/session_015iUtjSgiL1ZUNggvj434gP

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-06 11:12:13 -04:00
Chris Parsons
1ee0d51fb3
Clean up migration chain and add verification migration (#268)
* Fix broken drizzle migration chain and add prevention guidelines

The migration system was broken due to three issues:
1. Snapshot 0067 had an invalid `autoincrement` field (PostgreSQL doesn't
   support this) causing Zod validation to fail with "data is malformed"
2. Migrations 0068 and 0069 were missing snapshot files, breaking the
   snapshot chain required by `drizzle-kit generate`
3. Orphaned file 0048_mean_enchantress.sql existed outside the journal

Fixed by removing the invalid field, regenerating migrations 0068-0069
with proper snapshots via `drizzle-kit generate`, deleting the orphaned
file, and adding a no-op verification migration (0070). Made migration
0069 idempotent with IF EXISTS/IF NOT EXISTS guards for production safety.

Updated CLAUDE.md with rules to prevent manual migration/journal editing
and ensure snapshots are always generated.

https://claude.ai/code/session_01JuVHpRPa974MKSHoXNGkgU

* Update package-lock.json from npm install

https://claude.ai/code/session_01JuVHpRPa974MKSHoXNGkgU

* Preserve original migration tags and SQL to match production hashes

Restores the original tag name (0068_cs2_major_simulator) and exact SQL
content for migrations 0068 and 0069 so their hashes match what's already
recorded in the production __drizzle_migrations table. Also fixes the
snapshot id/prevId chain to use consistent tag-based identifiers.

https://claude.ai/code/session_01JuVHpRPa974MKSHoXNGkgU

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-06 10:53:51 -04:00
Chris Parsons
a395f10064
Fix migration check in deploy script to use reliable exit code (#267)
`docker compose wait migrate | grep -qx "0"` was unreliable because
`docker compose wait` output format may not match the literal string "0".

Replace with `docker compose up --no-deps migrate` (foreground, no -d),
which exits with the container's actual exit code — no grep needed.

https://claude.ai/code/session_01WRe4qZuV2NQqDYurpDodF4

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-06 00:44:04 -04:00
Claude
0f97ab258f
Fix migrate.mjs exiting with code 1 after successful migration
client.end() in the finally block was throwing (postgres driver already
cleaned up connections internally during migrate()), causing an unhandled
rejection and exit code 1 despite the migration succeeding.

- Use explicit process.exit(0)/exit(1) instead of relying on implicit exit
- Wrap both client.end() calls with .catch(() => {}) to tolerate cleanup errors
- Add onnotice: () => {} to suppress noisy NOTICE messages (schema/table
  already exists) that are normal on every idempotent re-run

https://claude.ai/code/session_01ReaqH3o9NVH4QU4qE9WMMQ
2026-04-06 04:24:04 +00:00
Chris Parsons
f1af4b5171
Decouple database migrations from server startup (#265)
* Use Docker Compose init service pattern for database migrations

Replaces the fragile double-migration approach (server.ts startup +
drizzle-kit CLI in CI) with a one-shot migrate service in Docker Compose
that the app depends on via condition: service_completed_successfully.

- Add scripts/migrate.mjs: programmatic drizzle-orm migration (uses
  production deps, not drizzle-kit which is devOnly and absent from image)
- Dockerfile: copy scripts/ into image, remove drizzle.config.ts (only
  needed by drizzle-kit CLI)
- server.ts: remove runMigrations() entirely; migrations are now handled
  by the migrate container before the app starts
- deploy.yml: remove explicit docker run migration step; replace sleep 10
  health check with a poll loop and explicit migrate exit-code check

Production server's docker-compose.yaml needs a one-time manual update
to add the migrate service — see plan for exact config.

https://claude.ai/code/session_01ReaqH3o9NVH4QU4qE9WMMQ

* Move drizzle-kit to devDependencies; use docker compose wait in deploy

drizzle-kit is a dev-only tool (schema generation and local migrations).
Now that production migrations run via the programmatic drizzle-orm API
in the migrate init container, drizzle-kit has no runtime role.

Also replaces the polling health check loop with docker compose wait,
which blocks until the migrate service exits and returns its exit code
cleanly — no sleep or manual status inspection needed.

https://claude.ai/code/session_01ReaqH3o9NVH4QU4qE9WMMQ

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-06 00:07:36 -04:00
Chris Parsons
89d52cca5e
Run database migrations on deploy before starting container (#264)
Migrations were never being run against production on deploy, causing
schema mismatches when new columns are added. This adds a migration
step using the PROD_DATABASE_URL secret before bringing up the new
container, with set -e to abort the deploy if migrations fail.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-05 22:50:23 -04:00
Chris Parsons
2b680d7272
Replace isDraftable boolean with draftOn/draftOff date range (#263)
Fixes #262

* Replace isDraftable boolean with draftOn/draftOff date fields on sport seasons

Admins can now schedule when a sport season becomes available for drafting
by setting explicit open and close dates instead of a manual toggle.

https://claude.ai/code/session_01LHYgpyimF8v8odUB6kj8Qc

* Address code review feedback on draft window implementation

- sports-data-sync: use unambiguous past placeholder dates for synced seasons,
  with a comment explaining the intent
- sports-season model: remove redundant top-level lte/gte imports (callback
  form already supplies them)
- _journal.json: add missing trailing newline
- sports-season test: mock ~/database/schema instead of stubbing all drizzle
  builder functions, matching the established pattern in the codebase
- admin list: compute today once in component body instead of per-row

https://claude.ai/code/session_01LHYgpyimF8v8odUB6kj8Qc

* Fix: restore lte/gte imports removed in review cleanup

The relational query where-callback in this version of Drizzle does not
expose lte/gte as helper args, so they must be imported from drizzle-orm.
Removing them broke CI TypeScript.

https://claude.ai/code/session_01LHYgpyimF8v8odUB6kj8Qc

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 22:09:52 -04:00
Chris Parsons
fbeee4ed15
Refactor playoff event processing and improve code clarity (#261)
* Remove redundant processPlayoffEvent loop from finalize-bracket action

All bracket rounds are already processed (with scoring and Discord
notifications) as each match winner is set via set-winner/set-round-winners.
By the time the Finalize button is clicked, placements are current and
standings are up to date. The re-processing loop was firing recalculations
and Discord notifications once per round needlessly.

The finalize action now only assigns 0 points to non-bracket participants,
marks the event complete, and runs one final standings recalculation.

https://claude.ai/code/session_01RhQS6FQRh6iYtVNaryCEf5

* Fix stale comment in finalize-bracket action

The template is now fetched only as a validity guard, not for round
order iteration (which was removed in the previous commit).

https://claude.ai/code/session_01RhQS6FQRh6iYtVNaryCEf5

* Fix complete-round redundant Discord/recalculation and stale comment

complete-round was calling processPlayoffEvent without skipRecalculate,
firing recalculateAffectedLeagues and Discord even though each match
winner had already triggered those side effects via set-winner. Add
skipRecalculate: true to match the autoCompleteRoundIfDone pattern.

Also fix autoCompleteRoundIfDone comment which incorrectly said
"non-bracket eliminations are recorded" — that's a separate step in
finalize-bracket; processPlayoffEvent records bracket round placements.

https://claude.ai/code/session_01RhQS6FQRh6iYtVNaryCEf5

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 18:11:43 -04:00
Chris Parsons
a71e256bfd
Add CS2 Major Qualifying Points simulator and stage management (#260)
* Add CS2 Major qualifying points simulator

Implements a full CS2 Major tournament simulator with:
- 3-stage Swiss format (Opening Bo1, Elimination Bo1/Bo3, Decider all Bo3)
  + Champions Stage 8-team single-elimination (QF Bo3, SF Bo3, GF Bo5)
- Monte Carlo simulation (10,000 iterations) accumulating QP across 2 majors/season
- Sampled 24-team field per iteration: top 12 guaranteed, remaining weighted by 1/rank
- Stage 3 exits (placements 9-16) sub-ranked by W-L record (2-3 > 1-3 > 0-3)
- Stage assignments stored per-event so actual field composition drives simulation
- Admin CS Elo form for entering team Elo + HLTV world rankings
- Admin CS2 stage setup page for assigning teams to stages and tracking advancement
- Database migration: cs2_major_qualifying_points enum value + cs2_major_stage_results table
- 24 unit tests covering all exported pure functions

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

* Consolidate Elo + ranking input into generic elo-ratings page

The darts-elo and cs-elo pages were unreachable from the admin nav,
which always links to the generic elo-ratings page. Extended elo-ratings
to conditionally show world ranking fields for simulator types that need
it (darts_bracket, cs2_major_qualifying_points), then deleted the
redundant sport-specific pages.

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

* Consolidate server postgres connections into one shared pool

Four separate postgres() clients were open simultaneously (app, timer,
snapshots, socket), each defaulting to 10 connections, exhausting the
database's max_connections limit. Replaced with a single shared lazy-
initialized client in server/db.ts using a Proxy to defer the
DATABASE_URL check until first use (preserving test compatibility).

Also bumps the CS2 Champions Stage stochastic test from 200 → 1000
iterations to eliminate flakiness.

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

* Fix and() bug and add Swiss loop safety guard

- cs2-major-stage.ts: markCs2StageEliminations and setCs2FinalPlacements
  were using JS && instead of Drizzle and(), causing WHERE to filter only
  by participantId (not scoringEventId), which would update rows across
  all events instead of just the target event
- cs-major-simulator.ts: add break guard in simulateSwiss while loop to
  prevent infinite loop if pairGroups returns no pairs

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

* Fix all remaining code review issues

- cs2-major-stage.ts: use schema column reference for stageEliminated
  in markCs2StageEliminations instead of raw SQL string
- cs-major-simulator.ts: simulateOneMajor now locks in known stage
  results when a stage is complete (8 recorded eliminations), only
  simulating the remaining stages during live events
- admin event page: add CS2 Stage Setup button for cs2_major_qualifying_points
  simulator types; expose simulatorType in server loader type cast
- cs2-setup.tsx: replace document.getElementById DOM manipulation with
  React state (eliminatedChecked map) for checkbox show/hide logic;
  remove unused stageMap and unassignedParticipants variables

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

* Fix oxlint errors: non-null assertions, sort→toSorted, unused vars

- cs-major-simulator.ts: replace 5 non-null assertions (!) with safe
  optional chaining / if-guards; replace 6 .sort() with .toSorted()
- cs2-major-stage.ts: remove unused `inArray` import
- cs2-setup.tsx: remove unused `assignedIds` variable

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

* Fix flaky Champions Stage stochastic test

The makeTeams(8) helper creates only a 70-pt Elo spread (1800→1730).
With the Champions Stage bracket math this gives team-0 a ~19.6% win
rate — right at the 0.2 threshold, causing the test to fail ~63% of
the time in CI despite 1000 iterations.

Use 100-pt steps (1800→1100) instead, giving team-0 a ~40% win rate
and raising the assertion threshold to 0.25 for a clear safety margin.

https://claude.ai/code/session_019w21Nkf5TvTZHH6oVHaQXR

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-05 16:40:05 -04:00
Chris Parsons
61715b43d2
Load PROD_DATABASE_URL from .env automatically (#259)
Mirrors how DATABASE_URL is loaded, so users can store both in their
local .env instead of passing PROD_DATABASE_URL inline each time.

https://claude.ai/code/session_01EiYh5ZiuWAnpo1PND45Yi1

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-03 15:38:09 -07:00