Features
Overview
Section titled “Overview”| Feature | Page | Triggered by |
|---|---|---|
| Meta overview with charts | Overview | Auto on load |
| My matchups (all decks combined) | Deck | Auto on load |
| Live meta sync | Sidebar / Account Sheet | User clicks “Sync” |
| Deck management (add, import, edit, delete) | Deck | User actions |
| Deck versioning (snapshots) | Deck | User clicks “Snapshot” |
| Deck variant management | Deck | User creates/duplicates |
| Match log (add, view, delete) | Deck / Opponents | User actions |
| Battle log parsing (visual stats) | Deck → Match detail | Automatic on log open |
| Battle log analysis (server-side LLM, BYOK) | Deck → Match detail | User triggers + API key |
| Deck comparison vs. tournament lists | Deck → Tips | User triggers |
| Data-driven recommendations | Deck → Tips | Auto on data change |
| Deck synthesis (KI-text über aggregierte Daten) | Deck → Tips | User triggers |
| Archetype recommendation (ranked decklist clusters, KI-text, Global/Lokal-Umschalter) | Meta → Archetype drilldown | Auto on load (GET); user triggers generation |
| Local meta priority | Deck / Meta | User configures |
| Recent tournaments view | Meta | User triggers |
| Matchup matrix | Meta | Auto from meta data |
| Archetype drilldown (decklists + field score) | Meta | User clicks a meta-table row |
| Legal pages (Impressum / Datenschutz) | /impressum, /datenschutz |
Footer links; reachable signed-out |
1. Meta Overview
Section titled “1. Meta Overview”Page: OverviewPage
The default landing page shows four summary stat cards (overall win rate, games logged, deck size, top meta threat) and two charts:
- Meta Share Chart (
MetaShareChart): A pie or bar chart showing the frequency distribution of archetypes from the latestmetaSnapshots. - Win Rate Chart (
WinRateChart): Compares the user’s personal win rate against each archetype, on a Bo1-equivalent basis — Bo3 results are converted back to their single-game win rate (bo3ToBo1WinRate) and logs with no known match format are excluded from the number (shown as an excluded-games footnote) rather than folded in. Both this and the archetype’s own tournament win rate weight a tie as a third of a win (tournamentWinRatePct,@pokekon/shared).
Data source: Zustand store (metaSnapshots). No API calls on this page.
The MyMatchupsTable (“My Matchups”) used to render here — it now lives on DeckPage, next to the deck switcher (see §3), since archetypeStats aggregates across all decks and doesn’t belong to a single deck’s per-tab content.
2. Live Meta Sync
Section titled “2. Live Meta Sync”Triggered from: the “Sync Live Meta” button via the shared SyncControls component — in the desktop Sidebar (bottom) and on mobile via the Account Sheet (accessed from the account chip, top right), so it’s reachable on every viewport.
Runs server-side (POST /api/meta/sync → apps/api/src/jobs/syncMeta.ts, also runnable as a Railway cron): the server fetches the Limitless TCG API directly (no CORS proxy needed) and aggregates into the global meta_snapshots table.
Process:
- Fetches up to 100 recent completed Standard tournaments (last 30 days, post-rotation, ≥16 players)
- Delta import: checks which candidates are already in the DB with
pairingsSyncedAtset — those are skipped entirely. Only new events are probed and ingested; coverage accumulates across runs without re-fetching known-good data. - Classifies each new candidate via the Limitless
/detailsendpoint (isOnline,platform, Swiss-phasemode) and keeps only online Bo1-Swiss events — the proxy for local Bo1 Challenges/Cups. The tournament cap (maxTournaments=80,maxProbes=160) is high enough to ingest all qualifying events in the window; the delta skip keeps the per-run cost bounded. - Fetches standings for each selected tournament
- Fetches
/pairingsfor each tournament and resolves the round-by-round head-to-heads into per-archetype matchup rows, which are persisted intournament_matchups. Simultaneously, per-pilot match results are derived: for each standing, the pairing data is mapped intoStandingMatchResult[]records (opponent archetype slug + W/L/T + round number) and stored intournament_standings.match_results(jsonb, added in migration0009). A failed pairings fetch leavespairingsSyncedAtnull so the event is retried next run (its standings still persist). - Persists the raw data (plan §5.2): upserts
tournaments, replaces the event’stournament_standingsrows — including player name, placing, wins/losses/ties, pruned decklist jsonb,icons(Limitlessdeck.icons), andmatch_results— so the archetype drilldown, time-window analyses, and the prediction drill-down read from the database instead of re-fetching. - Recomputes
meta_snapshotsfrom the full DB (not only the current run’s fetch): because the delta skip means a run may not have fetched every event in the week, the weekly snapshots are derived from all persisted standings matching the window — so accumulated runs compose into a complete picture. Icons are surfaced from whichever pilot carried them. - Filters out archetypes with fewer than 2 total players; computes
frequencyPct(players / total players) andwinRatePctviatournamentWinRatePct(a tie counts as a third of a win,nullonly when there were no games at all —packages/shared/src/winRate.ts); upsertsmeta_snapshots(keyedperiod+archetype, also carrying the Limitless slug inarchetype_idand the summedties).
One-off historical backfill: npm run job:backfill-winrates -w @pokekon/api [-- --dry-run] (apps/api/src/jobs/backfillMetaWinRates.ts) recomputes win_rate_pct/ties on existing meta_snapshots rows from the raw tournament_standings history, so the tie-aware formula applies retroactively without a code-only trend break. It only overwrites a row when its stored wins/losses still exactly match the freshly recomputed raw totals for that period (a mismatch means the row was originally synced under a different scope and is left untouched, only counted); periods with no raw data at all (pre-migration-0005 history) are also left untouched. Always run --dry-run first and check the counters before the real run (plan §5).
Downstream consumers of match_results: The archetype-lists endpoint (GET /api/meta/archetypes/:id/lists) joins each standing’s match_results jsonb and returns it as the matchResults field of every ArchetypeListEntry. The prediction panel’s per-list drill-down (ListFieldPerformance) reads this field to show real game-by-game W/L vs the local field — no additional server call needed.
Progress feedback: The Zustand store exposes isSyncing and syncProgress strings that the SyncControls component renders in real time — visible in both desktop Sidebar and mobile Account Sheet.
3. Deck Management
Section titled “3. Deck Management”Page: DeckPage — “Deck List” section
The app supports multiple decks. Each deck has an archetype (for Limitless matching), an archetype name (display), and a variant label.
My Matchups (MyMatchupsTable, moved here from Overview — see §1): renders directly below the DeckSwitcher, outside the section tabs, so it stays visible regardless of the selected deck or tab. It shows archetypeStats — the user’s personal win/loss/tie record against every archetype aggregated across all decks — and is deliberately distinct from DeckAnalyticsPanel’s MatchupList (§5/§10, Analytics tab), which is scoped to only the currently active deck’s logs.
Operations available:
- Create deck: Via
CreateDeckModal— enter name and variant - Switch deck: Via
DeckSwitcher— tab bar showing all decks - Add card manually: Via
AddCardModal - Import deck from text: Via
ImportDeckModal— paste a PTCG export list - Edit card count: Inline in
DeckPanel - Delete card: Via delete button in
DeckPanel - Rename deck: Via
DeckSettingsWidget(Archetype name, variant label, Limitless slug) - Delete deck: Cascades to all related cards, snapshots, and logs
- Duplicate as new variant: Creates a new deck row with the same archetype/archetypeName but a new variant label, optionally copying cards
Deck import format: Standard PTCG list format with sections Pokémon:, Trainer:, Energie: (German) or Energy: (English). Each card line: <count> <name> <set> <number>. The importer infers card role automatically, keeps the print (set + number) for export, and understands PTCGL’s variants: a trailing PH marker, the pseudo set Energy (11 Basic {W} Energy Energy 29) and hyphenated promo codes (PR-SV).
Deck export (“Copy for TCG Live”): CopyDeckListButton (apps/web/src/components/shared/) copies a list in PTCGL format via the shared exportDeckList — on the own deck (DeckPanel header), on every published tournament list (DecklistCard) and on the representative list of each ranked cluster (ArchetypeRecommendationPanel, TournamentBestListPanel). Section headers carry the summed copy count, the list ends with Total Cards: N. Basic Energy in any spelling (Darkness Energy, Basis-Finsternis-Energie, …) is written as Basic {D} Energy SVE 7 when no print is known. Cards without a print (quick-added by name, or imported before prints were stored) are still exported but flagged below the button, because PTCGL resolves cards by set code + number. Headers are always English — the format PTCGL and Limitless emit by default.
4. Deck Versioning (Snapshots)
Section titled “4. Deck Versioning (Snapshots)”Page: DeckPage — Deck List section, “Version History” side panel
Users can save a named snapshot of the current deck list at any moment. Snapshots:
- Store the full card list as JSON (not a diff)
- Can be attached to match logs when logging a game
- Are used by the recommendation engine to compare win rates across deck versions
Snapshot selection is offered in the logging context (the “more options” section of “Match loggen”) rather than as its own main area — it is secondary information a log can carry, not a destination of its own (see §6’s battle-log-first flow and the deck-page IA change described there).
Typical workflow:
- Build deck variant A, play some games
- Save snapshot “v1 — original build”
- Make changes (add/remove cards)
- Save snapshot “v2 — added Fezandipiti”
- Play more games, log them with snapshot v2 selected
- Recommendations engine detects if WR changed significantly between versions
5. Deck Variants
Section titled “5. Deck Variants”Multiple decks can share the same archetype slug (e.g., all "n-zoroark" variants). This allows comparing different builds head-to-head in the DeckAnalyticsPanel.
The DeckSwitcher component shows all decks as tabs. The DeckAnalyticsPanel fetches variant stats via getDeckVariantStats() to produce per-variant win rates and matchup breakdowns.
6. Match Log
Section titled “6. Match Log”Page: DeckPage — the deck page has two co-equal sections (Deck List /
Analytics); the match log is no longer a third tab. A small, always-visible
“Log match” button next to the section tabs opens AddLogModal from either
section; the log list itself lives as an initially-collapsed section at the
end of Analytics, titled with the current log count (plan
personal-data-role-rework.md §3.8 — the deck-page IA acceptance criterion demotes
this area, not the logging action, which stays one tap away). Also accessible
as standalone OpponentsPage.
Battle-log-first entry (plan §3.6): pasting a PTCG-Live battle log is the first field in “Match loggen”, before the manual archetype/result pickers. If the pasted log’s evidence uniquely identifies the opponent archetype and/or the game’s result, those fields pre-select themselves (still fully editable — a manual override is never silently reverted by a later render). Three outcomes, no invented percentages:
- Unique — exactly one archetype candidate’s card-name signature is fully covered by the opponent’s cards in the log → pre-selected automatically.
- Ambiguous — more than one candidate is equally well covered (or none reaches full coverage) → up to three candidate chips are offered; none is auto-picked.
- None — no signature fragment matched at all → the form behaves exactly as if no log had been pasted, with a neutral hint, never error styling.
The result is only pre-filled for Bo1 — a single battle log covers one game,
not a whole Bo3 match — and only once the local player is unambiguously identified
in the log; if the parser’s two detected names don’t include an exact match for the
stored player name, the modal asks “Welcher Spieler bist du?” once, persists the
answer to localStorage['tcg-player-name'], and only then proceeds with the guess.
This logic lives entirely in a new, pure @pokekon/shared module
(battleLogPrefill.ts) that consumes ParsedBattleLog output — it does not change
the parser itself (see §7’s one narrow exception) or persist anything beyond what
already existed.
Saving a log now also sends the local player’s name (playerName, already accepted
but previously unused by the web client) so the server-side parse
(match_log_parsed) is pinned to the correct side from the moment of creation,
instead of falling back to a frequency heuristic that could silently attribute the
wrong player’s turns.
Records the result of each game played. Fields:
- Opponent deck archetype (text, matched against meta data)
- Event type (LC, LCup, Regional, Worlds, Online)
- Match format — Bo1 or Bo3 (
bestOf, required on new logs). Defaults from the event type (Regional/Worlds → Bo3, else Bo1) but is always changeable before saving, and stays fixed once changed even if the event type changes afterwards. Logs written before this field existed havebestOf: null(“format unknown”): shown as a badge in the log list and match detail, they count toward the personal win rate but are excluded from the Bo1-equivalent comparison (§1) until backfilled via the one-time hint in the match detail modal (dismissable,preferences.ts).bestOfis hard-required onPOST /api/logs(400 without it) so this can never be guessed for a newly-logged match; the one exception is the one-time legacy-Dexie migration (localImport.ts), which sends the whole local export as ONE batch to a dedicatedPOST /api/logs/importendpoint that explicitly accepts (and requires)bestOf: null— the only place a client may sendnullfor this field. That endpoint is genuinely single-use per account (legacy_import_state, database.md): a second attempt at any time returns409, so it can never become a standing second path around the hard-required guarantee above. - Event date
- Result (W / L / T)
- Round number (optional)
- Deck snapshot (optional — which version was played)
- Notes (free text)
- Battle log (optional — raw protocol text from TCG Live, capped at
MAX_BATTLE_LOG_CHARS= 200,000 characters server-side, ~2x the largest realistic log; the client textarea carries the samemaxLength)
Logs drive the archetypeStats computation and all recommendation rules that depend on personal match history.
7. Battle Log Parsing
Section titled “7. Battle Log Parsing”Automatic — triggered whenever a match detail modal opens for a log that has a battle log attached.
The battle log is the raw text from TCG Live’s in-game protocol. It is in German because TCG Live uses German UI for German-language accounts.
What is parsed:
- Player names (detected by frequency analysis on action lines) — this is name detection only, not opponent archetype detection (see correction below).
- Turn-by-turn breakdown: cards played, energy attached, damage dealt, KOs, prizes taken
- Prize progression chart data (how many prizes each player had after each turn)
- Damage-by-turn chart data
- Card frequency (how often each card was played by the user)
- Winner detection, including a game the local player conceded (
"Du hast aufgegeben. X hat gewonnen.") — the regex tolerates a sentence prefix before “X hat gewonnen”, not just an anchored start-of-line match, so the common online case of a conceded game still yields a winner (planpersonal-data-role-rework.md§3.4/§0.5; the one sanctioned, additive exception to that plan’s “the parser is out of scope” rule — it changes no persisted field and has exactly one display consumer).
Output types: ParsedBattleLog, ParsedTurn, PrizePoint, DamagePoint, CardCount
The parser relies on the tcg-player-name localStorage key to identify which player is “you”. If not set, it defaults to the most-frequent actor in the log.
Corrections (plan personal-data-role-rework.md §0.3/§0.5 — belegt, replacing an
earlier, inaccurate description):
- The parser detects no opponent archetype and exposes no confidence value at
all.
ParsedBattleLoghas no archetype field and no score. Archetype detection (§6 above) is a separate, newer module (@pokekon/shared/battleLogPrefill.ts) that consumes the parser’s output (cards played, bench, active Pokémon, KOs) without modifying it, and reports a coverage-basedunique/ambiguous/noneresult instead of a fabricated percentage. - Card names in real German logs are German, not English. The previous claim
here (and the doc comment this section was based on) — that PTCG Live’s German
client prints English print names for Trainers — does not hold for real
logs: Konrad’s own reference log (
apps/api/src/lib/demoSeed.ts) shows fully localised Pokémon and Trainer names (Ns Zoroark-ex,Mega-Kangama-ex= Kangaskhan,Rockos Erkundung,Schloss von N,Höhlensystem Null, …).battleLogPrefill.ts’s archetype signatures therefore carry an optional, hand-maintainedlogNamesfield with the German fragments per archetype (currently filled in for a handful of archetypes verified against that real log; a missing or wrong fragment only ever causes a missed detection, never a wrong one). - Known gap, not fixed here:
KNOWN_SUPPORTERS(the allow-listbattleLogParser.tsuses to flag a “clean setup”) is English-only and therefore effectively never matches in a real German log, sosetupCleanByTurn2(and the recommendation rules that depend on it, §10 rules 11/12) work from a systematically weak signal today. Fixing this is parser work and out of scope for this plan; noted here so it doesn’t read as an oversight.
8. Battle Log Analysis (server-side LLM · BYOK)
Section titled “8. Battle Log Analysis (server-side LLM · BYOK)”Page: Match detail modal, “Analyze” button
The analysis runs server-side: the web client calls POST /api/analysis/log
(apps/api/src/routes/analysis.ts), which runs
the battle log through a provider-agnostic adapter. The default (and currently
only) provider is GitHub Models (OpenAI-compatible, default model
openai/gpt-4.1); the abstraction in apps/api/src/ai/ lets
other providers plug in without touching callers.
What is analyzed:
- Key turning-point moments with exact evidence quotes
- Play mistakes with suggestions for improvement
- Card-level performance observations
- Deck change recommendations (add/remove/increase/decrease specific cards)
Anti-hallucination measures (enforced in the shared engine @pokekon/shared, so every provider is grounded):
- The full raw log is included in the prompt — the model cannot invent events
- Every analysis item must include an
evidencefield that is a verbatim quote from the log - After parsing the JSON response,
validateAnalysis()drops any item whoseevidencecannot be found in the raw log temperature: 0and JSON-only output for deterministic, parseable results- The prompt restricts references — and deck suggestions — to cards that appear explicitly in the log
BYOK key handling: The user supplies their own provider API key. It is stored
AES-256-GCM-encrypted in PostgreSQL (user_ai_settings, key derived from the
server’s ENCRYPTION_KEY) and decrypted only server-side for the call — it is
never returned to the browser or written to IndexedDB/localStorage. The guest/demo
flow may pass an ephemeral key that is used once and never stored (see
demo-mode.md).
9. Deck Comparison vs. Tournament Lists
Section titled “9. Deck Comparison vs. Tournament Lists”Page: DeckPage — “Tips” section (“List Comparison” subsection)
Compares the user’s current deck against public decklists submitted to recent Limitless tournaments.
Process:
- Fetches top 8 largest recent Standard tournaments
- Collects all decklists from players whose deck matches the user’s archetype slug
- Computes for each card: how many lists include it, average copy count, top-placing average count
- Compares against user’s current deck
Output:
suggestedAdds: Cards in 55%+ of tournament lists that the user does not runsuggestedRemoves: Cards the user runs that appear in 20% or fewer tournament listscountAdjustments: Cards the user runs where their copy count differs by 1+ from the typical count in top-placing lists
Second signal: Card performance deltas (Spec 5, §3.7–§3.8)
In addition to copy frequency, each card now carries a performance delta — a measured correlation between that card’s presence and tournament placement percentile. This appears as a second bar/signal per card:
- Confirmed: Frequent (≥55%) and significantly correlated with better placements
- Hidden Gem: Rare (<55%) but significantly correlated with better placements
- Popularity Paradox: Frequent but no positive performance delta — a card everyone plays that does not actually help
- Discouraged: Significantly correlated with worse placements
- Neutral: Measurable data but no strong signal
- Insufficient: Too few lists to compute a reliable delta
The delta is derived from precomputed tournament data (own database, archetype_card_stats table) and represents the Mann-Whitney probability of superiority — how often a list with the card ranked better than a list without it, converted to percentage points (0 = equally; 50 = no difference; 100 = always better).
Important data-source distinction: Copy frequency comes from a Limitless browser fetch (8 largest recent tournaments, all scopes), while performance deltas come from the server’s own database of online-Bo1-only tournaments (7–28 day window). These are two different tournament populations, and the same card can show different inclusion percentages between them. The UI labels both data sources separately, and inclusionPct (from the server) does not drive the 55%/20% thresholds — those remain on the Limitless-based frequency data only. This design ensures the two signals stay independent and avoids confusing two data streams.
Limitation: Requires the deck’s archetype slug to be set correctly in Deck Settings (e.g., "n-zoroark"). If no public decklists are found for the slug, an error is shown.
10. Data-Driven Recommendations
Section titled “10. Data-Driven Recommendations”Page: DeckPage — “Tips” section (primary panel)
Generated by the useRecommendations hook. Runs entirely in the browser — no API calls. Produces DeckRecommendation items sorted by priority (high → medium → low) then by data points.
The 14 recommendation rules:
| # | Rule | Priority | Requires |
|---|---|---|---|
| 1 | Deck version WR swing ≥15% in a matchup | medium/high | ≥2 snapshots, ≥4 logs |
| 2 | Weak matchup flag (from own data) + pointer to List Comparison | medium/high | ≥5 encounters, ≥1 win |
| 3 | Zero wins vs. ≥8% meta archetype | high | Any losses |
| 3b | Local meta archetype with no log data | high | Local meta configured |
| 4 | Boss’s Orders missing | medium | Deck loaded |
| 5 | No Pokemon search (Ultra Ball / Nest Ball etc.) | medium | Deck loaded |
| 6 | Overall WR drop ≥15% between oldest and newest snapshot | high | ≥2 snapshots, ≥6 logs |
| 7 | Meta archetype ≥10% with 0 personal encounters | low | Meta data + logs |
| 8 | Fewer than 5 total games logged | low | Any logs |
| 9 | Card played in <25% of analyzed games | medium | Battle logs present, ≥3 games |
| 10 | Card WR ≥15% below overall WR | low | Battle logs, ≥3 decisive games |
| 11 | Turn-1 average actions <1.5 | medium | Battle logs, ≥3 games |
| 12 | Low-activity turn rate >35% (“brick rate”) | medium | Battle logs, ≥3 games |
| 13 | Average prizes taken in losses <2 | high | Battle logs, ≥2 losses |
| 14 | Wins average ≥3 turns longer than losses | medium | Battle logs, both outcomes |
Rule 2 — no fabricated tech card, backed by measured card deltas: The old hand-curated TECH_SUGGESTIONS table (archetype → “add card X”) has been removed. Asserting a specific counter card is not defensible: a card that appears often in winning lists may be a universal staple (not a tech), and a genuine tech may not fit every deck’s energy or shell. Rule 2 now reports the matchup weakness from the user’s own logged games and points to the data-driven List Comparison (successful lists of the user’s own archetype, which is deck-fit-safe). When card performance deltas are available (Spec 5), the rule enriches its reasoning by naming specific cards from the user’s archetype that correlate with better tournament placements — specifically, cards classified as 'hiddenGem' or 'confirmed' that the user does not yet play, sorted by strength of correlation. The statement remains archetypwide and correlational, never matching-specific; it never claims a card counters a particular opponent, only that it correlates with the archetype’s placement improvements.
Local meta priority: When the user marks specific archetypes as “local meta” (via LocalMetaPanel), those archetypes receive a priority boost in tech suggestions (always high priority when WR is bad) and generate blind-spot warnings even if their global meta share is below the normal threshold.
Unchanged by the battle-log-first rework (plan personal-data-role-rework.md
§3.8): the 14 rules and their thresholds above are untouched. What changed is
visibility at zero logs — OverviewPage and DeckPage now show a
static, honest notice explaining that the meta table / recommendations above work
from real tournament data, and listing exactly three of the real thresholds a
user can unlock by logging matches (rule 2’s ≥5 encounters, rules 9–12’s ≥3 games with a battle log, rule 1/6’s ≥2 deck versions + ≥4 logs) — a
static list, not a live re-explanation of all 14 rules, since that belongs to a
future prediction-focused feature, not this one.
11. Local Meta Configuration
Section titled “11. Local Meta Configuration”Page: MetaPage — inside the merged “Local Meta & Prediction” section (§16) — LocalMetaPanel component
Users can tag archetypes as frequently played at their local store. This affects the recommendations engine:
- Tech suggestions for these matchups are always
highpriority - Archetypes in local meta with no logged games generate “Log matches” warnings
- Local meta archetypes bypass the 8% meta frequency threshold for zero-win alerts
Persisted to localStorage as tcg-local-meta-v1. Since Spec 10 Slice D this list is also the
single source of truth for §16’s Local-Meta Prediction field — Prediction no longer keeps its
own, independent archetype list.
12. Recent Tournaments
Section titled “12. Recent Tournaments”Page: MetaPage — “Recent Tournaments” section
Fetches individual recent tournaments from Limitless with configurable filters:
- Days back (3, 7, 14, 30)
- Minimum players (10, 15, 30, 50, 100) — defaults to
DEFAULT_MIN_TOURNAMENT_PLAYERS(@pokekon/shared, currently 15), the single shared default also used by the server-side sync job (syncMeta.ts) and the client-sidemetaFetch.ts. Used to be three independent, out-of-sync literals (16/30/30) with no way to filter below 30 at all — unified in Spec 10 Slice G (specs/archetype-meta-analysis.md). - Online only toggle (uses heuristic: name contains “online”, “live”, “ptcgl”, “weekly”, or player count ≥150)
For each tournament, shows the top 5 archetypes by player count with their win rates. Links to the Limitless standings page.
This data is not persisted — it lives only in Zustand’s recentTournaments array for the current session.
13. Matchup Matrix
Section titled “13. Matchup Matrix”Page: MetaPage (collapsible section, collapsed by default — unlike the Tournament Meta section below it) — MatchupMatrix component
A head-to-head win-rate cross-table for the current Standard meta. Every cell that has any data shows its win rate — there is no hard sample-size cutoff (Spec 3, plan confidence-aware-matchups.md). Colour hue still encodes the win rate (green favorable, red unfavorable), but colour intensity/opacity now encodes confidence: a narrow 95 % Wilson interval (@pokekon/shared’s matchupCellInterval/confidenceTier, ≤10/20/35 percentage points wide) renders fully saturated, a wide one washed out. Each cell shows a small second line with its low–high band (0 decimals), and the tooltip states the full interval. The mirror diagonal is a documented special case: no band, no tier, plain win rate at reduced opacity — the bundled TrainerHill export double-counts mirror wins/losses (see below), so a Wilson interval over wins+losses+ties there would be wrong. The user-controlled min-games filter (1/10/20/50, still purely a display filter, never a model cutoff) now defaults to 1 instead of 10, so the view built to retire the cutoff doesn’t keep hiding thin cells by default.
Data source: GET /api/meta/matchups?days&online&bo1 — a real online-Bo1 matrix built from the round pairings persisted in tournament_matchups, blended with the external TrainerHill CSV as a coverage fallback. Win rate uses the shared tournament formula (a tie counts as a third of a win). The blend works as follows: for each directed pair (A vs B), the own data takes precedence when it has at least MIN_MATCHUP_GAMES decisive games; otherwise the TrainerHill row fills in. (This blend threshold is a data-source decision, unrelated to and unchanged by the Spec-3 confidence bands — see plan §0.) The response includes a matchupSource object (ownPairs, fallbackPairs, ownGames, trainerHillImportedAt, conflictCount, conflicts) so the UI can display a source note distinguishing real head-to-heads from the approximate external fallback.
Source conflicts: when our own data overrides the TrainerHill fallback for a pair (>= MIN_MATCHUP_GAMES) and the two win rates differ by more than 15 percentage points, detectMatchupConflicts (packages/shared/src/matchupConflict.ts) flags it — the matrix note shows the count with a tooltip listing each pair’s own/fallback values, and the server logs one summary line per request. The displayed win rate is always the own value; a conflict is a hint for a human to look at, never an auto-fix. Update (Spec 3): TrainerHill’s tie convention, previously listed as unknown (Spec 2 risk 4), is now confirmed identical to ours — cross-checking apps/api/data/matchup-matrix.csv shows all 178 non-mirror rows satisfy win_rate == (wins + ties/3)/total × 100 within 0.06pp, i.e. TrainerHill also counts a tie as a third of a win. The two numbers being compared in a conflict are defined the same way. Separately, all 14 mirror rows in that CSV are internally inconsistent (wins == losses and wins+losses+ties double the row’s own total) — mirror rows must never have a Wilson interval computed over wins+losses+ties; computeFieldScores never looks them up (the mirror is definitional 50 %), and the matrix diagonal is excluded from banding for the same reason.
The legacy GET /api/matchups endpoint (external TrainerHill batch only, no window filter) remains available for the local-meta prediction panel and CSV import (POST /api/matchups/import). The server lazily seeds matchup_matrix from the CSV bundled at apps/api/data/matchup-matrix.csv on first read.
Archetype icons in the matrix are data-driven, sourced from the Limitless deck.icons field persisted during sync.
14. Legal Pages (Impressum / Datenschutz)
Section titled “14. Legal Pages (Impressum / Datenschutz)”Routes: /impressum and /datenschutz — standalone pages rendered by LegalPage (apps/web/src/pages/LegalPage.tsx).
Unlike the three dashboard tabs (which are Zustand activeTab state, not URLs), these are real paths. App.tsx checks legalDocForPath(window.location.pathname) before the login gate — like /reset-password — so the pages are reachable while signed out (a legal requirement) and survive a reload via the API’s SPA fallback.
- Content lives entirely in the
legali18n namespace (apps/web/src/i18n/locales/{de,en}/legal.json) as{ heading, body[] }sections, so switching DE/EN reflows the whole document. The German version is the legally binding one (stated in the page footer). - Links are rendered by the shared
LegalLinkscomponent in three places: theWelcomeScreenfooter (signed-out), the desktopSidebarbottom, and the mobileMobileAccountSheet. Plain<a>anchors — a full navigation is acceptable for legal pages and keeps the router-less app simple. - The privacy policy reflects the current server-side architecture: PostgreSQL on Railway (EU,
europe-west4), Better Auth sessions (storing IP + user-agent), Resend for transactional email, GitHub Models for the BYOK battle-log analysis (key stored AES-256-GCM-encrypted server-side), optional Google sign-in, and GitHub-hosted sprite images.
15. Archetype Drilldown (Tournament Decklists & Field Score)
Section titled “15. Archetype Drilldown (Tournament Decklists & Field Score)”Page: MetaPage — click any row of the Tournament Meta table (ArchetypeDetail component)
Layout (UI/UX redesign, 2026-09-23 — WIP on design/frontend-uiux-overhaul, not yet on main): the KPI header, trend chips and window control below stay always visible; everything else sits behind a SegmentedTabs bar (apps/web/src/components/shared/SegmentedTabs.tsx, the same reusable component DeckPage.tsx’s Deck/Analytics/Tips switcher now also uses) with four tabs — Matchups (field performance + preparation panel + the full matchup table, collapsed by default behind a counted data-testid="archetype-matchups-full-toggle"-style “Vollständige Liste (N)” button so the curated preparation panel and the exhaustive table don’t both render at once), Empfehlung (ArchetypeRecommendationPanel), Turnier-Liste (TournamentBestListPanel, only offered once ≥1 tournament is known), Decklisten (the raw decklist cards). Previously all seven sections rendered as separate full-width cards stacked vertically on one page — reworked after Konrad reported “so viele Listen und Erklärungen und so viel Scroll”, following researched patterns from 17Lands/TrainerHill/Untapped.gg/op.gg (segmented control over stacked panels; a curated top-N list with a counted, explicit “show all” escape hatch instead of an always-rendered full list; sample size next to a percentage instead of prose).
Every archetype row is clickable and opens an in-tab drilldown. The whole Meta tab shares one window control — a free numeric day input (accessible QuantityStepper, range 1–180) with preset buttons (7 / 14 / 30 / 60 days) for quick-jumps, plus an online-Bo1 toggle (default on: only ground-truth online Bo1-Swiss events, the local-Bo1 proxy) — that drives both the overview and the drilldown:
- KPI header: meta share, tournament win rate, pilot count, field score + rank, weekly share/WR trend chips. Both the tournament win rate and the field score KPIs show their 95 % confidence band as a small second line (Spec 3) — the tournament WR band comes straight from
wilsonInterval(wins, losses, ties), the field score band from the samefieldWinRateLowPct/HighPctshown in the field-performance panel below. The trend readsmeta_snapshots.win_rate_pctdirectly, so it only reflects the tie-aware formula for periods the one-off backfill job (§2) has touched or that were synced after the formula changed; older, un-backfilled periods (or periods with no persisted raw standings to recompute from) keep their original value. The trend line itself does not show a band (deferred, plan §6 risk 6 — no acceptance criterion requires it, though the raw wins/losses/ties needed are already selectable frommeta_snapshots). - Field performance (the core metric, plan §3.4):
FieldWR(A) = Σ share(B) × MatchupWR(A vs B)over all opponents with any matchup data at all — Spec 3 (confidence-aware-matchups.md) removed the previous ≥10-games-per-pair cutoff. A thin cell (even a single game) now counts fully; its uncertainty shows up as an explicit 95 % confidence band (fieldWinRateLowPct/fieldWinRateHighPct, full error propagation over the share-weighted sum of independent per-cell Wilson intervals, seedocs/data-types.md) instead of the cell vanishing from the score. The mirror still counts as 50 %, definitionally, with zero variance. Normalised by the covered share; the coverage % is always shown (low coverage < 40 % gets a warning).coveragePctchanged meaning with Spec 3: it used to mean “share of the field with ≥10 games”, now it means “share of the field with any data at all” — it typically reads higher than before, and no longer implies the number is reliable by itself. Coverage and confidence are two separate questions: coverage says how much of the field has data, the band says how sure we are about the part that does (surfaced as a tooltip next to the band). Computed inpackages/shared/src/fieldWinRate.ts, served byGET /api/meta/archetypes/:id/analysis. - Preparation panel: opponents weighted by frequency × matchup weakness — common and bad-for-you decks rank first (“Darauf musst du vorbereitet sein”), plus the mirror probability and the good matchups (free wins). Each entry shows its own confidence band (as a compact
n={{games}}sample-size label under the win-rate badge, the raw interval moved to atitletooltip rather than sitting in the row as text); entries whose interval still includes 50 % (significant === false) carry aCircleHelpicon + tooltip (previously a long inline “unsicher — Intervall schließt 50 % ein” text badge, which wrapped and visually overlapped the win-rate badge at moderate widths) and sort behind significant entries at the same weight tier, rather than disappearing. Both the threats and free-wins lists are capped to the top 5 (already weight-sorted) with a counted “+N weitere” expand link — the underlyingFieldScorestill carries every covered opponent, none of it is dropped, just not rendered until asked for. - Matchups vs the field: a table (
MatchupTable) listing this archetype’s record against every covered opponent — win rate, its 95 % interval, game count, and meta share — sorted from most favourable to least favourable. Data comes from the same real online-Bo1 blend (tournament_matchups+ TrainerHill fallback) as the matrix. Opponent icons are data-driven fromiconsByIdreturned byGET /api/meta/archetypes/:id/analysis. Lives inside the drilldown’s “Matchups” tab, collapsed by default behind a “Vollständige Liste (N)” toggle beneath the preparation panel — it repeats the same underlying threats/free-wins data as one long list, so it stopped always-rendering alongside the curated panel above it. - Most successful decklists: published lists from the persisted standings, ordered by relative finish (placing ÷ field size, ties → bigger event, then more recent), 4 per page with a load-more button (
GET /api/meta/archetypes/:id/lists). Each card shows placing, record, player, event and the full list grouped Pokémon/Trainer/Energy, linking to the Limitless standings. Pokémon icons are data-driven from Limitlessdeck.icons. - Archetype recommendation (
ArchetypeRecommendationPanel, Spec 10 Slice C UI, between the matchup table and the raw decklists): a ranked decklist-cluster list (RankedCluster[], already sorted byrank) plus an optional KI-text recommendation, backed byGET/POST /api/analysis/archetype/:archetypeId. Three toggle chips, “Global”/“Lokal”/“Mein Spielstil” (amodestate, not a fourth backendscope), re-fetch the ranking on click. Each cluster shows its rank, Wilson-lower-bound win rate + interval, average placement percentile (when available), W/L/T record, member-list count, a compact Pokémon-card preview of the representative list, and (behind adata-testid="archetype-recommendation-cluster-decklist-toggle"<details>disclosure, since the preview only ever showed Pokémon and had no way to see the rest besides an unusable-on-touch hover tooltip) the full 60-card decklist grouped Pokémon/Trainer/Energy viaDecklistCard.tsx’s exportedCardGroup. Adata-testid="archetype-recommendation-methodology"<details>disclosure (collapsed by default, above the cluster list) spells out in plain language how rank/interval/record/placement/field-score are actually derived — added after Konrad pointed out the numbers had no explanation attached. The KI-text half follows the exact same state machine asDeckSynthesisPanel(§ “Deck synthesis” above) — cold start / missing key (+ demo ephemeral-token path) / stale badge / honest empty / error — generation is user-triggered only, a mode switch never auto-regenerates. Deliberately uses its own local component state (request-key pattern, likeArchetypeDetailitself) rather than thedashboardStore. “Mein Spielstil” (Spec 10 Slice E UI, completing the backend from § “Archetype synthesis” below): sendsscope: 'local'+usePersonalPrior: true+ apersonalRecordderived from theArchetypeStatsentry matchingarchetypeId(same Limitless-slug identifier space) —archetypeStatsis passed downMetaPage→ArchetypeDetail→ this panel as a prop, so the panel itself stays store-free. Below the sharedDEFAULT_MIN_OWN_GAMES(5) threshold (same one the server silently applies), adata-testid="archetype-recommendation-personal-insufficient-data"hint explains that the recommendation currently matches the local mode, without duplicating the server’s threshold value. Local field weighting (Spec 10 Slice D UI, completing the backendlocalFieldfield described in § “Archetype Synthesis” below): in “Lokal” AND “Mein Spielstil” mode (both arescope: 'local'server-side), the panel derives alocalField: LocalFieldEntry[]from the sharedlocalMeta: string[]store slice (§11LocalMetaPanel) — same derivationPredictionPanel.tsxuses (now shared vialocalFieldWeight.ts’sseedWeight), resolving each archetype NAME to its realarchetypeIdvia the current online meta (archetypes, anArchetypeRecommendationPanelprop passed downMetaPage→ArchetypeDetail) and weighting it by a stored override (getLocalMetaWeightOverrides(), read once on mount) or, by default,seedWeight(sharePct). Sent aslocalFieldon both GET and POST wheneverlocalField.length > 0; never sent in “Global” mode, even with a non-empty local field. WhenlocalMetais empty, adata-testid="archetype-recommendation-local-field-empty"hint explains that “Lokal”/“Mein Spielstil” currently match the global ranking. Each cluster whosefieldScorethe server actually re-ranked (regardless of the panel’s currentmode, the field’s presence is itself the signal) renders an extradata-testid="archetype-recommendation-cluster-field-score"line with the field-weighted win rate + interval band, alongside the existing Wilson-based one. - Per-tournament best list (
TournamentBestListPanel, Spec 10 AC-G third bullet,specs/archetype-meta-analysis.md— after the raw decklists, conceptually separate from the KI recommendation above): answers “which list of this archetype would have performed best at this one, specific tournament”, backed by the read-onlyGET /api/analysis/tournament/:tournamentId/archetype/:archetypeId— never an LLM call. A<select>lists every tournament this archetype had a published decklist at in the window, from the dedicatedGET /api/meta/archetypes/:archetypeId/tournaments(its own web-clientgetArchetypeTournaments,apps/web/src/lib/api.ts) — not derived from the paginated decklists list (§ “Most successful decklists” above), which used to be the source and silently only ever offered whichever page of decklists happened to already be loaded (Konrad reported the picker looking “veraltet”/stale). Fetched in its ownuseEffect/failure domain inArchetypeDetail.tsx, deliberately separate from the main analysis+listsPromise.all— a failure or an older, not-yet-deployed API here (verified locally: the endpoint 404s against the current production API until this change ships) just omits the “Turnier-Liste” tab entirely rather than failing the whole drilldown. Picking a tournament clusters that archetype’s decklists from only that tournament’s own standings (reusing the exact sameclusterDecklists/rankClusters/computeClusterFieldScores/reorderClustersByFieldScorecomposition Slice C/D already use for a multi-tournament window, just scoped to one tournament — no newpackages/sharedfunctions needed) and re-ranks them by their field-weighted score against that tournament’s actual field (derived from its own standings, not a window aggregate). Each cluster renders the same rank/Wilson-interval/field-score/record/member-count/card-preview-plus-full-decklist-disclosure layout as the recommendation panel’s clusters (owndata-testid="tournament-best-list-cluster-decklist-toggle"), but as its own independent component (not shared, since the two features are conceptually distinct: multi-tournament KI text vs. single-tournament pure computation), including its owndata-testid="tournament-best-list-methodology"disclosure with tournament-scoped wording (the field score here is always vs. this one event’s field, never a window). The evidence for the top-ranked cluster reusesListFieldPerformance(§16) with that cluster’s aggregatedmatchResultsagainst the response’sfield(the tournament’s own archetypes, so opponent names resolve without a second request) — real per-opponent win/loss chips, not generated text. An archetype not played at the selected tournament renders an explicit empty state (clusters: [], “honestly empty”, not an error); an unknown tournament id 404s (a bad parameter, not a legitimately empty result, unlike an unknown archetype).
The overview Meta Table is the day-window field analysis itself (GET /api/meta/field-analysis?days&online&bo1): share, win rate, record and a sortable Feld-Score column per archetype, so the best-positioned deck — not merely the most-played one — is visible at a glance, and the day/online controls genuinely drive the metashare (not just the score).
Cold start: before the first server sync there are no persisted standings — the drilldown and the overview table show explicit empty states pointing to “Sync Live Meta” (in the Sidebar on desktop, or via the Account Sheet on mobile).
16. Local Meta & Prediction
Section titled “16. Local Meta & Prediction”Page: MetaPage → “Local Meta & Prediction” section, collapsed by default — one merged CollapsibleSection containing LocalMetaPanel (§11, archetype picker) followed by PredictionPanel.
Answers “what should I play at my local event?”. Spec 10 Slice D/F merged what used to be two separate sections with two independent ways to manage “which decks do I expect locally” — a documented user complaint (“beide zu ähnlich… man braucht nicht beides”, specs/archetype-meta-analysis.md). LocalMetaPanel’s localMeta list (§11) is now the only place to add/remove archetypes from the local field; PredictionPanel derives its field directly from that list and only adds a per-archetype weight.
Weights: default to the archetype’s current online meta share (seedWeight, rounded, min 1); a per-archetype override is stored separately (tcg-local-meta-weight-overrides-v1, keyed by archetype id) and takes precedence when set. “Seed from online meta” now populates the shared localMeta list itself (not a second copy) and resets all overrides back to their online-share defaults. Each row’s weight is set via an accessible QuantityStepper (−/+ buttons + numeric spinbutton, clamped to [0, 99]); the live share % is computed and shown beside it. Weights are normalised to shares and fed into the same computeFieldScores engine (@pokekon/shared) as the online field analysis, so every deck in the field gets an expected win rate against that custom field (share × matchup WR, mirror 50 %, coverage shown).
Legacy migration: before Slice D, PredictionPanel kept its own independent list at tcg-local-meta-field-v1. On first render after the update, any such legacy data is folded once into localMeta (missing names added) and the weight-override map (weights carried over), then the legacy key is deleted — a normal browser reload never sees it again.
Deck perspective: Instead of a count-ordered ranking list, a deck-perspective picker (a <select> ordered by descending field win rate) lets the user choose which deck to evaluate against the field. Above the picker a best-positioned headline (Trophy icon) always names the deck with the highest field WR, its score and its 95 % confidence band (Spec 3 — computeFieldScores propagates the same Wilson-interval error propagation here as it does server-side, since PredictionPanel calls it client-side with the fetched MatchupRow[]), so the answer is visible at a glance without opening the dropdown.
When a deck is selected the panel shows its field-score and weighted threats/free-wins panels, and fetches that deck’s most successful tournament lists (getArchetypeLists → GET /api/meta/archetypes/:id/lists) as build templates.
Per-list drill-down: Each suggested list has a collapsible “Why?” toggle. Expanding it renders ListFieldPerformance, which shows that list’s real game-by-game W/L vs every deck in the local field — drawn from StandingMatchResult[] on entry.matchResults (tournament round pairings, see §2). Results are grouped by opponent with a W-L record and per-game chips colour-coded like the match log (green win / red loss / amber tie), sorted with the best matchups first. If pairings have not been synced for that event the component renders an empty-state message; it never fabricates results.
Runs entirely client-side over the windowed matchup matrix (getMetaMatchups → GET /api/meta/matchups) — no extra server round-trip beyond the initial fetch. The matchup matrix is the real online-Bo1 blend (own data + TrainerHill fallback), flagged with a source note showing real vs approximate coverage.
17. Card Performance Deltas
Section titled “17. Card Performance Deltas”Context: Part of Spec 5 (recommendation-to-prognosis), providing a second signal alongside copy frequency in the Deck Comparison panel and enriching Rule 2 reasoning.
What it measures
Section titled “What it measures”For each card within an archetype, the system compares tournament placements of published lists that include the card versus those that don’t. The performance delta quantifies this difference using the Mann-Whitney probability of superiority (θ): the proportion of all head-to-head pairings where a list-with-card ranked better than a list-without-card. This is converted to percentage points (deltaPp = (θ − 0.5) × 100, so 0 = no difference, +20 = 70% superiority).
Why placement percentile, not Field WR: Placement is ordinal (the rank a pilot achieved in the tournament) and is directly available in the persisted tournament data. Deriving a hypothetical Field WR change would require a full-list Matchup matrix, which is the scope of later phases. Placement percentile is simpler, already exists, and captures whether the card correlates with finishing higher in the field.
Confidence framing (Wilson-calibrated band)
Section titled “Confidence framing (Wilson-calibrated band)”Like the matchup matrix (Spec 3), the delta carries a 95% confidence band. The band is derived by treating θ as an effective Bernoulli proportion and applying the Wilson-Score interval via an effective sample size that reproduces the exact Mann-Whitney null variance:
n_eff = 3 × n1 × n2 / (n1 + n2 + 1), where n1/n2 are the list counts in each group- At the null point (θ = 0.5), this gives a Wilson band with the correct calibration for the underlying rank-comparison variance
The band defines when data is too thin to report: cards with widthPct > 40 percentage points are marked 'insufficient' — a derived classification based on uncertainty, not a hard sample-size cutoff. This ensures the signal respects the Spec 3 principle (confidence-aware, never a false-precision cutoff).
Three technical assumptions documented here (plan §3.0):
- Ties assumption: The no-ties variance formula assumes placement percentiles never collide. In practice, ties (identical percentiles) make the true variance smaller than the formula predicts, so the band is conservative (too wide, never too narrow). This prevents over-confidence.
- Null-point calibration: The n_eff bridge makes the Wilson interval exact at θ = 0.5 (the decision boundary: “Is the band consistent with no effect?”). Away from the null point, the interval becomes a conservative approximation with credible coverage but not exact matching of the underlying distribution.
- Correlation, not causation: Lists are not randomly assigned to include or exclude cards — decks come as packages, and card presence is correlated with pilot skill, meta-knowledge, and other confounders. The delta measures association (lists with X ranked better), never causal impact (X makes you better). This distinction is mandatory in all UI text.
Six signal tiers
Section titled “Six signal tiers”Derived by classifyCardSignal() in packages/shared/src/cardPerformance.ts:
| Tier | Condition | Meaning |
|---|---|---|
'insufficient' |
delta = null OR band width > 40pp | Not enough lists to compute a reliable delta |
'confirmed' |
Significant positive delta AND frequency ≥55% | Staple that earns its slot |
'hiddenGem' |
Significant positive delta AND frequency <55% | Underplayed, worth testing |
'popularityParadox' |
Frequency ≥55% AND (delta ≤ 0 OR not significant) | Everyone plays it, but no placement boost |
'discouraged' |
Significant negative delta | Correlates with worse placements |
'neutral' |
Measurable but no strong signal | Everything else |
Multiple-comparisons risk
Section titled “Multiple-comparisons risk”At ~80 cards per archetype with 95% confidence, pure chance alone predicts ~4 “significant” cards per archetype per window. The system deliberately does not apply Bonferroni or FDR corrections — they would suppress almost all signals at these sample sizes (the hidden cost of the conservative approach). Instead:
- The delta is positioned as a hint for human interpretation, not a statistical test
MAX_USABLE_BAND_PP = 40filters the unreliable tail- The UI always displays the confidence band; users can judge whether it’s conclusive
This is honest communication: acknowledge the noise, show the uncertainty, let the pilot decide whether to act.
Data pipeline
Section titled “Data pipeline”GET /api/meta/archetypes/:archetypeId/card-stats?days=7..180 returns precomputed deltas from the archetype_card_stats table. The job computeCardStats runs once per sync window (separate from syncMeta, typically after it) and rewrites the table for each (archetype, window) pair in a single transaction. Cold start (empty table) yields computedAt: null and cards: []; the UI tolerates this gracefully.
19. Deck Synthesis (KI-Text über Kennzahlen)
Section titled “19. Deck Synthesis (KI-Text über Kennzahlen)”Page: DeckPage — “Tips” section (primary panel, below recommendations)
A second, structured analysis type (distinct from the Battle-Log Analysis §8): the LLM receives pre-computed, aggregated facts — Field-Score with confidence bands, weighted matchups, card performance deltas, equilibrium signals — rather than a raw battle log, and synthesizes a personalized text summary without inventing numbers or claiming evidence that isn’t there.
What it does
Section titled “What it does”Combines three data sources into a closed set of structured facts (each with an id, value, neutral threshold, and confidence band), feeds them to the LLM with strict rules, and renders the surviving claims into a final text with sections (headline, strengths, risks, recommendations, context). Unlike battle-log analysis which grounds claims in wörtliche quotes, this synthesis grounds in structure + direction: each claim must reference a fact by id (exists in the input list) and must declare direction (positive/negative/neutral) that matches the fact’s derived direction (from its confidence band, not guessed by the model).
The grounding principle (how it avoids hallucination)
Section titled “The grounding principle (how it avoids hallucination)”- Closed facts list: The prompt contains only and exactly the facts the model may discuss, each with a stable
id— no invention, no speculation on data outside this list. - Direction from the band, not the point: A fact’s direction (positive/negative/neutral) is derived from its confidence interval: does the band exclude the neutral value and lie above/below it? This inherits the Spec 3 principle (confidence-aware, never overconfident at low sample sizes). A matchup with 8–2 record from 10 games has a wide band including 50 %, so it’s
neutral, and a claim “you’re strong here” is rejected. - No numbers from the model: Claims contain placeholders (
{value},{low},{high},{label}), which the server fills deterministically from the fact. Impossible to hallucinate a number when it’s never left the server. - Evidence threshold: A claim of type
recommendationmay only reference facts meeting the Spec 3/5 confidence bar (significantin matchups,tier !== 'insufficient'in card deltas). The KI-layer doesn’t lower the standard.
Trigger and caching
Section titled “Trigger and caching”- Trigger: User clicks “Synthesize” button in Deck Tips section — not automatic on every page load (saves tokens, consistent with battle-log analysis pattern).
- Cache: The text is cached by an input hash (canonical hash over the facts list + language + prompt version). Text is reused until the underlying numbers change. If data shifts, the old text remains as “snapshot from {timestamp}” with a “Re-synthesize” button, but the rendered numbers are always fresh.
Data sources
Section titled “Data sources”| Source | Fields | Used for |
|---|---|---|
| Field Score (Spec 3) | fieldWinRatePct, confidence band, coverage % |
field.winRate, field.coverage facts |
| Weighted matchups | Per-opponent winRatePct, band, meta share |
matchup.* facts |
| Card performance deltas (Spec 5) | deltaPp, tier, band, in-deck status |
card.* facts |
| Equilibrium signals (Spec 6, optional) | Weight, gap, trend, fitness delta | equilibrium.* facts |
20. Archetype Synthesis (Spec 10 Slice C — UI in § 15, ArchetypeRecommendationPanel)
Section titled “20. Archetype Synthesis (Spec 10 Slice C — UI in § 15, ArchetypeRecommendationPanel)”Route: GET/POST /api/analysis/archetype/:archetypeId (apps/api/src/routes/analysis.ts)
Archetype-level counterpart to Deck Synthesis (§19) — instead of one user’s deck, it synthesizes
over an archetype’s ranked decklist clusters (Spec 10 Slice A: near-identical published
tournament lists merged into one data point; Slice B: ranked by Wilson-score lower bound of the
tie-weighted win rate, so a lucky small sample can’t outrank a proven large one). Clustering is
deterministic (Spec 1, specs/archetype-list-foundation.md): the same standings always yield the
same clusters, independent of the order the database returns them in, and each cluster shows its
most typical list (the medoid: largest summed card overlap with the other members) instead of an
arbitrary first member. Equal win-rate bounds are tie-broken by placement, cluster size and
standing id. Reuses the exact
Spec 8 anti-hallucination gate (validateSynthesis) — a claim must reference a real fact id and
declare a matching direction, same as Deck Synthesis.
No ownership check (unlike the deck route): archetype data isn’t user-owned. An archetype with no standings in the window simply returns an empty cluster list, not a 404.
scope: 'global' | 'local' distinguishes a run against the global meta from one against the
user’s local-meta field — separate cache rows, separate LLM calls (a 'local' row is tied to the
requesting user; a 'global' row is shared across all users).
Real field-reweighting (Spec 10 Slice D, UI in § 15 ArchetypeRecommendationPanel): an
optional localField: { archetypeId, name, weight }[] (same shape as the
Prediction panel’s local field, § 11 LocalMetaPanel/PredictionPanel) on both GET (as a
JSON-encoded query param, localField=<encodeURIComponent(JSON.stringify(...))> — query strings
have no native array encoding) and POST (a real JSON array in the body). Only takes effect for
scope: 'local' with a non-empty localField — scope: 'global', or scope: 'local' without a
localField, still rank the exact same clusters as before (backward compatible, no behaviour
change for existing callers). When active, each cluster’s game-by-game matchResults (aggregated
across every member standing, Spec 10 Slice A/D) are turned into a per-opponent-archetype
MatchupCell[] and scored against localField via computeFieldScores (fieldWinRate.ts, Spec
3 — reused verbatim, not re-derived: clusterFieldScore.ts injects one synthetic zero-share
subject per cluster into the shares list, so the cluster can run through the exact same
field-weighting math as a real archetype). Clusters are then re-ranked by this field-weighted
score (fieldWinRateLowPct, same “lower bound protects against a small sample” principle as the
Wilson-based default ranking) instead of the plain Wilson lower bound; a cluster with no recorded
games against localField sinks to the end rather than being dropped. GET accepts the same
localField shape as POST so currentInputHash stays consistent between a field-weighted POST
and a matching GET (same reasoning as the personalisation fields below — otherwise GET would
wrongly report stale: true right after generating a field-weighted synthesis).
Data source: tournament_standings joined to tournaments, filtered to the archetype, the
online-Bo1 window (same scope as every other meta read), and players >= DEFAULT_MIN_TOURNAMENT_PLAYERS
(Spec 10 Slice G, currently 15) — unrepresentative small events don’t feed the ranking.
Caching: archetype_synthesis table (docs/database.md), keyed by
(archetypeId, scope[+userId for local], windowDays, language), same input-hash mechanism as
deck_synthesis.
Surfaced in the UI as ArchetypeRecommendationPanel on the archetype drilldown (§15).
Personalisation (“Mein Spielstil”, Spec 10 Slice E, UI in § 15): optional
usePersonalPrior: boolean + a personal win/loss/tie record (personalWins/personalLosses/
personalTies query params on GET, a personalRecord: { wins, losses, ties } object on POST).
Only takes effect for scope: 'local' — on scope: 'global' it is silently ignored (no
validation error). When active and the record has at least DEFAULT_MIN_OWN_GAMES (5) games, the
win rate of the cluster shown first (after local-field re-ranking, if any) is blended with the
personal record
(blendWithPersonalPrior/personalPriorBlend.ts) and surfaces as one extra personalPrior fact
that the LLM prompt can reference — a below-threshold record contributes nothing (no silent
substitute for the global facts). GET accepts the same fields as POST so currentInputHash stays
consistent between a personalised POST and a matching GET (otherwise GET would wrongly report
stale: true right after generating a personalised synthesis).
Known, documented compromise: the personal record is meant to be the opponent-facing
ArchetypeStats balance (how well the user does playing AGAINST this archetype, same numbers
MyMatchupsTable shows) — not a “my results piloting this archetype” record, which does not exist
as a data source. Two different reference frames intentionally coexist: the cluster win rate
answers “how do this list’s pilots perform against the field”, personalPrior answers “how does
this user perform against this archetype as an opponent”. See docs/data-types.md for the full
rationale. The apps/web UI is the third “Mein Spielstil” toggle chip on
ArchetypeRecommendationPanel (§15), reading ArchetypeStats passed down from the store via
MetaPage → ArchetypeDetail (the panel itself stays store-free).
18. Game-Theoretic Meta Layer (Experimental)
Section titled “18. Game-Theoretic Meta Layer (Experimental)”Page: MetaPage — “Equilibrium Analysis” section (collapsed by default)
A second, independent analysis layer built atop the Field Score. Instead of answering “how does deck A perform against the observed field”, this section answers “what deck mixture would be optimal against itself, and which decks fall out of that optimal mix regardless of their popularity”. This is experimental and does not replace the Field Score feature.
The problem and the method
Section titled “The problem and the method”Every archetype has a win rate against every other archetype, stored in the matchup matrix. If we treat this as a constant-sum game (a symmetric zero-sum payoff matrix), we can solve for the Nash equilibrium mixture — the deck distribution where no single-game prediction player can unilaterally improve by switching decks. For a symmetric game, the equilibrium is unique, and we can ask: “which decks belong in that optimal mix?”
The matchup matrix in meta_snapshots uses the tournament tie convention (a tie = ⅓ of a win), which makes p_ij + p_ji = 1 − t/(3n) — slightly less than 1 per pair. For the equilibrium calculation, this matrix is symmetrized into a zero-sum game via the formula p_sym(i,j) = (1 + p_ij − p_ji) / 2, which is mathematically identical to the “half-tie” convention (w + t/2) / n and ensures p_sym(i,j) + p_sym(j,i) = 1 exactly. This is the same symmetrization the reference paper uses.
The equilibrium is computed via linear programming (Phase-II simplex with Bland’s rule, standard form max 1·q subject to P q ≤ 1, q ≥ 0). The resulting weights x = q/Σq form the optimal mixed strategy. A byproduct is an exclusion certificate: any archetype whose payoff against the equilibrium is strictly below the game value is provably excluded from every equilibrium, not just this one.
Robustness: Monte-Carlo resampling over uncertainty
Section titled “Robustness: Monte-Carlo resampling over uncertainty”A single equilibrium composition is fragile — small changes in data can reshuffle the support (which decks are in the mix). To quantify this, the system runs a Monte-Carlo resampling over the matchup matrix’s Wilson-interval uncertainty: each unordered pair {i, j} is sampled once from its Jeffreys-Beta posterior (reflecting the observed win-rate uncertainty), and the mirror cell is set to 1 − p to maintain constant-sum-ness. The equilibrium is re-solved for each resample (2000 by default), and we report per archetype in what percentage of resamples that archetype was excluded (payoff strictly below the value). This “exclusion robustness” is the strong claim: “this deck falls out of the optimal mix in X% of reasonable scenarios, even accounting for sampling uncertainty.”
Three mathematical assumptions documented in code and docs/data-types.md:
- Symmetrization: The matchup matrix is not naturally zero-sum under the tie convention, so it must be symmetrized first — this restores the minimax theorem’s applicability.
- Jeffreys-Beta resampling distribution: We sample from the Jeffreys posterior
Beta(s + 0.5, n − s + 0.5)rather than uniform over the Wilson band, because it is the Bayesian dual of the Wilson interval and is consistent with the symmetrization (its mirror is the exact posterior of the opposite direction). At thin sample sizes, Jeffreys differs from the Wilson band at the tails, so the reported robustness percentages are not identical to “resampling uniformly in the Wilson interval”—a distinction that matters for reproducibility. - Exclusion is one-directional: The certificate proves exclusion (payoff < value ⇒ not in any equilibrium), but does not prove inclusion—equal payoff does not guarantee a deck is in equilibrium, because the equilibrium can be non-unique in degenerate cases. The UI reports the exclusion robustness for decks that are excluded, and shows the equilibrium composition (with a fragility warning if exact-support reproducibility is low) for decks in the point estimate.
Three easily-confused numbers
Section titled “Three easily-confused numbers”After implementing this feature, three different win-rate-shaped numbers exist and must not be conflated. They have different meanings, use different weight vectors, and handle missing data differently:
| Number | Definition | Weight vector | Remis convention | Missing data | Used in |
|---|---|---|---|---|---|
fieldWinRatePct |
Share-weighted EV against the observed field | Observed archetype shares | ⅓ of a win (tournament) | Excluded from coverage | Field Score panel, Spec 3 |
fitnessPct |
Fitness Σ_j x_j P_ij against the observed field with a constant-sum payoff matrix |
Observed archetype shares | ½ of a win (symmetrized) | Imputed as 50% | Replicator fitness display, this feature |
equilibriumPayoffPct |
Payoff Σ_j x*_j P_ij against the equilibrium, where x* is the Nash mix |
Nash equilibrium weights x* |
½ of a win (symmetrized) | Imputed as 50% | Deck strength report in equilibrium composition, this feature |
All three are valid metrics for different questions, but showing one in place of another would mislead. The UI labels each distinctly and carries tooltips explaining the difference.
Replicator fitness and week-over-week direction
Section titled “Replicator fitness and week-over-week direction”From the equilibrium weights x*, we compute each archetype’s fitness f_i = Σ_j x_j P_ij against the equilibrium mixture. Mean fitness for a constant-sum game is exactly 50% — a built-in self-check.
To track whether the meta is favoring a deck, we compare the week-over-week fitness delta: the fitness of archetype i against the most recent completed full week’s observed shares minus its fitness against the prior completed week’s shares, both evaluated on the same payoff matrix (so the delta isolates meta shifts, not sampling noise). This gives a direction (rising / falling / stable / unknown — unknown when fewer than two complete weeks exist). The delta is shown alongside the observed share change (descriptive only, never used for the direction, so theory and reality can diverge visibly).
Data and computation
Section titled “Data and computation”Precomputed weekly: The job computeEquilibrium runs once per week (Monday recommended, after syncMeta completes), reads the default-scope (online, Bo1) tournament data for four analysis windows (7 / 14 / 21 / 28 days), computes the equilibrium for each, and persists to two tables: meta_equilibrium_runs (one row per window, carrying run-level metadata: game value, support size, robustness counters, imputation rate) and meta_equilibrium_archetypes (one row per archetype per window, with weights, payoffs, coverage, robustness percentiles, and trend data).
API: GET /api/meta/equilibrium?days=7..180 returns the precomputed run for a snapped window (7 / 14 / 21 / 28 days). Cold start (before first job run) returns computedAt: null, run: null, archetypes: [] — an honest empty state, never an error.
UI placement: The section is a CollapsibleSection without defaultOpen, titled with an “experimental” badge, appearing after the Field Score and Matchup Matrix sections on the Meta page. It includes:
- Robust exclusions (archetypes with
exclusionBand !== 'likelyIn'): plain-language sentence (“Dragapult is in the most scenarios not a good choice — in 77.9% of 2000 resamples not part of the optimal mix (±0.9 pp)”) plus raw percentage and confidence band - Exact composition (the point-estimate equilibrium weights, shown only with a fragility warning if the exact support was reproduced in fewer than 50% of resamples, or if the equalizerCount suggests non-uniqueness)
- Week-over-week trend (arrow icon + direction label + fitness delta, with observed share change noted as descriptive context)
- Source and limits (computation timestamp, window, resample count, seed, imputation percentage)
The “popularity paradox” framing
Section titled “The “popularity paradox” framing”Decks in equilibrium are not necessarily popular, and popular decks are not necessarily in equilibrium. When a deck has high observed meta share but zero equilibrium weight (or a very low weight), that’s the “popularity paradox”—played by many pilots despite being suboptimal to play against the current distribution. This is flagged with an icon and label pair (not color alone, for accessibility) in the equilibrium composition display, and the exclusion robustness for such a deck reinforces the statement: “in X% of scenarios, this deck drops out entirely.”
21. Archetype-first Coach UI (Spec 7 Scheibe 1, behind archetypeCoachUi)
Section titled “21. Archetype-first Coach UI (Spec 7 Scheibe 1, behind archetypeCoachUi)”Try it: open the app with ?ff=archetypeCoachUi (remembered in this browser; turn it off
with ?ff=-archetypeCoachUi). Everyone else keeps the old layout until the flag is switched
after Scheibe 2. The UI revolves around one coached archetype and makes the core loop
visible: pick a list → copy it for TCG Live → play → paste the log (+ in the bottom nav) →
coaching. Areas: Start · Deck · Coaching · Opponents in the bottom nav, Tools in the header
menu (desktop: all five in the sidebar). The header shows the archetype switcher (reopens the
onboarding in switch mode) and the active list. Onboarding appears only when no archetype is
set; existing accounts are migrated once and skip it; the demo opens on Dragapult ex.
Active archetype (server-side)
Section titled “Active archetype (server-side)”Route: GET/PATCH /api/preferences (apps/api/src/routes/preferences.ts)
Foundation of the archetype-first UI (specs/archetype-first-ui.md): the archetype the app
coaches (activeArchetypeId, a Limitless slug) and, per archetype, the last active deck
(activeDeckIdByArchetype) live in PostgreSQL (user_preferences), so the choice follows the
user to a second device. GET returns defaults (null, {}) without a stored row. PATCH is
partial (at least one of activeArchetypeId / activeDeck, unknown keys → 400, invalid slug →
400); a remembered deck must belong to the user (404 otherwise, indistinguishable from a missing
deck) and have exactly that archetype (400 otherwise); deckId: null forgets the entry. The new
UI itself is gated by the client-side archetypeCoachUi flag (architecture.md
§Feature flags); with the flag off nothing visible changes, but every account
already loads its preferences and is migrated once (legacy slug or the active deck’s archetype),
which also gives the old layout’s deck comparison its archetype.
Onboarding (built, not yet mounted — the coach layout wires it in PR (c)): archetype (most played last 7 days + search) → list (take the meta list = best cluster’s medoid, paste own list, or later; skipped when a deck of the archetype exists) → TCG Live name (skippable). Details: architecture.md §Archetype-first UI.
Start (coach layout, pages/coach/StartPage.tsx, namespace coach): five blocks for the
coached archetype only — Active list (name + “copy for TCG Live”; without a deck “set up a
list” → Deck › My lists), Next step (Scheibe 1: set up a list, else paste a log → AddLogModal
for the active deck; experiments / meta-list changes / coaching hotspots join with Specs 5/6/8),
Your form (last 7 days incl. today, like every own record in the coach layout counting only games with decks of the coached archetype, tie-weighted win rate, W–L–T, Wilson range), Field this
week (top 5 by share over 7 days with your own win rate matched by name → Opponents) and
Recent games (3 newest logs of decks of this archetype → Coaching). Pure logic in
lib/coach/start.ts.
Deck (coach layout, pages/coach/DeckHubPage.tsx): segments Meta list (for now the existing
deck tips, DeckTipsSection; its local-meta link opens Opponents instead of the old Meta tab — the
optimised meta list arrives with Spec 5) and My lists (DeckSwitcher filtered to the coached
archetype, DeckPanel, DeckSettingsWidget with lockArchetype — archetype shown, not
editable, only the variant is saved (E13) — and DeckAnalyticsPanel over this archetype’s decks and
games only, without turn quality, which moves to Coaching). Below the switcher
components/deck/OtherArchetypeDecks lists decks of other archetypes: “switch to …” for valid
archetypes, “assign … to this archetype” for legacy free-text ones (reassignDeckArchetype, existing
PATCH /api/decks/:id). Lab joins with Spec 6. Without a list of the archetype both segments show
the onboarding’s list step (ListSetup: take the meta list / paste own list). DeckSettingsWidget
now lives in components/deck/ (extracted from DeckPage, unchanged in the old layout).
Coaching (coach layout, pages/coach/CoachingPage.tsx, Scheibe 1): a prominent paste TCG
Live log action (AddLogModal for the active deck), the history of this archetype’s games
(OpponentLog, only logs of decks of the coached archetype; detail modal and match stats as in §6)
and the active deck’s turn quality (DeckTurnQualityPanel, moved here from Deck analytics). Without
logs a four-step text guide explains how to copy a log from TCG Live. Filters, the result card after
pasting and the hint to AI settings arrive with Spec 8 / Scheibe 6.
Opponents (coach layout, pages/coach/OpponentsPage.tsx): the shared meta window
(store metaWindow, MetaWindowControl; online and Bo1 move together) and a segment
Global field · My field. Global field (components/opponents/GlobalFieldPanel, formerly the
Matchups tab of ArchetypeDetail) shows the coached archetype’s field score, threats / free wins and
the full head-to-head table on demand. My field is LocalMetaPanel + PredictionPanel with a
fixed perspective (perspectiveArchetypeId): no picker, no “best positioned” line — field score,
threats and lists are always the coached archetype’s, scored with share 0 when it is not part of
the local field (lib/coach/opponents.ts#ownFieldScore). Below always the own record per opponent
(MyMatchupsTable, this archetype only). Opponent detail
(typical cards, coaching hotspot) arrives with Specs 5/8.
Tools (coach layout, pages/coach/ToolsPage.tsx): everything about the coached archetype only
(Spec 7 Scheibe 2), in this order: the shared meta window; Your archetype in the meta
(components/tools/ArchetypeMetaSummary: share, win rate with Wilson band, players, field score with
rank, weekly trend); Tournament lists (components/tools/TournamentListsPanel: recommendation =
ranked clusters + AI text §20, best list per tournament, published decklists with “load more”); Card statistics (components/tools/CardStatsPanel: every card of the archetype from archetype_card_stats with play rate, average count and performance delta + signal tier, grouped by type, tier filter chips; header shows the snapped window 7/14/21/28 days and “always online Bo1”; cold start explained; §17);
then, collapsed, the matchup matrix (§13; focusArchetypeId shows only the coached archetype’s row until “show full matrix”) and game theory (§18; highlightArchetypeId marks the row with aria-current and a “your archetype” label and adds a one-line summary; the only Tools section that stays meta-wide, Spec 7 decision F9); finally link cards to Limitless and
TrainerHill for the general meta. ArchetypeDetail is no longer used here — its matchups tab lives
under Opponents › Global field.