Commit graph

320 commits

Author SHA1 Message Date
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
Chris Parsons
139061e702
Add production database sync script with sanitization (#258)
* Add prod-to-dev database sync script

Adds scripts/sync-prod-db.sh and npm run db:sync-prod to safely copy
production data to the development database. After restoring, the script
nulls all Discord webhook URLs and anonymizes non-admin user PII (email,
name, avatar) to prevent notification leaks and reduce PII exposure on
developer machines. Admin accounts are preserved intact.

https://claude.ai/code/session_01EiYh5ZiuWAnpo1PND45Yi1

* Fix six code review issues in sync-prod-db.sh

- Add upfront check for pg_dump/pg_restore/psql availability (#5)
- Fix password masking to use sed instead of broken bash glob (#6)
- Replace DROP/CREATE DATABASE with pg_restore --clean --if-exists,
  which works on managed cloud databases without superuser access (#2)
- Remove dead ADMIN_DB assignment that was immediately overwritten (#3)
- Handle pg_restore exit code 1 (non-fatal warnings) gracefully
  instead of aborting via set -e (#1)
- Count webhook URLs before the UPDATE for an accurate cleared count (#4)

https://claude.ai/code/session_01EiYh5ZiuWAnpo1PND45Yi1

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-03 15:17:58 -07:00
Chris Parsons
1d3eb4aac2
Add inline edit for participant names on admin sports season page (#257)
Fixes #224

* Add inline edit for participant names on admin sports season page

Adds a pencil icon button next to each participant's delete button. Clicking
it switches the row into edit mode with an input field, a save (checkmark) and
cancel (X) button. Escape also cancels. Submits via intent="update-name" and
validates uniqueness within the season before persisting.

https://claude.ai/code/session_01Q94DWQ1HZEB9PJhGMArU8D

* Simplify edit state and surface edit errors to user

- Combine editingId + editingName into single editing: { id, name } | null state object
- Extract cancelEdit() helper called in 3 places instead of repeating setEditing(null)
- Tag all update-name action responses with intent: "update-name" so errors can be
  identified and routed correctly
- Show update-name errors inline below the edit input
- Guard single-add and bulk-add error displays against showing update-name errors

https://claude.ai/code/session_01Q94DWQ1HZEB9PJhGMArU8D

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-01 17:56:42 -07:00
Chris Parsons
c5ccee2225
Show events on multiple dates when games span requested date range (#254)
* Fix admin Games to Score panel missing bracket events

The panel was silently dropping bracket events in two cases:

1. When a bracket event had `scoringEvents.eventDate` set to a future
   round date (e.g. "April 5") but an individual game's `scheduledAt`
   was today, the old dedup code picked `eventDate` first and the
   component filter `displayDate === today` never matched.

2. When an event had games on both today and tomorrow, whichever row
   the unordered step-1 query returned first "won" — potentially hiding
   a today game from the today tab entirely.

Fix: replace the `Map<id, firstDate>` deduplication with
`Map<id, Set<date>>` that collects every requested date an event
qualifies for (via either `eventDate` or `gameDate`). The return uses
`flatMap` to emit one entry per (event, date) pair, so events with
games on multiple days now appear correctly in both tabs.

https://claude.ai/code/session_01QkFxCF4xmKjdVCNPysWDML

* Fix lint errors: replace .sort() with .toSorted() and remove non-null assertion

- Replace Array#sort() with Array#toSorted() in two places (unicorn rule)
- Remove non-null assertion on Map#get(); use early continue instead

https://claude.ai/code/session_01QkFxCF4xmKjdVCNPysWDML

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-01 13:39:03 -07:00
Chris Parsons
6df66e9cc6
Optimize GitHub Actions CI/CD pipeline (#252)
- Switch Docker layer cache from local filesystem to GHA native cache
  (type=gha), eliminating the cache-size workaround hack
- Consolidate cancel-previous-runs into a single dedicated job to
  prevent race conditions from concurrent API calls
- Remove DATABASE_URL build-arg that was never consumed by the Dockerfile
- Add post-deploy health check that fails the job and prints logs if any
  container exits unexpectedly
- Add .nvmrc and use node-version-file instead of hardcoded node-version: 20

Fixes #249

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 00:59:21 -07:00
Chris Parsons
383315d0c3
Auto-eliminate non-group participants on group generation (#250)
When generating groups for a tournament (e.g. FIFA World Cup), any
participants in the sport season who were not assigned to a group are
now automatically marked as eliminated (finalPosition = 0) — the same
result as running "Reprocess Eliminations" manually.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-01 00:40:55 -07:00
Chris Parsons
005a5a82a7 Fix noisy and broken tests. 2026-03-31 15:53:43 -07:00
Chris Parsons
8c3663e01b
Add PDC World Darts Championship simulator with Elo-based bracket (#248)
Fixes #123

* Add PDC World Darts Championship simulator (128-player bracket)

- New DartsSimulator: 128-player single-elimination, 7 rounds with
  PDC-accurate best-of-sets formats (bo3/bo5/bo5/bo7/bo7/bo11/bo13).
  ELO_DIVISOR=500 via set-level Bernoulli model. Two simulation paths:
  Path A (bracket drawn) simulates from actual DB matches; Path B
  (pre-bracket) seeds top 32 by world ranking in fixed positions and
  randomly draws the remaining 96 per simulation run (50,000 iterations).
- darts_bracket added to simulatorTypeEnum and simulator registry.
- world_ranking nullable integer column added to participant_expected_values
  (migration 0067); batchSaveSourceElos now accepts and persists it.
- Admin route /admin/sports-seasons/:id/darts-elo: bulk import with format
  "Player Name, 2099, 1" (name, Elo, optional world ranking), fuzzy name
  matching, auto-runs simulation and updates EV/snapshots on save.
- DARTS_128 bracket template added (scoring starts at Quarterfinals).
- 30 unit tests: math helpers, bracket seeding structure, Path A/B integration.

https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz

* Review fixes: pre-compute hot-loop invariants, import normalizeName

- Pre-compute seededSlots and getSeededMatchOrder(32) before the 50k
  simulation loop — was being recomputed every iteration
- Pad unseeded pool to 96 once before the loop instead of inside it
- Inline bracket-building in the hot loop using pre-computed seededSlots;
  removes the per-iteration call to buildR1Bracket/getSeededMatchOrder
- Remove dead SEEDED_R1_PAIRS constant (was never referenced)
- Import normalizeName from ~/lib/fuzzy-match instead of redefining it locally

https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz

* Fix lint failures: unused vars, eqeqeq, toSorted

- Remove unused seededSet/unseededSet variables in test
- Replace != null with !== null && !== undefined (eqeqeq rule)
- Replace .sort() with .toSorted() in simulator and route (unicorn/no-array-sort)

https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz

* Fix TS2552: restore seededSet declaration removed during lint fix

https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-31 15:37:28 -07:00
Chris Parsons
efbd28b446
Exclude completed playoff matches from upcoming events query (#247)
* Exclude scored bracket matches from upcoming events calendar

Add `eq(schema.playoffMatches.isComplete, false)` to the bracket-sports
query in `getUpcomingEventsForDraftedParticipants` so that individual
playoff matches already scored (isComplete = true) no longer appear on
the upcoming events calendar, even when the parent scoring event is still
open.

Also update the schema mock in upcoming-calendar.test.ts to include
`playoffMatches.isComplete` and add a test covering this behaviour.

https://claude.ai/code/session_01GMLmjN9mwoANfpgSciD7Bi

* Fix leaked mockReturnValueOnce in scored-match test

The new test only triggers one selectDistinct call (rows is empty so the
max-game-number lookup is skipped). The second mockReturnValueOnce was
never consumed, leaving a makeMaxGameChain value in the queue that was
then picked up by the subsequent "uses leftJoin" test, causing it to fail
with "leftJoin is not a function".

https://claude.ai/code/session_01GMLmjN9mwoANfpgSciD7Bi

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-31 10:08:25 -07:00
Chris Parsons
28a670666c
Fix test:run failing in CI due to missing Playwright browser (#246)
Scope test:run to the unit project only so it doesn't attempt to launch
Playwright/Chromium (needed by the storybook browser project) in environments
where browsers aren't installed. Add test:storybook script for running
storybook stories explicitly when Playwright is available.

https://claude.ai/code/session_01PqDTVMzP7dMtLpkn5Sw442

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-30 14:42:23 -07:00
Chris Parsons
2b13e153d6 Initial storybook components. 2026-03-29 22:09:45 -07:00
Chris Parsons
c604dc9bc5
Fix tiebreaker incorrectly separating tied teams with pending participants, fixes #244 (#245)
Placement counts (used to break points ties) previously only included
fully-finalized participants. A team whose events all resolved first would
accumulate real placement counts while tied teams with pending events had
zeros, causing the tie to be broken in favour of whichever team finished
scoring first rather than on merit.

Fix: count a participant's current position toward the tiebreaker regardless
of isPartialScore. Their position is the best available signal; if it changes,
recalculateStandings reruns and ranks update naturally.

Also removes a redundant bounds check (finalPosition > 0 was already
asserted by the outer if-condition).

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-29 16:59:13 -07:00
Chris Parsons
131945ddeb
Install Storybook with React Router Vite plugin fix, closes #229 (#243)
- Install Storybook 10 with @storybook/react-vite framework
- Fix React Router Vite plugin conflict by filtering it out in viteFinal
  (reactRouter() returns a plugin array, so the filter must flatten first)
- Integrate Storybook stories as a vitest browser project via @storybook/addon-vitest
- Point stories glob at app/ instead of scaffold stories/ dir
- Remove unused @chromatic-com/storybook and @storybook/addon-onboarding addons
- Clean up duplicate __dirname in vitest.config.ts

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-29 15:20:48 -07:00
Chris Parsons
338979e0a8
Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator (#242)
* Add FIFA World Cup 2026 support with group stage display and Monte Carlo simulator, fixes #127

- New `groupStageMatches` table for recording group play results (W/D/L, scores, matchday, schedule)
- `computeGroupStandings()` model function: pts → GD → GF → name tiebreaker ordering
- `GroupStageStandings` component showing all 12 groups with standings table and manager column
- Admin bracket UI: group match score entry, per-group standings, "Recalculate Floors" action
- `WorldCupSimulator`: 50k Monte Carlo covering group stage + best-8 3rd-place + knockout + 3rd place game
  - Fuzzy name matching for national team Elo lookup (exact → substring → word-overlap), warns on miss
  - Partial group completion: completed matches replayed with real scores, remaining matches simulated
  - Elo priority: admin-entered sourceElo > futures odds converted to Elo > hardcoded national team ratings
- `fifa_48` bracket template: added Third Place Game round with `loserFeedsInto` on Semifinals
- Scoring rules: distinct 3rd/4th place for `fifa_48` (not averaged), QF losers share 5th–8th equally
- Floor scoring: SF participants guaranteed 4th (provisional), finalized after 3rd place game
- `recalculate-floors` admin action deletes and replays all results from scratch (fixes stale guard bug)
- Unique index on `(tournamentGroupId, participant1Id, participant2Id)` to prevent duplicate pairings
- Batch `findMatchesByGroupIds()` replacing N sequential queries in the sport season loader
- League home mini-standings now shows `actualPoints` (includes floor) instead of `totalPoints` only
- Elo ratings admin page supports World Cup (same bulk-import flow as snooker)

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

* Fix TypeScript errors: update GroupStandingData type to use findMatchesByGroupIds

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

* Increase Node heap to 4GB for unit tests in CI to prevent OOM

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

* Fix OOM in CI: make WorldCupSimulator simulation count configurable for tests

Tests now pass numSimulations=500 instead of the production default of 50,000.
Six simulator tests × 50k iterations each was exhausting the 4GB heap on GitHub
Actions runners. Also reduce simGroupMatch stat tests from 50k to 5k iterations.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-29 10:27:47 -07:00
Chris Parsons
611e1ccf0a
Show tied ranks with T prefix across standings and Discord (#239)
* Show tied ranks with T prefix across standings and Discord notifications, fixes #197

- Add buildTiedRankChecker() utility to standings-display.ts; replaces
  four copies of inline rank-count logic spread across components,
  the league home route, and the Discord service
- Prefix shared ranks with "T" (e.g. "T3") in StandingsTable (league
  panel), StandingsTable (full standings), the league home preview, and
  Discord webhook notifications
- Add useMemo wrapping in StandingsTable components so tie detection
  does not recompute on every render
- Fix compareTeamsForRanking to round total points to hundredths before
  comparing, preventing floating-point noise from producing spurious
  non-ties in the standings

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

* Fix discord test to expect escaped period in rank display

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 20:45:15 -07:00
Chris Parsons
8f55d0d135
Prevent duplicate participants within a sports season, fixes #69 (#236)
- Add unique index on (sports_season_id, name) in participants table
- findParticipantByName uses case-insensitive lower() comparison
- Single add: check for existing name before insert, return clear error
- Bulk add: load existing names once upfront (1 query vs N), dedup
  input case-insensitively, report skipped names in UI
- Fix golf-skills and surface-elo routes which called createParticipant
  without any duplicate guard (would have thrown DB constraint errors)

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 01:09:04 -07:00
Chris Parsons
3c4ed67946
Add upcoming events pages and fix timezone filtering, fixes #213 (#235)
- Fix UTC midnight rollover bug: server now queries from yesterday UTC
  as a buffer; UpcomingCalendarPanel filters to local-today client-side
  via useEffect + Intl.DateTimeFormat, removing the need for any
  cookie or server-side timezone detection
- Cap homepage and league page panels at 6 events with a "View all" link
- Add /upcoming-events page (60-day view across all leagues)
- Add /leagues/:leagueId/upcoming-events page (60-day per-league view)
- Add emptyMessage prop to UpcomingCalendarPanel for context-specific copy
- Change getUpcomingEventsForDraftedParticipants to accept pre-computed
  date strings instead of Date objects

fixes #213

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-27 00:49:16 -07:00
Chris Parsons
29ea93ad6d
Add support page with Discord link and contact form, fixes #233 (#234)
- New /support route with Discord join button and contact form
- Contact form sends via Resend to support@brackt.com (email stays hidden from users)
- Spam protection: honeypot field + Cloudflare Turnstile verification
- Server-side input length limits (subject: 200, message: 5000 chars)
- Added Support nav link to navbar (desktop + mobile)

Fixes #233

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 17:17:49 -07:00
Chris Parsons
bde1e6e5f0
Add WNBA playoff simulator with SRS-based Elo ratings, fixes #125 (#231)
* Add WNBA playoff simulator with SRS-based Elo ratings, fixes #125

- New WNBASimulator: Monte Carlo (50k sims) projecting remaining regular
  season games → seeding → R1 Bo3 / Semis Bo5 / Finals Bo7 bracket
- Hybrid Elo sourcing: pre-season uses futures odds (ICM); once avg
  gamesPlayed ≥ 5, switches automatically to SRS-derived Elo
  (elo = 1500 + srs × 20)
- New WnbaStandingsAdapter: fetches ESPN standings + teams endpoints in
  parallel; includes zero-records for 2026 expansion teams (Portland
  Fire, Toronto Tempo) not yet in standings
- Added srs column to regular_season_standings (migration 0063);
  stored as net rating proxy (avgPointsFor − avgPointsAgainst)
- Added wnba_bracket to simulatorTypeEnum

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

* Fix missing afterEach import in wnba standings test

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-26 00:34:51 -07:00
Chris Parsons
eca1508b3f
Improve admin dashboard stats and fix scoring event bugs (#230)
* Improve admin dashboard stats and fix scoring event date bugs, fixes #92

- Add "Seasons by Status" breakdown card (pre-draft / drafting / active / completed)
- Replace full-table fetches with COUNT queries for sports, sports seasons, and templates
- Fix bracket events with null eventDate disappearing from the Games to Score tabs by
  computing a displayDate from matched playoffMatchGames.scheduledAt in getEventsForDates
- Fix Today tab badge showing stale count when all events are scored
- Hide "Getting Started" checklist once the system has sports configured
- Use explicit "en-US" locale in formatEventTime for deterministic output

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

* Fix scoring-event-dashboard tests after select/sql changes

- Rename mockSelectDistinct → mockSelect to match implementation change
  from .selectDistinct() to .select()
- Add sql to drizzle-orm mock
- Update mock row shapes to include eventDate and gameDate fields
- Add two tests covering displayDate derivation from eventDate and gameDate

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 20:46:54 -07:00
Chris Parsons
2b48ef285d
Rework MLB simulator: RDif-based matchup probs, 2026 data, fixes #227 (#228)
Fixes #227

- Replace hardcoded Elo ratings with 2026 FanGraphs Depth Charts projected
  run differential (RDif) for all 30 teams
- Replace Elo formula with Bill James log5 using RDif → win rate conversion
- Restore p_div/p_wc from FanGraphs playoff odds (divTitle/wcTitle) for
  seeding draws — previously these were incorrectly derived from raw win
  rates, which gave the Dodgers only ~24% division win probability instead
  of the correct ~90%
- Add RDIF_DIVISOR constant to compress team strengths toward .500 for
  playoff parity; set to 8000 (Dodgers +137 → ~51.7% per-game win rate)
- Fix minimum team check: < 5 → < 6 (need 3 div winners + 3 wild cards)
- Fix Colorado Rockies p_div 0.000 → 0.001 for consistency
- Fix stale comments throughout; update tests

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-25 19:05:12 -07:00