14 KiB
AGENTS.md: Training Minigames
Parent:
../../../AGENTS.md(root guide: commands, Server Actions convention, domain guide index).
Five XP-earning minigames under one parent: routes live at /minigames/* (moved from /qualification, /radio, /flappy, /eod, /opord; next.config.mjs redirects keep the old URLs working), components under src/components/frontend/minigames/<game>/ (shared bits like UnlockNotice.tsx at the root), game-rule libs under src/lib/minigames/ (custom-content libs in src/lib/minigames/custom/), stats under Profiles progression.minigames.*. The realtime presence channel strings ("eod", "radio", ...) are unchanged:
- Qualification Course (aim trainer):
/minigames/qualification(src/app/(frontend)/minigames/qualification/), game rules insrc/lib/minigames/aim-trainer.ts(recruit/veteran/elite difficulties, civilian targets, scoring/accuracy/XP, injected rng). Components:src/components/frontend/minigames/qualification/(AimTrainerArena,AimTrainerGame,AimTrainerCanvas,AimTrainerLeaderboard). ActionsubmitAimTrainerResultvalidates result bounds, updates profile stats, awards XP, emitsminigame:aim-trainer. - Radio Traffic:
/minigames/radio, sprint + watch modes, procedural message generation (src/components/frontend/minigames/radio/messageGenerator.ts). ActionsubmitRadioResultemitsminigame:radio-traffic; stats underprogression.minigames.radioTraffic(incl.bestSprintTimeMs). - Flight Simulator:
/minigames/flappy(canvas game + leaderboard). Minefield Clearance (EOD):/minigames/eod. OPORD Recall:/minigames/opord(src/lib/minigames/opord-recall.ts). - Call for Fire (artillery observer):
/minigames/call-for-fire, game rules insrc/lib/minigames/call-for-fire.ts(patrol/checkpoint/compound difficulties, compass bearing observer reports, ADD/DROP + RIGHT/LEFT corrections, scoring/accuracy/XP, injected rng, pure). Components:src/components/frontend/minigames/call-for-fire/(CallForFireArena,FireMissionBoard,CallForFireLeaderboard). ActionsubmitCallForFireResultvalidates result bounds, updates profile stats, awards XP + chips, emitsminigame:call-for-fire, and records the ledger entry (accuracy is distance-to-target on a win, null on a loss). - Call for Fire: Versus (multiplayer):
/minigames/call-for-fire-versus, categorymultiplayer(out of periods). Pure engine insrc/lib/minigames/call-for-fire-versus/(engine.ts,views.ts,types.ts,constants.ts; client-safe) plus a server-only in-memory match registry inregistry.ts(mirrorsblackjack/tables.ts:globalThis-anchored Map, lobby, per-turn timeout, expiry sweep, SINGLE-INSTANCE ONLY). Each player hides a FOB fleet, then alternates fire corrections (first shot is a grid designation, later shots adjust from the last impact).views.tsbuilds per-viewer snapshots that never serialize the opponent's fleet. Client pollsfetchVersusMatch(the in-memory SSE bus is unreliable across dev module copies, same as blackjack). Rewards on completion viastats.ts(minigame:call-for-fire-versus, profile groupcallForFireVersus). - Ordnance Disposal (multiplayer, real-time):
/minigames/bomperator(internal keybomperator, label "Ordnance Disposal"), categorymultiplayer(out of periods), a 2-8 player free-for-all Bomberman-style charge-clearing drill. Same pure-engine + in-memory-registry split as CFF versus, but upgraded from turn-based to a fixed ~20 Hz tick loop (was ~10 Hz until v0.12.3; every tick-denominated constant doubles with the rate so real-world durations stay identical):src/lib/minigames/bomperator/{constants,types,engine,views}.tsare pure/client-safe (seeded RNG viastate.rngState/gridSeed;generateGrid,createMatchState,startRound,applyInput,tick), andregistry.tsruns onesetInterval(TICK_MS)per live match (started onstartMatch, cleared on complete/dissolve;globalThis.__bomperatorMatches; SINGLE-INSTANCE ONLY: a restart/redeploy kills live matches). Grid is 15x13 (border + even/even pillars + seeded crates with one hidden power-up each; four classic pickups bomb/range/speed/kick). Movement is grid-locked with sub-cell interpolation; charges fuse ~2.5s, cross-flames stop at walls, destroy crates, chain-detonate, and kick-push; round ends at <=1 alive; sudden death spawns random-cell explosions after the 150s timer, with a draw guard. FFA has no hidden info sobuildBomperatorViewserves every viewer the same board (yourSeat: null= spectator). Clients POST inputs (sendBomperatorInput, rate-limited 40/s) and pollfetchBomperatorMatch(~500ms fallback behind the SSE stream); a rolling event buffer (monotonic ids) drives client SFX without diffing. Disconnects hold the seat forRECONNECT_WINDOW_MSthen eliminate; below two active seats the match dissolves. Rewards on completion viastats.ts(minigame:bomperator, profile groupbomperator: matchesPlayed/matchWins/roundsWon/kills/xpEarned; XP win/loss base + per-kill bounty, chips auto-derived). Registry row shipsstatus: "upcoming"(page rendersMinigameComingSoonuntil an admin flips it active).- Client prediction & correction:
BomperatorGame.tsxpredicts its own seat between snapshots and reconciles with a lead-aware envelope policy (helpers inbomperator/prediction.ts): gaps insidemax(PRED_DEADZONE, speed*(rttEnv/2 + TICK_MS/2 + PRED_ENVELOPE_BUDGET_MS)/1000)ride untouched, anything beyond is trimmed by at most 0.35 cells per snapshot (a run-speed glide, never a one-frame pull), and gaps past 2.5 cells ease toward the estimate at up to 2.5x run speed instead of teleporting (round resets still snap via the ack-backwards branch).rttEnvismin(300, max(rtt, ackLat - rtt)): transport RTT plus the server-side share of the measured input-to-ack EMA, because ping/pong alone omits the tick queue and snapshot turnaround (sizing from ping alone put the envelope under the real gap noise floor). Prediction advances by real elapsed time with a 1s sanity cap, so a main-thread hitch does not leave a permanent gap (the engine runs on wall clock); correction easing keeps its own 100ms slice so one catch-up frame cannot discharge a whole gap. A hidden tab releases held keys (input is level-triggered, so the server would otherwise keep running the player). Optimistic ghost charges are replayed in BOTH the local prediction and the server estimate. The estimator's replay clock only moves FORWARD: an unacknowledged input older than the snapshot contributes its direction, never its age (rewinding the clock let a stale 400ms keepalive inflate the estimate by up to 4 cells, which the reconcile then chased). Root cause of the old teleport-back: Node event-loop stalls make the server's 20Hz tick loop DROP setInterval callbacks (no catch-up), so the sim permanently lags wall clock; the old all-inputs-acked pull let that gap stack and discharge at once.tests/int/bomperator-prediction.int.spec.tsis an offline deterministic harness (real engine + modeled network + frame-by-frame reconcile mirror) including production-latency replay (tests/fixtures/bomperator-prod-rtt.json, from HAR) and a server-stall A/B proof; change client prediction in BOTH component and mirror, and run the trace scenarios before shipping. v0.12.4 lesson (reverted in v0.12.5): do not add mechanisms that trust precise latency estimates (decision nudges, projected ghost placement); real TTFB swings 31-463ms and they glitch under it. - Arena transport (WebSocket match replication): when
NEXT_PUBLIC_ARENA_URLis baked into the bundle, the client tries a dedicated arena process first (src/arena/, Node 22 +ws, Coolify service #2, Docker targetrunner-arena): its own event loop runs the 20 Hz tick via a drift-correctedsetTimeoutchain (capped catch-up,tick-driftlog every 30s), inputs/snapshots ride one socket (src/arena/protocol.ts), and RTT comes from 2s ping/pong instead of POST timing. Transport selection lives incomponents/frontend/minigames/bomperator/transport.ts: WS first, automatic fallback to the unchanged HTTP path (registry actions + SSE + slow poll) after 2 connection failures or a 5s setup timeout; absentNEXT_PUBLIC_ARENA_URL= pure HTTP (kill switch/rollback). Server side,ARENA_SECRET+ARENA_INTERNAL_URLmake the bomperator actions proxy the lifecycle to the arena (match ownership moves); the arena holds NO Payload dependency: auth is 30s jose tickets{uid, matchId, iat}minted bycreateArenaTicket(query string on the WS handshake; no replay store by design), awards go back throughPOST /api/minigames/bomperator/results(secret header, idempotent by matchId). Restarting the arena kills live matches (process memory, like the SSE bus before it; acceptable for ~90s matches). The seq/lastInputSeq pending ledger and envelope reconcile work over both transports; the prediction harness pins the low-latency end too ("ws-grade latency" scenario). - Mobile / touch input:
BomperatorTouchControls.tsxrenders a D-pad (+ stop) and plant button on coarse pointers only ((pointer: coarse)); the board itself accepts swipes (dominant-axis cardinal, sets direction) and taps (stop). ALL input sources feed the samepressDir/releaseDir/stopAlledge callbacks inBomperatorGame.tsxthat keyboard uses, so prediction/keepalive/pending logic stays source-agnostic; held-stack priority makes D-pad + swipe coexist. Canvas is CSS-scaled (w-full h-auto, max 520px wrapper) with fixed internal resolution. Backgrounded-tab safety is harness-proven ("backgrounded tab" scenario: 4s rAF freeze under prod trace replay, teleports=0). E2E smoke:tests/e2e/bomperator-mobile.e2e.spec.ts(phone viewport, no horizontal overflow); run withE2E_BROWSER_PATH=<playwright chromium>when Vivaldi crashes.
- Client prediction & correction:
- Leaderboards match active players by user id (not display name) — see commit
72715c4if leaderboard queries look wrong.
Periods, achievements & the game registry
Anchored 14-day scoring periods, close-time achievements, and a registry that lets games be phased in and out without losing history. Full behavior is documented in the code; the invariants are:
- Scope: only the Core five (flappy, eod, radio, qualification, opord) score periods. Poker and Blackjack keep their all-time profile boards and are out of periods.
- Anchor:
minigame-rules.anchorDate(default2026-10-12T00:00:00Z) starts Period 1 and is treated as immutable; changing it re-slices and re-labels every period. All math is UTC. - Ledger:
minigame-entriesis an append-only row per completed scored run, written ONLY by the five submit actions throughrecordMinigameEntry(src/lib/minigames/periods/record.ts), which swallows failures so a ledger hiccup never breaks a submission. Each row carriesoccurredAt(the run's own instant) plus itsperiod. - Boards & awards:
src/lib/minigames/periods/boards.tsis pure. Best score ranks each board, the top-N placement ladder (default 10) sums across the Core boards, and ties break on raw period score then earliest submission. Period awards: period-champion, diligence, dedication, precision (minprecisionMinAttempts), most-improved (skipped in Period 1). - Close pipeline:
src/lib/minigames/periods/lifecycle.tscloses a period, writes itsachievementsrows and marks it closed. Idempotent: the status is re-checked before committing and theachievementsunique key (type:windowStart:user) makes a duplicate close insert nothing.closeCalendarWindowsadditionally crowns Player of the Month and Player of the Year for completed calendar windows (scored by runoccurredAt; the first window of each kind is partial). - Tick & override: the
period-tickbin (src/scripts/periodTick.ts, external cron) runs the sweep; the admin close/reopen control (src/components/admin/minigames/PeriodCloseControl.tsx→POST /api/minigame-periods/close, permissionminigame-periods:close) is the manual override. - Registry:
minigamesdrives the sidebar grouping and period scoring. Retired games leave the nav and stop accruing next-period points while their ledger history stays. Period scoring uses core games withcountsForPeriods;loadMinigameRegistryfalls back toBUILTIN_MINIGAMESif the collection is empty. - Surfaces:
/minigames/leaderboards(period selector + game tabs + achievements honor roll, fed byGET /api/minigames/leaderboards?period=current|<id>|all-time) and, on each Core game page, a current-periodPeriodStandingsCardas the primary board with the game's all-time board below it inside a collapsedAllTimeLeaderboarddisclosure. All-Time reads the untouchedprofiles.progression.minigames.*bests. - Notifications: winners are notified in-app on close (
minigame:achievement, muteable); the Discord bot servicesrc/bot/services/achievementAnnouncements.tsposts ONE embed per window toDISCORD_ANNOUNCE_CHANNEL_IDand stampsannouncedAt+discordMessageId. - Upcoming games: a registry row with
status: "upcoming"shows in the sidebar greyed out and non-interactive (a hoverable row, not a disabled menu item, because a disabled item setspointer-events: noneand would swallow its tooltip). The tooltip and the game page carry a countdown to the optionalestimatedReleaseDate. Upcoming games are excluded from the leaderboards, and their page rendersMinigameComingSooninstead of the arena. The date is display only: the game goes live when an admin flipsstatusto active. Countdown formatting:src/lib/minigames/countdown.ts; page gate:getMinigameReleaseStateplus a per-page check. - Phasing-out games: a registry row with
status: "phasingOut"stays fully playable and keeps scoring periods until it is removed. It shows an amber "Phasing out" badge in the sidebar (tooltip over the optionalestimatedRemovalDate, viaphasingOutTooltip) and a banner (PhasingOutBanner) on its game page, both rendering the countdown to removal. Unlikeretiredgames, phasing-out games stay visible in the nav (visibleRegistryGamesdoes not filter them) and on the leaderboards (buildLeaderboardPayloadonly excludesupcoming). The date is display only: the game keeps playing until an admin flipsstatustoretired.