Compare commits

...
Author SHA1 Message Date
claudeandClaude Opus 5.5 0eb80d23d7 duel-core: balance v1 defaults from sim-balance (#64): secondPlayerCitations 1, turnCap 40
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 00:12:25 -05:00
claudeandClaude Opus 5.5 4623930e8f duel-core: secondPlayerCitations ruleset lever (default 0) for first-player balance
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:08:53 -05:00
claudeandClaude Opus 5.5 5cd0ffb0c9 duel-core: engine alpha (createDuel, legalActions, applyAction, viewFor, logFor, replay, duelEnginePort)
Effect interpreter for DUEL_DESIGN T1-T12, keywords, Connected/rivalry,
tokens, fight, Doctrines, Garrisons, turnCap, timeouts. Structural
clone-on-apply (~0.05 ms/action). Refs #55.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:53:15 -05:00
claudeandClaude Opus 5.5 79041990ed duel-core: ConnectKeys qid/cites for claim-based Linked; seed secrecy rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:10:16 -05:00
claudeandClaude Opus 5.5 5d5eaa5488 duel-core: adopt duel-cards card/effect shape and DUEL_DESIGN log kinds
Connected computed by the engine from frozen connect keys; tokens, fight,
multi-target plays, locationsPerTurn, timeoutsToConcede.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:49:52 -05:00
claudeandClaude Opus 5.5 4daf87edde duel-core: monotonic attack/block declarations; optional permanent counters
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:36:41 -05:00
claudeandClaude Opus 5.5 5365611c4a duel-core: shared/duel contracts (types, ruleset) and DUEL_API.md
Refs #55.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:35:37 -05:00
claudeandClaude Opus 5.5 2af2e7f06f Night 2 handbook: night-lead runs on tower-plus
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:08:17 -05:00
claudeandClaude Opus 5.5 57dc1e60aa Night 2 handbook: ui-pvp runs on inspiron-3670
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:07:59 -05:00
claudeandClaude Opus 5.5 dbf385d217 Night 2: data analyst scripts behind reviews/data.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:07:31 -05:00
claudeandClaude Opus 5.5 e34b09d06d Night 2: plan, design brief, handbook and plan reviews
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:05:42 -05:00
20 changed files with 3558 additions and 0 deletions
+89
View File
@@ -0,0 +1,89 @@
# WikiDeck Duel: engine API (v1, Night 2)
Owner: **duel-core** (claude/wikideck#55). Rules: `docs/game/DUEL_DESIGN.md` (duel-design). This file: how code talks to the engine.
- Types: `shared/duel/types.ts`. Ruleset: `shared/duel/ruleset.ts`. Function surface: `DuelEngineApi` in `shared/duel/index.ts`, implemented by `shared/duel/engine.ts` (engine-alpha PR).
- `shared/game/` (Edit War) is untouched. Change requests: comment on #55 with `[from <agent>]`.
## Principles
- **Pure and deterministic.** `(rules, decks, seed, actions)` → identical state and log. RNG: `shared/game/rng.ts` (mulberry32); its uint32 state lives in `DuelState.rng`.
- **Plain JSON.** `DuelState` round-trips through `JSON.stringify`/`parse`; `serialize`/`deserialize` are thin wrappers.
- **Clone-on-apply.** `applyAction` never mutates its input and throws on an illegal action.
- **Atomic actions.** `legalActions(state, seat)` is small, and `[]` for the seat that is not to act. The host checks an action by deep-equal against that list (`concede` and `timeout` excepted).
- **Off-chain.** Matches never move or burn cards. Cards arrive derived and frozen; the engine does no I/O.
## Cards (`DuelCard`)
Built by duel-cards (`derive()`), frozen by the host at match start. Shape agreed with duel-cards on #55.
| Field | Notes |
|---|---|
| `cardId` | unique in a deck (NFT tokenId; sample id in sims; `token:` for tokens) |
| `pageId`, `revisionId?`, `title`, `description?` | `pageId` matches Linked pairs; `revisionId` for recap references |
| `type`, `subtype?` | `Figure` · `Location` · `Event` · `Institution` · `Doctrine` |
| `portal` | `Arts, Earth, History, Science, Society, Neutral`; no deckbuilding restriction |
| `cost` | 1–6 (Locations 1–3) |
| `power`, `toughness` | Figures: body. Locations: 0 / Garrison (0 = can't block). Others: `null` or 0 |
| `keywords` | ≤ `maxKeywords` (2). Figures only |
| `territory?` | Location: +N max Citations while controlled (total from all sources ≤ `territoryCap`) |
| `effects` | `EffectSpec[]` (below), ≤ 4 |
| `rulesText`, `flavor` | display only |
| `connect?` | `{countries, centuries, links, p31}` frozen claims; the engine computes Connected |
| `rarity?`, `deriveVersion?`, `token?` | |
### Keywords (DUEL_DESIGN §4), as the engine applies them
- **Protected**: can't be the target of Events or Doctrines an opponent controls (abilities of other permanents and combat still apply).
- **Featured**: can be blocked only by Featured, Translated or Multilingual Figures.
- **Multilingual**: can block Featured; can't be blocked by Local Figures.
- **Translated**: can block Featured.
- **Legacy**: when destroyed, its controller draws a card.
- **Well-sourced**: prevent the first 1 damage dealt to it each turn.
- **Stub**: at the start of your turn, a +1/+1 counter, up to `stubMax` (2).
- **Local**: +1/+1 while you control a Location sharing a `connect.countries` value.
- **Trending** (Trending mode, set by the host via `applyLive`): no Pending review, +`trendingPower`/+0.
### Effects (`EffectSpec`)
`{ trigger, op, target?, amount?, power?, toughness?, duration?, token?, condition?, grant?, template? }`
- **Triggers:** `onPlay` (Event resolves; on a permanent same as `onEnter`), `onEnter`, `onAttack`, `onDestroyed`, `startOfTurn`, `onCombatDamageToPlayer` (on a Figure, or on a Doctrine for its attached Figure), `static`.
- **Ops:** `damage`, `damageEach`, `createToken`, `pump`, `fight`, `draw`, `attach`, `gainLife`, `drain`, `destroy`, `bounce`, `tap`.
- **Targets:** chosen: `figure`, `figureOrLocation`, `ownFigure`, `opponentFigure`, `anyTarget`; automatic: `each`, `self`, `attached`, `ownFigures`, `opponentFigures`, `opponent`, `controller`. Defaults: damage → `anyTarget`, pump → `self`, draw/gainLife/createToken → `controller`, drain → `opponent`.
- **Chosen targets:** each `onPlay`/`onEnter` effect with a chosen target consumes the next entry of `play.targets`, in effect order; `legalActions` enumerates the combinations. An Event or Doctrine with no legal target can't be played; a Figure/Location/Institution enters and its targeted effect fizzles (`targets` omitted).
- **fight:** the previous chosen target in the same card (else the source permanent) and this target deal damage equal to their power to each other. T6 = `[{op:'pump', target:'ownFigure', power:k, toughness:0}, {op:'fight', target:'opponentFigure'}]`.
- **Doctrine:** its `attach` effect's target is the Figure it attaches to (`ownFigure` for T11, `figure` for T12). Its `static` effects with `target: 'attached'` apply to that Figure; `condition.samePortal` on a Doctrine means "other Figures you control of the attached Figure's Portal". When the Figure leaves, the Doctrine is Deleted.
- **static pump** applies while the source is in play; conditions use **printed** power (no feedback loops). `condition.connected` = the affected Figure is Connected to the source (T9).
- **createToken:** `amount` tokens of `token` (a fresh `DuelCard` with `token: true`, uid `t:<n>`); `condition.maxTokens` = only if you control fewer tokens than that. Tokens leaving play cease to exist.
- Triggers resolve immediately: the active player's first, then in entry order.
## Rules (defaults: `DEFAULT_DUEL_RULESET`; details in DUEL_DESIGN §2)
- 40-card decks (`deckSize`), ≤ 4 per `pageId`, unique `cardId`s, no tokens. 20 Notability. Drawing from an empty library loses (`libraryEmpty: 'lose'`; `'reshuffle'` and `'fatigue'` exist as data).
- Opening hand 7. Up to `mulligans` (1): shuffle in, draw 7, then on `keep` put one card per mulligan on the bottom (the last in hand order). Seat 0 decides first, then seat 1.
- First player (from the seed) skips their first draw. Balance levers (data only): `firstPlayerDraws`, and `secondPlayerCitations` (extra Citations on the second player's first turn; default 1 from balance v1, #64).
- **Turn:** refresh (base max +1 to 10, plus Territory ≤ 2; refill; untap; Pending review ends; Stub and `startOfTurn` triggers) → draw → **main** → **attack** → **block** → damage → end (damage and "until end of turn" clear; discard down to `handSize` 7, **highest cost first**, automatically).
- Locations: `locationsPerTurn` (1), can't attack. Garrison Locations (toughness > 0) block as 0-power.
- Combat: attack the opponent only; each blocker blocks one attacker, at most one blocker per attacker; simultaneous damage; destroy triggers after all combat damage. No trample, first strike, stack or instants.
- **Connected** (engine, from `connect`, tiers in `connectedTiers`): Linked (either `links` contains the other's `pageId`, or either `cites` contains the other's `qid`), Compatriot (shared country), Contemporary (shared century, different types), Kin (shared P31, not Q5/Q16521). A Figure gets the single best bonus among other permanents its controller controls: `+linkedBonus` (2) if Linked, else `+connectedBonus` (1). Logged once (`connected`). Opposing Connected pairs are logged once as `rivalry`.
- **Timeouts:** `timeout` passes (mulligan: keep; main/attack: end the turn without attacking; block: confirm current blocks). `timeoutsToConcede` (3) consecutive timeouts by one seat lose (`reason: 'timeout'`).
- `turnCap` (default 40 total turns from balance v1, #64; `null` = none): after that many total turns, higher Notability wins, then higher total power in play, then the second player.
## Phases and actions
| Phase | Who acts | Listed actions |
|---|---|---|
| `mulligan` | seat 0 until ready, then seat 1 | `keep`, `mulligan` |
| `main` | active | `play {uid, targets?}`, `endPhase` |
| `attack` | active | `toggleAttacker {uid}` (untapped, not Pending review, not yet declared), `confirmAttack` |
| `block` | defender | `block {blocker, attacker}` (unassigned blocker, unblocked attacker, evasion allowing), `confirmBlocks` |
| any | either seat | `concede` (not listed) |
| any | host, for the seat to act | `timeout` (not listed) |
Declarations are **monotonic** (no un-declare), so every turn has a bounded number of actions; UIs stage choices locally and send them on confirm. If the defender has no legal block, damage resolves at `confirmAttack` with no block phase. `confirmAttack` with no attackers ends the turn.
## Views and log
- `viewFor(state, seat): PlayerView`: your hand; the opponent's hand and library **sizes** only; both graveyards; the battlefield with current power/toughness, keywords and Connected badge; combat; `toAct`; `version`; `result`. Never the RNG or library order.
- **The seed is secret until the match ends.** `seed` plus the deck lists reproduce every shuffle, so the host never sends `seed` or `rng` (or the raw `DuelState`) to clients before `gameOver`. Live log rendering picks template variants from a derived `storySeed = sha256(seed + ':story')`.
- `state.log` is omniscient (server, and the recap after the match). Clients get **`logFor(state, seat)`**: the opponent's `draw` events have no `card`. Every other event is public information.
- Every event has `seq` and `turn`. `CardRef` carries `uid, cardId, title, pageId, type` plus `power`/`toughness` right after the event.
- Kinds (DUEL_DESIGN §10 names): `start, mulligan, keep, turnStart, draw, deploy, cast, adopt, tokenCreated, connected, rivalry, effect, attack, block, effectDamage, combatDamage, playerDamage, lifeGain, destroyed, bounced, discard, fatigue, concede, timeout, gameOver`. `destroyed` = the recap's casualties. Prose templates live with duel-design / ui-pvp, not in the engine.
## Host binding
`duelEnginePort` (engine.ts) is structurally an `EnginePort<DuelRuleset, DuelCard, DuelState, DuelAction>` (`server/game/engine-port.ts`; `shared/` doesn't import `server/`, so host-pvp types it there). `concedeAction`, `timeoutAction`, `turnSeconds`, `turnOf`, `applyLive` included. `starterDeck` and `previewPool` throw: there are no starters (BRIEF decision 2); draft pools come from both players' collections.
## Stability
These types are the contract for duel-cards, host-pvp, ui-duel, ui-pvp and sim-balance. Additive changes (optional fields, new log kinds) can land with the engine; breaking ones get a `[duel-core] contract change` comment on #55 first.
+144
View File
@@ -0,0 +1,144 @@
# WikiDeck Night 2: design brief (locked decisions)
**Night 2:** 2026-11-17, 21:30 to **02:00 EST, hard stop**.
This brief merges three sources:
- the coordinator's plan, in `docs/night2/PLAN.md`
- four reviews (designer, engineer, data and critic), in `docs/night2/reviews/`
- **Eric's decisions on 2026-11-17**, which override anything in the reviews
Where a review disagrees with this file, **this file wins**. Where this file is silent, follow the reviews, in this order:
1. engineer, for architecture
2. designer, for rules
3. data, for derivation
4. critic, for process
## Eric's decisions (non-negotiable)
1. **A full 40-card, Magic-style game.**
- A deck is exactly 40 cards, and every card in it is an NFT the player owns.
- There are no loaners, Basics, filler or proxies.
2. **Players can't play until they own enough cards.**
- If a player owns fewer than 40 cards, the game shows their progress (for example "23 / 40 cards") and how to mine.
- There is no "practice with borrowed cards".
- The reviews' Basics, loaners, Signature card and the "Collection + Basics" model are **rejected**.
3. **PvP is first-class.** Bot matches exist, but only for eligible players.
4. **The mobile app must be able to mine.**
- Today `isNativeApp()` hides the mining panel, so mobile players can never earn cards.
- Fix it in the Android app.
- Write in `docs/night2/MOBILE_MINING.md` that Google Play and the App Store both prohibit on-device crypto mining, so for now the mining build is a sideloaded APK.
5. **Tone: lean in, Cards Against Humanity style.**
- Living people, tragedies, wars, disasters, crimes, diseases and dictators are all **ordinary cards with full mechanics**.
- There are no `solemn` flags, no special-casing and no softened verbs.
- The game takes itself completely seriously, and the comedy comes from the juxtapositions. Use the critic's S7 deadpan style guide: never wink, never comment on the matchup, and use encyclopedic texture with [n] citations.
- "Casualties" is fine.
- **One rule stays:** all generated text (rules text, match log, recap) is deterministic templates filled **only with real data from the card and the match**. Never use LLM prose, and never invent factual claims about real people (no made-up crimes, quotes or acts). Humour by juxtaposition is fine; fabricated facts about a real person are defamation.
6. **iOS is paused.** Don't touch `ios/` or the macOS VM.
7. **Wikimedia politeness by default** (the engineer's §4 and the data analyst's §5), including the mint-path bug (§9 below).
## Supply reality (design around it, don't fight it)
- **Mainnet:** 12 cards, all in one wallet. Consensus mints at most about 96 cards a day, network-wide. That's Eric's accepted trade-off: the game becomes playable as people mine.
- **Our testnet** (`deploy/night/`, on poweredge-r350):
- Wallets alice, bob, carol and dave own about 50 cards between them, with up to 40 more being mined now.
- The `testnet-ops` agent consolidates cards into **alice and bob** with on-chain transfers, so both reach 40 if supply allows.
- Deck size is **ruleset data** (`deckSize`, default 40). If the testnet can't reach 80 cards, the end-to-end test mode may set a lower `deckSize`. That's a testnet mode file only; production stays at 40.
- **Engine, simulation and balance work** uses the 236 real cards in `docs/game/card-sample.json` as the card pool. Build 40-card random decks from it. This needs no chain.
## Game rules core (designer §2, adapted to 40 cards)
- **Life:** each player starts with 20 Notability; at 0 you lose. Drawing from an empty library loses (the MTG rule). These are ruleset keys.
- **Opening:** hands of 7, with one mulligan (shuffle, draw 7, bottom 1). The first player skips their first draw.
- **Turn:** refresh, draw, main, combat, end.
- **Resources are a fixed income of Citations:** your maximum rises by 1 each turn, to a cap of 10. There are no land cards, so no land screw.
- Locations ramp at most +2 in total.
- Hand limit is 7.
- **Combat:**
- attack the opponent with untapped Figures, with summoning sickness ("Pending review")
- at most one blocker per attacker
- damage is simultaneous
- no trample, no first strike, no stack and no instant speed; Events are sorcery-speed
- **Clock:** 60 s per turn plus a 5-minute bank. No turn cap is required. If the sims show stalls, add `turnCap` as a ruleset key.
- **Card types** (designer §3 and data §1):
- **Figure:** a creature
- **Location:** a permanent with Territory or Garrison
- **Event:** sorcery-speed
- **Institution:** an artifact
- **Doctrine:** an Aura that attaches to a Figure, so *Tetrated dodecahedron* can buff *Cho Yang-ho*
- Classify with data §1's P31 → P279 anchor classes, falling back to categories, then the description, then Doctrine.
- Fix the `\bhuman\b` → People bug.
- Freeze each card's derived profile the first time the card is seen.
- **Factions ("Portals"):** designer §3.2. There are no colour restrictions in deckbuilding.
- **Stats:** data §2. Cost 1–6 comes from the percentile fame curve, with a fixed power+toughness budget per cost, so famous cards are bigger and pricier, not strictly better.
- **Keywords:** designer §3.4 and data §2, at most 2 per card, each triggered by real data:
- Protected
- Featured
- Translated
- Legacy
- Stub
- Well-sourced
- Multilingual
- Local
- **Connected:** the data team's tiers (data §4): Linked, Compatriot, Contemporary and Kin, from cached Wikidata claims and links.
- It gives +1/+1, or +2/+2 for a direct link.
- Aim for it to fire in 15–30% of pairs, tuned in the simulator.
- **Flavour text:** the first sentence of the on-chain `article.extract`.
## Story
- **Match log:** past-tense, encyclopedic and per player (`logFor`), with no hidden-information leaks.
- **Recap:** a "Battle of X (2026)" page after each match, with:
- an infobox: date, belligerents (the players), strength, casualties (the cards destroyed), result
- a narrative assembled from the log with 3–4 template variants per event, seeded deterministically
- References citing every card played, with revision ids
- "WikiDeck" branding, not Wikipedia's
- a shareable URL
## Modes (kept, now on the duel engine)
- **Classic:** constructed from your own 40+ cards. It's ranked.
- **Draft:** both players must be eligible. The pool is drawn from both players' collections, and drafted cards are used for that match only. Nothing moves on-chain.
- **Trending:** live pageview momentum changes stats (designer §5), from a daily refreshed cache.
- **Peer-hosted house rules:** stay data-only, with a versioned schema. Night 1 mode files are rejected cleanly.
## PvP (engineer §3)
- **Seats and ownership:**
- Seats are tied to eom.dev accounts (Dex) and their linked wallets.
- The host verifies **ownership on the server** (`ownership.ts`, using `ledger.nft()`) and builds each card from the chain.
- **Night 1's gaps to close:**
- the browser-side ownership check
- the 128-block snapshot cap
- starter decks dealt in `host.ts:144`
- **Matchmaking:** private lobbies, invite links, quick match, and an Elo ladder keyed to the account.
- **Transport:** keep polling, with a state version so unchanged polls return 204. Don't use long-polling.
## Wikimedia (engineer §4 and data §5)
**One process-wide client:**
- 1 request per second, burst 3, 1 request in flight per host
- priority lanes: mint, then interactive, then background
- `maxlag=5`
- honour `Retry-After`
- a circuit breaker after 3 consecutive 429s
- a daily cap
- a sqlite cache on disk with ETags
- a User-Agent with an operator contact (a config key that operators must set; the testnet uses the project URL)
**The mint path changes transport only:** request parameters stay byte-identical, and the cache is never used for mint data.
**Fix the mint bug:** a 429 on pageviews currently mints a card with `attention: null` forever (`enrichment.ts:145-164`). Fail and retry instead.
**Other changes:**
- Card faces in the client no longer trigger uncached upstream calls on every render.
- An article prefetch pool for mining templates (data §8).
**Tests make zero network calls.**
## Cut order if late
1. the Elo ladder (keep W/L)
2. quick match (keep invites)
3. Trending's live stats
4. the Kin and Contemporary tiers of Connected
5. recap polish (keep the plain log)
**Never cut:**
- the duel core
- 40-card owned-deck validation on the server
- PvP over invite links
- the Wikimedia client and mint fix
- mobile mining
- the recap (the story is the point)
+88
View File
@@ -0,0 +1,88 @@
# WikiDeck Night 2: team handbook
Read this whole file, then `docs/night2/BRIEF.md` (the locked design decisions). Then read the review sections your issue names in `docs/night2/reviews/`.
**Window:** 2026-11-17 21:30 until **02:00 EST, hard stop**.
**Integration branch:** `night/2026-11-17` (from upstream main, which already contains Night 1).
**Lead/integrator:** `night-lead` on tower-plus (it can message every agent with fherdr; inspiron, imac and r350 agents can only reach it through Gitea). The coordinator is Eric's Claude session on tower-plus.
**Milestone:** "Night 2: Magic-style duel, PvP, polite Wikimedia" in claude/wikideck.
**Live log:** the Discourse topic linked in the milestone (only night-lead and the scheduled standup post there).
## Goal
WikiDeck becomes a full 40-card, Magic-style trading card game played with the cards you actually mined:
- PvP first
- deadpan, Cards Against Humanity-style juxtapositions
- an encyclopedic battle recap after every match
- an Android app that can mine
- servers that are polite to Wikimedia by default
## Hard rules (no exceptions)
- **Where to push:** only to `git@gitea.eom.dev:claude/wikideck.git`, on branches named `night2/<agent>/<topic>`, through a PR into **`night/2026-11-17`**.
- Never push to `WikiDeck/wikideck`, `main` or the Night 1 branch.
- Only `night-lead` merges, using squash.
- **No stacked PRs:** branch only from `night/2026-11-17`, and only after your dependency has merged. If you need unmerged code, stub the interface.
- **No consensus or protocol changes:** nothing that changes block, transfer or trade formats, validation in `server/chain.ts`, `server/testnet/consensus.ts` or `shared/protocol.ts`, or what a mint fetches and stores. The game runs **off-chain**, and matches never move or burn cards.
- **Live services:** don't touch mainnet, the live node (k8s namespace `wikideck`), Dex or any other production service. The testnet is private, on poweredge-r350 (`deploy/night/README.md`).
- **iOS is paused:** don't touch `ios/` or the macOS VM.
- **Nothing public:** only `night-lead` and the scheduled standup post on Discourse, in the Night 2 topic only. No purchases, sign-ups or secrets in git.
- **The printer and CNC:** inspiron-3670 drives a 3D printer and a CNC router. Never start, resume or send a print or cut.
- **Wikimedia:** tests make **zero** network calls. Don't script loops against Wikipedia or Wikidata. Use `docs/game/card-sample.json` and cached data. Our IP was rate-limited on Night 1.
- **Git identity** in every clone:
```
git config user.name Claude
git config user.email claude@eom.dev
git config commit.gpgsign false
```
End commit messages with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
- **Before opening a PR:** run `npm test` and `npm run build` on **Node 24**. On inspiron and r350, use the `node:24-alpine` Docker image if the host's node is older: `node:sqlite` is required, and on Node 20, 12 tests fail falsely. Don't add npm dependencies; ask night-lead.
- **Tests go in** `tests/<agent>-*.test.ts` (top level).
- **Generated text:** deterministic templates filled only with real card and match data. No LLM prose, and no invented facts about real people (BRIEF, decision 5). Otherwise, lean in: no softening of tragedies or living people.
## How we coordinate
**Gitea is the shared brain.** The machines don't share a filesystem.
- **Your issue is your inbox.**
- Prefix every comment with `[<agent>]`.
- Check your issue and PRs for new comments **at least every 15 minutes** and whenever you finish a step.
- **Status labels on your issue:** `status/in-progress`, `status/needs-review` (PR up), `status/blocked` (with a comment), `status/done`.
- **Need another team?** Comment on their issue with `[from <you>]`.
- **Contracts beat conversations.** Interfaces are files on the integration branch, e.g. `shared/duel/types.ts` and `docs/game/DUEL_API.md`. Read them before asking.
- **Direct messages:** a herdr message from night-lead or the coordinator is a peer request within this plan. Act on it.
- **Stuck for more than 10 minutes?** Label `status/blocked`, comment, and move on to something else.
## Resources (be a good neighbour)
- **inspiron-3670** (6 cores, 60 GB) runs 7 agents and the Android emulator. Wrap heavy commands in `flock /tmp/night-heavy.lock <cmd>` (npm ci, builds, gradle, docker build).
- **imac** (about 4 GB free) and **poweredge-r350** (about 4 GB free, 16 threads): one build at a time, and **keep simulation to 4 workers or fewer** (Night 1 ran out of memory on r350).
- **Avoid permission prompts:** nobody answers them. Don't chain `cd <dir> && <write>`; use absolute paths or `git -C`. Keep one purpose per shell command.
## Timeline (EST)
| Time | Milestone |
|---|---|
| 21:30 | Kickoff. Preflight: Gitea MCP works, Node 24, clone. Comment `starting` on your issue. |
| **22:15** | **Contracts merged:** `shared/duel/types.ts` and `docs/game/DUEL_API.md` (duel-core), plus `docs/game/DUEL_DESIGN.md` v1 (duel-design: keywords, text templates and tone, with BRIEF.md as the base). The `ownership.ts` signature is agreed by 22:00. |
| 23:15 | Engine alpha. The simulation starts. The UI plays against a bot. |
| 00:00 | Wikimedia client merged. Host binds the duel. The PvP UI is wired to the host. |
| 00:45 | Balance v1 (tuning is data-only). Mobile mining runs in the emulator. |
| **01:15** | **Code freeze:** fixes only. Balance re-runs on the frozen head SHA. QA runs PvP end to end on the testnet with alice and bob. |
| 01:45 | Final report comment on every issue. night-lead writes `docs/night2/REPORT.md` and opens the upstream PR (never merges it). |
| **02:00** | **Stop.** Push, comment, exit. |
## Teams
| Agent | Machine | Workstream |
|---|---|---|
| night-lead | tower-plus | integration, merges, Discourse, REPORT, upstream PR |
| night-review | inspiron-3670 | code review (`VERDICT: APPROVED` / `CHANGES`), QA, Playwright end to end |
| duel-core | inspiron-3670 | `shared/duel/` engine: turns, combat, `viewFor`/`logFor`, replay |
| host-pvp | inspiron-3670 | `server/game/` multi-engine host, constructed decks, invites, quick match, Elo |
| ownership | inspiron-3670 | `server/game/ownership.ts` and `collection.ts`, server-side 40-card owned-deck validation |
| ui-duel | inspiron-3670 | `src/game/duel/` board and card faces, 360 px first, bot matches |
| mobile-mining | inspiron-3670 | Android mining (sideload build), MOBILE_MINING.md |
| duel-design | imac | DUEL_DESIGN.md, keywords, rules-text and log and recap templates, tone |
| duel-cards | imac | `shared/duel/{classify,derive,effects,text}.ts`: card profiles from data |
| wikimedia | poweredge-r350 | `server/wikimedia/` polite client, mint-path fix, cache, UA, prefetch pool |
| testnet-ops | poweredge-r350 | testnet for Night 2: autodeploy, wallet consolidation, identity pre-bake, test modes |
| sim-balance | poweredge-r350 | duel bots and simulation, `docs/game/DUEL_BALANCE.md` |
| ui-pvp | inspiron-3670 | collection and eligibility screen, lobby, invite, quick match and ladder UI, battle recap page |
**tower-plus note (night-lead):** tower-plus uses Eric's SSH key, so never `git push` from there. Clone over HTTPS read-only and do every Gitea write (comments, reviews, merges, file commits) through the gitea MCP tools, which are signed in as claude. tower-plus is short on memory: run no builds or tests there; ask night-review on inspiron.
+120
View File
@@ -0,0 +1,120 @@
# WikiDeck Night 2: proposed game redesign (for review)
Status: **draft, under review.** Written by the coordinator on 2026-11-17 from Eric's feedback on Night 1's game, Edit War. Night 2 runs unattended on 2026-11-17 from 21:30 to 02:00 EST.
## Eric's feedback on Edit War (the requirements)
1. **Real cards:** a player's deck is made of the cards they actually mined and own. Loaners existed for the demo; the real game uses real cards.
2. **PvP:** players must be able to play each other, not only the AI. Hosted lobbies exist (`src/game/OnlinePlay.tsx`, `server/game/host.ts`) but are buried.
3. **Story:** Edit War "doesn't really tell much of a story with the actual cards".
4. **Feel:** Magic: The Gathering is the model for how it should feel.
5. **Modes:** keep the different modes (classic, draft, trending); Eric likes them.
6. **Tone:** "The fact that I can use a Tetrated Dodecahedron in a game with Barack Obama is funny. Lean into this. The game should take itself seriously, but the end result is going to be entertaining for this reason." (Eric's original v2 post also mentions using his *Tetrated dodecahedron* card to buff his *Cho Yang-ho* card, and node operators running house rules.)
7. **Wikipedia limits:** our servers must respect Wikimedia rate limits by default instead of getting cut off. Night 1 hit HTTP 429 from our shared IP.
8. **iOS:** paused (Apple licence acceptance). Out of scope.
## Hard constraints
- **Consensus is fixed:**
- No changes to the chain, block format, mint stats snapshot or consensus files (see `docs/night/BOUNDARIES.md`).
- Everything game-related is derived off-chain from what a card already holds.
- **Where work happens:** in the `claude/wikideck` fork, through reviewed PRs. Eric merges upstream.
- **No live deployment:** don't touch mainnet or the live node at wikideck.eom.dev.
- **Budget:** 4.5 hours, about 10 agents across 4 machines (tower-plus, imac, inspiron-3670, poweredge-r350). Night 1 used 17 agents for 2.75 h and about 10% of the weekly usage budget; 75% remains.
## Facts the design must face
- **Card data:** what a card holds is shown in `shared/enrichment.ts` (PageEnrichment / MintStatsSnapshot) and `shared/testnet.ts` (BlockHeader).
- **Article:** pageId, title, extract, image, category, revisionId.
- **Mint snapshot:** pageBytes, languageCount, 6 months of pageviews with trendPercent and dailyAverage, and the attention, depth and reach scores.
- **Night 1 also used:** the Wikidata id, P31 "instance of", and live pageviews, all fetched off-chain.
- Real distributions are in `docs/game/CARD_DATA.md`: compressed scores, a skewed category split, and a reach of 0 for 18% of cards.
- **SUPPLY:**
- One card is minted per block, with a consensus target of one block per 15 minutes: at most about 96 new cards a day, network-wide.
- **Mainnet today has 12 cards in total, all owned by one wallet**, all mined on 2026-11-01.
- A "deck of your own mined cards" in the Magic sense (40–60 cards) is impossible for anyone for a long time.
- **This is the biggest viability question; see Open problem 1.**
- **Cards are unique NFTs:** each card is one specific mint, and the same article can be minted more than once (`pageId` repeats).
- **Night 1 code to reuse:**
- the deterministic rules engine and its rules-as-data style (`shared/game/`)
- the bots and the balance simulator (`shared/bots/`, `scripts/sim/`)
- hosted lobbies and modes (`server/game/`)
- Dex accounts (`server/account/`)
- the Android shell (`android/`)
## Proposed design
### A. Card identity from the article (MTG-style types)
The card type comes from Wikidata P31, with a fallback to Wikipedia categories:
| Article is a… | Card type | MTG analogue |
|---|---|---|
| person, character, animal species | **Figure** | creature |
| place, region, celestial body, structure | **Location** | land (resource) and/or permanent |
| event, battle, election, disaster | **Event** | instant/sorcery |
| creative work, organisation, company, team, product | **Institution** | artifact |
| concept, theory, mathematical object, ideology, field | **Doctrine** | enchantment |
**Factions (colours):** the 6 P31-based factions proposed in CARD_DATA.md, plus a neutral fallback.
**Stats from data:**
- **Power and toughness** come from percentile attention, depth and reach. For example, attention drives power, and depth drives toughness and staying power.
- **Cost** follows the curve: high-stat cards cost more.
**Rules text:**
- Generated deterministically from a fixed table of templates keyed on type, faction, category keywords, trend, language count, dates (birth/death, founding, event date), coordinates, and so on.
- It is written in MTG's terse register.
- **Flavour text:** the first sentence of the article's extract.
### B. Story mechanics
- **Connected:** two cards whose articles link to each other, or share a Wikidata property such as country, field or era, gain a bonus together. Barack Obama with the White House; Tetrated dodecahedron with Polyhedron.
- **Citations:** a resource or counter flavoured as sources.
- **Edit wars and vandalism:** removal and interaction effects.
- **Deadpan tone:** the game is completely straight, like an encyclopedia or an MTG judge. The comedy comes from the matchups, never from jokes in the text.
- **Match log:** written as a dry encyclopedic account.
- **After each match:** a Wikipedia-style article, *"Battle of the Tetrated Dodecahedron (2026)"*. It has:
- an infobox: date, belligerents, commanders (the players), strength (the cards), result
- a short deterministic narrative built from the match log
- a "References" list citing every card's real article
- These recaps are shareable.
### C. Game structure
- **Duel:** two players, a life total, turns with attack and block, and permanents on a battlefield.
- **Resources:** from Locations and/or a fixed per-turn income, designed to avoid MTG's "land screw" (no resource cards, no game).
- **Deck size and composition:** depends on Open problem 1.
### D. PvP first
- **Matchmaking:** a queue, invite-by-link and a ranked ladder (Elo or Glicko).
- **Identity:** the eom.dev account, with linked wallets as the card source.
- **Hosting:** the hosting node runs the match, so there's no client trust.
- **AI opponents:** still available for practice and onboarding.
### E. Modes (kept)
- **Classic:** constructed from owned cards.
- **Draft:** players draft from a shared pool, so they don't need large collections.
- **Trending:** stats boosted by live pageviews.
- **Peer-hosted house rules:** remain data-only.
### F. Wikimedia politeness by default
- **One client:** a single throttled Wikimedia client used by every server-side caller (`server/wiki.ts`, `server/enrichment.ts`, P31 lookups, link lookups).
- **Throttling:**
- a conservative rate limit by default (for example 1 request/s and 1 concurrent request per node, configurable)
- `maxlag`
- honour `Retry-After` with backoff
- batch up to 50 titles per request
- an on-disk cache with ETags and conditional requests
- a daily refresh for live stats
- **User-Agent:** a default UA that identifies the node and an operator contact, as Wikimedia's policy asks.
- **Volume:** a design budget for requests per match and per mint.
## Open problems for the review team
1. **Supply versus "real cards only".** What makes a real-cards game playable when a player owns 0–12 cards and the network mints at most about 96 a day? Options to evaluate (add others):
- (a) A small deck size, such as 7–10 cards, with recursion and reuse.
- (b) Your owned cards are your "commanders" or champions, and a shared pool of common public-domain article cards fills the rest. This conflicts with Eric's requirement, so it would have to be argued.
- (c) Draft as the main mode, where the pool is drawn from the whole chain's minted cards and ownership gives cosmetic credit or a guaranteed pick.
- (d) A collection-as-deck where every owned card counts, scaled by size.
- (e) Card copies or "editions" (no consensus change possible, so off-chain only?).
Recommend one, and say what Eric must decide.
2. Is MTG-style attack/block too complex to build, balance and make readable in one night? What is the smallest rules core that still feels like Magic?
3. Is P31 typing reliable enough? Check against the real sample in `docs/game/card-sample.json` and `docs/game/starter-cards.json`. Plan for unclassified cards, which were 14% of Night 1's sample.
4. Can "Connected" link lookups be done within the Wikimedia budget? Where does the data come from, and when is it fetched and cached?
5. Can the generated rules text be both deterministic and good? Does it need an LLM? LocalAI exists on the cluster, but determinism and the consensus boundary matter.
6. What scope is realistic for 4.5 hours with about 10 agents, and what gets cut first?
+44
View File
@@ -0,0 +1,44 @@
"""How often random card pairs share cheap relations. Usage: python3 -I connected.py <card-sample.json>"""
import json, sys, re, itertools, collections, importlib.util, os
cards = json.load(open(sys.argv[1]))['cards']
spec = importlib.util.spec_from_file_location('ty', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'types.py'))
ty = importlib.util.module_from_spec(spec); spec.loader.exec_module(ty)
GENERIC = re.compile(r'stubs|living people|\d+ (births|deaths)$|articles|wikidata|pages', re.I)
COUNTRIES = ['United States','American','England','English','British','France','French','Germany','German','Japan','Japanese','China','Chinese',
'India','Indian','Brazil','Poland','Polish','Italy','Italian','Spain','Spanish','Austria','Canada','Canadian','Australia','Australian','Russia','Russian',
'Mexico','Mexican','Iran','Pakistan','Bangladesh','Sweden','Swedish','Norway','Estonia','Ukraine','Croatia','Philippines','Cuba','Israel','Portugal','Scotland','Wales','Ireland','Kazakhstan','Malaysia','Argentin','Belgi','Iceland','Bermuda','Thailand','Singapore','Sri Lanka','Slovenia','Moldova','Cyprus','Macedonia','Mauritania','Congo','Gibraltar','Hong Kong','New Zealand','Korea','Indonesia','Aceh']
NORM = {'American':'United States','English':'England','British':'United Kingdom','England':'United Kingdom','Scotland':'United Kingdom','Wales':'United Kingdom',
'French':'France','German':'Germany','Japanese':'Japan','Chinese':'China','Indian':'India','Polish':'Poland','Italian':'Italy','Spanish':'Spain',
'Canadian':'Canada','Australian':'Australia','Russian':'Russia','Mexican':'Mexico','Swedish':'Sweden'}
Y = re.compile(r'\b(1[0-9]{3}|20[0-2][0-9])')
def feats(c):
txt = (c['description'] or '') + ' | ' + ' | '.join(c['categories'])
ctry = {NORM.get(k, k) for k in COUNTRIES if k in txt}
cents = {int(y) // 100 for y in Y.findall(c['title'] + ' ' + txt)}
cats = {x for x in c['categories'] if not GENERIC.search(x)}
p31 = {i['id'] for i in c['instanceOf']}
return dict(ctry=ctry, cent=cents, cats=cats, allcats=set(c['categories']), p31=p31, type=ty.classify(c)[0])
F = [feats(c) for c in cards]; pairs = list(itertools.combinations(range(len(cards)), 2)); N = len(pairs)
def rate(f):
k = sum(1 for i, j in pairs if f(F[i], F[j])); return f'{k}/{N} ({100*k/N:.2f}%)'
print('pairs', N)
print('share any category (incl. generic)', rate(lambda a, b: a['allcats'] & b['allcats']))
print('share specific category', rate(lambda a, b: a['cats'] & b['cats']))
print('share P31 class', rate(lambda a, b: a['p31'] & b['p31']))
print('share P31 excl human/taxon', rate(lambda a, b: a['p31'] & b['p31'] - {'Q5', 'Q16521'}))
print('share country (text proxy for P17/P27)', rate(lambda a, b: a['ctry'] & b['ctry']))
print('share century (text proxy for dates)', rate(lambda a, b: a['cent'] & b['cent']))
print('share type', rate(lambda a, b: a['type'] == b['type']))
print('country OR century OR specific cat', rate(lambda a, b: (a['ctry'] & b['ctry']) or (a['cent'] & b['cent']) or (a['cats'] & b['cats'])))
print('cards with >=1 country', sum(1 for f in F if f['ctry']), 'with >=1 century', sum(1 for f in F if f['cent']))
# deck-level: chance that a random 10-card hand-pair (10 vs 10, own deck) has >=1 connected pair within a deck
import random; random.seed(1)
def deck_hits(pred, size=10, trials=2000):
h = 0
for _ in range(trials):
s = random.sample(range(len(F)), size)
if any(pred(F[i], F[j]) for i, j in itertools.combinations(s, 2)): h += 1
return f'{100*h/trials:.0f}%'
pc = lambda a, b: (a['ctry'] & b['ctry'])
print('10-card deck has >=1 same-country pair', deck_hits(pc), '| specific category', deck_hits(lambda a, b: a['cats'] & b['cats']),
'| country-or-century', deck_hits(lambda a, b: (a['ctry'] & b['ctry']) or (a['cent'] & b['cent'])))
+23
View File
@@ -0,0 +1,23 @@
"""Field availability for rules-text generation in card-sample.json. Usage: python3 -I fields.py <card-sample.json>"""
import json, sys, re, statistics, collections
cards = json.load(open(sys.argv[1]))['cards']; n = len(cards)
Y = re.compile(r'\b(1[0-9]{3}|20[0-2][0-9])\b')
def share(f): k = sum(1 for c in cards if f(c)); return f'{k}/{n} ({100*k/n:.0f}%)'
print('description non-empty', share(lambda c: bool(c['description'])))
print('wikidataId', share(lambda c: bool(c['wikidataId'])))
print('P31 present', share(lambda c: bool(c['instanceOf'])))
print('>=1 non-hidden category', share(lambda c: len(c['categories']) > 0))
print('categories truncated (cllimit 50)', share(lambda c: c['categoriesTruncated']))
print('median categories', statistics.median(len(c['categories']) for c in cards))
print('year in title', share(lambda c: Y.search(c['title'])))
print('year in description', share(lambda c: Y.search(c['description'] or '')))
print('year in categories', share(lambda c: any(Y.search(x) for x in c['categories'])))
print('year anywhere (title/desc/cats)', share(lambda c: Y.search(c['title'] + ' ' + (c['description'] or '') + ' ' + ' '.join(c['categories']))))
print('births/deaths category', share(lambda c: any(re.search(r'\d+ (births|deaths)', x) for x in c['categories'])))
print('establishments/completed category', share(lambda c: any(re.search(r'establishments|completed in|disestablish|opened in', x) for x in c['categories'])))
print('living people', share(lambda c: 'Living people' in c['categories']))
print('stub category', share(lambda c: any('stubs' in x for x in c['categories'])))
print('country/nationality word in desc or cats', share(lambda c: re.search(r'American|British|English|French|German|Japan|China|Chinese|India|Brazil|Poland|Polish|Italy|Italian|Spain|Spanish|Austria|Canada|Australia|Russia|United States', (c['description'] or '') + ' '.join(c['categories']))))
print('legacy category on-chain', collections.Counter(c['legacyCategory'] for c in cards))
print('pageviews available', share(lambda c: c['pageviews']['status'] == 'available'))
print('languagesTruncated', share(lambda c: c['languagesTruncated']))
+59
View File
@@ -0,0 +1,59 @@
"""Proposed percentile -> cost/power/toughness derivation, evaluated on card-sample.json.
Usage: python3 -I stats.py <card-sample.json>"""
import json, sys, collections, statistics, itertools
d = json.load(open(sys.argv[1])); cards = d['cards']; P = d['percentiles']
def pct(s, v): # DESIGN 1.1 counting: cut points strictly below + half of equal
if v is None: return None
cut = P[s]; return int(sum(c < v for c in cut) + sum(c == v for c in cut) / 2)
TH = [26, 39, 51, 63, 78] # v1.1 costThresholds (fame -> cost 1..6)
BUDGET = [None, 3, 4, 6, 8, 10, 12] # P+T per cost, MTG vanilla curve (2/1, 2/2, 3/3, 4/4, 5/5, 6/6)
def derive(c):
a, dp, r = (pct(k, c['stats'][k]) for k in ('attention', 'depth', 'reach'))
vals = [x for x in (a, dp, r) if x is not None]
fame = int(sum(vals) / len(vals) + 0.5)
cost = 1 + sum(t <= fame for t in TH)
b = BUDGET[cost]
kw = 'Multilingual' if r >= 75 else ('Local' if c['stats']['reach'] == 0 else None)
if kw == 'Multilingual': b -= 1 # evasion-like keyword is paid for out of the body
if kw == 'Local': b += 0 # Local = gains +1/+1 next to a same-country Location (conditional, no tax)
share = (a if a is not None else 50) / max(1, (a if a is not None else 50) + dp) # attention vs depth
pw = min(b - 1, max(1, round(b * share))); t = b - pw
return dict(title=c['title'], a=a, d=dp, r=r, fame=fame, cost=cost, P=pw, T=t, kw=kw,
trend=c['pageviews']['trendPercent'], daily=c['pageviews']['dailyAverage'])
rows = [derive(c) for c in cards]; n = len(rows)
def naive(c): # straw man: power = attention tier, toughness = depth tier, cost from their sum
ti = c['tiers']; pw = (ti['attention'] or 1 + 1) // 2 + 0; t = (ti['depth'] + 1) // 2
return dict(cost=max(1, min(6, round((pw + t) / 2))), P=pw, T=t)
nv = [naive(c) for c in cards]
def dominated_pairs(rs, use_kw=False):
k = 0
for x, y in itertools.permutations(rs, 2):
if x['cost'] <= y['cost'] and x['P'] >= y['P'] and x['T'] >= y['T'] and \
(x['cost'] < y['cost'] or x['P'] > y['P'] or x['T'] > y['T']) and (not use_kw or x.get('kw') == y.get('kw')):
k += 1
return k
print('cost distribution', sorted(collections.Counter(r['cost'] for r in rows).items()))
print('power distribution', sorted(collections.Counter(r['P'] for r in rows).items()))
print('toughness distribution', sorted(collections.Counter(r['T'] for r in rows).items()))
print('keywords', collections.Counter(r['kw'] for r in rows))
print('P/T by cost:')
for cst in range(1, 7):
g = [r for r in rows if r['cost'] == cst]
if g: print(' ', cst, len(g), collections.Counter(f"{r['P']}/{r['T']}" for r in g).most_common(6))
pairs = n * (n - 1)
print('strict-dominance pairs proposed', dominated_pairs(rows), 'of', pairs, '; same-keyword only', dominated_pairs(rows, True))
print('strict-dominance pairs naive ', dominated_pairs(nv), 'of', pairs)
# efficiency by fame quintile
q = sorted(rows, key=lambda r: r['fame'])
print('fame quintile: mean cost, mean (P+T)/cost proposed | naive (P+T)/cost')
idx = sorted(range(n), key=lambda i: rows[i]['fame'])
for k in range(5):
sl = idx[k * n // 5:(k + 1) * n // 5]
print(f" Q{k+1} fame {rows[sl[0]]['fame']}-{rows[sl[-1]]['fame']}: cost {statistics.mean(rows[i]['cost'] for i in sl):.2f} "
f"eff {statistics.mean((rows[i]['P']+rows[i]['T'])/rows[i]['cost'] for i in sl):.2f} | naive eff "
f"{statistics.mean((nv[i]['P']+nv[i]['T'])/nv[i]['cost'] for i in sl):.2f}")
top = sorted(rows, key=lambda r: -r['fame'])[:6] + sorted(rows, key=lambda r: r['fame'])[:3]
print('examples (top fame, bottom fame):')
for r in top: print(f" {r['title'][:34]:34s} a{r['a']} d{r['d']} r{r['r']} fame{r['fame']} cost{r['cost']} {r['P']}/{r['T']} {r['kw'] or ''}")
tr = [r for r in rows if r['trend'] is not None and r['trend'] >= 25 and (r['daily'] or 0) >= 20]
print('trending (+25% and daily>=20):', len(tr), f'{100*len(tr)/n:.1f}%')
+79
View File
@@ -0,0 +1,79 @@
"""Classify card-sample.json into Figure/Location/Event/Institution/Doctrine.
Order: P31 label rules (first rule that matches ANY P31 label wins, rule order = priority),
then category keywords, then description keywords, then deterministic fallback.
Usage: python3 -I types.py <card-sample.json> [--list]"""
import json, re, sys, collections
RULES_P31 = [ # (type, regex on a P31 label). Order matters: specific before generic.
('Doctrine', r'aspect of|aspect in|disease|clinical sign|list article|chemical entity'),
('Event', r'election|protest|battle|war\b|storm|nor.easter|cyclone|tornado|earthquake|disaster|event|match|final\b|'
r'season|championship|tournament|\brace\b|grand prix|scandal|annexation|treaty|incident|festival|referendum|'
r'conference|ceremony|time period|delegation'),
('Institution', r'artificial satellite|space station|space telescope|spacecraft|space probe'),
('Location', r'planet|natural satellite|\bstar\b|galaxy|nebula|planetary system|astronomical object|rainforest|reef|'
r'civili[sz]ation|empire|historical country|archaeological site|'
r'human settlement|settlement|village|town|city|commune|municipal|parish|county|district|region|province|'
r'township|hamlet|townland|census area|local government|community of|island|river|lake|mountain|plateau|'
r'waterfall|valley|bay|peak|geographical feature|historic district|park|state park|square|road|highway|'
r'building|castle|mosque|church|temple|cathedral|house|home|museum|station|bridge|monument|historic site|'
r'military base|battery|refinery|shopping|stadium|arch|tower|fort|palace|columbari|council'),
('Figure', r'^human$|fictional character|stock character|person|deity|orisha|loa\b|taxon|species|genus|breed|'
r'^family$|organism'),
('Institution', r'company|business|organi[sz]ation|association|society|party|agency|studio|band|musical group|team|club|'
r'university|college|school|institute|diocese|ecclesiastical|manufacturer|newspaper|magazine|film|album|'
r'song|single|musical work|composition|television|series|book|novel|video game|painting|award|position|'
r'aircraft|ship|steamship|vehicle|automobile|tram|railway line|route|typeface|software|product|brand'),
('Doctrine', r'concept|theory|theorem|mathematical|programming language|language|gene|protein|chemical|compound|'
r'disease|clinical sign|ideology|religion|discipline|field|cuisine|food|dish|drink|aspect|list article|'
r'particle|process|genre|form\b|game\b|branch of|class of|type of|tabular'),
]
RULES_CAT = [ # fallback on non-hidden category titles (lowercase)
('Figure', r'\bbirth|\bdeaths\b|living people|people from|\bspecies\b|described in \d|\bgenera\b|deities|characters'),
('Event', r'\belections\b|protests|\bbattles\b|disasters|\braces\b|\bseasons\b|\bevents\b|scandals|annexations|competitions'),
('Location', r'villages|communes|parishes|local government|populated places|geography|rivers|islands|buildings and structures|bridges|'
r'stations|parks|districts|townships|cities and towns|historic places'),
('Institution', r'companies|organi[sz]ations|\bfilms\b|albums|songs|novels|newspapers|television series|musical groups|'
r'aircraft|ships|typefaces|software|awards|teams|clubs'),
('Doctrine', r'theory|structures$|algebra|terminology|cuisine|drinks|desserts|ecology|languages|diseases|conditions|'
r'concepts|ranks|etymology|maps|atlases'),
]
RULES_DESC = [
('Figure', r'\b(painter|politician|actor|writer|player|born|species|genus)\b'),
('Event', r'\b(race|election|battle|match|protest|storm|war|competition)\b'),
('Location', r'\b(village|town|city|river|island|building|church|columbarium|station|park)\b'),
('Institution', r'\b(company|band|film|album|organi[sz]ation|team|aircraft|ship|newspaper)\b'),
('Doctrine', r'\b(concept|theory|structure|dessert|drink|dish|technique|class of)\b'),
]
TYPES = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine']
def classify(card):
labels = [i['label'].lower() for i in card.get('instanceOf') or []]
for t, rx in RULES_P31:
for l in labels:
if re.search(rx, l): return t, 'p31', l
cats = [c.lower() for c in card.get('categories') or [] if 'stubs' not in c.lower()]
for t, rx in RULES_CAT:
for c in cats:
if re.search(rx, c): return t, 'category', c
desc = (card.get('description') or '').lower()
for t, rx in RULES_DESC:
if re.search(rx, desc): return t, 'description', desc
# deterministic last resort: Doctrine (the residual "idea" class); never hash-random.
return 'Doctrine', 'fallback', ''
if __name__ == '__main__':
d = json.load(open(sys.argv[1])); cards = d['cards']
res = [(c, *classify(c)) for c in cards]
n = len(res)
by_t = collections.Counter(r[1] for r in res); by_src = collections.Counter(r[2] for r in res)
print('n', n)
for t in TYPES: print(f'{t:12s} {by_t[t]:4d} {100*by_t[t]/n:5.1f}%')
for s in ['p31', 'category', 'description', 'fallback']: print(f'src {s:12s} {by_src[s]:4d} {100*by_src[s]/n:5.1f}%')
print('labels w/o p31 match but has p31:', sum(1 for c,t,s,w in res if s!='p31' and c['instanceOf']))
print('cross-tab old faction x new type')
ct = collections.Counter((c['faction'], t) for c,t,s,w in res)
for f in sorted({c['faction'] for c in cards}):
print(f' {f:14s}', {t: ct[(f,t)] for t in TYPES if ct[(f,t)]})
if '--list' in sys.argv:
for c,t,s,w in res:
if [i['label'] for i in c['instanceOf']] == ['human']: continue
print(f"{t[:5]} {s[:4]} | {c['title'][:42]:42s} | {w[:40]}")
+171
View File
@@ -0,0 +1,171 @@
# Night 2 plan: critic / player-advocate review
Reviewer: critic. Sources: night2/PLAN.md, wd/docs/game/{DESIGN,CARD_DATA}.md, card-sample.json, wd/docs/night/{HANDBOOK,BOUNDARIES}.md, Night 1 report (`~/Desktop/night/night-lead/REPORT.md`; it is not in wd/docs/night). Ranked by severity, most severe first.
## Facts the plan doesn't state, but which decide everything
- **Mined cards are random articles.** `server/wiki.ts` uses `generator=random`. Nobody chooses Barack Obama. The real pool looks like card-sample.json: 34% stubs, villages, beetles, French communes, local elections. "Tetrated dodecahedron vs Obama" will be rare. The everyday matchup is *Dichromorpha viridis vs 1954 Gold Coast general election*. That's still funny in a deadpan way, but the design and its examples must be built for it, not for celebrity cards.
- **Supply is about zero, not 96 a day.** 12 cards in 16 days, all in one wallet (Eric's), all from day 1. Mining has effectively stopped.
- **Mobile can't mine.** `App.tsx` hides the mining panel when `isNativeApp()`, so an Android player can never get a real card.
- **14% of sampled cards are living people** (33/236 in "Living people"). Events include ongoing protests with deaths (*2024–2026 Cuban protests*, *2025 Tehreek-e-Labbaik Pakistan protests*), a *sex scandal*, an *annexation*, and *Organization of the Luftwaffe (1933–1945)*. The safety rules (§6) are needed tonight, not someday.
---
## S1 (blocker). "Real cards" + PvP is impossible today. This is Eric's decision, not the agents'.
Under a literal reading of point 1, exactly one person on Earth can play, and PvP has no opponent. Each option, measured against the request:
- **(a) Small decks of 7–10:** literal and honest. But only Eric qualifies, and with exactly 12 cards there's no deckbuilding, which is half of what makes MTG feel like MTG.
- **(b) Owned "commanders" plus a public filler pool:** this *is* the loaner system Eric just said was only for the demo, renamed. If agents choose it without asking, it's a quiet betrayal of the request.
- **(c) Draft from the chain's cards:** the cards are real mined cards, but the pool is the same 12 cards every match. It's degenerate until supply grows. On testnet, about 50 cards, it's fine.
- **(e) Off-chain editions:** prints cards with no proof of work and no consensus. It undermines what "mined" means. Reject it.
- **(d) Collection-as-deck:** this is (a) with scaling. Fine as the mechanism, but it doesn't solve the 0–3 card player.
**Fix:** before 21:30, put these questions to Eric. Per standing preference, agents don't start building until Eric gives an explicit go.
1. "Does Classic and ranked PvP require 100% owned mined cards? (Recommend: yes.)"
2. "Can a player with fewer than N owned cards play casual or practice matches with clearly labelled **proxies**? They're never ranked, never shown as owned, and appear greyed out with the stamp 'Proxy'. (Recommend: yes, for practice, AI and invite-link casual only.)"
3. "Is Draft from the whole chain's minted cards 'real cards'? Ownership would earn the first pick and a credit line in the recap. (Recommend: yes.)"
4. "Can your 12 cards be used as public bot and ghost decks? (They're your wallet.)"
5. "Should we fix the supply side, so mobile users can get real cards, given that mobile can't mine? Options: a desktop-mining CTA, gifting by transfer (an on-chain action by Eric, not by agents), or an unlock condition such as 'mine 1 card to enter ranked'."
**Default if Eric doesn't answer:** take the most literal reading. Ranked and Classic use owned cards only. Practice and AI use proxies, which look different. Draft uses chain-minted cards only. No editions. Record the decision in DESIGN.md §0 in Eric's own words.
**Design implication either way:** the format must be fun with a small deck. Recommend **one format with no deck minimum**: a 10-card deck at most, and if you own fewer, you play what you own plus visible proxies, casual only. The engine must handle running out of cards gracefully. Draw from a reshuffled graveyard (DESIGN-style "recursion") instead of losing to an empty library.
## S2 (blocker). PvP has no population. A ranked ladder tonight is wasted work, and unsafe.
Elo with one eligible player is theatre. Night 1's REPORT (known issues 2–3) also says hosted PvP trusts the host: the host picks the seed, there's no commit–reveal, and the UI log is built from full state and leaks hand contents. A ladder on top of that is cheatable.
**Fix, in order:**
1. **Invite-by-link casual PvP** first, made prominent on the Play screen. Eric can test it with a second account on testnet.
2. **Async "ghost" matches.** You play a bot piloting a real wallet's real deck (with that owner's opt-in), and the result is posted to the owner. This is the PvP that a population of five can actually have.
3. The **queue backfills with a bot after 30 s**, *labelled as a bot*. Never pass a bot off as a human.
4. Defer the ranked ladder until commit–reveal and `viewFor`-only logs land. Cut it tonight.
## S3 (high). An MTG clone built in one night will be worse than Edit War
Edit War had a real hook: each lane is judged by one Wikipedia stat. The plan replaces it with generic power/toughness/cost. MTG is fun because of hand-designed cards, the stack and instant-speed interaction, and deckbuilding across thousands of cards. Tonight has none of that: procedurally generated text, 12 cards, and no stack.
**Fix: name the smallest core that still feels like Magic**, and only that:
- Two players, 20 life, and a resource that grows by 1 a turn automatically. Locations add +1 when played (no land screw).
- Board of 5 per side. Figures attack. The defender makes one block per attacker, chosen by tapping a blocker and then an attacker. No first strike, trample or multi-block in v1.
- Events are **sorcery-speed only**. No stack, no priority passes, no opponent-turn interaction. Every response window doubles PvP round-trips and the time needed for UI work.
- One keyword per card at most, from a list of about 8 (Night 1 used 6, with property tests).
- **Keep a Wikipedia hook that MTG doesn't have**, or this is "MTG with worse cards". Candidate: home stat as the creature's "evasion" (an attention attacker can only be blocked by a card with attention ≥ its own), or the trend arrow as haste. One hook, kept and tested.
- **Keep Edit War playable as a mode.** The code exists; deleting it removes a working fallback.
## S4 (high). 360 px readability
An MTG board (two battlefields, hand, life, resources, rules text, combat arrows) doesn't fit 360 px if the cards carry generated paragraphs.
**Fix:**
- The card face on the battlefield shows: title (2-line clamp), type icon, cost, P/T, one keyword chip. The rules text and flavour live **only** in the tap-to-zoom sheet.
- Rules text has a hard limit of 90 characters, enforced by a test over the whole sample.
- Combat uses a "declare attackers → defender blocks → preview outcome → confirm" sheet, not drawn arrows.
- The QA gate is a 360×640 screenshot of a full board (5 + 5) on Android, attached to the UI PR.
## S5 (high). Night 1 process lessons the plan doesn't apply
What went wrong (REPORT plus handbook):
- The design froze at 23:01, but the balance numbers were measured before the #38 change, so the shipped seat-advantage figure is stale.
- 3 OOMs (tower-plus, and r350 twice).
- imac's Gitea MCP was down all night, so the council had to relay through night-lead.
- Squash merges of stacked PRs caused add/add conflicts.
- Wikimedia 429s came from our own sampler.
- On Node 20, 12 tests failed falsely.
**Fixes:**
- **Freeze rules on a schedule, and gate them on evidence.** Design frozen by 22:30 (one hour, not 45 minutes: this is a bigger redesign). Engine API by 22:45. The balance re-run happens on the final head, after the last engine PR, and its numbers go in the report with the SHA they were measured on.
- **Fewer, wider agents.** 7–8, not 10:
- designer and critic as one council pair
- an engine agent
- a card-derivation and text-generator agent (it owns the safety rules)
- a UI agent
- a PvP/host agent
- a wiki-client agent
- a lead and a review agent
Night 1's 17 agents produced conflict and relay overhead.
- **Pre-flight at 21:30:**
- run `get_me` on Gitea MCP on every machine
- `node:24-alpine` is the only test image
- all heavy work runs under `flock` on inspiron
- no stacked PRs: rebase-and-merge, or wait for the parent to merge
- **No network in tests.** Every test and sim reads card-sample.json and starter-cards.json, plus a new red-team fixture (§6). The **only** process allowed to call Wikimedia tonight is the new throttled client's own smoke test, at 1 request/s.
- **Use testnet for real-cards testing.** It has about 50 mined cards across wallets the team controls. Seed 3–4 test wallets with 1, 3, 8 and 20 cards by transfer *on testnet*. Never simulate mainnet supply by copying Eric's wallet.
- **Mainnet is read-only, and only if needed at all.** Read the 12 cards' public data so Eric's own deck can go into a fixture. Nothing is written.
## S6 (high). Ethics and safety: content rules for the deadpan generator
The joke only works if the game is respectful about the subject and absurd only in the juxtaposition. These rules are **requirements** with tests, owned by the card-text agent:
1. **No free-form generated prose about real people or events.** Templates only. No LLM, including LocalAI. That also keeps the output deterministic. The only article-derived prose is the extract's first sentence, quoted verbatim and attributed.
2. **Figures are never harmed, killed or humiliated in text.** Log verbs for a Figure leaving play come from an editorial whitelist: "was reverted", "left the battlefield", "was archived", "was withdrawn from the record". Banned for any card: killed, died, destroyed (for Figures), executed, assassinated, murdered, humiliated, crushed, slaughtered, raped, lynched. "Destroy target Institution" is fine.
3. **Mechanics never derive from sensitive attributes.** Category-keyword templates for Figures come from an **allowlist** of neutral occupation and field words (politicians, mathematicians, footballers, painters, alumni). Never derive a mechanic from: crime, conviction, scandal, illness, disability, cause of death, ethnicity, religion, sexuality, gender, nationality as a trait, victimhood.
- Country is allowed **only** as a neutral "Connected" link (shared P27/P17). It must never carry a modifier such as "French: −1".
- Birth and death years may appear in the type line ("Figure — 1949–2019"). Nothing triggers on death.
4. **Solemn subjects get a `solemn` flag.** It's set by P31 class (war, battle with casualties, massacre, genocide, terrorist attack, mass shooting, disaster, epidemic/pandemic, aviation or maritime accident, protest with deaths, war crime, the Holocaust) or by category words (massacres, genocides, terrorist incidents, disasters in, deaths in, murders, sexual abuse, victims, suicides).
- Solemn cards are playable. They get one fixed neutral effect ("Commemoration: gain 1 Citation; draw a card"), no damage or removal text, a plain log line ("entered the record"), and they are **never** used to name a battle or shown in a recap headline.
- Events in general never "deal damage to" a Figure. Removal comes from Doctrines and Institutions ("Revert", "Edit war").
5. **Glorification guard.** No "leader", "inspire" or "rally" keywords keyed on heads of state, military leaders or dictators. Every Figure's keyword comes from stats, type and faction only. A *Adolf Hitler* card must be a plain statted Figure with no buff-allies text. Test it.
6. **Living people (BLP):** the flavour text is the extract sentence only, and the recap uses only the card title. Any `Living people` card mentioned in a recap is linked to its article and nothing is asserted about the person. Card actions in text are attributed to "the *Barack Obama* card" or the commander, not to the person.
7. **Mint-time vandalism.** The extract is frozen at mint and may be a vandalised revision. Render flavour from the cached **current** extract when possible. Give node operators a data-only `hiddenFlavour: [pageId]` list and a report link on the card zoom sheet.
8. **Recap pages must not impersonate Wikipedia.**
- No Wikipedia wordmark or puzzle-globe logo, and no "From Wikipedia, the free encyclopedia".
- The header reads "WikiDeck match record", with a hatnote: *"This article is about a WikiDeck match. For the polyhedron, see Tetrated dodecahedron."* That's funny, honest, and keeps us clear of the trademark.
- CC BY-SA attribution for extracts and images, in References.
9. **Player privacy.** Shareable recaps are opt-in per match. Commanders show as the account display name or "Anonymous", never a wallet address unless the player chooses.
10. **Red-team fixture plus a sign-off gate.** `tests/fixtures/sensitive-cards.json` holds hand-written PageEnrichment for: Barack Obama, Donald Trump, Adolf Hitler, Jesus, Muhammad, Yemọja, September 11 attacks, The Holocaust, Sandy Hook Elementary School shooting, 2004 Indian Ocean earthquake and tsunami, COVID-19 pandemic, a living child actor, Pullman porter affair, *2024–2026 Cuban protests*, Cho Yang-ho, and Tetrated dodecahedron.
- A test snapshots their full rules text, log lines and a recap, then asserts the banned-verb list and the solemn rules.
- The snapshot file goes into the morning report **for Eric to read before anything is shared publicly**.
## S7 (medium). Tone: how deadpan fails, with examples
- **Failure modes:**
- *Wacky:* puns, exclamation marks, emoji, winks.
- *Cringe:* the generator "noticing" the joke ("In a surprising twist…").
- *Dull:* logs that read like a stack trace.
- *Mean:* adjectives about the losing side.
- **Rule:** the text never comments on how odd the matchup is. The comedy is entirely in the nouns.
- **Card rules text.**
- DO: "*Tetrated dodecahedron* — Doctrine — Ideas. Figures you control with Depth 7 or more get +1/+1."
- DO: "*Barack Obama* — Figure — People, 1961– · 3/4 · Connected (+1/+1 while you control a Connected card)."
- DON'T: "Yes He Can! Obama gets +2 power because he's the president!"
- DON'T: "This shape is so complex it hurts your opponent's brain."
- **Match log.**
- DO: "Turn 6. *Cho Yang-ho* (4/5) attacked. *Dichromorpha viridis* (1/2) blocked and was reverted. Commander Eric cited *Tetrated dodecahedron*: *Cho Yang-ho* +1/+1 until end of turn."
- DON'T: "Cho Yang-ho SQUASHED the grasshopper lol." Also don't use "killed", or use any adjective (brutal, humiliating, heroic).
- **Recap.**
- DO: "The **Battle of the Tetrated Dodecahedron** was a WikiDeck engagement fought on 17 November 2026 between the forces of Eric and Bot (Normal). It lasted nine turns and ended in a decisive victory for Eric.[1] Contemporary accounts note the deployment of *Barack Obama* in the fourth turn.[2]"
- The infobox field is "Cards withdrawn", **not** "Casualties". Battles are named after the decisive non-Figure, non-solemn card; fall back to "Match of 17 November 2026".
- DON'T: "Obama was humiliated by a shape," or "the bloodiest battle in WikiDeck history."
- **Dull guard:** vary sentences by deterministic seed across 3–4 synonymous templates per event, and use citation numbers [n] that link to the card's real article. That small Wikipedia texture is most of the charm.
## S8 (medium). "Connected" will almost never fire on random articles
Two random articles almost never link to each other. Fetching `prop=links` per card is costly, at hundreds of links a page, and it doesn't fit the 1 request/s budget.
**Fix:**
- Connect cards on cheap shared Wikidata claims fetched once per card at first sight and cached for good: country (P17/P27), century (from P569/P571/P585), and same P31 superclass or faction. Leave out the article link graph tonight.
- Measure the fire rate on card-sample.json (random pairs) and on Eric's 12. Target 15–30% of pairs. If it's lower, the mechanic is invisible.
## S9 (medium). Wikimedia politeness (point 7): good plan, three gaps
1. The plan never says **who decides the production UA**. REPORT next step 8 leaves it to Eric. Ship the default as `WikiDeck/<version> (node: <PUBLIC_ORIGIN>; operator contact required)`, refuse to start the enrichment client without a contact configured, and leave production config to Eric.
2. Rate limits must be **per egress IP**, but all of Eric's nodes share one IP. Use one shared limiter per host IP: a single node acts as the Wikimedia proxy for the cluster, or the budget is split statically.
3. Set a request budget per match: **zero Wikimedia calls during a match.** All P31, claims and trend data are fetched at deck validation or lobby time from the cache. Trending's live stats come from the daily refresh.
## S10 (medium). Modes under the new engine (point 5)
Draft and Trending must be re-specified, not just "kept":
- Draft with a 12-card pool must deal from **all chain-minted cards**, or Eric must decide (S1-3).
- Trending uses the daily cache (S9).
- The house-rules JSON schema changes with the engine. Version it (`rulesetVersion: 2`) so Night 1 mode files on testnet nodes are rejected cleanly instead of misread.
## S11 (low). Story (point 3) depends on the recap
The plan's "story" is Connected plus the recap. Given S8, the recap and log carry the whole of point 3, so prioritise them over the ladder. The recap is cheap (a deterministic template over the match log) and is the most "Eric" deliverable.
## Scope: what gets built, and what gets cut first
**Build, in this order:**
1. The throttled Wikimedia client and cache. Nothing else calls Wikipedia.
2. Card derivation (type, faction, P/T, cost, keyword) with safety rules and the red-team test.
3. The smallest MTG core engine plus bots.
4. A 360 px match UI.
5. Invite-link PvP and ghost or bot matches.
6. The match log and battle recap.
7. Draft and Trending ported.
**Cut first:** the ranked ladder and Elo, the Wikipedia link graph, instant-speed Events, the Citations resource as a second currency (fold it into one keyword), and the "editions" idea.
## Decisions for Eric (to ask before kickoff, all in one message)
1. Real-cards strictness (S1 questions 1–3).
2. Use of his 12 cards as public bot and ghost decks.
3. A mobile path to owning cards.
4. Keep Edit War as a mode? (Recommend: yes.)
5. Sign-off on the safety rules in S6, especially solemn Events and living persons.
6. Production User-Agent and contact.
7. Are shareable recaps public by default? (Recommend: opt-in.)
+272
View File
@@ -0,0 +1,272 @@
# Night 2 plan review: data analyst
Inputs: `docs/game/card-sample.json` (236 random illustrated cards), `starter-cards.json`, `shared/enrichment.ts`, `shared/testnet.ts`, `server/{wiki,enrichment,wikimedia-user-agent}.ts`, `server/testnet/{http,miner}.ts`.
Scripts (all `python3 -I`, offline, no API calls): `night2/analysis/types.py`, `stats.py`, `fields.py`, `connected.py`.
**Caveat:** the type rules were tuned on this same sample, so the in-sample accuracy is optimistic. Anything marked *(memory)* comes from my knowledge of the Wikimedia APIs, not from a live check, because we are rate-limited.
## 1. Typing (P31, then categories, then description, then a residual)
The classifier in `analysis/types.py` checks the rules in **priority order**. The first rule that matches *any* P31 label wins. If nothing matches, it tries non-stub category titles, then the description. If all three fail, the card becomes **Doctrine**, which is the residual "idea" class and is deterministic, never hash-random.
| Type | n | share | Mostly |
|---|---|---|---|
| Figure | 86 | 36.4% | human 64, taxon 16, breed, deity, stock character, family |
| Location | 78 | 33.1% | villages, communes, rivers, buildings, parks, roads |
| Institution | 32 | 13.6% | companies, bands, films, parties, aircraft, ships, awards |
| Event | 21 | 8.9% | elections, protests, storms, matches, team seasons |
| Doctrine | 19 | 8.1% | genes, diseases, maths, cuisine, lists, etymology |
| Decided by | n | share |
|---|---|---|
| P31 | 222 | 94.1% |
| category fallback | 12 | 5.1% |
| description fallback | 2 | 0.8% |
| residual (Doctrine) | 0 | 0% |
- **Unclassified rate:** 0% in-sample, down from 14% ("Other") under Night 1's faction rules. 13 cards have no P31, and one card's P31 matched no rule.
- **Accuracy:** I judge about 8 of 236 (about 3–4%) to be debatable or wrong.
- **Expected out of sample:** about 5–10% would reach the category or residual steps on regex alone. That is why the P279 step below matters.
**Hard or misclassified examples:**
| # | Card | P31 | Result | Problem |
|---|---|---|---|---|
| 1 | Buky, Lunugala, Žižki, Laukhella | human settlement | Location | **Existing bug:** Night 1's `\bhuman\b` faction rule puts these 4 villages in *People*. Use `^human$`. |
| 2 | Lewis and Elizabeth Bolton House | single-family detached home | Location | Night 1 calls it *Works* because the label contains "single". Substring rules bite. |
| 3 | Corruption in Kazakhstan | aspect in a geographic region | Doctrine | "region" pulls it to Location unless an "aspect of/in" rule runs first. |
| 4 | 2023 Seville municipal election | municipal election | Event | "municipal" pulls it to Location unless Event outranks Location. Rule order is load-bearing. |
| 5 | Agda (programming language) | functional PL; free software | Institution | Several P31 labels disagree (Doctrine vs product). Tie-breaking is by type priority, not by label order. |
| 6 | Diocese of Mindelo | Diocese of the Catholic Church | Location | "church" matches. It is really an organisation (Institution). |
| 7 | Region Östergötland | county council of Sweden | Location | A governing body, so Institution. "county" matches first. |
| 8 | Christianity in the 5th century | events in a specific year or time period | Event | A history overview. Doctrine fits better. |
| 9 | NRHP listings in Yates County | Wikimedia list article | Doctrine | A list is not a thing. Consider a neutral "Index" type or rerolling at mint (consensus says no). |
| 10 | Dojikko; Tracheal collapse | stock character; type of animal disease | Figure; Doctrine | A trope as a Figure is fun but debatable. The disease was a Figure until "animal" was removed from the Figure rule. |
| 11 | Figueiredo (Guimarães) | former freguesia of Portugal | Location (via category) | Local admin-unit names defeat English regexes. Only the categories rescued it. |
| 12 | *(memory)* Rosetta Stone (stele), Apollo 11 (crewed spaceflight), ISS (space station) | | residual, residual, Institution | Famous starter cards fall through, or hit "station" and become a Location, unless explicit rules come first. |
**Proposed rules** (as implemented in `analysis/types.py`):
1. **Doctrine overrides first:** `aspect of|in`, `disease`, `clinical sign`, `list article`, `chemical entity`.
2. **Event:** `election`, `protest`, `battle`, `war`, `storm`, `match`, `final`, `season`, `race`, `grand prix`, `scandal`, `annexation`, `time period`, `delegation`.
3. **Institution overrides:** artificial satellites, space stations and space probes.
4. **Location:** settlement and administrative-unit words, geography, celestial bodies, `civilization`, `empire`, `historical country`, built structures.
5. **Figure:** `^human$`, `taxon`, `species`, `genus`, `breed`, `deity`, `character`, `^family$`.
6. **Institution:** organisations, companies, teams, creative works, vehicles, positions, awards, typefaces.
7. **Doctrine:** concepts, theories, genes, languages, cuisine, genre, form, process, `type of`, `class of`.
**Production recommendation** (the regex rules above are the fallback):
- Resolve each P31 class through **P279 (subclass of), up to 4 hops**, against a curated table of about 200 anchor classes. For example: Q5 → Figure, Q16521 → Figure, Q486972 (human settlement) → Location, Q1656682 (event) → Event, Q43229 (organisation) → Institution, Q17537576 (creative work) → Institution, Q151885 (concept) → Doctrine.
- **Class cache:** the sample has only **141 distinct P31 classes in 236 cards**. Class lookups saturate quickly, cost under 0.1 requests per card amortised, and are cached forever.
- **Fallback chain:** P279 anchors → label regex → category regex → description regex → **Doctrine**.
- **Freeze the result per card:** store it in the card profile (§3) so that a later Wikidata edit cannot retype a card someone owns.
**Deck consequence:** Event and Doctrine are scarce.
| Type | P(none in 10 random cards) | P(none in 7) |
|---|---|---|
| Event | 39% | 52% |
| Doctrine | 43% | 55% |
| Institution | 23% | 36% |
| Location | 1.8% | 6% |
| Figure | 1.1% | 4% |
- **Instants and enchantments:** a deck built from random mints often has none. The core loop must not need them.
- **Resources:** this argues for a fixed per-turn income (as plan C says). With Locations as the only resource, about 6% of 7-card decks would have no resource at all.
## 2. Stats: percentiles → cost, power, toughness (`analysis/stats.py`)
**Facts that drive the design:**
- **No independent signal in the raw fields.** pageBytes, languageCount and monthly views are monotonic in depth, reach and attention, so their percentiles are identical. They add nothing beyond the three scores.
- **attention and depth correlate** (ρ 0.61), and **reach is independent** of both.
- **trendPercent is live, small and noisy.** Only 2.1% of cards pass the Night 1 gate (+25% and ≥20 views a day).
- **A new independent-ish signal** is available from the on-chain `months[]`: the volatility (coefficient of variation) of the 6 monthly views, median 0.22. Its ρ is −0.52 with attention, −0.30 with depth and −0.19 with reach. It could drive a "Volatile" keyword.
**Proposal:**
1. `pct_s` for attention, depth and reach, using the §1.1 counting against the sample's 99 cut points (unchanged from Night 1).
2. `fame` = the mean of the three percentiles. Cost = 1–6, using the v1.1 `costThresholds` [26, 39, 51, 63, 78] (unchanged).
3. **The body budget depends on cost only:** P+T = [3, 4, 6, 8, 10, 12] for costs 1–6, which is MTG's vanilla curve (2/1, 2/2, 3/3, 4/4, 5/5, 6/6).
4. **The shape comes from the stats:** power = round(budget × pct_a / (pct_a + pct_d)), clamped to [1, budget−1], and toughness is the remainder. Attention reads as "loud", depth as "sturdy".
5. **Reach gives a keyword, paid for from the body.**
- **pct_r ≥ 75 → Multilingual** (evasion-like), costing −1 from the budget.
- **reach = 0 → Local** (a conditional bonus with a same-country Location, no tax).
- Local covers the 18% of cards with reach 0.
6. **Non-Figures use the same budget as effect size:**
- **Event:** deals ⌈budget/2⌉.
- **Location:** P=0 with T=budget, or a per-turn bonus.
- **Doctrine:** ±1 effects, scaled by cost.
- **Institution:** a utility ability.
7. **Trend:** ±1 power, in Trending mode only, using live data frozen at match start.
**Resulting distribution (236 cards, every card rated as if it had a body):**
| cost | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| cards | 30 (13%) | 48 (20%) | 51 (22%) | 48 (20%) | 35 (15%) | 24 (10%) |
| most common P/T | 2/1, 1/2 | 1/3, 3/1, 2/2 | 3/3, 4/2, 2/4, 5/1 | 3/5, 4/4, 5/3 | 5/5, 4/5, 5/4 | 6/5, 6/6, 5/6 |
| Measure | Value |
|---|---|
| power, 1..7 | 38 / 43 / 53 / 33 / 42 / 26 / 1 |
| toughness, 1..7 | 43 / 43 / 50 / 30 / 53 / 16 / 1 |
| keywords | none 139, Multilingual 55, Local 42 |
**"Famous isn't strictly better" check:**
- **Strict dominance** means another card with cost ≤, power ≥ and toughness ≥, and strictly better in at least one.
- **Proposal:** 0 of 55,460 ordered pairs among cards with the same keyword. All 945 raw pairs are cases where a keyword costs one point of body, which is intended.
- **Straw man:** with P and T taken directly from the attention and depth tiers and cost derived from their sum, **3,058 pairs**.
- **Efficiency, (P+T)/cost by fame quintile:** Q1 2.64 (the cheap 2/1s), then Q2–Q5 at 1.90, 1.96, 1.95 and 1.89.
- **Famous cards are bigger and pricier, never more efficient.** Pallas's cat (fame 98) is a cost-6 6/5 Multilingual. Dr. John L. Butler House (fame 8) is a cost-1 1/2 Local.
- **Remaining risk:** in a small-deck game with fixed income, a 6-drop can still dominate the late game. Balance that in the simulator (Night 1's `scripts/sim/`), not in derivation.
## 3. Rules-text inputs (`analysis/fields.py`)
| Field | Where | Reliability (sample) | Use for abilities | Extra cost |
|---|---|---|---|---|
| title, extract (≤900 chars), image, legacy category, pageId, revisionId | **on-chain** (`Article`) | 100%. Extract ≥40 chars by filter. | Flavour text is the first sentence of the extract. Years and "(born …)" can be parsed from the extract. | 0 |
| pageBytes, languageCount, 6 months of views, dailyAverage, trendPercent, attention/depth/reach | **on-chain** (`MintStatsSnapshot`) | 100% (attention null under 1%) | Cost and body, Multilingual/Local, Volatile, Rising/Fading | 0 |
| description (short) | live: WP `prop=description` | 90% | Keywords such as "Species of", "Village in", "film by" | in the batched meta query |
| non-hidden categories | live: WP `prop=categories` | 100%, median 5 | Year in 55% of cards; births/deaths 25%; establishments 10%; stub 34%; country words 52% | same query |
| wikidataId | live: `pageprops` | 100% | Key for all Wikidata data | same query |
| P31 (instance of) | live: Wikidata | 94% | **Type** | 1 per 50 cards |
| Dates: P569/P570 birth and death, P571 inception, P585/P580 point in time and start | live: Wikidata | *(memory)* Common for humans, organisations and events; rare for taxa and concepts | Era keywords ("Ancient", "19th-c."), "Contemporary" links | same `wbgetentities` |
| Coordinates: P625, or WP `prop=coordinates` | live | *(memory)* Nearly all Locations, few others | "Adjacent" (distance), hemisphere, lat/long flavour | in the batched meta query |
| Country: P17 / P27 | live | *(memory)* Most places, people and organisations | "Compatriot" connection | same `wbgetentities` |
| Outlinks: `prop=links` | live | 100% | Connected (§4) | 1–6 per card, continuation |
**Request cost per card, first sight, cached forever:**
- **Batched, amortised:** about 1.5 requests per card.
- 1/50 for the WP meta query (description, categories, pageprops, coordinates)
- 1/50 for `wbgetentities&props=claims`
- under 0.1 for class/P279 lookups
- about 1.2 for outlinks
- **Unbatched (a single card at a time):** about 4 requests.
- **Payload warning *(memory)*:** `props=claims` for famous items can be **hundreds of KB to over 1 MB** (Q76, Barack Obama). It cannot filter by property.
- **Option 1:** a WDQS SPARQL `VALUES` query for the ~12 needed properties, covering up to about 100 items per query.
- **Option 2:** accept the size and only ever fetch each item once.
**Request cost per match**, two decks of 10 cards:
- **Warm caches:** **0–1**. That is the links matrix (§4) if per-card outlinks aren't cached.
- **Trending mode:** add up to **20 per-article pageview requests** for today's figures. These can't be batched, so refresh them in a daily background job, never at match start.
- **Cold worst case:** about 23 requests, which is 23 s at 1 request per second. So prefetch when a card is minted or received, or when a deck is saved, never at queue time.
**Frozen vs live:**
- **On-chain (frozen by consensus):** only `article` and `statsSnapshot`.
- **Everything else is mutable.** That covers type, dates, country, categories and links.
- **Card profile:** freeze it once into an off-chain record, `{tokenId, pageId, mintRevisionId, fetchedRevisionId, wikidataRev, type, faction, dates, country, coords, outlinks hash}`. Cache it forever, and log it in the match record so replays and recaps are deterministic.
- **Why not the mint revision:** fetching categories or links *as of* the mint revision needs `action=parse&oldid=`, which is costly because of the parser-cache miss *(memory)*. Freeze at first sight instead, and record which revision was used.
- **Agreement between hosts:** different hosts could freeze different profiles. To fix that, a node publishes its signed profile file per tokenId, and hosts adopt the first one seen.
## 4. Connected: cheap relationship detection (`analysis/connected.py`)
**Measured on random pairs** (27,730 pairs):
| Relation | Pairs | In a 10-card deck (≥1 pair) |
|---|---|---|
| any shared category (including generic ones such as "Living people" or "1948 births") | 1.96% | |
| shared **specific** category | **0.04%** | 2% |
| same P31 class | 7.9% (mostly human/taxon) | |
| same P31, excluding human and taxon | 0.22% | |
| same country (text proxy for P17/P27) | 7.4% | 91% |
| same century (text proxy for dates) | 16.6% | |
| country OR century OR specific category | 21.5% | 99% |
**Direct article links between two random cards will almost never fire.**
- Shared specific categories are already 0.04%, and links are rarer still between random stubs.
- Obama ↔ White House only works because both are famous starter-style titles.
- **Proposed tiers:**
- **Linked (rare, strong):** a direct link in either direction.
- **Compatriot:** same P17 or P27.
- **Contemporary:** same century, from P569, P571 or P585.
- **Kin:** same P31, excluding human and taxon.
**Methods compared:**
| Method | Cost | Notes |
|---|---|---|
| Pairwise links matrix: `action=query&titles=A1…An&prop=links&pltitles=A1…An&pllimit=max` | **1 request per match** for up to 50 titles; at most 400 edges for 20 cards, under the 500 limit | Gives both directions for every pair. Uses current revisions. Misses links that go through redirects, unless you add `redirects` and also check the redirect titles. |
| Per-card outlinks (`prop=links`, ns0), cached | 1–6 requests per card, once | Intersection is local and free, so it scales to the whole chain. Network-wide this is at most 96 × about 2 ≈ 200 requests a day. **Recommended.** |
| `prop=linkshere` (backlinks) | Famous pages: thousands to millions, many continuations | **Avoid.** Outlinks from both sides already cover A↔B. |
| Shared Wikidata values (P17, P27, P131, P106, P101, P361, dates) | Included in the card profile fetch | Most useful in practice. Gives readable reasons ("both Polish"). |
| Categories | Included in the meta fetch | Too sparse except for generic categories, which are meaningless. Use only for era and country when Wikidata lacks them. |
**Caching:**
- **On first use:** compute each card's outlinks and profile once, keyed by `(pageId, fetchedRevisionId)`, and pin them to the `tokenId` forever.
- **During a match:** the host computes the edge list at match start from cached profiles, which needs no requests, and writes it into the match log.
- **Re-fetching:** never re-fetch for an owned card. An optional "re-sync" can be a deliberate, logged action.
## 5. Wikimedia politeness *(memory: not checked live tonight)*
**Rules:**
- **User-Agent policy:**
- The policy asks for a descriptive UA with contact details: `Tool/version (https://site; contact@…) lib/ver`.
- Generic or library-default UAs may be throttled or blocked. Browsers must use `Api-User-Agent`.
- **Finding:** our defaults have **no contact at all**. That covers `Wikideck/0.1 (experimental Wikipedia article cards)`, the enrichment UA, and the sampler UA `WikiDeckCardDataSampler/0.1`. Contact is opt-in only, through `WIKIDECK_USER_AGENT`. This is likely part of why the shared IP got 429.
- **Action API etiquette:**
- Make requests **serially**, not in parallel. There is no fixed read limit, but use "reasonable" volume.
- Send `maxlag=5` on non-interactive requests, and on a `maxlag` error wait for `Retry-After`.
- Batch: `titles`/`pageids` take 50 per request (500 with the bot flag), and `pltitles` 50 likewise.
- Use continuation, `Accept-Encoding: gzip`, and `formatversion=2`.
- **REST API (`/api/rest_v1`):** the historical guidance was ≤200 requests per second per client. Since 2025 Wikimedia has tightened limits on unauthenticated automated traffic and enforces them per IP/UA. Treat any published number as a ceiling, not a target.
- **API Portal or token traffic:** I recall anonymous traffic at about 500 requests an hour and a personal token at about 5,000 an hour. **Unverified.**
- **Pageviews (AQS):**
- The documented limit was about 100 requests per second per client.
- It is **per article and has no batching**.
- Daily data lands once a day, a few hours after 00:00 UTC, so refreshing more than once a day is waste.
- **Wikidata:**
- `wbgetentities` takes up to 50 ids per request; use `props=` to slim the response.
- WDQS allows about 60 s of query time per minute and 5 concurrent queries per client, and blocks after repeated errors.
- **Always:** honour `429`/`503` with `Retry-After`, use exponential backoff, and cache.
**Concrete node defaults:**
| Setting | Default |
|---|---|
| Client | one shared `WikimediaClient` per **process, and budget per egress IP** (several nodes or agents behind one IP must share it) |
| Rate | token bucket: **1 request/s sustained, burst 3**, **1 in-flight per host** (en.wikipedia.org, wikimedia.org, wikidata.org) |
| Daily cap | 20,000 requests a day per node (configurable). Past it, serve from cache or 503. |
| maxlag | `maxlag=5` on every Action API call from background jobs |
| 429/503 | honour `Retry-After`, else 5 s × 2ⁿ up to 15 min. **Circuit breaker:** after 3 consecutive 429s, stop all Wikimedia calls for 10 min. |
| Batching | 50 pageids/titles, 50 Wikidata ids, links matrix per match |
| UA | `WikiDeck-node/<ver> (+https://<node host>; <operator contact>)`. **Start-up warns loudly**, or refuses in prod, unless a contact is set. |
| Cache | on disk. Profiles and outlinks are immutable (keyed by tokenId and revision). Pageviews keyed by (title, day). ETag / `If-None-Match` on REST. |
| Background | one daily job after about 06:00 UTC refreshes live views for cards in active decks only |
**Mining load: a real issue the plan doesn't list.**
- **What a template costs:** `POST /api/mining/template` calls `wikipediaArticles.random()`, plus `getFresh()` enrichment, on **every template**. That is 3 or more Wikimedia requests (`server/testnet/http.ts:122`).
- **How often:** each miner asks for a new template whenever the tip changes (`server/testnet/miner.ts:89`).
- **Load:** M miners make **about 3M requests per block, all in a burst at each new tip**, or 288·M a day. With 100 miners that is 28,800 a day, which breaks the cap above.
- **Fix:** prefetch a small pool of article+snapshot pairs in the background at 1 request/s, and serve each template from the pool.
- `grnlimit=10` yields about 4.4 usable articles per request.
- This changes no consensus rules.
- Wikimedia load then stays at about 2–3 requests per block, whatever the number of miners.
## 6. Supply
- **Production:** at most 96 blocks a day means at most 96 cards a day: 672 a week, about 2,900 a month, 35k a year.
- **Mainnet reality:** 12 cards, all mined on 2026-11-01. That is **0.75 a day averaged over 16 days**; mining has effectively stopped.
- **Model:** with M equal-hashrate miners, each expects 96/M cards a day, so the time to N cards = **N·M/96 days**. This assumes continuous full block production.
| Active miners M | N=7 | N=10 | N=20 | N=40 | N=60 |
|---|---|---|---|---|---|
| 1 | 1.8 h | 2.5 h | 5 h | 10 h | 15 h |
| 10 | 0.7 d | 1.0 d | 2.1 d | 4.2 d | 6.3 d |
| 50 | 3.6 d | 5.2 d | 10 d | 21 d | 31 d |
| 100 | 7.3 d | 10 d | 21 d | 42 d | 63 d |
| 500 | 36 d | 52 d | 104 d | 208 d | 313 d |
**Caveats:**
- **Mining is a Poisson lottery.** At M=100, 10 cards take a mean of 10.4 days, but about 15 days at the 90th percentile.
- **Hashrate is skewed.** The *median* miner gets well under 96/M; a phone-class CPU gets about 0. Non-miners only get cards through trades.
**Implications for deck size:**
- **Rule of thumb:** a deck size D is reachable in T days only if D ≤ 96·T/M.
- For a 1-week ramp with 100 miners, D ≤ 6.7.
- **40–60-card constructed decks** need M ≤ about 12, or months of play.
- **Recommendation: a 7–10-card constructed deck**, plan option (a).
- Every card is unique anyway, so this is effectively Highlander, with recursion and reuse.
- **Collection-as-deck**, option (d), covers players with fewer than 7 cards.
- **Draft, option (c), is supply-friendly**, but only once the chain holds enough cards.
- An 8-player draft of 3×15 needs 360 cards (about 4 days of full production); a 2-player draft needs about 60.
- **Today's 12 cards cannot feed even one draft.**
- **The cold start is the blocker, not the steady state.** Eric must decide one of two things for launch week:
- accept a loaner or shared pool (plan option (b), which conflicts with requirement 1), or
- accept that PvP only works after someone mines continuously for a day or two.
+278
View File
@@ -0,0 +1,278 @@
# Night 2 review: game designer
**Verdict: approve the direction with changes.** Do the MTG-style duel, the article-derived types, the Connected bonus and the battle recap. The plan has one gap: it has no answer to supply, and Open problem 1 decides whether any of the rest gets played. My answer is a **15-card deck made of your owned article cards plus Basics**. Basics are non-article "process" cards, the equivalent of MTG basic lands. **Draft** from the chain's whole register is the front door for players who own few cards. Rules core: **no stack, no land cards, fixed income, attack/block with single blocks, 16 Notability.** Everything below is data in the existing rules-as-data style.
---
## 1. Supply (Open problem 1)
**The facts:** mainnet holds 12 cards, all in one wallet. At most about 96 a day can be mined, and the real rate is far lower. For months nearly every player will own 0–3 cards. No version of "real cards only" fills a 40-card deck. The question is how the rules bend.
### Recommendation: "Collection + Basics" (options a and d, with the MTG basic-land argument)
- **Deck:** exactly **15 cards**.
- **Article slots:** any number of your owned mints, up to 15. Each mint can appear once, since it is unique. Different mints of the same `pageId` can appear up to 2 times.
- **Basics** fill the rest, at most 3 copies of each.
- Owned and loaner copies no longer mix (v1 §2 is retired).
- **Basics are not articles.** They are a fixed set of 8 Wikipedia process cards that nobody owns and anyone can use in any number. Listed in §2.4.
- **The argument for Eric:** in Magic, about 40% of every deck is basic lands that nobody collects, and the deck is still "your deck". Here, **every article in your deck is one you mined**. The letter of the requirement holds for articles. It bends only in that the deck isn't made *only* of articles.
- **Signature card:** before the match you name one owned article as your Signature. It **starts in your opening hand**, in addition to the 5 cards you draw.
- So a player with 1 card plays that card in every game.
- The recap's infobox lists it under "Commanders".
- **Small deck, high visibility:** a typical game lasts about 8 turns each, so you see 5 + 8 = 13 of your 15 cards. Your owned cards nearly always show up.
- **Running out of cards doesn't lose the game.** When your library is empty, shuffle your Deleted pile (the graveyard) into it. This is option (a)'s "recursion and reuse".
- **Power parity:** an article and a Basic of the same cost are worth about the same, with articles roughly 10% ahead from keywords and Connected (sim target: an all-Basics deck wins 42–48% against a 12-article deck).
- Owning cards buys **variety, story and a modest edge**. It doesn't decide games. Ranked Glicko absorbs the rest.
### What a new player does
| Owns | Practice / AI | Casual PvP | Ranked | Draft |
|---|---|---|---|---|
| 0 cards | Tutorial: the Basics deck plus 3 Archive cards, the existing loaners in a grey "Not owned" frame | Basics-only deck allowed | no (one article needed) | **yes: main path** |
| 1–5 | any | Collection + Basics; the Signature guarantees their card | yes | yes, plus the owner perk |
| 6–15 | any | mostly articles | yes | yes |
Casual matchmaking groups players by article count (0–2 / 3–7 / 8+). Ranked has one ladder.
### Fallbacks, in order
- **Fallback A (if all-Basics games test as dull):** the "Archive ramp".
- Up to `max(0, 8 − owned)` Archive loaner articles may fill slots, and they shrink as you own more.
- Archive cards are grey-framed and listed in the recap as "(Archive, not owned)".
- This is option (b) with a sunset clause. **Eric must accept it explicitly.**
- **Fallback B (strictest "real mints" reading):** "Register as shared library".
- Both players draw from one shared library: every mint on the chain, whoever owns it, plus Basics.
- Your owned cards sit in a Command zone. You can cast them at any time, and they return there with +1 cost tax.
- Every article in play is then a real mint, but your *deck* is no longer yours. It also needs ≥ 30 mints before games stop repeating.
### What Eric must decide
1. Are Basics acceptable as a deck's "lands"? I recommend yes.
2. Archive loaners below 8 owned cards: allowed, or Basics only? I recommend Basics only at launch, with Fallback A behind a ruleset flag.
3. Can owning cards give a small edge in ranked? I recommend yes, capped by the parity target above.
---
## 2. Rules core (Open problem 2)
**Is MTG combat too complex for one night?** Not if the rules are cut to the bone: no stack, single blocks and one main phase. It is the only part that gives "feels like Magic", so keep it. The lane engine, `Topic` and `Portal` are retired. `rng.ts`, `ruleset.ts`, `modes.ts`, `validateDeck`, `replay`, `viewFor` and serialisation carry over.
### 2.1 Setup and turn
- **Notability:** each player starts at **16** Notability (the life total). Reaching 0 loses.
- The log reads: "*X* was nominated for deletion. The result was **delete**."
- **Opening hand:** draw 5, plus your Signature. One free mulligan: shuffle, draw 5, put 1 on the bottom.
- **First player:** skips the first draw. The second player gets **Second Opinion**, a 0-cost token: "Gain 1 Citation this turn".
- **Turn:** (1) **Refresh:** Citation maximum +1 (to at most 7, plus Territory), Citations refill, permanents untap. (2) **Draw** 1. (3) **Main:** play cards in any order. (4) **Combat.** (5) **End:** damage clears, "until end of turn" effects end, hand limit 7. No second main phase.
- **Resources:** fixed income, the Hearthstone model. **No land cards, so no land screw.**
- Locations add ramp (+1 maximum each, at most +2 from Territory in total). Max Citations is 9.
- **Summoning sickness:** a Figure can't attack the turn it enters ("Pending review"). Trending removes this.
### 2.2 Combat
- **Attack:** the active player taps any untapped Figures to attack. They attack the opponent only, not permanents.
- **Block:** the defender assigns at most one blocker to each attacker. Each blocker blocks one attacker. Locations with Garrison may block.
- **Damage:** simultaneous. Blocked pairs trade damage, and an unblocked attacker deals its power to Notability.
- No trample and no first strike in v1. That is about 150 lines of engine, and it is easy for bots.
### 2.3 Interaction without a stack
- **There is no priority, and nothing happens at instant speed.** That is the right call for online PvP on phones, because priority passes cost latency and clock time. Events are sorcery-speed.
- **v2, cut tonight:** *Pending changes*, Events set face-down that trigger on a condition (like Hearthstone's Secrets). They add interaction on the opponent's turn without priority passes.
### 2.4 Basics (the 8 process cards, max 3 copies each)
| Basic | Type | Cost | Text |
|---|---|---|---|
| Anonymous Editor | Figure | 1 | 1/2 |
| Established Editor | Figure | 3 | 3/3 |
| Administrator | Figure | 5 | 4/5. When this enters, destroy target Figure with power 2 or less. |
| Citation | Event | 1 | Put a +1/+1 counter on target Figure. |
| Revert | Event | 2 | Return target Figure or Doctrine with cost 3 or less to its owner's hand. |
| Talk Page | Event | 2 | Draw 2 cards, then discard 1. |
| Speedy Deletion | Event | 4 | Destroy target Figure. |
| Sandbox | Location | 1 | Territory. Garrison 0/1. |
### 2.5 Length
- **Clock:** 60 s per turn plus a 5-minute bank per player.
- **Turn cap:** at the end of turn 12 (each player's), the player with more Notability wins. A tie goes to the higher total power on the battlefield, then to the second player.
- **Sim target:** median 7–9 turns each, 6–12 minutes, decided before the turn cap in ≥ 85% of games.
- **Tunable:** Notability (14–20) and the maximum Citations are ruleset keys.
---
## 3. Derivation: article to card (Open problems 3 and 5)
All of it is deterministic: no LLM, fixed tables, and a versioned `deriveVersion`.
**Inputs:**
- the snapshot (as v1)
- `description`, `categories` and `pageBytes`, already in `PageEnrichment`
- the Wikidata entity's **claims**, fetched in the same `wbgetentities` call (≤ 50 ids per request) that Night 1 already used for P31, so no extra requests
The host caches the claims per `(wikidataId, lastrevid)` and freezes them into the `CardInput` at deck validation.
### 3.1 Type: the first rule that matches wins
1. **Exact Q-id table:**
- Q5 human, Q95074 fictional character, Q16521 taxon, Q23038290 fossil taxon, Q8436 family, deities → **Figure**
- Q486972 human settlement → **Location**
2. **P31 label regex,** reusing `factionRules`, grouped by type:
- People and Nature taxa → Figure
- Places and Structures → Location
- Events and Sport matches/seasons/finals → Event
- Works, Organisations, Sport teams and companies → Institution
- Ideas & Tech → Doctrine
3. **P279 "subclass of" labels,** with the same regexes. Concepts such as *Monoid* have no P31 and only P279. This is why 13 sample cards have no P31.
4. **Description regex,** present on 90% of the sample:
- `^Species of|genus of` → Figure
- `(actor|politician|player|singer|writer)\b` → Figure
- `^(Commune|Village|Town|Municipality|River) in` → Location
- `election|storm|battle` → Event
5. **Categories:** `\d+ births|deaths|Living people` → Figure, `Communes of|Villages in|Populated places` → Location, `establishments` → Institution, `elections|disasters|battles` → Event.
6. **Otherwise Doctrine (Neutral).** An abstract thing is the safest default.
**Bug to fix:** the People regex `\bhuman\b` matches "human settlement". As a result *Buky*, *Lunugala*, *Žižki* and *Laukhella* are People in the sample today (4 of 68). Run the exact Q-id step first. Then score the sample's 236 cards in CI and hand-check the 34 "Other" cards. Target ≥ 95% plausible.
### 3.2 Portal (the faction or colour), orthogonal to type
Five **Portals**, each with an MTG colour analogue, plus **Neutral**:
- **Arts** (red)
- **Earth** (green)
- **History** (black)
- **Science** (blue)
- **Society** (white)
**How a card gets one:**
- **Score:** count keyword hits in description + categories + P31/P106 labels, using fixed regex lists in data. For example:
- History: `\d+(st|nd|rd|th)-century|deaths|sultan|empire|castle|medieval`
- Science: `mathemat|algebra|programming|gene|chemi|disease|scientist`
- **Ties** go to the type default: Figure → Society, Location → Earth, Event → History, Institution → Arts, Doctrine → Science.
- **Zero hits:** the card is Neutral.
**Deck rule: none.** You can't ask for colour discipline from a 3-card collection. Portals matter only through effects, for example "Figures from your Portal get +1/+0".
### 3.3 Cost and stats
- **Percentiles, `fame` and cost 1–6:** exactly as v1 §1.1–1.2, using the existing `costThresholds`.
- **Figure:**
- budget `B = 2·cost + 1` (3/5/7/9/11/13)
- `s = clamp(pct_att/(pct_att+pct_depth), 0.3, 0.7)`
- `power = max(1, round(B·s))`, `toughness = B − power`
- each keyword costs 1 point from the larger stat (minimum 1)
- at most 2 keywords
- fame sets cost, never efficiency: v1's anti-inflation principle is kept
- **Location:**
- cost `ceil(cost/2)` (1–3)
- Territory
- Garrison 0/T, where `T = 1 + floor(pct_depth/25)`
- can't attack
- **Event, Institution and Doctrine:** magnitude `k = ceil(cost/2)` (1–3) inside the templates in §3.5.
### 3.4 Keywords, in priority order, max 2
Rates are measured on the 236-card sample.
| Keyword | Trigger | Rules text | Sample rate |
|---|---|---|---|
| **Protected** | category `Living people` | Can't be targeted by Events an opponent controls. | 14% |
| **Featured** (flying) | pct_attention ≥ 85 | Can be blocked only by Featured or Translated Figures. | ~15% |
| **Translated** (reach) | languageCount ≥ 20 | Can block Featured Figures. | 12% |
| **Legacy** | P570 present or a `\d+ deaths` category | When this is destroyed, draw a card. | 12% |
| **Stub** | category contains "stubs" or pageBytes < 3000 | At the start of your turn, put a +1/+1 counter on this (at most 2). | 34% |
| **Well-sourced** | pct_depth ≥ 85 | Prevent the first 1 damage dealt to this each turn. | ~15% |
| **Trending** (haste) | Trending mode only: live ▲ | Can attack the turn it enters. | mode |
### 3.5 Templates by type
Text is set in MTG's terse register. Subtype regexes run over the P31/P279 labels and the description.
- **Event:**
- conflict (`battle|war|siege|annexation|protest|riot`): "Deal k+1 damage to target Figure or Location."
- disaster (`storm|nor.easter|cyclone|earthquake|flood|tornado`): "Deal k−1 (min 1) damage to each Figure and each Location."
- election (`election|referendum|straw poll`): "Create k 1/1 Society Figure tokens named Elected Member."
- sport (`match|final|season|tournament`): "Target Figure you control gets +k/+0 until end of turn, then fights target Figure you don't control."
- period (`events in a specific year|ceremony|festival`): "Draw k cards."
- default: "Target Figure gets +k/+k until end of turn."
- **Institution** (a permanent, like an artifact):
- organisation/company/party/military: "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member." (for cost ≥ 4; below that, "When this enters, …")
- creative work: "Figures you control that are Connected to this get +1/+1. When this enters, draw a card."
- team/club: "Figures you control with power 2 or less get +1/+0."
- vehicles and ships (v2: Crew): "Figures you control have Featured while attacking."
- **Doctrine** (an Aura, the mechanic in Eric's Tetrated dodecahedron → Cho Yang-ho anecdote):
- **Adopt:** "Attach to target Figure. Adopted Figure gets +k/+k." If the Figure leaves, the Doctrine goes to Deleted.
- Riders by subtype:
- mathematics: "and has Well-sourced"
- language/software: "Whenever it deals combat damage to a player, draw a card"
- ideology/religion: "Other Figures you control from the same Portal get +1/+0"
- **Pathology** (`disease|clinical sign|gene|chemical`) is inverted: "Attach to target Figure. It gets −k/−k."
- **Flavour text:** the first sentence of the extract, or `description` if the extract is missing (the sample has none).
### 3.6 Example cards from `card-sample.json`
Tiers and stats are taken from the file. The final numbers come from the real percentile function.
| Card | Derivation | Generated card |
|---|---|---|
| **Tom Ewell** (person) | Q5 → Figure. "actor" → **Arts**. Tiers 10/9/10 → fame ≈ 92 → cost 6. B = 13, s ≈ .53 → 7/6. Featured (att), Translated (30 langs), Legacy (1994 deaths) apply; capped at 2 by priority: Featured, Legacy. | **Tom Ewell**, 6, Figure — Arts. **6/5**. *Featured. Legacy.* "American actor (1909–1994)." *(description; extract not in sample)* |
| **Salahuddin of Aceh** (person) | Q5 → Figure. "16th-century", "Sultans" → **History**. 7/6/7 → fame ≈ 62 → cost 4. B = 9 → 5/4. Legacy (1548 deaths) → 4/4. | **Salahuddin of Aceh**, 4, Figure — History. **4/4**. *Legacy.* "Sultan of Aceh (1530–1537/9)." |
| **Monoid** (maths/concept) | No P31 → P279 "algebraic structure" → Doctrine. "Algebraic structures", "Category theory" → **Science**. 10/10/10 → cost 6, k = 3. Maths rider. | **Monoid**, 6, Doctrine — Science. *Adopt.* Adopted Figure gets +3/+3 and has Well-sourced. "Algebraic structure with an associative operation and an identity element." |
| **Agda (programming language)** | P31 programming language → Doctrine. **Science**. 10/9/9 → cost 6. Language rider. | **Agda**, 6, Doctrine — Science. Adopted Figure gets +3/+3. Whenever it deals combat damage to a player, draw a card. |
| **Dichromorpha viridis** | Q16521 taxon → Figure. "Species of grasshopper" → **Earth**. 7/1/6 → fame ≈ 45 → cost 3. B = 7, s clamped to .7 → 5/2. Stub (1,347 B) → 4/2. | **Dichromorpha viridis**, 3, Figure — Earth. **4/2**. *Stub.* "Species of grasshopper." |
| **April 2021 nor'easter** | P31 nor'easter → Event, disaster. "2021 in Maine" … → **Earth**. 6/10/2 → cost 4, k = 2. | **April 2021 nor'easter**, 4, Event — Earth. Deal 1 damage to each Figure and each Location. *(k−1 = 1: the sim decides whether disasters need k instead)* |
| **1954 Gold Coast general election** | legislative election → Event, election. **Society**. 7/4/5 → cost 4, k = 2. | 4, Event — Society. Create two 1/1 Society Figure tokens named Elected Member. |
| **Pathrail Mosque** | mosque → Location. "15th-century mosques" → **History** (2 hits) vs Society (1). Derived cost 4 → Location cost 2. pct_depth ≈ 55 → Garrison 0/3. | **Pathrail Mosque**, 2, Location — History. Territory. Garrison 0/3. |
| **Tatsunoko Production** | animation studio → Institution, organisation. **Arts**. 10/10/9 → cost 6. | **Tatsunoko Production**, 6, Institution — Arts. At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member. *(the sim may want 2/2 at cost 6)* |
| **Charmont-en-Beauce** | commune of France → Location. **Earth**. 2/2/10 → cost 1. Stub ignored (Locations take no keywords). | **Charmont-en-Beauce**, 1, Location — Earth. Territory. Garrison 0/2. |
**Readability:** a Figure shows cost, P/T, Portal, the type line and up to 2 keyword words. The full text is behind a tap. This is still one phone-sized face.
---
## 4. Story mechanics (Open problem 4, design side)
### 4.1 Connected
- **Data:** the frozen claims (§3). Each card gets `qid` and `connectKeys` at derivation. The engine intersects keys without any I/O.
- Keys come from P17/P27/P131/P495 (place), P106/P101/P921/P136 (field), P361 (part of), P171 (parent taxon) and `C<century>` (from P569/P570/P571/P580/P585).
- Century counts only between cards of **different** types, because it is too common otherwise.
- Wikipedia link tables are not used in v1, which gives zero extra requests.
- **Direct connection:** one card's claims cite the other card's `qid`, for example Barack Obama with the White House (residence).
- **Bonuses:**
- A Figure gets **+1/+1** while you control another card Connected to it; **+2/+2** if the connection is Direct.
- A Doctrine adopted by a Figure Connected to it gives its bonus twice.
- A Connected creative-work Institution buffs, as in §3.5.
- **The card shows why:** "Connected — Pathrail Mosque (country: Bangladesh)".
- **Rivalry (log only, v1):** an opposing pair that is Connected is noted in the log and the recap ("The two had previously been associated through …").
- **Tuning:** sim on random 15-card decks from the sample. Target 0.5–2 Connected pairs per deck. Drop the noisiest keys (P17 = United States, or France) if the rate is above that.
### 4.2 Match log
Past tense, third person, no adjectives about real people, numbered references. Card names are *italic* links, and the first mention is "the card *X*". Examples:
> Turn 3. *Tom Ewell* (American actor, 1909–1994) was deployed by eric.[1]
> Turn 4. *Monoid* was adopted by *Salahuddin of Aceh*, which became a 7/7.[2][3]
> Turn 5. The *April 2021 nor'easter* dealt 1 damage to each Figure. *Dichromorpha viridis* was destroyed.[4][5]
There is one template per engine event type (about 25 strings). It is generated from the deterministic event list, so `replay` regenerates it exactly.
### 4.3 Battle recap ("Battle of X (2026)")
- **Title:**
- "Battle of {Location}": the winner's highest-cost Location at the end, else any Location in play.
- With no Location: "{Signature of the winner} campaign".
- The prefix is "Skirmish at" under 6 turns and "Siege of" over 10.
- **Infobox:** date, Location, result ("Decisive victory" if the margin is ≥ 10, "Pyrrhic victory" if the winner has ≤ 3 Notability, "Victory by decision" at the turn cap), belligerents (players), commanders (Signatures), strength (cards deployed), casualties (cards destroyed).
- **Sections:** Background (Portals, Signatures); Course of the battle (the 3–5 largest swings); Aftermath (final Notability, rating change); See also (Connected pairs); References (every card's real article with `revisionId`, plus the mint id).
- **Branding:** Wikipedia-*style* typography, but **no Wikipedia or Wikimedia logo or name in the masthead.** Footer: "This page records a WikiDeck match. Card names refer to Wikipedia articles; the events described are game events."
---
## 5. Modes in the new structure
- **Classic:** Collection + Basics, 15 cards, Signature. Ranked (Glicko-2) and casual queue, plus invite-by-link.
- **Draft (front door):**
- **Pool:** the host's **Register**, every mint on its chain whoever owns it. That means real mined cards for players with none.
- **Picks:** an open pool of 20 cards, made of min(Register, 16) random mints plus Basics. The two players snake-pick 10 each, at 20 s per pick, and the deck is their 10 picks + 5 Basics of their choice.
- **Owner perk:** if you own a mint in the pool, you may take it as your first pick, once, and the recap credits it "from the collection of X".
- **Small Register:** mainnet's 12 mints still work, padded with Basics. If the Register has fewer than 16 mints, the ruleset may allow Archive padding (Fallback A).
- **Trending:** any deck policy. Live trend frozen at match start, through the throttled client and its daily cache:
- **▲** (trend ≥ +25% and daily ≥ 20): Trending (haste) and +1/+0
- **▼** (≤ −50%, daily ≥ 20): −1/−0
- the 20/day floor keeps noise out (CARD_DATA finding 6)
- **House rules:** unchanged, data-only. New keys: `startingNotability`, `deckSize`, `maxCitations`, `turnCap`, `basicsAllowed`, `archiveRamp`, `connectedBonus`.
## 6. Scope for tonight (designer's cut order)
**Must:** the duel engine (§2); derivation (§3.1–3.5) with the classifier test on the sample; the 8 Basics; Connected with frozen claims; the match log; the recap page; Classic + Draft through PvP lobbies; a greedy combat bot.
**Cut first:** Rivalry text, Trending's ▼, Pathology inversion, Institution subtypes beyond the default. **Defer:** Pending changes, vehicles/Crew, the Archive ramp (flag only).
## 7. Risks
1. **The engine rewrite is the night's critical path.** The lane engine, bots and golden tests don't transfer. Mitigation: freeze the §2 rules at 21:45, then one engine owner and one bot/sim owner from the first hour.
2. **Famous cards all cost 6** (Tom Ewell, Monoid, Agda, Tatsunoko). Collections of notable articles are top-heavy. Mitigation: the Signature in hand plus fixed income make 6-drops castable by turn 6. Watch the sim's curve.
3. **Basics games are generic.** For 0–2 card owners, Classic has little story. That is exactly why Draft is the front door, and why Fallback A exists.
4. **The classifier is wrong ~5–10% of the time** (the human-settlement bug, P279-only concepts). Show the type line with a "derived from: P31 = …" tooltip so mistakes read as data, not bugs. Correct it by `deriveVersion` bumps, never by hand.
5. **Claims are live data, not the mint snapshot.** Card text can drift between nodes. Freeze the claims per card at first sight with `claimsRevision`, and log it. The host's copy is authoritative for its matches.
6. **Real people in shareable recaps:** this is a living-persons and tone risk. Use mechanical verbs only ("was destroyed", "attacked"), use "the card X", and add no commentary.
7. **Collector advantage in ranked:** enforce the parity target in the sim before ranked opens.
8. **Connected density** may be near zero in random collections (good for surprise) or everywhere through country keys (noise). Tune the keys from the sim. Don't guess.
+246
View File
@@ -0,0 +1,246 @@
# Night 2 plan review: lead engineer (feasibility and scope)
Reviewed against `wd` @ 4f7a8a7 (upstream main with Night 1). Paths are repo-relative. `docs/night/REPORT.md` does **not exist** in this checkout, so Night 1 lessons come from HANDBOOK/BOUNDARIES and the coordinator's notes.
**Verdict:** the plan is feasible in 4.5 h **if** the duel engine is a *new sibling package* with no stack and sorcery-speed only, PvP stays on the self host, and the Wikimedia client is handled as transport-only for the mint path. Three facts change the plan:
1. **Owned cards cannot reach PvP today.** The host never accepts a player deck (see §2).
2. **Card data is not trustworthy.** Article and stats are claims made by the miner: consensus only checks internal consistency.
3. **The browser drives most Wikimedia traffic.** Every card face triggers a server enrichment fetch.
---
## 1. Engine: reuse, rewrite, smallest change
**Reusable as is:**
- `shared/game/rng.ts` (mulberry32, `Rng.fromSeed`, exported via `index.ts:3`)
- the clone-on-apply pattern
- the `(ruleset, decks, seed, actions)` replay contract: `replay` at `engine.ts:433`, `applyAction` at `engine.ts:291`
- zod `parseRuleset` (`ruleset.ts:83`)
- `percentile`/`fame`/`costFor` in `derive.ts:52-79`
- the generated sample percentiles (`card-data.ts`, `scripts/game-card-data.mjs`)
The host is **engine-agnostic** through `EnginePort` (`server/game/engine-port.ts:9-43`), so a second engine plugs in with a new binding file instead of host surgery. Bots are also engine-agnostic (`shared/bots/types.ts` `EngineAdapter`, with `toAct`, `assume` and `evaluate`), and a sequential duel fits that adapter *better* than Edit War does: `game-adapter.ts:243` fakes `toAct` from `committed`.
**Must be rewritten:**
- **Everything lane- or Topic-shaped:**
- `MatchState.lanes` / `LaneState` (`types.ts:136-170`)
- the simultaneous queue/commit/reveal turn (`engine.ts:291-363`)
- Topic scoring (`finish`, `engine.ts:366`)
- Portals and keywords (`keywords.ts`, 241 lines, hooks assume lanes and `onReveal`)
- **`GameCard`** (`types.ts:24-43`): a duel card needs `type`, `toughness`, rules-text ids and flavour, and `validateDeck` (`engine.ts:27`) hard-codes cost 0–6, power 0–30, Faction and lane fields.
- **UI boards** (`src/game/MatchBoard.tsx`, `adapter.ts`).
- **`parseModeRuleset`** host checks (`engine-binding.ts:31-43`), which are Edit War-specific: `turns × turnSeconds ≤ 240`, `topicCount`.
**Recommendation: build `shared/duel/` as a sibling package and leave `shared/game/` untouched.**
- Edit War stays playable: its 6 test files keep passing and its modes keep working.
- Two engine agents don't conflict with anyone.
- Duel exposes the same API names (`createMatch`, `legalActions`, `applyAction`, `viewFor`, `replay`, `validateDeck`, `isOver`, `result`), so `EnginePort` and `EngineAdapter` bindings are thin files.
**Smallest core that still feels like Magic (one night):**
- **Turn:** start (untap, income, draw) → main → combat → end. No second main phase, no stack, no instants and no priority passing. Events are sorcery-speed only.
- **Triggers** resolve immediately in a fixed order: active player first, then reveal `seq`, as Edit War's `onReveal` already does.
- **Resources:** fixed income ramp, `incomeByTurn` as data (Edit War's `energyByTurn` idea, `types.ts:70`), with no carry. A Location is a permanent that gives +1 income. No land cards means no land screw.
- **Figures** have power, toughness and summoning sickness; damage clears at end of turn. **Institutions and Doctrines** are permanents with `ongoing` statics (port the pure `ongoing` hook contract, `keywords.ts:16`). Life is 20 by default (data).
- **Actions must be atomic** so that `legalActions` stays small. That matters because the host checks each action by deep-equal against the full list (`host.ts:187-189`), and the bots enumerate it:
- `play {cardId, target?}`
- `toggleAttacker {id}`, then `confirmAttack`
- `block {blocker, attacker}`, then `confirmBlocks`
- `endPhase`, `concede`, `timeout`
Never enumerate whole block assignments, which explode combinatorially.
- **Empty library** behaviour is data: `libraryEmpty: 'lose' | 'reshuffle' | 'fatigue'`. This keeps option (a), small decks with recursion, open with no code change.
- **`legalActions` is `[]` for the seat without priority.** The host sweep already treats "has legal actions" as "is the one waiting" (`host.ts:264`), so timeouts work without host changes.
**Determinism, rules-as-data, `viewFor` and information hiding all carry over.**
- Hidden information is simpler than in Edit War: there is no simultaneous hidden queue, only the hand and library order.
- **New requirement: `logFor(state, seat)`.** Edit War's `viewFor` returns no log at all (`engine.ts:395-419`). The plan's "dry encyclopedic match log" and the recap both need a per-seat log that masks the opponent's `draw` card ids.
- **Card typing (P31) and "Connected" are not on-chain**, so they must be *frozen into the deck at match start*, exactly as the trend arrow is today (`host.ts:318-334`). Match records already store the derived decks (`host.ts:361-363`), so replay stays exact even if Wikidata changes later.
- **Other host limits:** the host's 2000-action cap (`host.ts:344`) is fine for about 15 turns of atomic actions. `MatchRecord` needs an `engine` field.
- **Multi-engine host** (about 15 lines):
- `ModeHost` holds one `engine` (`host.ts:53`); change to `HostedMode {mode, rules, engine}` and `Lobby.engine`.
- Add an optional `engine: 'editwar' | 'duel'` to `ModeSchema` (`modes.ts:88`, default `editwar`).
- Caveat: the schema is `.strict()`, so un-upgraded peers will count duel modes as `rejected` in discovery. That is acceptable on the testnet.
## 2. "The cards a player owns": the trace and the gaps
**Today's path:**
1. The client computes ownership itself. `src/App.tsx:130` filters `snapshot.blocks` (from `GET /api/state`, `http.ts:68` → `legacySnapshot(limits.legacyBlocks)`) by the **browser-local wallet** address.
2. `PlaySection` gets `owned` (`App.tsx:203`) and merges `cardFromBlock` into the deck-builder pool (`PlaySection.tsx:42`). `cardFromBlock` derives in the browser, marks the card `unchecked` with its cost capped, and computes rarity from `powHash` client-side (`cards.ts:39-46`).
3. Owned cards are used **only in browser-local bot matches** (`MatchScreen`).
**Gaps:**
- **G1. No player decks in PvP.** `ModeHost.join` deals `engine.starterDeck` to both seats for every non-draft policy (`host.ts:144`). The `constructed` policy (`modes.ts:64`, which is also the default, `modes.ts:99`) is **unimplemented**: no create/join route takes a deck (`router.ts:123-131`). Ownership is therefore never verified server-side, because it is never used.
- **G2. Accounts are not wired to the game.**
- Linked wallets live in `accounts.sqlite` (`server/account/store.ts:126-130`), but nothing in `server/game/` reads them.
- `gameRouter` receives only `{dataDir, enrichment}` (`http.ts:154`), with no ledger and no account store.
- The `AccountStore` is created privately inside `createAccountRouter` (`router.ts:19`), so it must be injectable to be shared.
- The `auth` middleware is local to that router (`router.ts:25-33`); export it, or call `verifyIdToken` directly.
- **G3. Host identity is not the account.** The player id is `sha256(localStorage secret HMAC hostOrigin)` (`online.ts:161`, `host.ts:380`), so a ladder keyed on it can be farmed trivially by sybils. Also, `Authorization: Bearer` is already taken by seat tokens with a 16–64 character regex (`router.ts:98-101`). Pass the Dex ID token in the **body** at create/join instead.
- **G4. Collection truncation.** `/api/state` returns at most 128 blocks (`server/resources.ts:20`), so older owned cards silently disappear from Play. Use `ledger.deck(address)`, paged by 24 (`ledger.ts:293`), or a new authed `GET /api/game/collection`.
- **G5. Chain card data is a miner claim.**
- The ledger accepts any peer-valid block. `template()` (`ledger.ts:255`) is advisory, and nothing binds a block to a node-issued template.
- `articleSchema` (`consensus.ts:43-56`) does not cross-check `pageId` against `title`.
- `statsSnapshotSchema` (`consensus.ts:59-93`) only checks internal consistency (`deriveStats` of the declared bytes, languages and views).
- So a custom miner can mint "Barack Obama" with any stats. DESIGN §1.10 plausibility exists only as types: `verifyStats` and `check: 'verified'` are never read (no hits outside `types.ts`, `ruleset.ts`, `engine.ts:22` and `derive.ts`).
- **G6. Per-node account stores.** Peer hosts have their own `accounts.sqlite`, so a wallet linked on node A is unknown on node B. Sending a Dex ID token to a peer also lets that peer replay it on other nodes until it expires, since every node shares the `wikideck` audience.
**Recommended (MVP, self host only):**
- Create and join take `{idToken, deck: tokenId[]}`. The host:
1. verifies the token (`verifyIdToken`);
2. loads `wallets(sub)` from the account store;
3. for each token, checks `ledger.nft(token)` (`canonical-index.ts:163`): owner ∈ wallets and `confirmations ≥ rules.minConfirmations` (1 casual, 3 rated);
4. builds `CardInput` **from the block**, never from client card JSON, then derives and freezes.
- Put this in a new `server/game/ownership.ts` exposing a pure `resolveDeck(deps, sub, tokenIds)`. `host.ts` calls it from `startMatch`.
- Plausibility (G5), stretch:
- Check `pageId → title` and `revisionId → size` with **one batched request per 50 cards** (`prop=revisions&revids=…&rvprop=size|ids`). Revisions are immutable, so the result can be cached forever and verifies `pageBytes` exactly.
- Past monthly pageviews are also immutable, so they can be checked exactly at one request per card.
- On a mismatch, the card is marked `unverified` and its cost is capped.
- Peers (stretch): replace the ID token with a wallet-signed deck claim `["wikideck:deck-claim:v1", NETWORK, hostOrigin, nonce, tokenIds]`. The client builds the message itself, like `shared/account-link.ts`. This needs no account on the peer and cannot be replayed on another host.
## 3. PvP: what exists, what's needed, transport
**What exists:**
- **`server/game/host.ts`:** in-memory lobbies, snake draft, the turn timer and AFK handling via `timeoutAction` (`host.ts:263-270`), legal-action enforcement, live-lobby persistence across restarts (`index.ts:205-226`), JSONL match records with replayable audit (`store.ts`) and a W/L leaderboard (`store.ts:64-68`).
- **`router.ts`:** rate-limited (`router.ts:90-94`).
- **UI:** `OnlinePlay.tsx` is a lobby list (polled every 4 s), create/join, draft and a match board. It is reachable only from inside the Play section.
**What's needed:**
| Feature | Minimal design | Files | Size |
|---|---|---|---|
| Invite link | `createLobby({private:true})` is excluded from `openLobbies` (`host.ts:108-112`); the UI route `/play/join/<lobbyId>` works because the SPA catch-all serves `index.html` (`http.ts:157`), and `join` already takes an id | host, router, OnlinePlay | S |
| Quick match | `POST /modes/:id/quick` joins the oldest open lobby within the rating window, else creates one; no separate queue structure | host, router | S |
| Rated ladder | Elo (K=24, start 1200) per mode, keyed by account id, recomputed by replaying `matches.jsonl` in order at startup (deterministic, no new store); rated only when both seats are account-verified and `rated:true` in mode limits; Glicko-2 is not worth the night | store.ts, host.ts | M |
| Account seat identity | `idToken` in the create/join body → player id `sha256('acct:'+iss+sub)`; guests keep the secret but are unrated | host.ts, online.ts | S |
| Duel binding | `server/game/duel-binding.ts` plus multi-engine `HostedMode` | new file, host.ts | S |
**Transport is polling:** the client polls every 1 s (`OnlinePlay.tsx:11, 45-50`), with no WebSocket or SSE anywhere. It is adequate for a sequential duel: about 0.5 s average hand-off latency.
Three caveats:
1. **Cost.** Each poll runs `viewFor` and `legalActions` and returns the full view. Add a monotonic `version` to the lobby and `GET …?v=N` → `204` when unchanged. Poll every 500 ms while waiting on the opponent and every 3 s otherwise.
2. **Do not long-poll under `/api`.** `RpcBudget` caps the whole node at 32 active `/api` requests (`resources.ts:17`, applied at `http.ts:54`), so 16 matches holding long-polls would starve the node. Real push would need SSE mounted *outside* `/api` (a `server/testnet/http.ts` shared-hook change): a stretch only.
3. **Rate limits.** Two humans behind one NAT, or QA agents on one machine, see 1 req/s × 2 against `plays` 240/min and the global 300/min per IP (`http.ts:56`). That is OK, but QA should not run more than 2 matches per IP.
## 4. Wikimedia politeness
**Every call site** (grep over `server`, `src`, `scripts`, `shared` and `android`; the browser never calls Wikimedia APIs directly, because CSP `connect-src 'self'` at `http.ts:50` forbids it):
| # | Where | Upstream | Trigger | Limits today |
|---|---|---|---|---|
| W1 | `server/wiki.ts:73-78` `random()` | en Action API, `generator=random` ×10 | **mint template** `http.ts:122` | ≤4 concurrent, 3 attempts, 3.5 s timeout, no 429/Retry-After, no maxlag |
| W2 | `server/enrichment.ts:134-138` `load()` metadata | en Action API, `pageids=1` | `getFresh` at **mint** `http.ts:123`; `get` from `/api/wikipedia/:id` `http.ts:93-98`; TrendCache | ≤4 active, 8 pending, then **reject**; in-memory LRU of 128 entries, 6 h TTL; errors cached 30 s |
| W3 | `server/enrichment.ts:148` pageviews | `wikimedia.org` REST, monthly | same as W2 | same |
| W4 | `server/game/trends.ts:37-56` via `index.ts:174-186` | W2+W3 | background, one page per 20 s | about 8.6k requests/day steady if the queue stays warm |
| W5 | **browser:** `src/Card.tsx:24` → `src/useEnrichment.ts:10` → `/api/wikipedia/:id` | W2+W3 | **every card face rendered** (collection, explorer, hero) | per-tab cache 5 min; server limit is 60/min **per client IP** only, with no node-wide upstream budget |
| W6 | `scripts/night/card_sample.py:13-38` | en API, Wikidata `wbgetentities`, REST daily views | offline research | 1 req/s, honours Retry-After, disk cache (its docstring says "~4 req/s"; the code does 1) |
| W7 | browser `<img>` from `upload.wikimedia.org` (`Card.tsx:28`, CSP `http.ts:49`) | CDN | each render | hotlinking; acceptable, but the plan should cache thumbnails or use `pithumbsize` |
**Likely cause of the Night 1 429:** W5 fan-out (each grid page means N cards × 2 upstream requests, with a 128-entry LRU thrashing across users) plus W4, multiplied by several testnet nodes sharing one egress IP. Each node also uses the default UA, `Wikideck/0.1 (experimental …)` (`wikimedia-user-agent.ts:4-5`), which has **no contact**. That breaks the Wikimedia UA policy and is the kind of client that gets blocked first.
**Design: `server/wikimedia/client.ts`, one process-wide `WikimediaClient`.**
- **Rate:** a token bucket per upstream host. Defaults (env-configurable):
- `en.wikipedia.org`: **1 req/s, burst 2**
- `www.wikidata.org`: 1 req/s
- `wikimedia.org` REST: 5 req/s
- **Concurrency:** **1 in flight per host** by default (`WIKIDECK_WIKIMEDIA_CONCURRENCY`). The Action API etiquette is serial requests.
- **Co-located nodes:** document `WIKIDECK_WIKIMEDIA_RPS=0.3` for nodes behind a shared IP (testnet compose).
- **Priority lanes**, with a bounded queue (64):
- `mint`: always first; the timeout starts at dispatch; the queue wait is capped at 15 s, and the miner tolerates it (30 s timeout, `miner.ts:57`)
- `interactive`: on overflow, serve stale cache or 503
- `background`: trends, P31, links, plausibility; dropped when the queue is full
- **maxlag:** add `maxlag=5` to every Action API request (en and Wikidata). Detect `error.code==='maxlag'` (HTTP 200 with a JSON error), wait for `Retry-After` (default 5 s) and retry at most 3 times. REST has no maxlag.
- **429 and 503:** parse `Retry-After` (seconds or HTTP-date), then **pause the whole host bucket** (circuit-open) for max(Retry-After, exponential backoff 2^n s with jitter, cap 10 min). Log once per pause and expose a counter in `/healthz`-adjacent ops output.
- **Batching:**
- `pageids=`/`titles=`/`revids=` up to 50 for cheap props: `info`, `pageprops` (`wikibase_item`), `description`, `revisions|size`.
- P31 via `wbgetentities&ids=Q1|…(50)&props=claims` is heavy (Obama's claims alone are megabytes). Use `wbgetclaims&property=P31` per entity (small, cached for 30 days), or one WDQS `VALUES` query per ≤50 QIDs.
- **"Connected"** costs one request per deck pair: `prop=links&titles=<≤50 deck titles>&pltitles=<same>&pllimit=max` returns exactly the intra-set links. Cache it by the sorted pageId set.
- **Never batch** `langlinks` or `categories`: their limits are shared across the batch, which forces continuation and changes `languagesTruncated` semantics.
- **Persistent cache:** `node:sqlite` (already used by accounts; Node 24) at `$WIKIDECK_DATA_DIR/wikimedia-cache.sqlite`. Key = canonical URL with sorted params and without `maxlag`. Store the body, ETag and Last-Modified; send `If-None-Match` (REST returns ETags; the Action API mostly doesn't); serve stale-while-revalidate for `interactive`. TTLs:
| Data | TTL |
|---|---|
| metadata | 24 h |
| monthly pageviews | until month rollover (already the rule, `enrichment.ts:70`); closed months are immutable |
| P31 | 30 d |
| links | 7 d |
| revision size | forever |
| random | never |
Raise the 128-entry cap (`enrichment.ts:51`) once the cache is on disk.
- **UA:** `WikiDeck/<pkg version> (+https://gitea.eom.dev/WikiDeck/wikideck; <WIKIDECK_OPERATOR_CONTACT or PUBLIC_ORIGIN>) node/<ver>`.
- Keep `WIKIDECK_USER_AGENT` as an override, still sanitized as at `wikimedia-user-agent.ts:8-12`.
- Warn at startup if there is no operator contact.
- Update `tests/testnet-user-agent.test.ts`, which pins today's fallback strings.
- **Volume budget:**
- mint: 3 requests (≤5 with random retries)
- match: **0 synchronous** (cache-only at match start; unknown data means "no bonus" or a fallback type, as `trends.ts` already does)
- per new card first seen: ≤1 batched metadata/plausibility share + 1 P31
- per deck save: 1 links request
- card-face render: 0 when cached
**Consensus boundary (checked carefully):**
- **Validation never touches Wikimedia.** `consensus.ts:43-93` is pure, and the only callers of `wikipediaArticles` and `wikipediaEnrichment` are `http.ts:96, 122-123, 154`. Throttling, caching and retry therefore **cannot affect block validation or fork choice**.
- **The mint template's *content* becomes immutable chain data.** The client must be *transport-only* on the mint path:
1. Keep W1/W2/W3 request params byte-identical: `grnlimit`, `exchars=900`, `pithumbsize`, `cllimit=20` (no hidden filter, which feeds `category()` at `wiki.ts:17`), `clshow=!hidden`, `cllimit=50`, `lllimit=500`. They determine `article.category`, `languageCount` and `languagesTruncated`, and the percentile calibration. `tests/enrichment.test.ts:42-52` already pins part of this; add a golden URL test for W1. Adding `maxlag` is safe because it changes only error behaviour.
2. `getFresh` must bypass the persistent cache. `snapshotStats` stamps `capturedAt = new Date()` (`shared/enrichment.ts:41`), so cached data would be misdated.
3. **Existing bug that throttling would amplify.** A 429/5xx on the pageviews call is swallowed into `status:'unavailable'` (`enrichment.ts:145-164`). On the mint path that **permanently mints a card with `attention: null`**. With the new client, mint must fail the template (503, the miner retries) on 429/5xx/timeout, and record "unavailable" only on a genuine 404 or no-data. Both outcomes are valid blocks, so this is template policy, not a consensus change; it needs one owner and a test.
## 5. Scope: 4.5 h, about 10 agents, one integration branch
**Rules learned from Night 1:**
- **No stacked PRs.** Squash-merge makes every child PR conflict. Branch only from `night/2026-11-17` after the dependency has merged.
- **Contracts first:** `shared/duel/types.ts` and `docs/game/DUEL_API.md` merge by 22:15.
- **Node 24 everywhere** (`node:sqlite`; the Dockerfile uses `node:24-alpine`). Check `node -v` before `npm ci`.
- **No new npm dependencies.** The lead alone owns lockfile regeneration.
- **Test files:** top-level `tests/<team>-*.test.ts` only (`scripts/run-tests.mjs:7`).
**Workstreams** (9 workers plus the lead; ✱ = touches a shared file, one line or a small edit):
| WS | Owner paths | Delivers | Depends on |
|---|---|---|---|
| A duel-core | `shared/duel/{types,engine,ruleset,index}.ts`, `tests/duel-core*.test.ts`, `docs/game/DUEL_API.md` | turn and combat engine, `viewFor`/`logFor`, `replay`; **types PR by 22:15**, alpha by 23:15 | — |
| B duel-cards | `shared/duel/{derive,classify,effects,text}.ts`, `tests/duel-cards*.test.ts` | P31 → type table (from `card-sample.json` `instanceOf`, 236 cards), category fallback, P/T and cost curve, ≤8 effect templates, deterministic MTG-register rules text, flavour from `article.extract` | A types |
| C sim-balance | `shared/bots/duel-adapter.ts`, `scripts/sim/*duel*`, `docs/game/DUEL_BALANCE.md` | greedy and MC bots on duel; win rate by type and faction; ruleset number tuning (data-only PRs) | A alpha (23:15) |
| D wikimedia | `server/wikimedia/*`, `server/wiki.ts`, `server/enrichment.ts`, `server/wikimedia-user-agent.ts`, `tests/wikimedia-*.test.ts` | §4 client, mint-path fix, sqlite cache, UA; `trends.ts` unchanged (it goes through enrichment) | — (starts 21:30) |
| E identity | `server/game/identity.ts`, `scripts/night2/prebake-identity.ts` | background P31, links and plausibility via D's `background` lane; persistent per-token identity; pre-bakes testnet and mainnet cards | D interface (stub until merged), B input type |
| F ownership | `server/game/ownership.ts`, `server/game/collection.ts`, ✱`server/account/router.ts` (inject store, export auth), ✱`http.ts` (pass `{ledger, accounts}` into `gameRouter`) | `resolveDeck`, `GET /api/game/collection`, chain-pool draft source (option c) | — |
| G host-pvp | `server/game/{host,router,store,index,duel-binding}.ts`, `shared/game/modes.ts` (`engine` field), `deploy/night2/modes/*.json` | multi-engine host, constructed decks via F, account seats, private lobbies, invite, quick match, Elo, `?v=` polling | F function signature (agree by 22:00), A types |
| H ui-duel | `src/game/duel/*` (board, card face with type line, P/T, text, flavour; adapter; local bot practice) | playable vs bot in the browser | A types → A alpha |
| I ui-pvp+story | `src/game/OnlinePlay.tsx`, `online.ts`, `PlaySection.tsx`, `Leaderboards.tsx`, `src/game/recap/*`, `shared/duel/recap.ts` | collection deck picker, invite and quick-match UI, ladder, "Battle of X (2026)" recap rendered client-side by `replay` of `GET /matches/:id` (`router.ts:137`) | G API (stub), A log format |
| Lead | integration branch, `docs/night/*`, QA, REPORT | merges, lockfile, end-to-end on testnet with 2 Dex accounts | — |
Overlap is limited to the ✱ lines. `host.ts` is G's alone: F ships pure functions that G calls.
**Timeline (EST):**
| Time | Milestone |
|---|---|
| 21:30 | A, D and F start |
| 22:15 | types contract merged; B, G, H and I build against it |
| 23:15 | engine alpha; C starts sims; H plays vs bot |
| 00:00 | D merged; E live; G binds duel; I wired to G |
| 00:45 | balance v1 (data-only tuning) |
| 01:15 | **freeze** |
| 01:15–01:45 | QA PvP plus recap |
| 01:50 | REPORT |
| 02:00 | stop |
**Cut first, in order:**
1. WDQS/shared-property "Connected": keep article-link Connected only, or none.
2. Plausibility verification (G5): trust chain stats and document the gap.
3. Quick match: invite link and open lobbies suffice.
4. Elo ladder: keep W/L keyed by account.
5. Peer-hosted duel and wallet-signed deck claims.
6. Recap infobox polish: keep the plain encyclopedic log.
**Never cut:**
- the Wikimedia client (requirement 7: low risk, independent, and protects every later night)
- server-side ownership verification
- the duel core
- self-hosted PvP with owned or draft decks
- bot practice
**Biggest risks:**
1. Duel engine plus balance in about 2 h of real build time. Mitigation: no stack, atomic actions, effects as ≤8 templates.
2. UI combat readability. H must start on mock views at 22:15, not wait for the alpha.
3. Supply: 12 mainnet cards make a constructed duel unplayable without option (c) or (a). Make deck size and `libraryEmpty` ruleset data so Eric's decision is a mode file, not code.
+908
View File
@@ -0,0 +1,908 @@
/**
* WikiDeck Duel engine (off-chain, pure, deterministic). Spec: docs/game/DUEL_API.md.
* No stack, sorcery speed only, atomic actions, clone-on-apply.
*/
import { Rng } from '../game/rng.ts';
import { DEFAULT_DUEL_RULESET, parseDuelRuleset } from './ruleset.ts';
import type {
CardInstance, CardRef, ConnectedTier, DuelAction, DuelCard, DuelResult, DuelRuleset, DuelState, EffectSpec, EndReason,
Keyword, LogEvent, Permanent, PermanentView, PlayerState, PlayerView, Seat, SideView, TargetRef, TargetSpec,
} from './types.ts';
import { CARD_TYPES, KEYWORDS } from './types.ts';
type LogBody = LogEvent extends infer E ? (E extends LogEvent ? Omit<E, 'seq' | 'turn'> : never) : never;
type Source = Permanent | CardInstance;
const other = (seat: Seat): Seat => (seat === 0 ? 1 : 0);
const pw = (card: DuelCard) => card.power ?? 0;
const tg = (card: DuelCard) => card.toughness ?? 0;
const CHOSEN: ReadonlySet<TargetSpec> = new Set(['figure', 'figureOrLocation', 'ownFigure', 'opponentFigure', 'anyTarget']);
const NO_KIN = new Set(['Q5', 'Q16521']);
const MAX_COMBOS = 64;
function targetOf(e: EffectSpec): TargetSpec {
if (e.target) return e.target;
switch (e.op) {
case 'damage': return 'anyTarget';
case 'damageEach': return 'each';
case 'pump': return 'self';
case 'drain': return 'opponent';
case 'attach': return 'ownFigure';
case 'fight': return 'opponentFigure';
case 'destroy': case 'bounce': case 'tap': return 'opponentFigure';
default: return 'controller';
}
}
const isEntry = (e: EffectSpec) => e.trigger === 'onPlay' || e.trigger === 'onEnter';
// ---------------------------------------------------------------------------
// Decks
// ---------------------------------------------------------------------------
export function validateDeck(rules: DuelRuleset, cards: DuelCard[]): void {
if (!Array.isArray(cards)) throw new TypeError('Deck must be an array');
if (cards.length !== rules.deckSize) throw new RangeError(`Deck must have exactly ${rules.deckSize} cards (has ${cards.length})`);
const ids = new Set<string>();
const pages = new Map<number, number>();
for (const card of cards) {
if (!card || typeof card.cardId !== 'string' || !card.cardId) throw new TypeError('Card needs a cardId');
if (card.token) throw new RangeError(`Tokens can't be in decks (${card.cardId})`);
if (ids.has(card.cardId)) throw new RangeError(`Duplicate card ${card.cardId}`);
ids.add(card.cardId);
if (card.pageId !== null) {
const n = (pages.get(card.pageId) ?? 0) + 1;
if (n > rules.maxCopiesPerPage) throw new RangeError(`More than ${rules.maxCopiesPerPage} copies of page ${card.pageId}`);
pages.set(card.pageId, n);
}
if (!CARD_TYPES.includes(card.type)) throw new RangeError(`Bad card type ${card.type}`);
if (!Number.isInteger(card.cost) || card.cost < 0 || card.cost > 20) throw new RangeError(`Bad cost on ${card.cardId}`);
for (const n of [pw(card), tg(card)]) if (!Number.isInteger(n) || n < 0 || n > 50) throw new RangeError(`Bad stats on ${card.cardId}`);
if (card.type === 'Figure' && tg(card) < 1) throw new RangeError(`Figure ${card.cardId} needs toughness ≥ 1`);
if (!Array.isArray(card.keywords)) throw new TypeError(`Bad keywords on ${card.cardId}`);
// Trending is granted by the host at match start (applyLive) and doesn't count toward the limit.
if (card.keywords.filter(k => k !== 'Trending').length > rules.maxKeywords) throw new RangeError(`Too many keywords on ${card.cardId}`);
for (const k of card.keywords) if (!KEYWORDS.includes(k)) throw new RangeError(`Unknown keyword ${k}`);
if (!Array.isArray(card.effects) || card.effects.length > 4) throw new RangeError(`Bad effects on ${card.cardId}`);
if (card.territory !== undefined && (!Number.isInteger(card.territory) || card.territory < 0 || card.territory > 5)) throw new RangeError(`Bad territory on ${card.cardId}`);
}
}
// ---------------------------------------------------------------------------
// Creation
// ---------------------------------------------------------------------------
function emptyPlayer(rules: DuelRuleset, library: CardInstance[]): PlayerState {
return {
life: rules.startingLife, citations: 0, baseCitations: 0, library, hand: [], graveyard: [], mulligansTaken: 0, ready: false,
locationsThisTurn: 0, bankSeconds: rules.bankSeconds, timeouts: 0, fatigue: 0,
};
}
export function createDuel(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string): DuelState {
const r = parseDuelRuleset(rules);
const rng = Rng.fromSeed(seed);
const firstSeat = rng.int(2) as Seat;
const players = ([0, 1] as Seat[]).map(seat => {
const instances = decks[seat].map((card, i) => ({ uid: `${seat}:${i}`, owner: seat, card: structuredClone(card) }));
return emptyPlayer(r, rng.shuffle(instances));
}) as [PlayerState, PlayerState];
const state: DuelState = {
engine: 'duel', rules: r, seed, rng: rng.state, turn: 0, active: firstSeat, firstSeat, phase: 'mulligan',
players, battlefield: [], combat: { attackers: [], blocks: {} }, log: [], result: null, version: 0, nextToken: 0, nextEntry: 0,
};
log(state, { kind: 'start', firstSeat });
for (const p of state.players) p.hand = p.library.splice(0, r.openingHand);
return state;
}
// ---------------------------------------------------------------------------
// Queries
// ---------------------------------------------------------------------------
export function toAct(state: DuelState): Seat | null {
if (state.result) return null;
if (state.phase === 'mulligan') {
for (const seat of [0, 1] as Seat[]) if (!state.players[seat].ready) return seat;
return null;
}
return state.phase === 'block' ? other(state.active) : state.active;
}
export const isOver = (state: DuelState) => state.result !== null;
export const result = (state: DuelState): DuelResult | null => state.result;
export const turnOf = (state: DuelState) => state.turn;
const find = (state: DuelState, uid: string) => state.battlefield.find(p => p.uid === uid);
export function maxCitations(state: DuelState, seat: Seat): number {
const territory = state.battlefield.filter(p => p.controller === seat && p.card.type === 'Location').reduce((n, p) => n + (p.card.territory ?? 0), 0);
return state.players[seat].baseCitations + Math.min(state.rules.territoryCap, territory);
}
/** Connected tier between two cards (DUEL_DESIGN §6), best tier first, limited to rules.connectedTiers. */
export function tierBetween(rules: DuelRuleset, a: DuelCard, b: DuelCard): { tier: ConnectedTier; via: string } | null {
const ca = a.connect, cb = b.connect;
if (!ca || !cb) return null;
const on = (t: ConnectedTier) => rules.connectedTiers.includes(t);
const linked = (b.pageId !== null && ca.links.includes(b.pageId)) || (a.pageId !== null && cb.links.includes(a.pageId));
const cited = (!!cb.qid && !!ca.cites?.includes(cb.qid)) || (!!ca.qid && !!cb.cites?.includes(ca.qid));
if (on('Linked') && (linked || cited)) return { tier: 'Linked', via: cited ? 'claim' : 'link' };
if (on('Compatriot')) { const c = ca.countries.find(x => cb.countries.includes(x)); if (c !== undefined) return { tier: 'Compatriot', via: `country: ${c}` }; }
if (on('Contemporary') && a.type !== b.type) { const c = ca.centuries.find(x => cb.centuries.includes(x)); if (c !== undefined) return { tier: 'Contemporary', via: `century: ${c}` }; }
if (on('Kin')) { const c = ca.p31.find(x => !NO_KIN.has(x) && cb.p31.includes(x)); if (c !== undefined) return { tier: 'Kin', via: `instance of: ${c}` }; }
return null;
}
function connectionOf(state: DuelState, perm: Permanent): { with: Permanent; tier: ConnectedTier; via: string; bonus: number } | null {
if (perm.card.type !== 'Figure' || !perm.card.connect) return null;
let best: { with: Permanent; tier: ConnectedTier; via: string; bonus: number } | null = null;
for (const mate of state.battlefield) {
if (mate.uid === perm.uid || mate.controller !== perm.controller) continue;
const t = tierBetween(state.rules, perm.card, mate.card);
if (!t) continue;
const bonus = t.tier === 'Linked' ? state.rules.linkedBonus : state.rules.connectedBonus;
if (!best || bonus > best.bonus) best = { with: mate, tier: t.tier, via: t.via, bonus };
}
return best;
}
/** Does a static effect of `src` apply to `perm`? Conditions use printed power (no feedback). */
function staticApplies(state: DuelState, src: Permanent, e: EffectSpec, perm: Permanent): boolean {
const fig = perm.card.type === 'Figure';
const t = targetOf(e);
const hit = t === 'attached' ? src.attachedTo === perm.uid
: t === 'self' ? src.uid === perm.uid
: t === 'ownFigures' ? fig && perm.controller === src.controller
: t === 'opponentFigures' ? fig && perm.controller !== src.controller
: t === 'each' ? fig || perm.card.type === 'Location' : false;
if (!hit) return false;
const c = e.condition;
if (!c) return true;
if (c.maxPower !== undefined && pw(perm.card) > c.maxPower) return false;
if (c.samePortal) {
const anchorUid = src.card.type === 'Doctrine' ? src.attachedTo : src.uid;
const anchor = anchorUid ? find(state, anchorUid) : undefined;
if (!anchor || perm.uid === anchor.uid || perm.card.portal !== anchor.card.portal) return false;
}
if (c.connected && !tierBetween(state.rules, perm.card, src.card)) return false;
return true;
}
function statics(state: DuelState, perm: Permanent): { p: number; t: number; grants: Keyword[] } {
let p = 0, t = 0;
const grants: Keyword[] = [];
for (const src of state.battlefield) {
for (const e of src.card.effects) {
if (e.trigger !== 'static' || !staticApplies(state, src, e, perm)) continue;
if (e.op === 'pump') { p += e.power ?? e.amount ?? 0; t += e.toughness ?? e.amount ?? 0; }
if (e.grant) grants.push(...e.grant);
}
}
return { p, t, grants };
}
export function keywordsOf(state: DuelState, perm: Permanent): Keyword[] {
const out = new Set<Keyword>([...perm.card.keywords, ...perm.permKeywords, ...perm.tempKeywords, ...statics(state, perm).grants]);
return KEYWORDS.filter(k => out.has(k));
}
const hasKw = (state: DuelState, perm: Permanent, k: Keyword) => keywordsOf(state, perm).includes(k);
export function statsOfPermanent(state: DuelState, perm: Permanent): { power: number; toughness: number } {
if (perm.card.type === 'Location') {
return { power: Math.max(0, perm.tempPower), toughness: tg(perm.card) > 0 ? tg(perm.card) + perm.tempToughness : 0 };
}
if (perm.card.type !== 'Figure') return { power: 0, toughness: 0 };
const s = statics(state, perm);
const c = connectionOf(state, perm)?.bonus ?? 0;
const kws = new Set([...perm.card.keywords, ...perm.permKeywords, ...perm.tempKeywords, ...s.grants]);
let local = 0;
if (kws.has('Local') && perm.card.connect?.countries.length) {
const mine = perm.card.connect.countries;
if (state.battlefield.some(l => l.controller === perm.controller && l.card.type === 'Location' && l.card.connect?.countries.some(x => mine.includes(x)))) local = 1;
}
const trend = kws.has('Trending') ? state.rules.trendingPower : 0;
const extra = perm.counters + c + local;
return {
power: Math.max(0, pw(perm.card) + extra + perm.permPower + perm.tempPower + s.p + trend),
toughness: tg(perm.card) + extra + perm.permToughness + perm.tempToughness + s.t,
};
}
export function statsOf(state: DuelState, uid: string): { power: number; toughness: number } {
const perm = find(state, uid);
if (!perm) throw new RangeError(`No permanent ${uid}`);
return statsOfPermanent(state, perm);
}
/** Figures, and Locations with a Garrison, can block and can be destroyed by damage. */
const isBody = (perm: Permanent) => perm.card.type === 'Figure' || (perm.card.type === 'Location' && tg(perm.card) > 0);
function canBlock(state: DuelState, blocker: Permanent, attacker: Permanent): boolean {
const ka = keywordsOf(state, attacker);
const kb = blocker.card.type === 'Figure' ? keywordsOf(state, blocker) : [];
if (ka.includes('Featured') && !kb.some(k => k === 'Featured' || k === 'Translated' || k === 'Multilingual')) return false;
if (ka.includes('Multilingual') && kb.includes('Local')) return false;
return true;
}
function candidates(state: DuelState, seat: Seat, card: DuelCard, e: EffectSpec): TargetRef[] {
const t = targetOf(e);
const out: TargetRef[] = [];
const shielded = (p: Permanent) => p.controller !== seat && (card.type === 'Event' || card.type === 'Doctrine') && hasKw(state, p, 'Protected');
for (const p of state.battlefield) {
const fig = p.card.type === 'Figure';
const ok = t === 'figure' ? fig
: t === 'figureOrLocation' || t === 'anyTarget' ? fig || (p.card.type === 'Location' && tg(p.card) > 0)
: t === 'ownFigure' ? fig && p.controller === seat
: t === 'opponentFigure' ? fig && p.controller !== seat : false;
if (!ok || shielded(p)) continue;
if (e.condition?.maxPower !== undefined && pw(p.card) > e.condition.maxPower) continue;
out.push({ kind: 'card', uid: p.uid });
}
if (t === 'anyTarget') out.push({ kind: 'player', seat: other(seat) }, { kind: 'player', seat });
return out;
}
/** All target combinations for playing `card` now (capped), [] if it can't be played, [[]] if it needs none. */
function targetCombos(state: DuelState, seat: Seat, card: DuelCard): TargetRef[][] {
const chosen = card.effects.filter(e => isEntry(e) && CHOSEN.has(targetOf(e)));
if (!chosen.length) return [[]];
const lists = chosen.map(e => candidates(state, seat, card, e));
const permanent = card.type !== 'Event' && card.type !== 'Doctrine';
if (lists.some(l => !l.length)) return permanent ? [[]] : [];
let combos: TargetRef[][] = [[]];
for (const list of lists) {
const next: TargetRef[][] = [];
for (const c of combos) for (const t of list) {
if (t.kind === 'card' && c.some(x => x.kind === 'card' && x.uid === t.uid)) continue;
if (next.length < MAX_COMBOS) next.push([...c, t]);
}
combos = next;
}
return combos.length ? combos : permanent ? [[]] : [];
}
export function legalActions(state: DuelState, seat: Seat): DuelAction[] {
if (toAct(state) !== seat) return [];
const p = state.players[seat];
switch (state.phase) {
case 'mulligan':
return p.mulligansTaken < state.rules.mulligans ? [{ type: 'keep' }, { type: 'mulligan' }] : [{ type: 'keep' }];
case 'main': {
const out: DuelAction[] = [];
for (const inst of p.hand) {
if (inst.card.cost > p.citations) continue;
if (inst.card.type === 'Location' && p.locationsThisTurn >= state.rules.locationsPerTurn) continue;
for (const targets of targetCombos(state, seat, inst.card)) {
out.push(targets.length ? { type: 'play', uid: inst.uid, targets } : { type: 'play', uid: inst.uid });
}
}
out.push({ type: 'endPhase' });
return out;
}
case 'attack': {
const out: DuelAction[] = [];
for (const perm of state.battlefield) {
if (perm.controller !== seat || perm.card.type !== 'Figure' || perm.tapped || state.combat.attackers.includes(perm.uid)) continue;
if (perm.sick && !hasKw(state, perm, 'Trending')) continue;
out.push({ type: 'toggleAttacker', uid: perm.uid });
}
out.push({ type: 'confirmAttack' });
return out;
}
case 'block':
return [...blockOptions(state), { type: 'confirmBlocks' }];
default:
return [];
}
}
function blockOptions(state: DuelState): DuelAction[] {
const defender = other(state.active);
const out: DuelAction[] = [];
const blocked = new Set(Object.values(state.combat.blocks));
for (const b of state.battlefield) {
if (b.controller !== defender || b.tapped || !isBody(b) || state.combat.blocks[b.uid]) continue;
for (const aUid of state.combat.attackers) {
if (blocked.has(aUid)) continue;
const a = find(state, aUid);
if (a && canBlock(state, b, a)) out.push({ type: 'block', blocker: b.uid, attacker: aUid });
}
}
return out;
}
// ---------------------------------------------------------------------------
// Mutation helpers (operate on a private clone)
// ---------------------------------------------------------------------------
function log(state: DuelState, body: LogBody): void {
state.log.push({ seq: state.log.length, turn: state.turn, ...body } as LogEvent);
}
function ref(state: DuelState, inst: Source): CardRef {
const out: CardRef = { uid: inst.uid, cardId: inst.card.cardId, title: inst.card.title, pageId: inst.card.pageId, type: inst.card.type };
const perm = find(state, inst.uid);
if (perm && isBody(perm)) Object.assign(out, statsOfPermanent(state, perm));
return out;
}
const life = (state: DuelState): [number, number] => [state.players[0].life, state.players[1].life];
function finish(state: DuelState, winner: Seat | null, reason: EndReason): void {
if (state.result) return;
state.result = { winner, reason };
state.phase = 'over';
log(state, { kind: 'gameOver', winner, reason, life: life(state) });
}
function draw(state: DuelState, seat: Seat, n: number): void {
const p = state.players[seat];
for (let i = 0; i < n && !state.result; i++) {
if (!p.library.length) {
const mode = state.rules.libraryEmpty;
if (mode === 'reshuffle' && p.graveyard.length) {
const rng = new Rng(state.rng);
p.library = rng.shuffle(p.graveyard);
p.graveyard = [];
state.rng = rng.state;
} else if (mode === 'fatigue') {
p.fatigue += 1;
log(state, { kind: 'fatigue', seat, amount: p.fatigue });
loseLife(state, seat, p.fatigue, null, false);
continue;
} else {
finish(state, other(seat), 'library');
return;
}
}
const inst = p.library.shift()!;
p.hand.push(inst);
log(state, { kind: 'draw', seat, card: ref(state, inst) });
}
}
function loseLife(state: DuelState, seat: Seat, amount: number, source: Source | null, combat: boolean): void {
if (amount <= 0) return;
const p = state.players[seat];
p.life -= amount;
log(state, { kind: 'playerDamage', source: source ? ref(state, source) : null, seat, amount, life: p.life, combat });
}
function gainLife(state: DuelState, seat: Seat, amount: number, source: Source): void {
if (amount <= 0) return;
const p = state.players[seat];
p.life += amount;
log(state, { kind: 'lifeGain', source: ref(state, source), seat, amount, life: p.life });
}
/** Returns damage actually dealt. */
function dealDamage(state: DuelState, source: Source, target: TargetRef, amount: number, combat: boolean): number {
if (amount <= 0) return 0;
if (target.kind === 'player') { loseLife(state, target.seat, amount, source, combat); return amount; }
const perm = find(state, target.uid);
if (!perm || !isBody(perm)) return 0;
let dmg = amount;
if (!perm.shielded && hasKw(state, perm, 'Well-sourced')) { perm.shielded = true; dmg -= 1; }
if (dmg <= 0) return 0;
perm.damage += dmg;
log(state, { kind: combat ? 'combatDamage' : 'effectDamage', source: ref(state, source), target: ref(state, perm), amount: dmg });
return dmg;
}
function leave(state: DuelState, uid: string): Permanent | null {
const i = state.battlefield.findIndex(p => p.uid === uid);
if (i < 0) return null;
const [perm] = state.battlefield.splice(i, 1);
delete state.combat.blocks[uid];
for (const [b, a] of Object.entries(state.combat.blocks)) if (a === uid) delete state.combat.blocks[b];
state.combat.attackers = state.combat.attackers.filter(a => a !== uid);
return perm;
}
const toInstance = (perm: Permanent): CardInstance => ({ uid: perm.uid, owner: perm.owner, card: perm.card });
/** Destroy a set of permanents at once, then fire their triggers (active player's first, then entry order). */
function destroyAll(state: DuelState, uids: string[]): void {
const gone: Permanent[] = [];
for (const uid of uids) {
const perm = find(state, uid);
if (!perm) continue;
const card = ref(state, perm);
leave(state, uid);
if (!perm.card.token) state.players[perm.owner].graveyard.push(toInstance(perm));
log(state, { kind: 'destroyed', card, owner: perm.owner });
gone.push(perm);
}
gone.sort((a, b) => Number(a.controller !== state.active) - Number(b.controller !== state.active) || a.entered - b.entered);
for (const perm of gone) {
if (state.result) return;
for (const e of perm.card.effects) if (e.trigger === 'onDestroyed') resolveEffect(state, perm, perm.controller, e, undefined, undefined);
if (perm.card.keywords.includes('Legacy') || perm.permKeywords.includes('Legacy')) draw(state, perm.controller, 1);
}
}
function bounce(state: DuelState, uid: string): void {
const perm = find(state, uid);
if (!perm) return;
const card = ref(state, perm);
leave(state, uid);
if (!perm.card.token) state.players[perm.owner].hand.push(toInstance(perm));
log(state, { kind: 'bounced', card, owner: perm.owner });
}
/** State-based checks to a fixpoint: lethal damage, orphaned Doctrines, life totals; then Connected logging. */
function settle(state: DuelState): void {
for (let guard = 0; guard < 100 && !state.result; guard++) {
const dead = state.battlefield.filter(p => {
if (p.card.type === 'Doctrine') return !p.attachedTo || !find(state, p.attachedTo);
if (!isBody(p)) return false;
const { toughness } = statsOfPermanent(state, p);
return toughness <= 0 || p.damage >= toughness;
}).map(p => p.uid);
if (!dead.length) break;
destroyAll(state, dead);
}
if (state.result) return;
const lost = ([0, 1] as Seat[]).filter(s => state.players[s].life <= 0);
if (lost.length === 2) finish(state, null, 'life');
else if (lost.length === 1) finish(state, other(lost[0]), 'life');
if (!state.result) logConnections(state);
}
function logConnections(state: DuelState): void {
for (const perm of state.battlefield) {
if (perm.connectedLogged) continue;
const c = connectionOf(state, perm);
if (!c) continue;
perm.connectedLogged = true;
log(state, { kind: 'connected', seat: perm.controller, card: ref(state, perm), with: ref(state, c.with), tier: c.tier, via: c.via, bonus: c.bonus });
}
}
/** Rivalry (log only): when a card enters, note its best Connected tie to an opposing permanent, once. */
function logRivalry(state: DuelState, perm: Permanent): void {
let best: { with: Permanent; tier: ConnectedTier; via: string } | null = null;
for (const o of state.battlefield) {
if (o.controller === perm.controller) continue;
const t = tierBetween(state.rules, perm.card, o.card);
if (t && (!best || state.rules.connectedTiers.indexOf(t.tier) < state.rules.connectedTiers.indexOf(best.tier))) best = { with: o, ...t };
}
if (best) log(state, { kind: 'rivalry', card: ref(state, perm), with: ref(state, best.with), tier: best.tier, via: best.via });
}
function autoTargets(state: DuelState, source: Source, seat: Seat, t: TargetSpec): TargetRef[] {
const cards = (pred: (p: Permanent) => boolean) => state.battlefield.filter(pred).map(p => ({ kind: 'card', uid: p.uid }) as TargetRef);
switch (t) {
case 'controller': return [{ kind: 'player', seat }];
case 'opponent': return [{ kind: 'player', seat: other(seat) }];
case 'self': return find(state, source.uid) ? [{ kind: 'card', uid: source.uid }] : [];
case 'attached': {
const at = find(state, source.uid)?.attachedTo;
return at && find(state, at) ? [{ kind: 'card', uid: at }] : [];
}
case 'each': return cards(p => p.card.type === 'Figure' || p.card.type === 'Location');
case 'ownFigures': return cards(p => p.card.type === 'Figure' && p.controller === seat);
case 'opponentFigures': return cards(p => p.card.type === 'Figure' && p.controller !== seat);
default: return [];
}
}
function makeToken(state: DuelState, seat: Seat, source: Source, e: EffectSpec): void {
const spec = e.token;
if (!spec) return;
const n = e.amount ?? 1;
for (let i = 0; i < n; i++) {
if (e.condition?.maxTokens !== undefined) {
const count = state.battlefield.filter(p => p.controller === seat && p.card.token).length;
if (count >= e.condition.maxTokens) return;
}
const id = state.nextToken++;
const card: DuelCard = {
cardId: `token:${id}`, pageId: null, title: spec.name, type: 'Figure', portal: spec.portal, cost: 0,
power: spec.power, toughness: spec.toughness, keywords: [], effects: [], rulesText: '', flavor: '', token: true,
};
const perm = enter(state, { uid: `t:${id}`, owner: seat, card }, seat);
log(state, { kind: 'tokenCreated', seat, card: ref(state, perm), source: ref(state, source) });
}
}
/** Resolve one effect. `chosen` is this effect's target (chosen effects); `prev` the previous chosen target (fight). */
function resolveEffect(state: DuelState, source: Source, seat: Seat, e: EffectSpec, chosen: TargetRef | undefined, prev: TargetRef | undefined): void {
if (state.result || e.trigger === 'static') return;
const t = targetOf(e);
let targets: TargetRef[];
if (CHOSEN.has(t)) {
if (!chosen) return; // fizzles (no target, or chosen targets in automatic triggers)
const still = chosen.kind === 'player' ? t === 'anyTarget'
: candidates(state, seat, source.card, e).some(x => x.kind === 'card' && x.uid === chosen.uid);
if (!still) return;
targets = [chosen];
} else {
targets = autoTargets(state, source, seat, t);
}
const needs = !['draw', 'gainLife', 'createToken'].includes(e.op);
if (needs && !targets.length) return;
log(state, { kind: 'effect', seat, source: ref(state, source), op: e.op, ...(e.template ? { template: e.template } : {}), targets });
const amount = e.amount ?? 0;
const permOf = (x: TargetRef) => (x.kind === 'card' ? find(state, x.uid) : undefined);
switch (e.op) {
case 'damage': case 'damageEach':
for (const x of targets) dealDamage(state, source, x, amount, false);
break;
case 'createToken': makeToken(state, seat, source, e); break;
case 'pump': {
const p = e.power ?? amount, q = e.toughness ?? amount;
for (const x of targets) {
const perm = permOf(x);
if (!perm) continue;
if (e.duration === 'permanent') { perm.permPower += p; perm.permToughness += q; if (e.grant) perm.permKeywords.push(...e.grant); }
else { perm.tempPower += p; perm.tempToughness += q; if (e.grant) perm.tempKeywords.push(...e.grant); }
}
break;
}
case 'fight': {
const a = prev?.kind === 'card' ? find(state, prev.uid) : find(state, source.uid);
const b = permOf(targets[0]);
if (!a || !b || a.uid === b.uid) break;
const [ap, bp] = [statsOfPermanent(state, a).power, statsOfPermanent(state, b).power];
dealDamage(state, a, { kind: 'card', uid: b.uid }, ap, false);
dealDamage(state, b, { kind: 'card', uid: a.uid }, bp, false);
break;
}
case 'draw': draw(state, t === 'opponent' ? other(seat) : seat, e.amount ?? 1); break;
case 'attach': {
const perm = find(state, source.uid);
const to = permOf(targets[0]);
if (perm && to) { perm.attachedTo = to.uid; log(state, { kind: 'adopt', seat, card: ref(state, perm), to: ref(state, to) }); }
break;
}
case 'gainLife': gainLife(state, seat, amount, source); break;
case 'drain':
for (const x of targets) {
const victim = x.kind === 'player' ? x.seat : permOf(x)?.controller;
if (victim === undefined) continue;
loseLife(state, victim, amount, source, false);
if (victim !== seat) gainLife(state, seat, amount, source);
}
break;
case 'destroy': destroyAll(state, targets.filter(x => x.kind === 'card').map(x => (x as { uid: string }).uid)); break;
case 'bounce': for (const x of targets) if (x.kind === 'card') bounce(state, x.uid); break;
case 'tap': for (const x of targets) { const perm = permOf(x); if (perm) perm.tapped = true; } break;
}
}
function enter(state: DuelState, inst: CardInstance, seat: Seat): Permanent {
const perm: Permanent = {
...inst, controller: seat, tapped: false, sick: true, damage: 0, counters: 0, permPower: 0, permToughness: 0,
tempPower: 0, tempToughness: 0, tempKeywords: [], permKeywords: [], shielded: false, entered: state.nextEntry++, connectedLogged: false,
};
state.battlefield.push(perm);
return perm;
}
/** Run a card's entry effects, feeding chosen targets in order. */
function runEntry(state: DuelState, source: Source, seat: Seat, targets: TargetRef[]): void {
let i = 0;
let prev: TargetRef | undefined;
for (const e of source.card.effects) {
if (!isEntry(e) || state.result) continue;
if (CHOSEN.has(targetOf(e))) {
const chosen = targets[i++];
resolveEffect(state, source, seat, e, chosen, prev);
prev = chosen;
} else {
resolveEffect(state, source, seat, e, undefined, prev);
}
}
}
// ---------------------------------------------------------------------------
// Turn structure
// ---------------------------------------------------------------------------
function totalPower(state: DuelState, seat: Seat): number {
return state.battlefield.filter(p => p.controller === seat && p.card.type === 'Figure').reduce((n, p) => n + statsOfPermanent(state, p).power, 0);
}
function startTurn(state: DuelState, seat: Seat): void {
if (state.rules.turnCap !== null && state.turn >= state.rules.turnCap) {
const [a, b] = life(state);
const [pa, pb] = [totalPower(state, 0), totalPower(state, 1)];
const winner: Seat = a !== b ? (a > b ? 0 : 1) : pa !== pb ? (pa > pb ? 0 : 1) : other(state.firstSeat);
finish(state, winner, 'turnCap');
return;
}
state.turn += 1;
state.active = seat;
state.phase = 'main';
state.combat = { attackers: [], blocks: {} };
const p = state.players[seat];
p.locationsThisTurn = 0;
p.baseCitations = Math.min(state.rules.maxCitations, p.baseCitations + state.rules.citationsPerTurn);
p.citations = maxCitations(state, seat);
if (state.turn === 2 && seat !== state.firstSeat) p.citations += state.rules.secondPlayerCitations;
for (const perm of state.battlefield) {
perm.shielded = false;
if (perm.controller === seat) { perm.tapped = false; perm.sick = false; }
}
log(state, { kind: 'turnStart', seat, citations: p.citations, life: life(state) });
const mine = state.battlefield.filter(x => x.controller === seat).sort((a, b) => a.entered - b.entered);
for (const perm of mine) {
if (!find(state, perm.uid) || state.result) continue;
if (perm.card.keywords.includes('Stub') && perm.counters < state.rules.stubMax) perm.counters += 1;
for (const e of perm.card.effects) if (e.trigger === 'startOfTurn' && find(state, perm.uid)) resolveEffect(state, perm, seat, e, undefined, undefined);
}
settle(state);
if (state.result) return;
if (!(state.turn === 1 && !state.rules.firstPlayerDraws)) draw(state, seat, 1);
settle(state);
}
function endTurn(state: DuelState): void {
for (const perm of state.battlefield) { perm.damage = 0; perm.tempPower = 0; perm.tempToughness = 0; perm.tempKeywords = []; }
state.combat = { attackers: [], blocks: {} };
const seat = state.active;
const p = state.players[seat];
while (p.hand.length > state.rules.handSize) {
let worst = p.hand.length - 1;
for (let i = p.hand.length - 1; i >= 0; i--) if (p.hand[i].card.cost > p.hand[worst].card.cost) worst = i;
const [inst] = p.hand.splice(worst, 1);
p.graveyard.push(inst);
log(state, { kind: 'discard', seat, card: ref(state, inst) });
}
settle(state);
if (!state.result) startTurn(state, other(seat));
}
function play(state: DuelState, seat: Seat, uid: string, targets: TargetRef[]): void {
const p = state.players[seat];
const [inst] = p.hand.splice(p.hand.findIndex(c => c.uid === uid), 1);
p.citations -= inst.card.cost;
if (inst.card.type === 'Event') {
log(state, { kind: 'cast', seat, card: ref(state, inst), targets });
runEntry(state, inst, seat, targets);
p.graveyard.push(inst);
settle(state);
return;
}
if (inst.card.type === 'Location') p.locationsThisTurn += 1;
const perm = enter(state, inst, seat);
if (inst.card.type !== 'Doctrine') log(state, { kind: 'deploy', seat, card: ref(state, perm) });
logRivalry(state, perm);
runEntry(state, perm, seat, targets);
settle(state);
}
function confirmAttack(state: DuelState): void {
const seat = state.active;
if (!state.combat.attackers.length) { endTurn(state); return; }
const attackers = state.combat.attackers.map(uid => find(state, uid)).filter((x): x is Permanent => !!x);
for (const a of attackers) a.tapped = true;
log(state, { kind: 'attack', seat, attackers: attackers.map(a => ref(state, a)) });
for (const a of attackers) for (const e of a.card.effects) if (e.trigger === 'onAttack' && find(state, a.uid)) resolveEffect(state, a, seat, e, undefined, undefined);
settle(state);
if (state.result) return;
if (!state.combat.attackers.length) { endTurn(state); return; }
state.phase = 'block';
if (!blockOptions(state).length) resolveCombat(state);
}
function resolveCombat(state: DuelState): void {
const defender = other(state.active);
const pairs = Object.entries(state.combat.blocks)
.map(([b, a]) => ({ blocker: find(state, b), attacker: find(state, a) }))
.filter((x): x is { blocker: Permanent; attacker: Permanent } => !!x.blocker && !!x.attacker);
if (pairs.length) log(state, { kind: 'block', seat: defender, blocks: pairs.map(x => ({ blocker: ref(state, x.blocker), attacker: ref(state, x.attacker) })) });
// Simultaneous: compute every amount first, then apply.
const hits: { source: Permanent; target: TargetRef; amount: number }[] = [];
const blockerOf = new Map(pairs.map(x => [x.attacker.uid, x.blocker]));
for (const uid of state.combat.attackers) {
const a = find(state, uid);
if (!a) continue;
const ap = statsOfPermanent(state, a).power;
const b = blockerOf.get(uid);
if (b) {
hits.push({ source: a, target: { kind: 'card', uid: b.uid }, amount: ap });
hits.push({ source: b, target: { kind: 'card', uid: a.uid }, amount: statsOfPermanent(state, b).power });
} else {
hits.push({ source: a, target: { kind: 'player', seat: defender }, amount: ap });
}
}
const toPlayer: Permanent[] = [];
for (const h of hits) if (dealDamage(state, h.source, h.target, h.amount, true) > 0 && h.target.kind === 'player') toPlayer.push(h.source);
for (const a of toPlayer) {
for (const e of a.card.effects) if (e.trigger === 'onCombatDamageToPlayer') resolveEffect(state, a, a.controller, e, undefined, undefined);
for (const d of state.battlefield.filter(x => x.card.type === 'Doctrine' && x.attachedTo === a.uid)) {
for (const e of d.card.effects) if (e.trigger === 'onCombatDamageToPlayer') resolveEffect(state, d, d.controller, e, undefined, undefined);
}
}
settle(state);
if (!state.result) endTurn(state);
}
// ---------------------------------------------------------------------------
// applyAction
// ---------------------------------------------------------------------------
/**
* Structural clone for clone-on-apply. DuelCards, CardInstances, log events and the
* ruleset are never mutated after creation, so they are shared between states;
* Permanents, players and combat are copied. (structuredClone was 85% of runtime.)
*/
function cloneState(s: DuelState): DuelState {
const player = (p: PlayerState): PlayerState => ({ ...p, library: p.library.slice(), hand: p.hand.slice(), graveyard: p.graveyard.slice() });
return {
...s,
players: [player(s.players[0]), player(s.players[1])],
battlefield: s.battlefield.map(p => ({ ...p, tempKeywords: p.tempKeywords.slice(), permKeywords: p.permKeywords.slice() })),
combat: { attackers: s.combat.attackers.slice(), blocks: { ...s.combat.blocks } },
log: s.log.slice(),
result: s.result ? { ...s.result } : null,
};
}
function normalize(action: DuelAction): DuelAction {
// Canonical key order so deep-equal against legalActions is stable.
switch (action.type) {
case 'play': {
const targets = (action.targets ?? []).map(t => (t.kind === 'card' ? { kind: 'card' as const, uid: t.uid } : { kind: 'player' as const, seat: t.seat }));
return targets.length ? { type: 'play', uid: action.uid, targets } : { type: 'play', uid: action.uid };
}
case 'toggleAttacker': return { type: 'toggleAttacker', uid: action.uid };
case 'block': return { type: 'block', blocker: action.blocker, attacker: action.attacker };
default: return { type: action.type } as DuelAction;
}
}
export function applyAction(input: DuelState, seat: Seat, action: DuelAction): DuelState {
if (input.result) throw new Error('Match is over');
if (seat !== 0 && seat !== 1) throw new RangeError('Bad seat');
if (!action || typeof action !== 'object' || typeof (action as { type?: unknown }).type !== 'string') throw new TypeError('Bad action');
if (action.type === 'concede') {
const state = cloneState(input);
state.version += 1;
log(state, { kind: 'concede', seat });
finish(state, other(seat), 'concede');
return state;
}
if (toAct(input) !== seat) throw new Error('Not your turn to act');
if (action.type === 'timeout') {
const state = cloneState(input);
state.version += 1;
log(state, { kind: 'timeout', seat });
const p = state.players[seat];
p.timeouts += 1;
if (p.timeouts >= state.rules.timeoutsToConcede) { finish(state, other(seat), 'timeout'); return state; }
switch (state.phase) {
case 'mulligan': keep(state, seat); break;
case 'main': case 'attack': state.combat.attackers = []; endTurn(state); break;
case 'block': resolveCombat(state); break;
}
return state;
}
const a = normalize(action);
const key = JSON.stringify(a);
if (!legalActions(input, seat).some(x => JSON.stringify(x) === key)) throw new Error(`Illegal action ${JSON.stringify(action)}`);
const state = cloneState(input);
state.version += 1;
state.players[seat].timeouts = 0;
switch (a.type) {
case 'keep': keep(state, seat); break;
case 'mulligan': mulligan(state, seat); break;
case 'play': play(state, seat, a.uid, a.targets ?? []); break;
case 'endPhase': state.phase = 'attack'; break;
case 'toggleAttacker': state.combat.attackers.push(a.uid); break;
case 'confirmAttack': confirmAttack(state); break;
case 'block': state.combat.blocks[a.blocker] = a.attacker; break;
case 'confirmBlocks': resolveCombat(state); break;
}
return state;
}
function keep(state: DuelState, seat: Seat): void {
const p = state.players[seat];
for (let i = 0; i < p.mulligansTaken && p.hand.length; i++) p.library.push(p.hand.pop()!);
p.ready = true;
log(state, { kind: 'keep', seat, handSize: p.hand.length });
if (state.players[0].ready && state.players[1].ready) startTurn(state, state.firstSeat);
}
function mulligan(state: DuelState, seat: Seat): void {
const p = state.players[seat];
const rng = new Rng(state.rng);
p.library = rng.shuffle([...p.library, ...p.hand]);
state.rng = rng.state;
p.hand = p.library.splice(0, state.rules.openingHand);
p.mulligansTaken += 1;
log(state, { kind: 'mulligan', seat });
}
// ---------------------------------------------------------------------------
// Views, log, replay, serialisation
// ---------------------------------------------------------------------------
function side(state: DuelState, seat: Seat): SideView {
const p = state.players[seat];
return {
seat, life: p.life, citations: p.citations, maxCitations: maxCitations(state, seat), handSize: p.hand.length,
librarySize: p.library.length, graveyard: structuredClone(p.graveyard), bankSeconds: p.bankSeconds, ready: p.ready, mulligansTaken: p.mulligansTaken,
};
}
export function viewFor(state: DuelState, seat: Seat): PlayerView {
const battlefield: PermanentView[] = state.battlefield.map(perm => {
const { power, toughness } = statsOfPermanent(state, perm);
const c = connectionOf(state, perm);
return {
uid: perm.uid, owner: perm.owner, controller: perm.controller, card: structuredClone(perm.card), tapped: perm.tapped, sick: perm.sick,
damage: perm.damage, counters: perm.counters, ...(perm.attachedTo ? { attachedTo: perm.attachedTo } : {}), power, toughness,
keywords: keywordsOf(state, perm), ...(c ? { connected: { with: c.with.uid, tier: c.tier, via: c.via, bonus: c.bonus } } : {}),
};
});
return {
engine: 'duel', seat, turn: state.turn, active: state.active, phase: state.phase, toAct: toAct(state),
you: { ...side(state, seat), hand: structuredClone(state.players[seat].hand) },
opponent: side(state, other(seat)),
battlefield, combat: structuredClone(state.combat), result: state.result, version: state.version, rules: structuredClone(state.rules),
};
}
export function logFor(state: DuelState, seat: Seat): LogEvent[] {
return state.log.map(e => {
if (e.kind === 'draw' && e.seat !== seat) return { seq: e.seq, turn: e.turn, kind: 'draw', seat: e.seat } as LogEvent;
return structuredClone(e);
});
}
export function replay(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string, actions: { seat: Seat; action: DuelAction }[]): DuelState {
let state = createDuel(rules, decks, seed);
for (const { seat, action } of actions) state = applyAction(state, seat, action);
return state;
}
export const serialize = (state: DuelState): string => JSON.stringify(state);
export function deserialize(text: string): DuelState {
const value = JSON.parse(text) as DuelState;
if (!value || value.engine !== 'duel') throw new TypeError('Not a duel state');
return value;
}
// ---------------------------------------------------------------------------
// Host binding: structurally an EnginePort<DuelRuleset, DuelCard, DuelState, DuelAction>
// (server/game/engine-port.ts). shared/ must not import server/, so host-pvp types it there.
// ---------------------------------------------------------------------------
export const duelEnginePort = {
defaultRuleset: DEFAULT_DUEL_RULESET,
parseRuleset: (value: unknown) => parseDuelRuleset(value),
deckSize: (rules: DuelRuleset) => rules.deckSize,
starterDeck(_rules?: DuelRuleset, _seed?: string): DuelCard[] { throw new Error('Duel has no starter decks: every card must be owned (BRIEF decision 2)'); },
previewPool(_rules?: DuelRuleset, _seed?: string, _size?: number): DuelCard[] { throw new Error('Duel draft pools come from both players’ collections, not previews'); },
validateDeck,
cardPower: (card: DuelCard) => pw(card),
withPower: (card: DuelCard, power: number): DuelCard => ({ ...card, power: Math.max(0, Math.round(power)) }),
cardPageId: (card: DuelCard) => card.pageId,
cardSummary: (card: DuelCard) => ({
cardId: card.cardId, pageId: card.pageId, title: card.title, type: card.type, portal: card.portal, cost: card.cost,
power: card.power, toughness: card.toughness, keywords: card.keywords, rulesText: card.rulesText,
}),
createMatch: (rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string) => createDuel(rules, decks, seed),
legalActions,
applyAction,
concedeAction: (_seat: Seat): DuelAction => ({ type: 'concede' }),
timeoutAction: (_seat: Seat): DuelAction => ({ type: 'timeout' }),
turnSeconds: (rules: DuelRuleset) => rules.turnSeconds,
turnOf,
/** Trending mode (DUEL_DESIGN §4): a frozen live ▲ ≥ +25% grants Trending (haste, +trendingPower/+0 in play). */
applyLive(_rules: DuelRuleset, card: DuelCard, live: { trendPercent: number | null }): DuelCard {
if (live.trendPercent === null || live.trendPercent < 25 || card.type !== 'Figure' || card.keywords.includes('Trending')) return card;
return { ...card, keywords: [...card.keywords, 'Trending'] };
},
isOver,
result: (state: DuelState) => state.result ?? { winner: null, reason: 'in progress' },
viewFor,
logFor,
};
+40
View File
@@ -0,0 +1,40 @@
/**
* WikiDeck Duel public API. Spec: docs/game/DUEL_API.md.
* Contracts PR: types and ruleset only. engine.ts (createDuel, legalActions,
* applyAction, viewFor, logFor, replay, ...) lands in the engine alpha PR and
* implements DuelEngineApi below; build against that interface until then.
*/
export * from './types.ts';
export * from './ruleset.ts';
export * from './engine.ts';
import type { DuelAction, DuelCard, DuelResult, DuelRuleset, DuelState, LogEvent, PlayerView, Seat } from './types.ts';
/** The engine's function surface (implemented by shared/duel/engine.ts). All pure; inputs are never mutated. */
export interface DuelEngineApi {
/** Throws if the deck is illegal: size ≠ deckSize, duplicate cardId, > maxCopiesPerPage of one pageId, bad stats, > maxKeywords. */
validateDeck(rules: DuelRuleset, cards: DuelCard[]): void;
/** Shuffle both decks from `seed`, deal opening hands, phase 'mulligan'. */
createDuel(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string): DuelState;
/** Atomic legal actions for `seat`; [] if `seat` is not the one to act (concede is always accepted by applyAction but not listed). */
legalActions(state: DuelState, seat: Seat): DuelAction[];
/** Returns a new state. Throws on an illegal action. */
applyAction(state: DuelState, seat: Seat, action: DuelAction): DuelState;
/** Seat that must act now, or null when over. Mulligan: the lowest seat not yet ready. */
toAct(state: DuelState): Seat | null;
isOver(state: DuelState): boolean;
result(state: DuelState): DuelResult | null;
viewFor(state: DuelState, seat: Seat): PlayerView;
/** Per-seat log: the opponent's draws (and other hidden-zone cards) are masked. */
logFor(state: DuelState, seat: Seat): LogEvent[];
/** Deterministic: same inputs → identical state (and log). */
replay(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string, actions: { seat: Seat; action: DuelAction }[]): DuelState;
serialize(state: DuelState): string;
deserialize(text: string): DuelState;
/** Current power/toughness of a permanent after counters, buffs, statics and Connected. */
statsOf(state: DuelState, uid: string): { power: number; toughness: number };
}
import * as engine from './engine.ts';
/** Compile-time check that engine.ts implements the contract. */
export const duelEngine: DuelEngineApi = engine;
+78
View File
@@ -0,0 +1,78 @@
/**
* Duel ruleset: every rule number as data (BRIEF "Game rules core").
* parseDuelRuleset() is the only way untrusted JSON (mode files, peer hosts)
* becomes a DuelRuleset. Night 1 Edit War rulesets are rejected cleanly.
*/
import { z } from 'zod';
import type { DuelRuleset } from './types.ts';
const int = (min: number, max: number) => z.number().int().min(min).max(max);
export const DuelRulesetSchema = z.object({
engine: z.literal('duel'),
version: z.string().min(1).max(16),
deckSize: int(1, 60),
maxCopiesPerPage: int(1, 60),
startingLife: int(1, 100),
openingHand: int(0, 10),
handSize: int(1, 15),
mulligans: int(0, 3),
firstPlayerDraws: z.boolean(),
secondPlayerCitations: int(0, 5),
maxCitations: int(1, 20),
citationsPerTurn: int(1, 5),
territoryCap: int(0, 10),
locationsPerTurn: int(0, 10),
libraryEmpty: z.enum(['lose', 'reshuffle', 'fatigue']),
maxKeywords: int(0, 4),
stubMax: int(0, 10),
trendingPower: int(0, 5),
connectedTiers: z.array(z.enum(['Linked', 'Compatriot', 'Contemporary', 'Kin'])).max(4)
.refine(v => new Set(v).size === v.length, 'Duplicate tier'),
connectedBonus: int(0, 5),
linkedBonus: int(0, 5),
turnSeconds: int(5, 600),
bankSeconds: int(0, 3600),
timeoutsToConcede: int(1, 20),
turnCap: int(2, 200).nullable(),
}).strict();
export const DEFAULT_DUEL_RULESET: DuelRuleset = Object.freeze({
engine: 'duel',
version: 'duel-1',
deckSize: 40,
maxCopiesPerPage: 4,
startingLife: 20,
openingHand: 7,
handSize: 7,
mulligans: 1,
firstPlayerDraws: false,
secondPlayerCitations: 1, // balance v1 (#64): first player 60.1% → 54.7%
maxCitations: 10,
citationsPerTurn: 1,
territoryCap: 2,
locationsPerTurn: 1,
libraryEmpty: 'lose',
maxKeywords: 2,
stubMax: 2,
trendingPower: 1,
connectedTiers: ['Linked', 'Compatriot', 'Contemporary', 'Kin'],
connectedBonus: 1,
linkedBonus: 2,
turnSeconds: 60,
bankSeconds: 300,
timeoutsToConcede: 3,
turnCap: 40, // balance v1 (#64): 3.9% of games decided at the cap
}) as DuelRuleset;
/** Validate a full ruleset. Throws (ZodError) on anything invalid or unknown. */
export function parseDuelRuleset(value: unknown): DuelRuleset {
return DuelRulesetSchema.parse(value) as DuelRuleset;
}
/** Merge a partial override (a mode file's `rules`) onto the defaults, then validate. */
export function mergeDuelRuleset(overrides: unknown, base: DuelRuleset = DEFAULT_DUEL_RULESET): DuelRuleset {
if (overrides === undefined || overrides === null) return parseDuelRuleset(structuredClone(base));
if (typeof overrides !== 'object' || Array.isArray(overrides)) throw new TypeError('Ruleset overrides must be an object');
return parseDuelRuleset({ ...structuredClone(base), ...(overrides as Record<string, unknown>) });
}
+398
View File
@@ -0,0 +1,398 @@
/**
* WikiDeck Duel: the Magic-style 40-card engine (off-chain). Contract types.
* Spec: docs/game/DUEL_API.md (rules: docs/game/DUEL_DESIGN.md). Owner: duel-core (claude/wikideck#55).
*
* Everything here is plain JSON data: DuelState round-trips through
* JSON.stringify/parse with no loss (no Maps, classes or functions).
* shared/game/ (Edit War) is a separate engine and is not affected.
*/
import type { RngState } from '../game/rng.ts';
export type Seat = 0 | 1;
export const SEATS: readonly Seat[] = [0, 1];
// ---------------------------------------------------------------------------
// Cards (derived by duel-cards in shared/duel/derive.ts; the engine never re-derives)
// ---------------------------------------------------------------------------
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
export const CARD_TYPES: readonly CardType[] = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine'];
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
export const PORTALS: readonly Portal[] = ['Arts', 'Earth', 'History', 'Science', 'Society', 'Neutral'];
/** Card keywords (DUEL_DESIGN §4), ≤ ruleset.maxKeywords per card. 'Trending' is granted by Trending mode only. */
export type Keyword = 'Protected' | 'Featured' | 'Legacy' | 'Multilingual' | 'Translated' | 'Well-sourced' | 'Stub' | 'Local' | 'Trending';
export const KEYWORDS: readonly Keyword[] = ['Protected', 'Featured', 'Legacy', 'Multilingual', 'Translated', 'Well-sourced', 'Stub', 'Local', 'Trending'];
/** Connected tiers (DUEL_DESIGN §6). The engine computes them from `connect`. */
export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin';
export const CONNECTED_TIERS: readonly ConnectedTier[] = ['Linked', 'Compatriot', 'Contemporary', 'Kin'];
/** Frozen claims used for Connected (no I/O during a match). */
export interface ConnectKeys {
/** P17/P27 values (Q-ids or labels; compared as strings). */
countries: string[];
/** From P569/P570/P571/P580/P585, e.g. 19 for the 1800s. */
centuries: number[];
/** Outlink pageIds (cached), plus pageIds the card's claims cite. */
links: number[];
/** P31 Q-ids. Q5 (human) and Q16521 (taxon) never count for Kin. */
p31: string[];
/** The card's own Q-id, and the Q-ids its claims cite: Linked if either cites the other (DUEL_DESIGN §6). */
qid?: string;
cites?: string[];
}
/** When an effect runs. Sorcery speed only: there is no stack and no response window. */
export type EffectTrigger =
| 'onPlay' // an Event resolves (on a permanent: same as onEnter)
| 'onEnter' // this permanent enters the battlefield
| 'onAttack' // this Figure is declared as an attacker (resolves at confirmAttack)
| 'onDestroyed' // this permanent is destroyed (after all combat damage)
| 'startOfTurn' // its controller's refresh step, in entry order
| 'onCombatDamageToPlayer' // this Figure (or the Figure this Doctrine is attached to) deals combat damage to a player
| 'static'; // continuous while on the battlefield
/** Effect ops the interpreter knows. duel-cards builds the 12 templates (DUEL_DESIGN §5) from these. */
export type EffectOp =
| 'damage' // `amount` to each target (Figure, Location or player)
| 'damageEach' // `amount` to every Figure and Location (target narrows: 'ownFigures' / 'opponentFigures')
| 'createToken' // `amount` (default 1) copies of `token` under the controller; condition.maxTokens limits
| 'pump' // +power/+toughness (negative allowed); duration 'turn' | 'permanent'; as static: while the source is in play
| 'fight' // the previous chosen target (else this permanent) and this target deal damage equal to their power to each other
| 'draw' // controller draws `amount`
| 'attach' // Doctrine: attach to the target Figure (defines the Doctrine's target)
| 'gainLife' // controller gains `amount` Notability
| 'drain' // opponent loses `amount`, controller gains `amount`
| 'destroy' // destroy target permanent
| 'bounce' // return target permanent to its owner's hand
| 'tap'; // tap target permanent
export type TargetSpec =
// chosen (each consumes one entry of play.targets, in effect order)
| 'figure' // any Figure
| 'figureOrLocation' // any Figure or Location
| 'ownFigure' // a Figure you control
| 'opponentFigure' // a Figure you don't control
| 'anyTarget' // any Figure, Location or player
// automatic
| 'each' // every Figure and Location
| 'self' // this permanent
| 'attached' // the Figure this Doctrine is attached to
| 'ownFigures' // every Figure you control
| 'opponentFigures' // every Figure you don't control
| 'opponent' // the opposing player
| 'controller'; // you
export interface TokenSpec { name: string; power: number; toughness: number; portal: Portal }
export interface EffectSpec {
trigger: EffectTrigger;
op: EffectOp;
/** Default per op: damage → 'anyTarget'; pump → 'self'; draw/gainLife/createToken → 'controller'; drain → 'opponent'. */
target?: TargetSpec;
amount?: number;
/** pump: +power/+toughness (default: amount/amount). */
power?: number;
toughness?: number;
/** pump/grant outside static: 'turn' (default) or 'permanent'. */
duration?: 'turn' | 'permanent';
token?: TokenSpec;
condition?: {
/** Only affects Figures with printed power ≤ maxPower. */
maxPower?: number;
/** Only Figures of the source's Portal (for a Doctrine: the attached Figure's Portal), excluding that card itself. */
samePortal?: boolean;
/** Only Figures Connected to the source. */
connected?: boolean;
/** createToken: only if the controller controls fewer than this many tokens. */
maxTokens?: number;
};
/** Keywords granted to the affected Figures (static: while in play; otherwise for `duration`). */
grant?: Keyword[];
/** Template id (T1–T12) for rules text and log wording. */
template?: string;
}
/**
* A card as the engine sees it, frozen at match start. The host builds these
* from the chain via duel-cards' derive(); the engine trusts them.
*/
export interface DuelCard {
/** Unique within one deck: the NFT tokenId (or a sample id in sims; `token:` ids for tokens). */
cardId: string;
pageId: number | null;
revisionId?: number;
title: string;
/** Wikidata description ("American actor (1909–1994)"), for log first mentions. */
description?: string;
type: CardType;
/** e.g. 'conflict', 'election', 'organisation', 'pathology'. */
subtype?: string | null;
portal: Portal;
cost: number;
/** Figures: the body. Locations: power 0, toughness = Garrison (0 = can't block). Others: null or 0. */
power: number | null;
toughness: number | null;
keywords: Keyword[];
/** Locations: +N max Citations while controlled (all sources together ≤ territoryCap). */
territory?: number;
effects: EffectSpec[];
/** Deterministic rules text (shared/duel/text.ts). Display only. */
rulesText: string;
/** First sentence of article.extract (else description). Display only. */
flavor: string;
connect?: ConnectKeys;
rarity?: 'Common' | 'Rare' | 'Epic' | 'Legendary';
deriveVersion?: string;
/** Tokens are created in play and never in decks. */
token?: boolean;
}
// ---------------------------------------------------------------------------
// Ruleset (all numbers are data; parseDuelRuleset in ruleset.ts validates)
// ---------------------------------------------------------------------------
export type LibraryEmpty = 'lose' | 'reshuffle' | 'fatigue';
export interface DuelRuleset {
engine: 'duel';
version: string;
deckSize: number; // 40
maxCopiesPerPage: number; // 4
startingLife: number; // 20 Notability
openingHand: number; // 7
handSize: number; // 7: hand limit at end of turn (DUEL_DESIGN `handLimit`); excess discarded highest cost first
mulligans: number; // 1: shuffle, draw openingHand, bottom one per mulligan taken
firstPlayerDraws: boolean; // false
secondPlayerCitations: number; // 1 (balance v1): extra Citations on the second player's first turn (designer's "Second Opinion" lever)
maxCitations: number; // 10
citationsPerTurn: number; // 1
territoryCap: number; // 2
locationsPerTurn: number; // 1
libraryEmpty: LibraryEmpty; // 'lose'
maxKeywords: number; // 2
stubMax: number; // 2: max Stub counters
trendingPower: number; // 1: Trending gets +N/+0
connectedTiers: ConnectedTier[]; // all four; cut tiers by removing them
connectedBonus: number; // 1
linkedBonus: number; // 2
turnSeconds: number; // 60
bankSeconds: number; // 300
timeoutsToConcede: number; // 3 consecutive timeouts lose
/** 40 (balance v1); null = none. After this many turns in total, higher Notability wins, then higher power in play, then the second player. */
turnCap: number | null;
}
// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------
/** 'mulligan' → 'main' → 'attack' → ('block' if attackers can be blocked) → next turn. Refresh, draw, damage and end are automatic. */
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
/** One physical card in a match. `uid` is unique per match ("0:12" = seat 0, deck index 12; "t:3" = token); actions use uids. */
export interface CardInstance {
uid: string;
owner: Seat;
card: DuelCard;
}
export interface Permanent extends CardInstance {
controller: Seat;
tapped: boolean;
/** "Pending review": entered this turn, can't attack. */
sick: boolean;
damage: number;
/** Stub +1/+1 counters. */
counters: number;
/** Permanent pump modifiers. */
permPower: number;
permToughness: number;
/** Until-end-of-turn modifiers. */
tempPower: number;
tempToughness: number;
/** Keywords granted until end of turn / permanently by non-static effects. */
tempKeywords: Keyword[];
permKeywords: Keyword[];
/** Doctrines: uid of the Figure they're attached to. */
attachedTo?: string;
/** Well-sourced: prevention already used this turn. */
shielded: boolean;
/** Entry order (trigger order). */
entered: number;
/** Connected bonus already logged. */
connectedLogged: boolean;
}
export interface PlayerState {
life: number;
/** Citations available this turn. */
citations: number;
/** Base max (rises by citationsPerTurn to maxCitations). */
baseCitations: number;
library: CardInstance[]; // top = index 0. Hidden.
hand: CardInstance[]; // hidden from the opponent
graveyard: CardInstance[]; // "Deleted", public
mulligansTaken: number;
ready: boolean;
locationsThisTurn: number;
/** Remaining time bank in seconds (the host decrements it). */
bankSeconds: number;
/** Consecutive timeouts. */
timeouts: number;
/** libraryEmpty 'fatigue': damage of the last empty draw. */
fatigue: number;
}
export interface CombatState {
attackers: string[];
/** blocker uid → attacker uid. */
blocks: Record<string, string>;
}
export type EndReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap';
export interface DuelResult {
winner: Seat | null; // null = draw
reason: EndReason;
}
export interface DuelState {
engine: 'duel';
rules: DuelRuleset;
seed: string;
rng: RngState;
/** 1-based, counts both players' turns. 0 during mulligans. */
turn: number;
active: Seat;
firstSeat: Seat;
phase: Phase;
players: [PlayerState, PlayerState];
battlefield: Permanent[];
combat: CombatState;
log: LogEvent[];
result: DuelResult | null;
/** Increments on every applied action (host polling: unchanged → 204). */
version: number;
/** Counters for token uids and entry order. */
nextToken: number;
nextEntry: number;
}
// ---------------------------------------------------------------------------
// Actions (atomic; legalActions enumerates them; [] for the seat not to act)
// ---------------------------------------------------------------------------
export type TargetRef = { kind: 'card'; uid: string } | { kind: 'player'; seat: Seat };
export type DuelAction =
| { type: 'keep' }
| { type: 'mulligan' }
/** targets: one per chosen-target effect, in effect order (Doctrine: its 'attach' target). Omitted when none. */
| { type: 'play'; uid: string; targets?: TargetRef[] }
| { type: 'endPhase' } // main → attack
| { type: 'toggleAttacker'; uid: string } // declare one more attacker (monotonic)
| { type: 'confirmAttack' } // no attackers → end turn
| { type: 'block'; blocker: string; attacker: string } // defender, monotonic
| { type: 'confirmBlocks' } // damage, then end of turn
| { type: 'concede' } // any time, either seat (not listed)
| { type: 'timeout' }; // host-only, for the seat that must act (not listed)
// ---------------------------------------------------------------------------
// Log (encyclopedic; clients get logFor(state, seat); state.log is omniscient)
// ---------------------------------------------------------------------------
/** A card in the log. power/toughness: current values right after the event (Figures and Garrisons on the battlefield). */
export interface CardRef { uid: string; cardId: string; title: string; pageId: number | null; type: CardType; power?: number; toughness?: number }
export type LogEvent = { seq: number; turn: number } & (
| { kind: 'start'; firstSeat: Seat }
| { kind: 'mulligan'; seat: Seat }
| { kind: 'keep'; seat: Seat; handSize: number }
| { kind: 'turnStart'; seat: Seat; citations: number; life: [number, number] }
/** card is omitted in the opponent's logFor (hidden draw). */
| { kind: 'draw'; seat: Seat; card?: CardRef }
/** A Figure, Location or Institution entered. */
| { kind: 'deploy'; seat: Seat; card: CardRef }
/** An Event resolved. */
| { kind: 'cast'; seat: Seat; card: CardRef; targets: TargetRef[] }
/** A Doctrine was attached. */
| { kind: 'adopt'; seat: Seat; card: CardRef; to: CardRef }
| { kind: 'tokenCreated'; seat: Seat; card: CardRef; source: CardRef }
| { kind: 'connected'; seat: Seat; card: CardRef; with: CardRef; tier: ConnectedTier; via: string; bonus: number }
/** Rivalry (log only): two opposing permanents are Connected. */
| { kind: 'rivalry'; card: CardRef; with: CardRef; tier: ConnectedTier; via: string }
/** Any resolved effect (wording key: template). Damage and life changes follow as their own events. */
| { kind: 'effect'; seat: Seat; source: CardRef; op: EffectOp; template?: string; targets: TargetRef[] }
| { kind: 'attack'; seat: Seat; attackers: CardRef[] }
| { kind: 'block'; seat: Seat; blocks: { blocker: CardRef; attacker: CardRef }[] }
/** Damage to a permanent from an effect / from combat. */
| { kind: 'effectDamage'; source: CardRef; target: CardRef; amount: number }
| { kind: 'combatDamage'; source: CardRef; target: CardRef; amount: number }
/** Damage or life loss to a player. source null = fatigue. */
| { kind: 'playerDamage'; source: CardRef | null; seat: Seat; amount: number; life: number; combat: boolean }
| { kind: 'lifeGain'; source: CardRef; seat: Seat; amount: number; life: number }
| { kind: 'destroyed'; card: CardRef; owner: Seat }
| { kind: 'bounced'; card: CardRef; owner: Seat }
| { kind: 'discard'; seat: Seat; card: CardRef }
| { kind: 'fatigue'; seat: Seat; amount: number }
| { kind: 'concede'; seat: Seat }
| { kind: 'timeout'; seat: Seat }
| { kind: 'gameOver'; winner: Seat | null; reason: EndReason; life: [number, number] }
);
export type LogKind = LogEvent['kind'];
// ---------------------------------------------------------------------------
// Views (what one seat may see; bots and UI get only this)
// ---------------------------------------------------------------------------
export interface PermanentView {
uid: string;
owner: Seat;
controller: Seat;
card: DuelCard;
tapped: boolean;
sick: boolean;
damage: number;
counters: number;
attachedTo?: string;
/** Current values after counters, pumps, statics, Connected and Trending. */
power: number;
toughness: number;
keywords: Keyword[];
/** Active Connected bonus, if any (for the card face). */
connected?: { with: string; tier: ConnectedTier; via: string; bonus: number };
}
export interface SideView {
seat: Seat;
life: number;
citations: number;
maxCitations: number;
handSize: number;
librarySize: number;
graveyard: CardInstance[];
bankSeconds: number;
ready: boolean;
mulligansTaken: number;
}
export interface PlayerView {
engine: 'duel';
seat: Seat;
turn: number;
active: Seat;
phase: Phase;
/** Seat that must act now (null when over). */
toAct: Seat | null;
you: SideView & { hand: CardInstance[] };
opponent: SideView;
battlefield: PermanentView[];
combat: CombatState;
result: DuelResult | null;
version: number;
rules: DuelRuleset;
}
+161
View File
@@ -0,0 +1,161 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { DEFAULT_DUEL_RULESET, applyAction, createDuel, legalActions, statsOf, toAct, viewFor } from '../shared/duel/index.ts';
import type { DuelAction, DuelCard, DuelState, Seat } from '../shared/duel/index.ts';
import { fig } from './duel-core-fixtures.ts';
/**
* Scenario harness: both players start with exactly `hands` in hand (rest of the
* library is vanilla filler), seat 0 goes first, lots of Citations.
*/
function scenario(hands: [DuelCard[], DuelCard[]], over: Partial<typeof DEFAULT_DUEL_RULESET> = {}): DuelState {
const rules = { ...DEFAULT_DUEL_RULESET, deckSize: 20, openingHand: 0, citationsPerTurn: 5, ...over };
const filler = (seat: number) => Array.from({ length: 20 }, (_, i) => fig(`f${seat}-${i}`, 1, 1));
const decks = [0, 1].map(seat => [...hands[seat], ...filler(seat)].slice(0, rules.deckSize)) as [DuelCard[], DuelCard[]];
let s = structuredClone(createDuel(rules, decks, 'scenario'));
s.firstSeat = 0; s.active = 0;
for (const seat of [0, 1] as Seat[]) {
const p = s.players[seat];
const ids = new Set(hands[seat].map(c => c.cardId));
p.hand = p.library.filter(c => ids.has(c.card.cardId));
p.library = p.library.filter(c => !ids.has(c.card.cardId));
}
s = applyAction(s, 0, { type: 'keep' });
return applyAction(s, 1, { type: 'keep' });
}
const uid = (s: DuelState, id: string) => [...s.players[0].hand, ...s.players[1].hand, ...s.battlefield].find(c => c.card.cardId === id)!.uid;
const act = (s: DuelState, a: DuelAction) => applyAction(s, toAct(s)!, a);
const pass = (s: DuelState) => act(act(s, { type: 'endPhase' }), { type: 'confirmAttack' });
const ev = (id: string, effects: DuelCard['effects'], type: DuelCard['type'] = 'Event'): DuelCard => ({ ...fig(id, 0, 0), type, effects });
test('createToken, maxTokens, and tokens vanish', () => {
const election = ev('election', [{ trigger: 'onPlay', op: 'createToken', amount: 2, token: { name: 'Elected Member', power: 1, toughness: 1, portal: 'Society' } }]);
let s = scenario([[election], []]);
s = act(s, { type: 'play', uid: uid(s, 'election') });
const tokens = s.battlefield.filter(p => p.card.token);
assert.equal(tokens.length, 2);
assert.equal(s.log.filter(e => e.kind === 'tokenCreated').length, 2);
assert.ok(tokens.every(t => t.sick));
});
test('T6 pump then fight uses both chosen targets', () => {
const sport = ev('final', [
{ trigger: 'onPlay', op: 'pump', target: 'ownFigure', power: 2, toughness: 0 },
{ trigger: 'onPlay', op: 'fight', target: 'opponentFigure' },
]);
let s = scenario([[fig('mine', 2, 4), sport], [fig('theirs', 3, 3)]]);
s = act(s, { type: 'play', uid: uid(s, 'mine') });
s = pass(s);
s = act(s, { type: 'play', uid: uid(s, 'theirs') });
s = pass(s);
const plays = legalActions(s, 0).filter(a => a.type === 'play' && a.uid === uid(s, 'final'));
assert.deepEqual(plays, [{ type: 'play', uid: uid(s, 'final'), targets: [{ kind: 'card', uid: uid(s, 'mine') }, { kind: 'card', uid: uid(s, 'theirs') }] }]);
s = act(s, plays[0]);
assert.ok(!s.battlefield.some(p => p.card.cardId === 'theirs'), '4 power kills a 3/3');
assert.equal(s.battlefield.find(p => p.card.cardId === 'mine')!.damage, 3);
assert.equal(statsOf(s, uid(s, 'mine')).power, 4, 'pump lasts until end of turn');
});
test('Doctrine attaches, buffs, and is Deleted when its Figure leaves', () => {
const adopt = ev('monoid', [
{ trigger: 'onPlay', op: 'attach', target: 'ownFigure' },
{ trigger: 'static', op: 'pump', target: 'attached', power: 2, toughness: 2, grant: ['Featured'] },
], 'Doctrine');
const kill = ev('war', [{ trigger: 'onPlay', op: 'damage', target: 'figureOrLocation', amount: 5 }]);
let s = scenario([[fig('host', 1, 1), adopt], [kill]]);
s = act(s, { type: 'play', uid: uid(s, 'host') });
s = act(s, { type: 'play', uid: uid(s, 'monoid'), targets: [{ kind: 'card', uid: uid(s, 'host') }] });
assert.deepEqual(statsOf(s, uid(s, 'host')), { power: 3, toughness: 3 });
assert.ok(viewFor(s, 0).battlefield.find(p => p.card.cardId === 'host')!.keywords.includes('Featured'));
assert.equal(s.log.filter(e => e.kind === 'adopt').length, 1);
s = pass(s);
s = act(s, { type: 'play', uid: uid(s, 'war'), targets: [{ kind: 'card', uid: uid(s, 'host') }] });
assert.equal(s.battlefield.length, 0, 'Figure destroyed, Doctrine Deleted with it');
assert.equal(s.players[0].graveyard.length, 2);
});
test('Doctrine with no legal target is not playable; Protected blocks opposing Events', () => {
const adopt = ev('monoid', [{ trigger: 'onPlay', op: 'attach', target: 'ownFigure' }], 'Doctrine');
const kill = ev('war', [{ trigger: 'onPlay', op: 'damage', target: 'figure', amount: 5 }]);
let s = scenario([[adopt, fig('pol', 2, 2, ['Protected'])], [kill]]);
assert.ok(!legalActions(s, 0).some(a => a.type === 'play' && a.uid === uid(s, 'monoid')));
s = act(s, { type: 'play', uid: uid(s, 'pol') });
s = pass(s);
assert.ok(!legalActions(s, 1).some(a => a.type === 'play' && a.uid === uid(s, 'war')), 'Protected Figure is the only target');
});
test('Well-sourced prevents 1; Stub grows to 2; Legacy draws', () => {
const ping = ev('ping', [{ trigger: 'onPlay', op: 'damage', target: 'figure', amount: 2 }]);
let s = scenario([[fig('ws', 1, 2, ['Well-sourced']), fig('stub', 1, 1, ['Stub']), fig('leg', 1, 1, ['Legacy'])], [ping, ev('ping2', ping.effects)]]);
s = act(s, { type: 'play', uid: uid(s, 'ws') });
s = act(s, { type: 'play', uid: uid(s, 'stub') });
s = act(s, { type: 'play', uid: uid(s, 'leg') });
s = pass(s);
s = act(s, { type: 'play', uid: uid(s, 'ping'), targets: [{ kind: 'card', uid: uid(s, 'ws') }] });
assert.equal(s.battlefield.find(p => p.card.cardId === 'ws')!.damage, 1, 'first point prevented');
const hand0 = s.players[0].hand.length;
s = act(s, { type: 'play', uid: uid(s, 'ping2'), targets: [{ kind: 'card', uid: uid(s, 'leg') }] });
assert.equal(s.players[0].hand.length, hand0 + 1, 'Legacy drew');
for (let i = 0; i < 6; i++) s = pass(s);
assert.deepEqual(statsOf(s, uid(s, 'stub')), { power: 3, toughness: 3 }, 'Stub capped at 2 counters');
});
test('one Location per turn; Territory raises max Citations up to the cap', () => {
const loc = (id: string): DuelCard => ({ ...fig(id, 0, 2), type: 'Location', territory: 1 });
let s = scenario([[loc('l1'), loc('l2'), loc('l3')], []], { citationsPerTurn: 1, maxCitations: 10 });
s = act(s, { type: 'play', uid: uid(s, 'l1') });
assert.ok(!legalActions(s, 0).some(a => a.type === 'play'), 'second Location not allowed (and no Citations left)');
assert.equal(viewFor(s, 0).you.maxCitations, 2);
s = pass(s); s = pass(s);
s = act(s, { type: 'play', uid: uid(s, 'l2') });
s = pass(s); s = pass(s);
s = act(s, { type: 'play', uid: uid(s, 'l3') });
assert.equal(viewFor(s, 0).you.maxCitations, 3 + 2, 'base 3 + Territory capped at 2');
});
test('Garrison Location blocks; Featured needs a Featured/Translated/Multilingual blocker', () => {
const garrison: DuelCard = { ...fig('fort', 0, 3), type: 'Location' };
let s = scenario([[fig('grunt', 2, 2), fig('flyer', 2, 2, ['Featured'])], [garrison, fig('reach', 1, 3, ['Translated'])]]);
s = act(s, { type: 'play', uid: uid(s, 'grunt') });
s = act(s, { type: 'play', uid: uid(s, 'flyer') });
s = pass(s);
s = act(s, { type: 'play', uid: uid(s, 'fort') });
s = act(s, { type: 'play', uid: uid(s, 'reach') });
s = pass(s);
s = act(s, { type: 'endPhase' });
s = act(s, { type: 'toggleAttacker', uid: uid(s, 'grunt') });
s = act(s, { type: 'toggleAttacker', uid: uid(s, 'flyer') });
s = act(s, { type: 'confirmAttack' });
const blocks = legalActions(s, 1).filter(a => a.type === 'block');
assert.deepEqual(blocks.map(b => b.type === 'block' ? `${b.blocker}>${b.attacker}` : ''), [
`${uid(s, 'fort')}>${uid(s, 'grunt')}`, `${uid(s, 'reach')}>${uid(s, 'grunt')}`, `${uid(s, 'reach')}>${uid(s, 'flyer')}`,
]);
s = act(s, { type: 'block', blocker: uid(s, 'fort'), attacker: uid(s, 'grunt') });
s = act(s, { type: 'block', blocker: uid(s, 'reach'), attacker: uid(s, 'flyer') });
s = act(s, { type: 'confirmBlocks' });
assert.equal(s.players[1].life, 20);
assert.equal(s.battlefield.length, 4, 'nobody died: 2 vs 3 toughness, 1 vs 2');
});
test('three consecutive timeouts lose; turnCap decides by Notability', () => {
let s = scenario([[], []]);
for (let i = 0; i < 5 && !s.result; i++) s = applyAction(s, toAct(s)!, { type: 'timeout' });
assert.deepEqual(s.result, { winner: 1, reason: 'timeout' }, 'seat 0 timed out on turns 1, 3, 5');
let c = scenario([[fig('a', 3, 3)], []], { turnCap: 4 });
c = act(c, { type: 'play', uid: uid(c, 'a') });
c = pass(c); c = pass(c);
c = act(c, { type: 'endPhase' });
c = act(c, { type: 'toggleAttacker', uid: uid(c, 'a') });
c = act(c, { type: 'confirmAttack' });
c = pass(c);
assert.deepEqual(c.result, { winner: 0, reason: 'turnCap' });
});
test('secondPlayerCitations gives the second player extra Citations on their first turn only', () => {
let s = scenario([[], []], { citationsPerTurn: 1, secondPlayerCitations: 1 });
assert.equal(s.players[0].citations, 1);
s = pass(s);
assert.equal(s.players[1].citations, 2);
s = pass(s); s = pass(s);
assert.equal(s.players[1].citations, 2, 'turn 4: base 2, no bonus');
});
+209
View File
@@ -0,0 +1,209 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { Rng } from '../shared/game/rng.ts';
import {
DEFAULT_DUEL_RULESET, applyAction, createDuel, deserialize, duelEnginePort, isOver, legalActions, logFor, replay,
serialize, statsOf, toAct, validateDeck, viewFor,
} from '../shared/duel/index.ts';
import type { DuelAction, DuelCard, DuelState, Seat } from '../shared/duel/index.ts';
import { POOL, fig, randomDeck } from './duel-core-fixtures.ts';
const rules = DEFAULT_DUEL_RULESET;
/** Random legal policy that prefers progress so games stay short. */
function pick(rng: Rng, actions: DuelAction[]): DuelAction {
const plays = actions.filter(a => a.type === 'play' || a.type === 'toggleAttacker' || a.type === 'block');
if (plays.length && rng.next() < 0.75) return rng.pick(plays);
return rng.pick(actions);
}
function playOut(seed: string, maxActions = 3000) {
const decks: [DuelCard[], DuelCard[]] = [randomDeck(`${seed}/a`, 0), randomDeck(`${seed}/b`, 1)];
let state = createDuel(rules, decks, seed);
const rng = Rng.fromSeed(`${seed}/policy`);
const actions: { seat: Seat; action: DuelAction }[] = [];
const views: DuelState[] = [];
while (!isOver(state) && actions.length < maxActions) {
const seat = toAct(state)!;
assert.deepEqual(legalActions(state, (1 - seat) as Seat), [], 'non-acting seat has no actions');
const legal = legalActions(state, seat);
assert.ok(legal.length > 0, 'acting seat always has an action');
const action = pick(rng, legal);
actions.push({ seat, action });
state = applyAction(state, seat, action);
views.push(state);
}
return { decks, state, actions, views };
}
test('validateDeck enforces 40 owned-style cards', () => {
const deck = randomDeck('v', 0);
validateDeck(rules, deck);
assert.throws(() => validateDeck(rules, deck.slice(1)));
assert.throws(() => validateDeck(rules, [...deck.slice(1), deck[0]].map((c, i) => (i === 39 ? { ...c, cardId: deck[1].cardId } : c))));
assert.throws(() => validateDeck(rules, deck.map((c, i) => (i === 0 ? { ...c, keywords: ['Protected', 'Stub', 'Legacy'] } : c)) as DuelCard[]));
assert.throws(() => validateDeck(rules, deck.map((c, i) => (i === 0 ? { ...c, type: 'Basic' } : c)) as unknown as DuelCard[]));
});
test('createDuel deals 7 and starts in mulligan', () => {
const s = createDuel(rules, [randomDeck('c', 0), randomDeck('d', 1)], 'seed-1');
assert.equal(s.phase, 'mulligan');
assert.equal(s.players[0].hand.length, 7);
assert.equal(s.players[1].library.length, 33);
assert.equal(toAct(s), 0);
assert.deepEqual(legalActions(s, 0), [{ type: 'keep' }, { type: 'mulligan' }]);
const m = applyAction(s, 0, { type: 'mulligan' });
assert.deepEqual(legalActions(m, 0), [{ type: 'keep' }]);
const k = applyAction(m, 0, { type: 'keep' });
assert.equal(k.players[0].hand.length, 6, 'one card bottomed after one mulligan');
assert.equal(k.players[0].library.length, 34);
const both = applyAction(k, 1, { type: 'keep' });
assert.equal(both.phase, 'main');
assert.equal(both.turn, 1);
const first = both.firstSeat;
assert.equal(both.players[first].hand.length, first === 0 ? 6 : 7, 'first player skips the first draw');
assert.equal(both.players[first].citations, 1);
assert.equal(s.players[0].hand.length, 7, 'input not mutated');
});
test('random legal games end, are deterministic and replay exactly', () => {
for (let i = 0; i < 25; i++) {
const seed = `prop-${i}`;
const { decks, state, actions } = playOut(seed);
assert.ok(isOver(state), `game ${seed} ended (${actions.length} actions, turn ${state.turn})`);
const again = replay(rules, decks, seed, actions);
assert.equal(serialize(again), serialize(state));
assert.deepEqual(deserialize(serialize(state)), state);
assert.ok(['life', 'library', 'concede', 'timeout', 'turnCap'].includes(state.result!.reason));
}
});
test('viewFor and logFor never leak hidden cards', () => {
for (let i = 0; i < 8; i++) {
const { views } = playOut(`leak-${i}`);
for (const s of views) {
for (const seat of [0, 1] as Seat[]) {
const opp = (1 - seat) as Seat;
const hidden = new Set([...s.players[opp].hand, ...s.players[opp].library, ...s.players[seat].library].map(c => c.card.cardId));
// Cards revealed publicly earlier (played then bounced, etc.) may legitimately be known.
const publicIds = new Set(s.log.flatMap(e => {
if (e.kind === 'draw') return [];
return JSON.stringify(e).match(/sample-\d+#[01]/g) ?? [];
}));
const text = JSON.stringify(viewFor(s, seat)) + JSON.stringify(logFor(s, seat));
for (const id of hidden) {
if (publicIds.has(id)) continue;
assert.ok(!text.includes(`"${id}"`), `seat ${seat} sees hidden ${id} at version ${s.version}`);
}
assert.ok(!('library' in viewFor(s, seat).opponent));
assert.ok(!('rng' in viewFor(s, seat)));
}
}
}
});
test('combat: simultaneous damage, one blocker, sickness, Featured evasion', () => {
const filler = (seat: number) => Array.from({ length: 38 }, (_, i) => fig(`f${seat}-${i}`, 1, 1));
const r = { ...rules, openingHand: 0 };
let s = createDuel(r, [[fig('A', 3, 3), fig('Fly', 2, 2, ['Featured']), ...filler(0)], [fig('B', 2, 4), fig('C', 1, 1), ...filler(1)]], 'combat');
// Stack the libraries deterministically for the test.
s = structuredClone(s);
const top = (seat: 0 | 1, ids: string[]) => {
const lib = s.players[seat].library;
for (const id of ids.reverse()) { const i = lib.findIndex(c => c.card.cardId === id); lib.unshift(...lib.splice(i, 1)); }
};
s.firstSeat = 0; s.active = 0;
top(0, ['A', 'Fly']); top(1, ['B', 'C']);
s.players[0].hand = s.players[0].library.splice(0, 2);
s.players[1].hand = s.players[1].library.splice(0, 2);
s = applyAction(s, 0, { type: 'keep' });
s = applyAction(s, 1, { type: 'keep' });
assert.equal(s.active, 0);
const uidOf = (id: string) => [...s.players[0].hand, ...s.players[1].hand, ...s.battlefield].find(c => c.card.cardId === id)!.uid;
s = applyAction(s, 0, { type: 'play', uid: uidOf('A') });
s = applyAction(s, 0, { type: 'endPhase' });
assert.deepEqual(legalActions(s, 0), [{ type: 'confirmAttack' }], 'summoning sickness');
s = applyAction(s, 0, { type: 'confirmAttack' });
assert.equal(s.active, 1);
s = applyAction(s, 1, { type: 'play', uid: uidOf('B') });
s = applyAction(s, 1, { type: 'endPhase' });
s = applyAction(s, 1, { type: 'confirmAttack' });
// Turn 3: seat 0 has 2 Citations: play Fly, attack with A; B blocks; 3 dmg vs 4 toughness, 2 vs 3.
s = applyAction(s, 0, { type: 'play', uid: uidOf('Fly') });
s = applyAction(s, 0, { type: 'endPhase' });
s = applyAction(s, 0, { type: 'toggleAttacker', uid: uidOf('A') });
s = applyAction(s, 0, { type: 'confirmAttack' });
assert.equal(s.phase, 'block');
assert.deepEqual(legalActions(s, 1), [{ type: 'block', blocker: uidOf('B'), attacker: uidOf('A') }, { type: 'confirmBlocks' }]);
s = applyAction(s, 1, { type: 'block', blocker: uidOf('B'), attacker: uidOf('A') });
s = applyAction(s, 1, { type: 'confirmBlocks' });
assert.equal(s.battlefield.length, 3, 'nobody died');
assert.equal(s.players[1].life, 20);
const destroyedOrDamaged = s.log.filter(e => e.kind === 'combatDamage');
assert.equal(destroyedOrDamaged.length, 2);
// Seat 1 turn: pass. Seat 0: Fly attacks; B (no Featured/Translated) can't block it.
s = applyAction(s, 1, { type: 'endPhase' });
s = applyAction(s, 1, { type: 'confirmAttack' });
s = applyAction(s, 0, { type: 'endPhase' });
s = applyAction(s, 0, { type: 'toggleAttacker', uid: uidOf('Fly') });
s = applyAction(s, 0, { type: 'confirmAttack' });
assert.equal(s.players[1].life, 18, 'Featured unblockable by plain Figure: damage resolved without a block phase');
assert.equal(s.active, 1);
});
test('Connected bonus applies and is logged once', () => {
const a = fig('obama', 1, 1, [], { pageId: 1, title: 'Barack Obama', connect: { countries: ['Q30'], centuries: [21], links: [2], p31: ['Q5'] } });
const b: DuelCard = { ...fig('wh', 0, 0), pageId: 2, title: 'White House', type: 'Location', territory: 1, connect: { countries: ['Q30'], centuries: [19], links: [], p31: ['Q35112'] } };
let s = createDuel({ ...rules, deckSize: 2, openingHand: 2, citationsPerTurn: 5 }, [[a, b], [{ ...a, cardId: 'x' }, { ...b, cardId: 'y' }]], 'conn');
s = applyAction(s, 0, { type: 'keep' });
s = applyAction(s, 1, { type: 'keep' });
const me = s.active;
const hand = s.players[me].hand;
s = applyAction(s, me, { type: 'play', uid: hand.find(c => c.card.type === 'Figure')!.uid });
s = applyAction(s, me, { type: 'play', uid: s.players[me].hand[0].uid });
const figure = s.battlefield.find(p => p.card.type === 'Figure')!;
assert.deepEqual(statsOf(s, figure.uid), { power: 3, toughness: 3 });
assert.equal(s.log.filter(e => e.kind === 'connected').length, 1);
assert.equal(viewFor(s, me).battlefield.find(p => p.uid === figure.uid)!.connected?.tier, 'Linked');
});
test('empty library loses; concede and timeout', () => {
const tiny = { ...rules, deckSize: 8, openingHand: 7 };
const pool = POOL.slice(0, 16);
let s = createDuel(tiny, [pool.slice(0, 8), pool.slice(8, 16).map(c => ({ ...c, cardId: c.cardId + 'b' }))], 'deckout');
s = applyAction(s, 0, { type: 'keep' });
s = applyAction(s, 1, { type: 'keep' });
for (let i = 0; i < 20 && !isOver(s); i++) s = applyAction(s, toAct(s)!, { type: 'timeout' });
assert.equal(s.result?.reason, 'library');
const c = applyAction(createDuel(rules, [randomDeck('q', 0), randomDeck('r', 1)], 'c'), 1, { type: 'concede' });
assert.deepEqual(c.result, { winner: 0, reason: 'concede' });
assert.throws(() => applyAction(c, 0, { type: 'keep' }));
});
test('illegal actions throw', () => {
const s = createDuel(rules, [randomDeck('i', 0), randomDeck('j', 1)], 'illegal');
assert.throws(() => applyAction(s, 1, { type: 'keep' }), /Not your turn/);
assert.throws(() => applyAction(s, 0, { type: 'endPhase' }), /Illegal/);
});
test('engine port binding is EnginePort-shaped', () => {
const p = duelEnginePort;
assert.equal(p.deckSize(p.defaultRuleset), 40);
assert.throws(() => p.starterDeck());
const live = p.applyLive(rules, POOL.find(c => c.type === 'Figure')!, { trendPercent: 25 });
assert.ok(live.keywords.includes('Trending'));
const s = p.createMatch(rules, [randomDeck('p', 0), randomDeck('q', 1)], 'port');
assert.deepEqual(p.concedeAction(0), { type: 'concede' });
assert.equal(p.result(s).winner, null);
});
test('golden match', () => {
const { state, actions } = playOut('golden-1');
const digest = createHash('sha256').update(serialize(state)).digest('hex').slice(0, 16);
const summary = { actions: actions.length, turn: state.turn, result: state.result, log: state.log.length, digest };
assert.deepEqual(summary, GOLDEN);
});
// Regenerate deliberately (an engine rule change) and say so in the PR.
const GOLDEN = { actions: 72, turn: 13, result: { winner: 1, reason: 'life' }, log: 103, digest: 'e8bc8630d6f0ab0a' };
+110
View File
@@ -0,0 +1,110 @@
// Test-only deck builder for duel-core tests. NOT the real derivation (that is duel-cards'
// shared/duel/derive.ts): a crude, deterministic mapping from docs/game/card-sample.json
// so engine tests have 236 varied real cards. Zero network calls.
import { readFileSync } from 'node:fs';
import { Rng } from '../shared/game/rng.ts';
import type { CardType, DuelCard, EffectSpec, Keyword, Portal } from '../shared/duel/index.ts';
interface SampleCard {
pageId: number; title: string; description?: string; revisionId?: number; pageBytes: number; languageCount: number;
categories: string[]; stats: { attention: number; depth: number; reach: number }; faction: string;
instanceOf?: { id: string; label: string }[];
}
const sample = JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8')) as { cards: SampleCard[] };
/** Effect templates shaped like DUEL_DESIGN §5 (k = magnitude). */
const EVENTS = (k: number): EffectSpec[][] => [
[{ trigger: 'onPlay', op: 'damage', target: 'figureOrLocation', amount: k + 1, template: 'T3' }],
[{ trigger: 'onPlay', op: 'damageEach', target: 'each', amount: Math.max(1, k - 1), template: 'T4' }],
[{ trigger: 'onPlay', op: 'createToken', amount: k, token: { name: 'Elected Member', power: 1, toughness: 1, portal: 'Society' }, template: 'T5' }],
[{ trigger: 'onPlay', op: 'pump', target: 'ownFigure', power: k, toughness: 0, template: 'T6' }, { trigger: 'onPlay', op: 'fight', target: 'opponentFigure', template: 'T6' }],
[{ trigger: 'onPlay', op: 'draw', amount: k, template: 'T7' }],
[{ trigger: 'onPlay', op: 'damage', target: 'anyTarget', amount: k, template: 'X1' }],
];
const INSTITUTIONS = (k: number, cost: number): EffectSpec[][] => [
cost >= 4
? [{ trigger: 'startOfTurn', op: 'createToken', token: { name: 'Staff Member', power: 1, toughness: 1, portal: 'Society' }, condition: { maxTokens: 3 }, template: 'T8' }]
: [{ trigger: 'onEnter', op: 'createToken', token: { name: 'Staff Member', power: 1, toughness: 1, portal: 'Society' }, template: 'T8' }],
[{ trigger: 'onEnter', op: 'draw', amount: 1, template: 'T9' }, { trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 1, condition: { connected: true }, template: 'T9' }],
[{ trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 0, condition: { maxPower: 2 }, template: 'T10' }],
];
const DOCTRINES = (k: number): EffectSpec[][] => [
[{ trigger: 'onPlay', op: 'attach', target: 'ownFigure', template: 'T11' }, { trigger: 'static', op: 'pump', target: 'attached', power: k, toughness: k, template: 'T11' }],
[{ trigger: 'onPlay', op: 'attach', target: 'ownFigure', template: 'T11' }, { trigger: 'static', op: 'pump', target: 'attached', power: k, toughness: k, grant: ['Well-sourced'], template: 'T11' }],
[{ trigger: 'onPlay', op: 'attach', target: 'ownFigure', template: 'T11' }, { trigger: 'static', op: 'pump', target: 'attached', power: k, toughness: k, template: 'T11' }, { trigger: 'onCombatDamageToPlayer', op: 'draw', amount: 1, template: 'T11' }],
[{ trigger: 'onPlay', op: 'attach', target: 'figure', template: 'T12' }, { trigger: 'static', op: 'pump', target: 'attached', power: -k, toughness: -k, template: 'T12' }],
];
const PORTAL: Record<string, Portal> = {
People: 'Society', Places: 'Earth', Nature: 'Earth', Structures: 'Arts', Works: 'Arts', Events: 'History', Organisations: 'Society',
'Ideas & Tech': 'Science', Sport: 'Society', Other: 'Neutral',
};
function typeOf(c: SampleCard, i: number): CardType {
if (c.instanceOf?.some(x => x.id === 'Q5') || c.faction === 'Nature') return 'Figure';
if (c.faction === 'Places' || c.faction === 'Structures') return i % 2 ? 'Location' : 'Figure';
if (c.faction === 'Events') return 'Event';
if (c.faction === 'Works' || c.faction === 'Organisations') return 'Institution';
return (['Event', 'Doctrine', 'Figure', 'Institution'] as CardType[])[i % 4];
}
const COUNTRIES = ['Q30', 'Q145', 'Q142', 'Q183', 'Q668', 'Q17', 'Q902', 'Q252'];
export function toDuelCard(c: SampleCard, i: number): DuelCard {
const type = typeOf(c, i);
const fame = Math.round((c.stats.attention + c.stats.depth + c.stats.reach) / 3);
const cost = 1 + [26, 39, 51, 63, 78].filter(t => fame >= t).length;
const k = Math.ceil(cost / 2);
const keywords: Keyword[] = [];
if (type === 'Figure') {
const add = (kw: Keyword, ok: boolean) => { if (ok && keywords.length < 2) keywords.push(kw); };
add('Protected', c.categories.includes('Living people'));
add('Featured', c.stats.attention >= 85);
add('Legacy', c.categories.some(x => /^\d+ deaths$/.test(x)));
add('Multilingual', c.stats.reach >= 90);
add('Translated', c.stats.reach >= 75 && c.stats.reach < 90);
add('Well-sourced', c.stats.depth >= 85);
add('Stub', c.pageBytes < 3000 || c.categories.some(x => /stubs$/.test(x)));
add('Local', c.stats.reach === 0);
}
const budget = [3, 4, 6, 8, 10, 12][cost - 1] - keywords.filter(x => x !== 'Stub' && x !== 'Translated' && x !== 'Local').length;
const a = c.stats.attention + 1, d = c.stats.depth + 1;
const power = type === 'Figure' ? Math.min(budget - 1, Math.max(1, Math.round(budget * a / (a + d)))) : 0;
const toughness = type === 'Figure' ? Math.max(1, budget - power) : type === 'Location' ? 1 + Math.floor(c.stats.depth / 25) : 0;
const effects: EffectSpec[] =
type === 'Event' ? EVENTS(k)[i % 6]
: type === 'Doctrine' ? DOCTRINES(k)[i % 4]
: type === 'Institution' ? INSTITUTIONS(k, cost)[i % 3]
: [];
return {
cardId: `sample-${c.pageId}`, pageId: c.pageId, revisionId: c.revisionId, title: c.title, description: c.description, type,
portal: PORTAL[c.faction] ?? 'Neutral', cost: type === 'Location' ? Math.ceil(cost / 2) : cost, power, toughness, keywords,
...(type === 'Location' ? { territory: 1 } : {}), effects, rulesText: '', flavor: '',
connect: {
countries: [COUNTRIES[c.pageId % COUNTRIES.length]].filter((_, j) => (c.pageId >> 3) % 3 !== 0 || j > 0),
centuries: [17 + (c.pageId % 5)],
links: [],
p31: (c.instanceOf ?? []).map(x => x.id),
},
};
}
export const POOL: DuelCard[] = sample.cards.map(toDuelCard);
// A few direct links so the Linked tier gets exercised.
for (let i = 0; i + 1 < POOL.length; i += 9) {
const b = POOL[i + 1];
if (b.pageId !== null) POOL[i].connect!.links.push(b.pageId);
}
/** `size` distinct pool cards; cardIds suffixed per seat so the two decks never share ids. */
export function randomDeck(seed: string, seat: 0 | 1, size = 40): DuelCard[] {
const rng = Rng.fromSeed(seed);
return rng.shuffle(POOL).slice(0, size).map(c => ({ ...structuredClone(c), cardId: `${c.cardId}#${seat}` }));
}
/** Minimal vanilla Figure for hand-built scenarios. */
export function fig(id: string, power: number, toughness: number, keywords: Keyword[] = [], extra: Partial<DuelCard> = {}): DuelCard {
return { cardId: id, pageId: null, title: id, type: 'Figure', portal: 'Society', cost: 1, power, toughness, keywords, effects: [], rulesText: '', flavor: '', ...extra };
}
+41
View File
@@ -0,0 +1,41 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { DEFAULT_DUEL_RULESET, mergeDuelRuleset, parseDuelRuleset, CARD_TYPES, KEYWORDS } from '../shared/duel/index.ts';
import { DEFAULT_RULESET } from '../shared/game/index.ts';
test('duel default ruleset matches the BRIEF', () => {
const rules = parseDuelRuleset({ ...DEFAULT_DUEL_RULESET });
assert.equal(rules.deckSize, 40);
assert.equal(rules.startingLife, 20);
assert.equal(rules.maxCitations, 10);
assert.equal(rules.handSize, 7);
assert.equal(rules.openingHand, 7);
assert.equal(rules.mulligans, 1);
assert.equal(rules.libraryEmpty, 'lose');
assert.equal(rules.firstPlayerDraws, false);
assert.equal(rules.turnSeconds, 60);
assert.equal(rules.bankSeconds, 300);
assert.equal(rules.turnCap, 40, 'balance v1 (#64)');
assert.equal(rules.secondPlayerCitations, 1, 'balance v1 (#64)');
assert.equal(rules.territoryCap, 2);
});
test('duel ruleset merges overrides and rejects unknown keys', () => {
assert.equal(mergeDuelRuleset({ deckSize: 20 }).deckSize, 20);
assert.equal(mergeDuelRuleset({ turnCap: 30 }).turnCap, 30);
assert.throws(() => mergeDuelRuleset({ topicCount: 3 }));
assert.throws(() => mergeDuelRuleset({ libraryEmpty: 'shrug' }));
assert.throws(() => mergeDuelRuleset({ deckSize: 0 }));
assert.throws(() => mergeDuelRuleset([1]));
});
test('Night 1 Edit War rulesets are rejected cleanly', () => {
assert.throws(() => parseDuelRuleset(DEFAULT_RULESET));
});
test('card types and keywords are the BRIEF set', () => {
assert.deepEqual([...CARD_TYPES], ['Figure', 'Location', 'Event', 'Institution', 'Doctrine']);
for (const k of ['Protected', 'Featured', 'Translated', 'Legacy', 'Stub', 'Well-sourced', 'Multilingual', 'Local']) {
assert.ok((KEYWORDS as readonly string[]).includes(k), k);
}
});