1
0
Fork 0
polaris-task-force/src/lib/minigames/AGENTS.md
Z8MB1E a9f047f214 revert(minigames): roll back Bomperator prediction update after prod regression
Reverts 655407a (component + guide). Production HAR showed input POST
TTFB p50 87ms / p90 236ms / max 384ms (server pipeline variance, not
network). The nudges and ghost projection trusted rttAvg too tightly and
glitched under that variance; v0.12.3 behavior is restored.

Kept on purpose: bomperator/prediction.ts and the offline prediction
harness stay as test-only infrastructure for the re-fix, which will be
calibrated against the recorded production latency trace.
2026-10-18 01:40:44 -04:00

62 lines
9.4 KiB
Markdown

# 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 in `src/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`). Action `submitAimTrainerResult` validates result bounds, updates profile stats, awards XP, emits `minigame:aim-trainer`.
- **Radio Traffic**: `/minigames/radio`, sprint + watch modes, procedural message generation (`src/components/frontend/minigames/radio/messageGenerator.ts`). Action `submitRadioResult` emits `minigame:radio-traffic`; stats under `progression.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 in `src/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`). Action `submitCallForFireResult` validates result bounds, updates profile stats, awards XP + chips, emits `minigame: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`, category `multiplayer` (out of periods). Pure engine in `src/lib/minigames/call-for-fire-versus/` (`engine.ts`, `views.ts`, `types.ts`, `constants.ts`; client-safe) plus a server-only in-memory match registry in `registry.ts` (mirrors `blackjack/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.ts` builds per-viewer snapshots that never serialize the opponent's fleet. Client polls `fetchVersusMatch` (the in-memory SSE bus is unreliable across dev module copies, same as blackjack). Rewards on completion via `stats.ts` (`minigame:call-for-fire-versus`, profile group `callForFireVersus`).
- **Ordnance Disposal (multiplayer, real-time)**: `/minigames/bomperator` (internal key `bomperator`, label "Ordnance Disposal"), category `multiplayer` (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}.ts` are pure/client-safe (seeded RNG via `state.rngState`/`gridSeed`; `generateGrid`, `createMatchState`, `startRound`, `applyInput`, `tick`), and `registry.ts` runs one `setInterval(TICK_MS)` per live match (started on `startMatch`, 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 so `buildBomperatorView` serves every viewer the same board (`yourSeat: null` = spectator). Clients POST inputs (`sendBomperatorInput`, rate-limited 40/s) and poll `fetchBomperatorMatch` (~500ms fallback behind the SSE stream); a rolling event buffer (monotonic ids) drives client SFX without diffing. Disconnects hold the seat for `RECONNECT_WINDOW_MS` then eliminate; below two active seats the match dissolves. Rewards on completion via `stats.ts` (`minigame:bomperator`, profile group `bomperator`: matchesPlayed/matchWins/roundsWon/kills/xpEarned; XP win/loss base + per-kill bounty, chips auto-derived). Registry row ships `status: "upcoming"` (page renders `MinigameComingSoon` until an admin flips it active).
- Leaderboards match active players by user id (not display name) — see commit 72715c4 if 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` (default `2026-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-entries` is an append-only row per completed scored run, written
ONLY by the five submit actions through `recordMinigameEntry` (`src/lib/minigames/periods/record.ts`),
which swallows failures so a ledger hiccup never breaks a submission. Each row carries
`occurredAt` (the run's own instant) plus its `period`.
- **Boards & awards**: `src/lib/minigames/periods/boards.ts` is 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 (min `precisionMinAttempts`), most-improved (skipped in Period 1).
- **Close pipeline**: `src/lib/minigames/periods/lifecycle.ts` closes a period, writes its
`achievements` rows and marks it closed. Idempotent: the status is re-checked before
committing and the `achievements` unique key (`type:windowStart:user`) makes a duplicate
close insert nothing. `closeCalendarWindows` additionally crowns Player of the Month and
Player of the Year for completed calendar windows (scored by run `occurredAt`; the first
window of each kind is partial).
- **Tick & override**: the `period-tick` bin (`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`,
permission `minigame-periods:close`) is the manual override.
- **Registry**: `minigames` drives 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 with `countsForPeriods`; `loadMinigameRegistry` falls back to
`BUILTIN_MINIGAMES` if the collection is empty.
- **Surfaces**: `/minigames/leaderboards` (period selector + game tabs + achievements honor roll,
fed by `GET /api/minigames/leaderboards?period=current|<id>|all-time`) and a `PeriodStandingsCard`
on each Core game page. All-Time reads the untouched `profiles.progression.minigames.*` bests.
- **Notifications**: winners are notified in-app on close (`minigame:achievement`, muteable);
the Discord bot service `src/bot/services/achievementAnnouncements.ts` posts ONE embed per
window to `DISCORD_ANNOUNCE_CHANNEL_ID` and stamps `announcedAt` + `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 sets
`pointer-events: none` and would swallow its tooltip). The tooltip and the game page carry a
countdown to the optional `estimatedReleaseDate`. Upcoming games are excluded from the
leaderboards, and their page renders `MinigameComingSoon` instead of the arena. The date is
display only: the game goes live when an admin flips `status` to active. Countdown formatting:
`src/lib/minigames/countdown.ts`; page gate: `getMinigameReleaseState` plus 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 optional `estimatedRemovalDate`, via `phasingOutTooltip`) and a banner (`PhasingOutBanner`) on its game page, both rendering the countdown to removal. Unlike `retired` games, phasing-out games stay visible in the nav (`visibleRegistryGames` does not filter them) and on the leaderboards (`buildLeaderboardPayload` only excludes `upcoming`). The date is display only: the game keeps playing until an admin flips `status` to `retired`.