From 2f494e399ccf539138d8a9812ea2401d0d0bd89c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:35:00 -0500 Subject: [PATCH 01/49] deploy/night: autodeploy follows night/2026-11-17 by default Co-Authored-By: Claude Opus 5.5 --- deploy/night/README.md | 2 +- deploy/night/autodeploy.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/deploy/night/README.md b/deploy/night/README.md index fa737ca..c9e2565 100644 --- a/deploy/night/README.md +++ b/deploy/night/README.md @@ -16,7 +16,7 @@ A 3-node **testnet-only** fixture on poweredge-r350. It is reachable on the LAN - `compose.lan.yaml` also sets, per node: - `WIKIDECK_USER_AGENT`, a Wikimedia-policy UA with a project URL (#19). Without it, Wikipedia returned 429 to our egress and templates failed. - the game-mode env from #22: A = classic and trending, B = draft, C = all three. -- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-16 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves. +- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-17 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves. - `testnet.sh` has `up`, `mine N [workers]`, `status` and `down`. Run it from the repo root on a checkout of the integration branch. `up` rebuilds the image from that checkout; the ledgers persist in the named volumes. Never point this at mainnet or the live `wikideck` namespace. diff --git a/deploy/night/autodeploy.sh b/deploy/night/autodeploy.sh index 3d994ea..fc1e6e8 100755 --- a/deploy/night/autodeploy.sh +++ b/deploy/night/autodeploy.sh @@ -6,7 +6,7 @@ # because lobbies are in memory and a restart ends games in progress. # Head detection uses the public Gitea API, which also works where SSH auth isn't available. set -u -BRANCH=${BRANCH:-night/2026-11-16} +BRANCH=${BRANCH:-night/2026-11-17} API=${API:-https://gitea.eom.dev/api/v1/repos/claude/wikideck} INTERVAL=${INTERVAL:-180} LOG=${LOG:-/tmp/wikideck-night-autodeploy.log} From bac186470d3726654480ed9a1a6bd4dfb5568abf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:35:07 -0500 Subject: [PATCH 02/49] DUEL_DESIGN.md v1: rules, keywords, templates, Connected, modes, tone, worked cards Co-Authored-By: Claude Opus 5.5 --- docs/game/DUEL_DESIGN.md | 275 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 275 insertions(+) create mode 100644 docs/game/DUEL_DESIGN.md diff --git a/docs/game/DUEL_DESIGN.md b/docs/game/DUEL_DESIGN.md new file mode 100644 index 0000000..330fffc --- /dev/null +++ b/docs/game/DUEL_DESIGN.md @@ -0,0 +1,275 @@ +# WikiDeck Duel: design v1 + +**Status:** v1, Night 2 (2026-11-17). Owner: duel-design (issue #60). +**Base:** `docs/night2/BRIEF.md` (Eric's locked decisions). Where this file and BRIEF disagree, BRIEF wins. Reviews used: designer (rules), data §2–4 (derivation), critic S7 (tone). +**Consumers:** duel-core (`shared/duel/` engine and `types.ts`), duel-cards (`classify/derive/effects/text.ts`), sim-balance (bots, `DUEL_BALANCE.md`), ui-duel / ui-pvp (faces, recap), host-pvp (rulesets). + +Every number in this file is a **ruleset key or a derivation table value**, not code. sim-balance tunes them in data-only PRs. + +--- + +## 1. The game in one paragraph +Two players each bring **40 cards they own on-chain**. Each card is a Wikipedia article turned into a Magic-style card by fixed rules over real data. You start at **20 Notability**. Every turn your **Citations** (mana) maximum rises by one. You deploy Figures, attack with them, block with yours, cast Events, adopt Doctrines onto Figures. The first player to 0 Notability, or unable to draw, loses. The match is written up afterwards as an encyclopedic "Battle of X (2026)" page. + +--- + +## 2. Rules + +### 2.1 Decks and eligibility (BRIEF decisions 1–2) +| Key | Default | Rule | +|---|---|---| +| `deckSize` | **40** | Exactly this many cards. Every card is an NFT the player owns (server-verified by `ownership.ts`). No Basics, loaners, proxies or tokens in decks. | +| `maxCopiesPerPage` | **4** | Different mints of the same `pageId` may appear up to 4 times (each mint once: it is unique). | +| colour/Portal rules | none | Any mix of Portals. | +| Eligibility | owns ≥ `deckSize` | Below it, the UI shows "23 / 40 cards" and how to mine. No practice with borrowed cards. Bot matches need eligibility too. | + +Testnet end-to-end mode files may lower `deckSize`. Production stays at 40. + +### 2.2 Setup +- **Notability** (life): `startingLife` **20**. At 0 you lose. +- **Empty library:** drawing from an empty library loses (`libraryEmpty: 'lose'`). +- **Opening hand:** `openingHand` **7**. One mulligan (`mulligans: 1`): shuffle, draw 7, put 1 on the bottom. +- **First player** (seeded coin flip) skips their first draw. + +### 2.3 Turn structure: refresh → draw → main → combat → end +1. **Refresh.** Citation maximum +1 (to `maxCitations` **10**), plus Territory (§2.5). Citations refill to the maximum. Your permanents untap. "Pending review" ends for your Figures. Start-of-turn triggers (Stub, Institutions) resolve in the order the permanents entered. +2. **Draw** 1 card. +3. **Main.** Play cards in any order while you can pay their cost in Citations: Figures, Locations (one per turn: `locationsPerTurn` 1), Institutions, Doctrines (attach to a Figure), Events (resolve immediately). +4. **Combat** (§2.4). +5. **End.** Damage on permanents clears. "Until end of turn" effects end. Discard down to `handLimit` **7** (the player chooses; bots discard highest cost first). + +There is **no second main phase, no stack, no priority and nothing at instant speed.** Events are sorcery-speed. Triggers resolve immediately, in a fixed order: the active player's first, in the order the cards entered. + +### 2.4 Combat +- **Attack:** the active player chooses any untapped Figures without Pending review and taps them. They attack the opponent only, never permanents. +- **Block:** the defender assigns **at most one blocker per attacker**, and each blocker blocks one attacker. Untapped Figures and Garrison Locations may block. Evasion (Featured) restricts who may block. +- **Damage:** simultaneous. A blocked pair deal their power to each other. An unblocked attacker deals its power to the defending player's Notability. +- A permanent with damage ≥ toughness is **destroyed** (goes to the Deleted pile, the graveyard). Destroy triggers (Legacy) fire after all combat damage. +- No trample, no first strike, no deathtouch, no lifelink in v1. + +### 2.5 Card types (BRIEF; classifier in data §1, built by duel-cards) +| Type | MTG analogue | Rules | +|---|---|---| +| **Figure** | creature | Power/toughness. Enters with **Pending review** (summoning sickness): can't attack until your next turn. | +| **Location** | land-ish permanent | Cost `ceil(derivedCost/2)` (1–3). **Territory:** +1 Citation maximum while you control it; at most **+2 in total** from Territory (`territoryCap` 2). **Garrison 0/T:** can block like a 0-power Figure (T = 1 + floor(pct_depth / 25), so 1–4). Can't attack. Damage clears at end of turn as usual; a Location destroyed in a block goes to Deleted. One per turn. | +| **Event** | sorcery | Resolves at once, then goes to Deleted. | +| **Institution** | artifact | A permanent with a static or triggered ability. | +| **Doctrine** | Aura | **Adopt:** attach to target Figure (yours or the opponent's for negative Doctrines). If the Figure leaves play, the Doctrine goes to Deleted. | + +Classification order (duel-cards owns it): P31 → P279 anchor classes → P31 label regex (`^human$`, fixing the `\bhuman\b` bug) → categories → description → **Doctrine**. The derived profile is **frozen** the first time a card is seen. + +### 2.6 Clock and length +- `turnSeconds` **60** per turn plus `bankSeconds` **300** per player. When both run out, the turn passes (`timeout` action). Three timeouts in a row concede. +- No turn cap by default. If the sim shows stalls, add `turnCap` (suggested 20 turns each; at the cap the higher Notability wins, then the higher total power in play, then the second player). +- **Sim targets** (for sim-balance): median 8–11 turns each; first-player win rate 48–54%; < 5% of games reach turn 20 each. + +### 2.7 Determinism +All randomness (shuffles, coin flip, template variants) comes from the match seed via `shared/game/rng.ts`. The same seed and actions always replay to the same state, log and recap. + +--- + +## 3. Derivation summary (duel-cards implements; data §2) +- **Percentiles** `pct_a`, `pct_d`, `pct_r` from the sample cut points (DESIGN.md §1.1 counting). **fame** = mean of the three, rounded. +- **Cost** 1–6 by `costThresholds` [26, 39, 51, 63, 78]. +- **Figure body budget** P+T = [3, 4, 6, 8, 10, 12] for cost 1–6 (MTG vanilla curve). Subtract **1 per taxed keyword** (§4). Then `power = clamp(round(budget × pct_a / (pct_a + pct_d)), 1, budget − 1)`, toughness = the rest. Famous cards are bigger and pricier, never more efficient. +- **Magnitude** for non-Figures: `k = ceil(cost / 2)` (1–3). +- **Portal** (faction): Arts, Earth, History, Science, Society, or Neutral, scored by regex hits (designer §3.2); ties go to the type default (Figure → Society, Location → Earth, Event → History, Institution → Arts, Doctrine → Science). No deckbuilding restriction. +- **Flavour text:** first sentence of on-chain `article.extract`; if absent (the sample has none), the Wikidata `description`; if that is empty too, none. + +--- + +## 4. Keywords (10) +Eight card keywords, each triggered only by real data and applied **to Figures only**, at most **2 per card** in the priority order below. Plus two rules keywords. Thresholds are measured on the 236-card sample (86 Figures); sim-balance may move them. + +| # | Keyword | Trigger (real data) | Rules text | Body tax | Rate among Figures | +|---|---|---|---|---|---| +| 1 | **Protected** | category `Living people` | Can't be the target of Events or Doctrines an opponent controls. | 1 | 38% | +| 2 | **Featured** (flying) | pct_attention ≥ 85 | Can't be blocked except by Featured, Translated or Multilingual Figures. | 1 | 15% | +| 3 | **Legacy** | a ` deaths` category (or P570 in the frozen profile) | When this is destroyed, draw a card. | 1 | 33% | +| 4 | **Multilingual** | pct_reach ≥ 90 | Can block Featured Figures. Can't be blocked by Local Figures. | 1 | ~5% | +| 5 | **Translated** (reach) | 75 ≤ pct_reach < 90 | Can block Featured Figures. | 0 | 19% | +| 6 | **Well-sourced** | pct_depth ≥ 85 | Prevent the first 1 damage that would be dealt to this each turn. | 1 | ~13% before cap | +| 7 | **Stub** | pageBytes < 3000 or a `…stubs` category | At the start of your turn, put a +1/+1 counter on this, to a maximum of 2. | 0 | 33% | +| 8 | **Local** | raw reach = 0 (no other language editions) | Gets +1/+1 while you control a Compatriot Location (same P17). | 0 | 7% before cap | +| 9 | **Connected** | the card pair's frozen claims and links (§6) | +1/+1 while you control another card Connected to it; +2/+2 if Linked. | – | target 15–30% of pairs | +| 10 | **Trending** (haste) | Trending mode only: frozen live ▲ (trend ≥ +25% and daily ≥ 20) | Can attack the turn it enters. Gets +1/+0. | – | ~2% of cards | + +Rule words that are not keywords: **Pending review** (summoning sickness), **Territory**, **Garrison**, **Adopt**, **Deleted** (the graveyard). + +Notes: +- Protected deliberately sits first: living people are the most targeted, and the rule that matters most for them is mechanical, not a tone rule. It doesn't stop combat. +- Multilingual and Translated are two bands of the same reach axis, so a card never has both. +- A card's face shows at most 2 keyword words; the reminder text is behind a tap. + +--- + +## 5. Effect templates (12, MTG register) +Subtype regexes run over the frozen P31/P279 labels, then the description, then categories. First match wins, in the order listed. `k = ceil(cost/2)`. + +| # | Type / subtype | Trigger regex (labels, description) | Rules text | +|---|---|---|---| +| T1 | Figure | (all Figures) | Vanilla body + keywords. No other text. | +| T2 | Location | (all Locations) | Territory. Garrison 0/T. | +| T3 | Event: conflict | `battle\|war\|siege\|annexation\|protest\|riot\|uprising\|massacre\|coup` | Deal k+1 damage to target Figure or Location. | +| T4 | Event: disaster | `storm\|nor.easter\|cyclone\|hurricane\|earthquake\|flood\|tornado\|wildfire\|eruption\|famine\|epidemic` | Deal k−1 damage (minimum 1) to each Figure and each Location. | +| T5 | Event: election | `election\|referendum\|straw poll` | Create k 1/1 Society Figure tokens named Elected Member. | +| T6 | Event: sport | `match\|final\|season\|tournament\|championship\|grand prix\|race` | Target Figure you control gets +k/+0 until end of turn, then fights target Figure you don't control. | +| T7 | Event: default (period, ceremony, scandal, other) | anything else | Draw k cards. | +| T8 | Institution: organisation | `company\|organi[sz]ation\|party\|agency\|studio\|military\|university\|diocese\|council` | Cost ≥ 4: "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member." Cost ≤ 3: "When this enters, create a 1/1 Figure token named Staff Member." | +| T9 | Institution: creative work | `film\|album\|song\|book\|novel\|series\|video game\|painting\|software\|typeface\|newspaper\|magazine` | When this enters, draw a card. Figures you control that are Connected to this get +1/+1. | +| T10 | Institution: team, award, vehicle, other | anything else | Figures you control with power 2 or less get +1/+0. | +| T11 | Doctrine: Adopt | (all non-Pathology Doctrines) | Attach to target Figure you control. It gets +k/+k. Rider 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 of its Portal get +1/+0"; otherwise none. | +| T12 | Doctrine: Pathology | `disease\|clinical sign\|pathogen\|syndrome\|disorder\|toxin\|poison` | Attach to target Figure. It gets −k/−k. | + +Tokens are not cards: they never appear in decks, are created only by T5/T8, and are removed when they leave play. Token names are fixed generic strings, never real people. + +Rules-text style: +- Second person, present tense, MTG terse register: "Deal 3 damage to target Figure." +- Card names appear in rules text only as "this" (never the article title), so text stays the same length on a 360 px face. +- No adjectives, no puns, no exclamation marks. + +--- + +## 6. Connected (data §4 tiers) +Computed by the host at match start from frozen card profiles. No network calls during a match; the edge list is written into the match record. + +| Tier | Test | Bonus | Cut order | +|---|---|---|---| +| **Linked** | either article links to the other (cached outlinks), or one card's claims cite the other's Q-id | +2/+2 | keep | +| **Compatriot** | share a P17 (country) or P27 (citizenship) value | +1/+1 | keep | +| **Contemporary** | same century from P569/P570/P571/P580/P585, **only between different types** | +1/+1 | cut 4th (BRIEF) | +| **Kin** | same P31 class, excluding Q5 human and Q16521 taxon | +1/+1 | cut 4th (BRIEF) | + +- A Figure gets the **single best** bonus among its Connected cards you control (no stacking): +2/+2 if any is Linked, else +1/+1. +- A Connected creative-work Institution (T9) gives its +1/+1 on top. +- **Target:** 15–30% of random card pairs connected (text proxies measured 21.5% for country OR century). If sims show more, drop the noisiest keys first (P17 = United States, then France); if fewer, add P131. +- The card shows why: "Connected — *Pathrail Mosque* (country: Bangladesh)". +- **Rivalry** (log only): when two opposing cards are Connected, the log may note it once (§8.3). No mechanical effect. + +--- + +## 7. Modes (on the duel engine) +| Mode | Decks | Notes | +|---|---|---| +| **Classic** | constructed from your own 40+ owned cards | Ranked (Elo, keyed to the eom.dev account). Invite links and quick match. | +| **Bot** | your own 40 | Only for eligible players. Not ranked. | +| **Draft** | both players eligible | Pool drawn from both players' collections (e.g. 30 cards from each, shuffled into one pool). Snake-pick until each has `deckSize`. Drafted cards are used for that match only; nothing moves on-chain. Ownership is credited in the recap ("from the collection of bob"). | +| **Trending** | any | Live pageview trend from the daily cache, frozen at match start: ▲ (≥ +25%, daily ≥ 20) gives Trending (haste, +1/+0); ▼ (≤ −50%, daily ≥ 20) gives −1/−0. Cut 3rd. | +| **House rules** | peer-hosted | Data-only, versioned schema. Keys: `deckSize`, `maxCopiesPerPage`, `startingLife`, `openingHand`, `mulligans`, `maxCitations`, `territoryCap`, `handLimit`, `turnSeconds`, `bankSeconds`, `turnCap`, `connectedTiers`, `keywordThresholds`. Night 1 mode files are rejected cleanly with a message. | + +--- + +## 8. Tone and story text + +### 8.1 Tone rules (BRIEF decision 5, critic S7) +1. **Lean in.** Living people, tragedies, wars, disasters, crimes, diseases and dictators are ordinary cards with full mechanics. No `solemn` flags, no special cases, no softened verbs. "Casualties" is fine. A protester shot in 1970 is a 6/3 with Legacy like anything else. +2. **Deadpan.** The text takes itself completely seriously. It **never winks** and **never comments on the matchup** ("in a surprising twist", "unlikely", "ironically" are banned). The comedy lives in the nouns: "*Heart rot* was adopted by *Tom Ewell*." +3. **Encyclopedic texture.** Past tense, third person, passive where Wikipedia would use it, dates and turn numbers, and `[n]` citations linking each card's real article at its revision. +4. **No adjectives about cards or players** (no "brutal", "heroic", "humiliating", "bloodiest"). Mechanical verbs only: deployed, attacked, blocked, was destroyed, was adopted by, took N damage, was cited. +5. **Never invent facts about real people.** All generated text is a deterministic template filled **only** with real card data (title, description, dates, categories, revision id) and real match data (turn, players, numbers). No LLM prose. No made-up quotes, crimes, acts, motives or feelings. The template verbs describe **game events of the card**, and every narrative paragraph is framed as a WikiDeck engagement; the footer says so. +6. **Allowed real data in text:** title, Wikidata `description`, birth/death years parsed from the description or frozen claims, the first extract sentence (flavour), Portal, type. Nothing else about a person. +7. **Dull guard:** 3–4 synonymous variants per event, chosen by the match seed (§8.2). + +| DO | DON'T | +|---|---| +| "Turn 6. *Zbyszek Godlewski* (6/3) attacked. *Pallas's cat* (5/5) blocked. *Zbyszek Godlewski* was destroyed.[3][4]" | "Godlewski got mauled by a cat lol" | +| "The *April 2021 nor'easter* dealt 1 damage to each Figure. *Dichromorpha viridis* was destroyed.[5][6]" | "Mother Nature wiped out the poor grasshopper!" | +| "*Heart rot* was adopted by *Tom Ewell*, which became a 2/2.[7][8]" | "Ewell caught a tree disease, how embarrassing" (adjective + invented claim) | +| "The **Battle of Pathrail Mosque (2026)** was a WikiDeck engagement fought on 17 November 2026 between the forces of alice and bob." | "the bloodiest battle in WikiDeck history" | + +### 8.2 Match-log templates (`shared/duel/story/log.ts`) +- One template group per engine `LogEvent` kind, each with **3–4 variants**. Variant = `rng(seed, turn, eventIndex) mod n`, using the match seed, so `replay` regenerates the log exactly. +- First mention of a card in a match adds its description in parentheses: "*Tom Ewell* (American actor, 1909–1994)". Later mentions use the title only. +- Each first mention of a card assigns it the next reference number `[n]`; later mentions reuse it. +- `logFor(seat)` hides the opponent's hand: their draws read "bob drew a card."; mulligans and discards of hidden cards are not named. + +| Event | Variants (`{card}` italic, `{player}` the seat name) | +|---|---| +| deploy (Figure/Location/Institution) | "{player} deployed {card}." · "{card} was deployed by {player}." · "{player} brought {card} into play." · "{card} entered play under {player}." | +| event cast | "{player} cited {card}." · "{card} was cited by {player}." · "{player} invoked {card}." | +| adopt | "{doctrine} was adopted by {figure}, which became a {p}/{t}." · "{figure} adopted {doctrine} and became a {p}/{t}." · "{player} attached {doctrine} to {figure} ({p}/{t})." | +| attack | "{card} ({p}/{t}) attacked." · "{player} sent {card} ({p}/{t}) into combat." · "{card} ({p}/{t}) advanced on {opponent}." | +| block | "{blocker} ({p}/{t}) blocked {attacker}." · "{attacker} was blocked by {blocker} ({p}/{t})." · "{blocker} ({p}/{t}) intercepted {attacker}." | +| player damage | "{opponent} lost {n} Notability ({life} remaining)." · "{card} dealt {n} damage to {opponent}, leaving {life} Notability." · "{opponent}'s Notability fell to {life}." | +| destroyed | "{card} was destroyed." · "{card} was moved to Deleted." · "{card} was removed from play." · "{card} did not survive the turn." | +| effect damage | "{source} dealt {n} damage to {target}." · "{target} took {n} damage from {source}." · "{source} inflicted {n} damage on {target}." | +| token created | "{source} produced {n} {token}." · "{n} {token} were created by {source}." · "{source} created {n} {token}." | +| draw (own) | "{player} drew {card}." · "{card} was drawn." · "{player} added {card} to their hand." | +| draw (hidden) | "{player} drew a card." · "{player} drew {n} cards." | +| Connected | "{a} and {b} were Connected ({reason})." · "{a} was Connected to {b} through {reason}." · "Records link {a} and {b} ({reason})." | +| rivalry (opposing Connected pair, once) | "{a} and {b} had previously been associated through {reason}." · "{a} and {b} share {reason}." · "The two sides were linked through {reason}." | +| turn start | "Turn {n}." (fixed) | +| game over | "{loser} was nominated for deletion. The result was **delete**." · "{loser} was reduced to 0 Notability. {winner} won." · "{winner} won on turn {n}." · (library) "{loser} could not draw a card and lost." · (concede) "{loser} withdrew." | + +### 8.3 Battle recap (`shared/duel/story/recap.ts`) +A deterministic function `recap(matchRecord) → RecapDoc` (structured data; ui-pvp renders it). Inputs are the match record only: seed, players, decks' frozen card profiles, the event list, the date. No network, no clock. + +**Title:** "{Prefix} {Name} ({year})" +- **Name:** the winner's highest-cost Location that entered play; else the loser's; else the highest-cost Event cast in the match; else the winner's highest-cost card deployed; ties broken by first played. Living people and tragedies are eligible like any card ("Battle of Zbyszek Godlewski (2026)" is valid). +- **Prefix:** "Skirmish at" (≤ 6 turns each), "Battle of" (7–12), "Siege of" (≥ 13). For a Figure name: "Battle of" becomes "{Name} campaign" (no prefix). +- **Year:** the match date's year (2026). + +**Infobox:** +| Field | Value | +|---|---| +| Date | the match date, "17 November 2026" | +| Location | the Name card if it's a Location, else "WikiDeck host {hostName}" | +| Result | "Decisive {winner} victory" (margin ≥ 10 Notability) · "Pyrrhic {winner} victory" (winner ≤ 3) · "{winner} victory" · "{winner} victory by withdrawal" (concession/timeout) · "{winner} victory by attrition" (empty library) · "Victory by decision" (turn cap) | +| Belligerents | the two seat names (account display names) | +| Commanders | each side's highest-cost Figure deployed | +| Strength | cards deployed per side ("14 cards") | +| Casualties and losses | cards destroyed per side, count, then the titles | + +**Sections:** +1. **Lead** (1 paragraph): "The {title} was a WikiDeck engagement fought on {date} between the forces of {a} and {b}. It lasted {n} turns and ended in {result-lowercase}.[1]" + one sentence on the first Figure deployed: "Contemporary accounts note the deployment of {card} in the {ordinal} turn.[n]" +2. **Background:** each side's Portal mix ("alice fielded a predominantly History force (11 of 40 cards)"), number of cards in each deck. +3. **Course of the battle:** the 3–5 largest Notability swings and every destroyed card with cost ≥ 4, in turn order, as log sentences (variants from §8.2, but seeded with `seed ⊕ 'recap'` so the recap doesn't repeat the log word for word). +4. **Aftermath:** final Notability, turns, rating change if ranked. +5. **See also:** Connected pairs and rivalries. +6. **References:** every card played by either side, in first-mention order: "{n}. ^ "{title}". Wikipedia. Revision {revisionId}. Minted as token {tokenId}." linking `https://en.wikipedia.org/w/index.php?title={title}&oldid={revisionId}`. + +**Branding and footer:** WikiDeck masthead, never the Wikipedia/Wikimedia name or logo. Footer: "This page records a WikiDeck match. Card names refer to Wikipedia articles; the events described are game events." Shareable at `/recap/{matchId}`. + +--- + +## 9. Worked examples (12 cards from `docs/game/card-sample.json`) +Computed with the rules above (data §2 budget, §4 keyword priority, §5 templates) by a script over the sample, and checked by hand. Flavour is the `description` because the sample has no extracts. Final numbers come from duel-cards' implementation; if they differ, the implementation and its golden test win and this table is updated. + +| # | Card | Derivation | Card | +|---|---|---|---| +| 1 | **Marc Fesneau** (living person) | P31 human → Figure. "politician" → Society. pct 76/68/63 → fame 69 → cost 5, budget 10. Living people → Protected (−1) → 9 split 76:68 → 5/4. | **Marc Fesneau** · 5 · Figure — Society · **5/4** · *Protected.* "French politician (born 1971)." | +| 2 | **Tom Ewell** | human → Figure, Arts. 94/83/93 → fame 90 → cost 6, budget 12. Featured (−1), Legacy (−1); Multilingual dropped by the cap. 10 → 5/5. | **Tom Ewell** · 6 · Figure — Arts · **5/5** · *Featured. Legacy.* "American actor (1909–1994)." | +| 3 | **Zbyszek Godlewski** (killed at a 1970 protest) | human → Figure, History. 77/48/78 → fame 68 → cost 5. Legacy (1970 deaths, −1), Translated (pct_r 78, 0). 9 split 77:48 → 6/3. | **Zbyszek Godlewski** · 5 · Figure — History · **6/3** · *Legacy. Translated.* "Polish protester (1952–1970)." | +| 4 | **Pallas's cat** | taxon → Figure, Earth. 99/97/99 → fame 98 → cost 6. Featured (−1), Multilingual (−1); Well-sourced dropped. 10 → 5/5. | **Pallas's cat** · 6 · Figure — Earth · **5/5** · *Featured. Multilingual.* "Species of small wild cat." | +| 5 | **Dichromorpha viridis** | taxon → Figure, Earth. 58/3/53 → fame 38 → cost 2, budget 4. Stub (1,347 bytes, untaxed). Split clamps to 3/1. | **Dichromorpha viridis** · 2 · Figure — Earth · **3/1** · *Stub.* "Species of grasshopper." | +| 6 | **Monoid** (maths) | no P31; category "Algebraic structures" → Doctrine, Science. fame 96 → cost 6, k = 3. Maths rider. | **Monoid** · 6 · Doctrine — Science · Adopt. Attach to target Figure you control. It gets +3/+3 and has Well-sourced. "Algebraic structure with an associative operation and an identity element." | +| 7 | **Heart rot** (disease) | P31 plant disease → Doctrine, Pathology (T12). Science. fame 68 → cost 5, k = 3. | **Heart rot** · 5 · Doctrine — Science · Attach to target Figure. It gets −3/−3. "Fungal disease of trees." | +| 8 | **April 2021 nor'easter** (disaster) | P31 nor'easter → Event, disaster (T4). Earth. fame 50 → cost 3, k = 2. | **April 2021 nor'easter** · 3 · Event — Earth · Deal 1 damage to each Figure and each Location. "Slow-moving nor'easter in April 2021." | +| 9 | **2025 Tehreek-e-Labbaik Pakistan protests** (conflict) | P31 protest → Event, conflict (T3). History. fame 64 → cost 5, k = 3. | **2025 Tehreek-e-Labbaik Pakistan protests** · 5 · Event — History · Deal 4 damage to target Figure or Location. "Gaza war protests in Pakistan." | +| 10 | **1954 Gold Coast general election** | P31 legislative election → Event, election (T5). Society. fame 45 → cost 3, k = 2. | **1954 Gold Coast general election** · 3 · Event — Society · Create two 1/1 Society Figure tokens named Elected Member. *(no flavour: empty description)* | +| 11 | **Pathrail Mosque** | P31 mosque → Location, History. fame 49 → cost 3 → Location cost 2. pct_d 54 → Garrison 0/3. | **Pathrail Mosque** · 2 · Location — History · Territory. Garrison 0/3. "Mosque in Faridpur, Bangladesh." | +| 12 | **Tatsunoko Production** | P31 animation studio → Institution, organisation (T8). Arts. fame 93 → 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. "Japanese animation studio." | + +Interactions these cards show: +- *Heart rot* on *Marc Fesneau* is illegal (Protected stops opponents' Doctrines). On *Tom Ewell* it makes a 2/2 Featured Legacy. +- *Monoid* on *Dichromorpha viridis* makes a 6/4 Well-sourced Stub that keeps growing to 8/6. +- *April 2021 nor'easter* destroys *Dichromorpha viridis* and both Elected Members, and leaves *Pathrail Mosque* at 0/3 with 1 damage. +- *Pathrail Mosque* and *2025 Tehreek-e-Labbaik Pakistan protests* are not Compatriots (Bangladesh vs Pakistan); *Pathrail Mosque* and *Zbyszek Godlewski* are not Contemporary (15th vs 20th century). + +Sample log: +> Turn 5. alice deployed *Zbyszek Godlewski* (Polish protester, 1952–1970).[1] +> Turn 6. bob cited the *April 2021 nor'easter* (Slow-moving nor'easter in April 2021).[2] The *April 2021 nor'easter* dealt 1 damage to *Zbyszek Godlewski*. +> Turn 7. *Zbyszek Godlewski* (6/3) attacked. *Pallas's cat* (5/5) blocked *Zbyszek Godlewski*.[3] *Zbyszek Godlewski* was destroyed. alice drew a card. + +--- + +## 10. Hand-offs +- **duel-core:** §2 rules and ruleset keys; `LogEvent` kinds needed by §8.2 (deploy, cast, adopt, attack, block, playerDamage, destroyed, effectDamage, tokenCreated, draw, connected, turnStart, gameOver with reason `life|library|concede|timeout|turnCap`). Each event carries card ids, P/T after the event, and Notability where relevant. +- **duel-cards:** §3 derivation, §4 thresholds and priority, §5 templates T1–T12, §6 tiers; the §9 table as golden tests. +- **sim-balance:** §2.6 targets; tune `keywordThresholds`, `connectedTiers`, T4's k−1, the Stub cap and the T8 token rate; report the first-player win rate and the cost-6 dominance check. +- **ui-pvp:** renders `RecapDoc` from §8.3. + +## 11. Open questions for the sim (not blockers) +1. Disaster T4 at k−1 may be weak against 40-card boards; try k. +2. Stub at +2 counters on cheap bodies may be too strong (33% of Figures); try max 1. +3. With 33% Locations in random collections and a Territory cap of 2, decks may flood; consider letting extra Locations cycle ("When this enters, if you control 3 or more Locations, draw a card") as a v2 template. From 5365611c4a477b2e6fa546826f334778952b9e9e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:35:37 -0500 Subject: [PATCH 03/49] duel-core: shared/duel contracts (types, ruleset) and DUEL_API.md Refs #55. Co-Authored-By: Claude Opus 5.5 --- docs/game/DUEL_API.md | 83 ++++++++ shared/duel/index.ts | 35 ++++ shared/duel/ruleset.ts | 65 +++++++ shared/duel/types.ts | 331 ++++++++++++++++++++++++++++++++ tests/duel-core-ruleset.test.ts | 40 ++++ 5 files changed, 554 insertions(+) create mode 100644 docs/game/DUEL_API.md create mode 100644 shared/duel/index.ts create mode 100644 shared/duel/ruleset.ts create mode 100644 shared/duel/types.ts create mode 100644 tests/duel-core-ruleset.test.ts diff --git a/docs/game/DUEL_API.md b/docs/game/DUEL_API.md new file mode 100644 index 0000000..31a5f78 --- /dev/null +++ b/docs/game/DUEL_API.md @@ -0,0 +1,83 @@ +# WikiDeck Duel: engine API (v1, Night 2) + +Owner: **duel-core** (claude/wikideck#55). Types: `shared/duel/types.ts`. Ruleset: `shared/duel/ruleset.ts`. +Function surface: `DuelEngineApi` in `shared/duel/index.ts` (implemented by `shared/duel/engine.ts` in the engine-alpha PR). +`shared/game/` (Edit War) is untouched. Change requests: comment on #55 with `[from ]`. + +## Principles +- **Pure and deterministic.** `(rules, decks, seed, actions)` → identical state and log. RNG is `shared/game/rng.ts` (mulberry32), its uint32 state stored 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; it throws on an illegal action. +- **Atomic actions.** `legalActions(state, seat)` is small and is `[]` for the seat that is not to act. The host checks an action by deep-equal against that list (concede excepted). +- **Off-chain.** Matches never move or burn cards. Cards arrive fully derived and frozen (type, stats, keywords, effects, Connected links); the engine never fetches anything. + +## Cards (`DuelCard`) +Built by duel-cards (`shared/duel/derive.ts`) and frozen by the host at match start. + +| Field | Notes | +|---|---| +| `cardId` | unique in a deck (NFT hash; sample id in sims) | +| `pageId`, `title`, `description?` | `pageId` is used to match Connected pairs | +| `type` | `Figure` (creature) · `Location` (Territory/Garrison permanent) · `Event` (sorcery) · `Institution` (artifact) · `Doctrine` (Aura on a Figure) | +| `portal` | faction id; no deckbuilding restriction | +| `cost` 1–6, `power`, `toughness` | non-Figures use 0/0 | +| `keywords` | ≤ `rules.maxKeywords` (2) of `Protected, Featured, Translated, Legacy, Stub, Well-sourced, Multilingual, Local` | +| `territory?` | Location: +1 max Citations (all sources together ≤ `territoryCap`) | +| `garrison?` | Location may block with `{power, toughness}` | +| `effects` | `EffectSpec[]` (below) | +| `text`, `flavour` | display only (rules text from `text.ts`; flavour = first sentence of `article.extract`) | +| `connections?` | `{pageId, tier, via}[]`, frozen claims | +| `revisionId?`, `source` | for the recap; `'owned' | 'draft' | 'sample'` | + +Engine-side keyword meanings (designer §3.4; duel-design owns the wording): +- **Protected**: can't be targeted by the opponent's Events or other chosen-target effects. +- **Featured** (flying): can be blocked only by Featured or Translated Figures. +- **Translated** (reach): can block Featured Figures. +- **Legacy**: when destroyed, its controller draws a card. +- **Stub**: at the start of its controller's turn, gets a +1/+1 counter (at most 2 from Stub). +- **Well-sourced**: prevent the first 1 damage dealt to it each turn. +- **Trending** (haste, Trending mode only): no summoning sickness. +- **Multilingual**, **Local**: no engine rule; duel-cards expresses them as `effects` if DUEL_DESIGN gives them one. + +### Effects (`EffectSpec`) +`{ trigger, op, target, amount?, amount2?, maxPower?, maxCost?, template? }` +- **Triggers:** `onPlay` (Event resolves / permanent enters), `onAttack`, `onDeath`, `startOfTurn`, `static`. +- **Ops (12):** `damage`, `heal`, `drain`, `draw`, `buff` (until end of turn; as `static`, while the source is in play), `counter` (+n/+n permanent), `destroy`, `bounce`, `tap`, `citations`, `ramp`, `mill`. +- **Targets:** chosen: `anyFigure`, `ownFigure`, `enemyFigure`, `enemyPermanent`, `anyTarget`; automatic: `none`, `self`, `attached`, `controller`, `opponent`, `allFigures`, `ownFigures`, `enemyFigures`. Optional filters `maxPower`, `maxCost`. +- **One chosen target per card**: the first `onPlay` effect with a chosen target defines `play.target`; other chosen-target effects on the same card reuse it. A card whose required target has no legal choice can't be played (Events) or enters with that effect fizzling (permanents). +- **Doctrine:** `play.target` is the Figure it attaches to (any Figure you control, unless its effects say `enemyFigure`); its `static` effects with `target: 'attached'` apply to that Figure. If the Figure leaves, the Doctrine goes to the graveyard. +- Triggers resolve immediately in a fixed order: active player's first, then battlefield order (oldest first). + +## Rules (defaults from `DEFAULT_DUEL_RULESET`) +- 40-card decks, ≤ 4 copies per `pageId`. 20 Notability; 0 loses. Drawing from an empty library loses (`libraryEmpty: 'lose'`; `reshuffle`/`fatigue` exist as data). +- Opening hand 7. Up to `mulligans` (1): shuffle hand in, draw 7, put `mulligansTaken` cards on the bottom (the last ones in hand order, automatically). Both players choose `keep`/`mulligan`; seat 0 then seat 1. +- First player (from the seed) skips the first draw. +- **Turn:** refresh (base max Citations +1 to `maxCitations` 10, plus bonus ≤ `territoryCap` 2; refill; untap; `startOfTurn` triggers) → draw → **main** → **attack** → **block** (only if attackers) → damage → end (temp buffs and damage clear; discard down to `handSize` 7, newest cards first). +- Figures have summoning sickness ("Pending review") unless Trending. Attack the opponent only. Each blocker blocks one attacker, at most one blocker per attacker; untapped Figures and Garrison Locations can block. Damage is simultaneous; unblocked attackers hit Notability. No trample, first strike, stack or instants. +- **Connected:** a Figure gets `+connectedBonus/+connectedBonus` (1) while its controller controls another permanent whose `pageId` appears in its `connections`, or `+linkedBonus` (2) if that link's tier is `Linked`. Only the best link counts. Logged once when it first applies. +- `turnCap` (optional, null by default): after that many total turns, higher Notability wins; equal = draw. + +## Phases and actions +`phase`: `mulligan` → `main` → `attack` → `block` → (next turn's `main`) … `over`. + +| Phase | Who acts | Actions | +|---|---|---| +| `mulligan` | each seat not yet ready (seat 0 first) | `keep`, `mulligan` | +| `main` | active | `play {uid, target?}` (cost ≤ Citations; Events and permanents), `endPhase` | +| `attack` | active | `toggleAttacker {uid}` (untapped, non-sick Figure), `confirmAttack` | +| `block` | defender | `block {blocker, attacker}`, `unblock {blocker}`, `confirmBlocks` | +| any | either seat | `concede` (not listed; always accepted) | +| any | host only | `timeout` for the seat that must act: in `main`/`attack` ends the turn without attacking, in `block` confirms the current blocks, in `mulligan` keeps. It does **not** lose the game; the host decides when a bank is exhausted and may then send `concede`. | + +`confirmAttack` with no attackers ends the turn. Attacking taps the attackers. `onAttack` triggers resolve at `confirmAttack`. + +## Views and log +- `viewFor(state, seat): PlayerView`: your hand, sizes of the opponent's hand and library, both graveyards, the battlefield with **current** power/toughness and Connected badge, combat, `toAct`, `version`, `result`. +- `state.log` is the full, omniscient event list (for the server and recap after the match). **Clients get `logFor(state, seat)`**: the opponent's `draw` events lose `card`, and nothing else from a hidden zone is revealed until it becomes public (`play`, `discard`, `mill`). Every event carries `seq` and `turn`. +- Event kinds: `start, mulligan, keep, turn, draw, play, attach, connected, effect, attack, block, damage, life, destroyed, bounced, discard, mill, fatigue, concede, timeout, end`. `destroyed` events are the recap's casualties. Text templates for these live with duel-design / ui-pvp (`shared/duel/recap.ts`), not in the engine. + +## Host binding +`shared/duel/engine.ts` will also export `duelEnginePort: EnginePort` (shape of `server/game/engine-port.ts`): `concedeAction`, `timeoutAction`, `turnSeconds`, `turnOf` included; `starterDeck`/`previewPool` throw (no starters, BRIEF decision 2) except where draft supplies the pool. host-pvp wires it into `server/game/`. + +## Stability +Types in this file are the contract for duel-cards, host-pvp, ui-duel, ui-pvp and sim-balance. Additive changes (new optional fields, new log kinds) can land with the engine; breaking ones get a `[duel-core] contract change` comment on #55 first. diff --git a/shared/duel/index.ts b/shared/duel/index.ts new file mode 100644 index 0000000..af9f705 --- /dev/null +++ b/shared/duel/index.ts @@ -0,0 +1,35 @@ +/** + * 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'; + +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 }; +} diff --git a/shared/duel/ruleset.ts b/shared/duel/ruleset.ts new file mode 100644 index 0000000..fb33fc0 --- /dev/null +++ b/shared/duel/ruleset.ts @@ -0,0 +1,65 @@ +/** + * 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(), + maxCitations: int(1, 20), + citationsPerTurn: int(1, 5), + territoryCap: int(0, 10), + libraryEmpty: z.enum(['lose', 'reshuffle', 'fatigue']), + maxKeywords: int(0, 4), + connectedBonus: int(0, 5), + linkedBonus: int(0, 5), + turnSeconds: int(5, 600), + bankSeconds: int(0, 3600), + 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, + maxCitations: 10, + citationsPerTurn: 1, + territoryCap: 2, + libraryEmpty: 'lose', + maxKeywords: 2, + connectedBonus: 1, + linkedBonus: 2, + turnSeconds: 60, + bankSeconds: 300, + turnCap: null, +}) 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({ ...base }); + if (typeof overrides !== 'object' || Array.isArray(overrides)) throw new TypeError('Ruleset overrides must be an object'); + return parseDuelRuleset({ ...base, ...(overrides as Record) }); +} diff --git a/shared/duel/types.ts b/shared/duel/types.ts new file mode 100644 index 0000000..d35ab5a --- /dev/null +++ b/shared/duel/types.ts @@ -0,0 +1,331 @@ +/** + * WikiDeck Duel: the Magic-style 40-card engine (off-chain). Contract types. + * Spec: docs/game/DUEL_API.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']; + +/** Keyword ids (BRIEF "Keywords"). At most `ruleset.maxKeywords` (2) per card. */ +/** Engine rules per keyword: docs/game/DUEL_API.md "Cards". 'Trending' (haste) is Trending-mode only. */ +export type Keyword = 'Protected' | 'Featured' | 'Translated' | 'Legacy' | 'Stub' | 'Well-sourced' | 'Multilingual' | 'Local' | 'Trending'; +export const KEYWORDS: readonly Keyword[] = ['Protected', 'Featured', 'Translated', 'Legacy', 'Stub', 'Well-sourced', 'Multilingual', 'Local', 'Trending']; + +/** Connected tiers (BRIEF "Connected", data §4). 'Linked' is the direct connection. */ +export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin'; + +/** When an effect runs. Sorcery speed only: there is no stack and no response window. */ +export type EffectTrigger = + | 'onPlay' // Event resolves, or a permanent enters the battlefield + | 'onAttack' // this Figure is declared as an attacker (resolves at confirmAttack) + | 'onDeath' // this permanent goes to the graveyard from the battlefield + | 'startOfTurn' // its controller's refresh step + | 'static'; // continuous while on the battlefield (Institution, Doctrine, Location) + +/** The ≤12 effect ops the interpreter knows. duel-cards builds templates from these. */ +export type EffectOp = + | 'damage' // deal `amount` damage to each target (Figure or player) + | 'heal' // target player gains `amount` Notability + | 'drain' // target player loses `amount`, controller gains `amount` + | 'draw' // controller draws `amount` + | 'buff' // +amount/+amount2 until end of turn (static: while the source is in play) + | 'counter' // permanent +amount/+amount counters + | 'destroy' // destroy target permanent + | 'bounce' // return target permanent to its owner's hand + | 'tap' // tap target permanent + | 'citations' // controller gains `amount` Citations this turn + | 'ramp' // controller's max Citations +amount (counts against ruleset.territoryCap) + | 'mill'; // target player puts the top `amount` library cards into the graveyard + +export type TargetSpec = + | 'none' // no target (draw, citations, ramp) + | 'self' // the source permanent itself + | 'attached' // the Figure a Doctrine is attached to + | 'controller' // the source's controller + | 'opponent' // the opposing player + | 'anyFigure' // chosen: any Figure + | 'ownFigure' // chosen: a Figure you control + | 'enemyFigure' // chosen: a Figure the opponent controls + | 'enemyPermanent' // chosen: any opposing permanent + | 'anyTarget' // chosen: any Figure or player + | 'allFigures' // every Figure + | 'ownFigures' // every Figure you control + | 'enemyFigures'; // every opposing Figure + +export interface EffectSpec { + trigger: EffectTrigger; + op: EffectOp; + target: TargetSpec; + amount?: number; + /** Second number where an op needs one (buff: toughness; default = amount). */ + amount2?: number; + /** Optional filter on chosen/all targets: only Figures with power ≤ maxPower, cost ≤ maxCost. */ + maxPower?: number; + maxCost?: number; + /** Template id from shared/duel/effects.ts (for rules text and log wording). */ + template?: string; +} + +export interface ConnectedLink { + /** The other card's Wikipedia page id (pairs are matched by pageId, never by I/O). */ + pageId: number; + tier: ConnectedTier; + /** Why, for the card face and log: e.g. "country: Bangladesh". */ + via: string; +} + +/** + * A card as the engine sees it, frozen at match start (classification, stats, + * Connected links). The host builds these from the chain; the engine trusts them. + */ +export interface DuelCard { + /** Unique within one deck: the NFT card hash (or a sample id in sims). */ + cardId: string; + pageId: number | null; + title: string; + /** Short description line ("American actor (1909–1994)") for log first mentions. */ + description?: string; + type: CardType; + /** Faction ("Portal") id, cosmetic for deckbuilding (no colour restrictions). */ + portal: string; + cost: number; + /** Figures; 0 for other types. */ + power: number; + toughness: number; + keywords: Keyword[]; + /** Locations: +1 max Citations each (capped by ruleset.territoryCap in total). */ + territory?: boolean; + /** Locations with Garrison may block with these stats. */ + garrison?: { power: number; toughness: number }; + effects: EffectSpec[]; + /** Deterministic rules text (shared/duel/text.ts). Display only. */ + text: string; + /** First sentence of article.extract. Display only. */ + flavour: string; + connections?: ConnectedLink[]; + /** For recap references. */ + revisionId?: number; + source: 'owned' | 'draft' | 'sample'; +} + +// --------------------------------------------------------------------------- +// 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: copies of one pageId in a deck + startingLife: number; // 20 Notability + openingHand: number; // 7 + handSize: number; // 7: hand limit at end of turn (excess discarded, newest first) + mulligans: number; // 1: shuffle, draw openingHand, bottom `mulligans taken` + firstPlayerDraws: boolean; // false: the first player skips their first draw + maxCitations: number; // 10: cap on base income + citationsPerTurn: number; // 1: base max rises by this each of your turns + territoryCap: number; // 2: total extra max Citations from Locations/ramp + libraryEmpty: LibraryEmpty; // 'lose' + maxKeywords: number; // 2 + connectedBonus: number; // 1: +1/+1 while you control a Connected card + linkedBonus: number; // 2: +2/+2 when the connection is Linked (direct) + turnSeconds: number; // 60 + bankSeconds: number; // 300 + /** Optional: after this many turns in total, more Notability wins (tie: draw). null = none. */ + turnCap: number | null; +} + +// --------------------------------------------------------------------------- +// State +// --------------------------------------------------------------------------- + +/** 'mulligan' → 'main' → 'attack' → ('block' if attackers) → next turn. Refresh, draw, damage and end are automatic steps. */ +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); 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; + /** Permanent +1/+1 counters. */ + counters: number; + /** Until-end-of-turn modifiers. */ + tempPower: number; + tempToughness: number; + /** Doctrines: uid of the Figure they're attached to. */ + attachedTo?: string; +} + +export interface PlayerState { + life: number; + /** Citations available this turn. */ + citations: number; + /** Base max (rises by citationsPerTurn to maxCitations). */ + baseCitations: number; + /** Extra max from Territory/ramp, ≤ territoryCap. */ + bonusCitations: number; + library: CardInstance[]; // top = index 0. Hidden. + hand: CardInstance[]; // hidden from the opponent + graveyard: CardInstance[]; // public + mulligansTaken: number; + ready: boolean; // kept the opening hand + /** Remaining time bank, in seconds (the host decrements it). */ + bankSeconds: number; +} + +export interface CombatState { + attackers: string[]; + /** blocker uid → attacker uid. */ + blocks: Record; +} + +export interface DuelResult { + winner: Seat | null; // null = draw + reason: 'life' | 'library' | 'concede' | 'timeout' | 'turnCap'; +} + +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; +} + +// --------------------------------------------------------------------------- +// 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' } + | { type: 'play'; uid: string; target?: TargetRef } + | { type: 'endPhase' } // main → attack + | { type: 'toggleAttacker'; uid: string } // attack phase + | { type: 'confirmAttack' } // no attackers → end turn + | { type: 'block'; blocker: string; attacker: string } // block phase (defender) + | { type: 'unblock'; blocker: string } + | { type: 'confirmBlocks' } // damage, then end of turn + | { type: 'concede' } // any time, either seat + | { type: 'timeout' }; // host-only, for the seat that must act + +// --------------------------------------------------------------------------- +// Log (encyclopedic, per seat via logFor; full log stays in DuelState.log) +// --------------------------------------------------------------------------- + +/** Public reference to a card in the log. */ +export interface CardRef { uid: string; cardId: string; title: string; pageId: number | null } + +export type LogEvent = { seq: number; turn: number } & ( + | { kind: 'start'; firstSeat: Seat } + | { kind: 'mulligan'; seat: Seat } + | { kind: 'keep'; seat: Seat; handSize: number } + | { kind: 'turn'; seat: Seat; citations: number } + /** card is omitted in the opponent's logFor (hidden draw). */ + | { kind: 'draw'; seat: Seat; card?: CardRef } + | { kind: 'play'; seat: Seat; card: CardRef; cardType: CardType; target?: TargetRef } + | { kind: 'attach'; seat: Seat; card: CardRef; to: CardRef } + | { kind: 'connected'; seat: Seat; card: CardRef; with: CardRef; tier: ConnectedTier; via: string; bonus: number } + | { kind: 'effect'; seat: Seat; source: CardRef; op: EffectOp; template?: string; amount?: number; targets: TargetRef[] } + | { kind: 'attack'; seat: Seat; attackers: CardRef[] } + | { kind: 'block'; seat: Seat; blocks: { blocker: CardRef; attacker: CardRef }[] } + | { kind: 'damage'; source: CardRef; target: TargetRef; amount: number } + | { kind: 'life'; seat: Seat; delta: number; life: number } + | { kind: 'destroyed'; card: CardRef; owner: Seat } + | { kind: 'bounced'; card: CardRef; owner: Seat } + /** card is omitted for the opponent if it left a hidden zone unseen (mill shows it: graveyard is public). */ + | { kind: 'discard'; seat: Seat; card: CardRef } + | { kind: 'mill'; seat: Seat; card: CardRef } + | { kind: 'fatigue'; seat: Seat; amount: number } + | { kind: 'concede'; seat: Seat } + | { kind: 'timeout'; seat: Seat } + | { kind: 'end'; winner: Seat | null; reason: DuelResult['reason'] } +); + +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 stats after counters, temp buffs, statics and Connected. */ + power: number; + toughness: number; + /** 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; +} diff --git a/tests/duel-core-ruleset.test.ts b/tests/duel-core-ruleset.test.ts new file mode 100644 index 0000000..5121474 --- /dev/null +++ b/tests/duel-core-ruleset.test.ts @@ -0,0 +1,40 @@ +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, null); + 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); + } +}); From 4daf87eddecbdb73ae04b2a24a1e15dc6410fe92 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:36:41 -0500 Subject: [PATCH 04/49] duel-core: monotonic attack/block declarations; optional permanent counters Co-Authored-By: Claude Opus 5.5 --- docs/game/DUEL_API.md | 6 +++--- shared/duel/types.ts | 13 ++++++++++--- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/docs/game/DUEL_API.md b/docs/game/DUEL_API.md index 31a5f78..a52fd32 100644 --- a/docs/game/DUEL_API.md +++ b/docs/game/DUEL_API.md @@ -64,12 +64,12 @@ Engine-side keyword meanings (designer §3.4; duel-design owns the wording): |---|---|---| | `mulligan` | each seat not yet ready (seat 0 first) | `keep`, `mulligan` | | `main` | active | `play {uid, target?}` (cost ≤ Citations; Events and permanents), `endPhase` | -| `attack` | active | `toggleAttacker {uid}` (untapped, non-sick Figure), `confirmAttack` | -| `block` | defender | `block {blocker, attacker}`, `unblock {blocker}`, `confirmBlocks` | +| `attack` | active | `toggleAttacker {uid}` (declare an untapped, non-sick Figure not yet declared), `confirmAttack` | +| `block` | defender | `block {blocker, attacker}` (unassigned blocker, unblocked attacker), `confirmBlocks` | | any | either seat | `concede` (not listed; always accepted) | | any | host only | `timeout` for the seat that must act: in `main`/`attack` ends the turn without attacking, in `block` confirms the current blocks, in `mulligan` keeps. It does **not** lose the game; the host decides when a bank is exhausted and may then send `concede`. | -`confirmAttack` with no attackers ends the turn. Attacking taps the attackers. `onAttack` triggers resolve at `confirmAttack`. +Declarations are **monotonic** (no un-declare action), 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, combat damage resolves at `confirmAttack` without a block phase. `confirmAttack` with no attackers ends the turn. Attacking taps the attackers. `onAttack` triggers resolve at `confirmAttack`. ## Views and log - `viewFor(state, seat): PlayerView`: your hand, sizes of the opponent's hand and library, both graveyards, the battlefield with **current** power/toughness and Connected badge, combat, `toAct`, `version`, `result`. diff --git a/shared/duel/types.ts b/shared/duel/types.ts index d35ab5a..f1b181c 100644 --- a/shared/duel/types.ts +++ b/shared/duel/types.ts @@ -176,6 +176,12 @@ export interface Permanent extends CardInstance { tempToughness: number; /** Doctrines: uid of the Figure they're attached to. */ attachedTo?: string; + /** Well-sourced: prevention already used this turn. */ + shielded?: boolean; + /** Stub: counters gained from Stub so far (≤ 2). */ + stubCounters?: number; + /** Connected bonus already logged. */ + connectedLogged?: boolean; } export interface PlayerState { @@ -193,6 +199,8 @@ export interface PlayerState { ready: boolean; // kept the opening hand /** Remaining time bank, in seconds (the host decrements it). */ bankSeconds: number; + /** libraryEmpty 'fatigue': damage of the next empty draw minus 1. */ + fatigue?: number; } export interface CombatState { @@ -236,10 +244,9 @@ export type DuelAction = | { type: 'mulligan' } | { type: 'play'; uid: string; target?: TargetRef } | { type: 'endPhase' } // main → attack - | { type: 'toggleAttacker'; uid: string } // attack phase + | { type: 'toggleAttacker'; uid: string } // attack phase: declare one more attacker (monotonic; UIs stage undo locally) | { type: 'confirmAttack' } // no attackers → end turn - | { type: 'block'; blocker: string; attacker: string } // block phase (defender) - | { type: 'unblock'; blocker: string } + | { type: 'block'; blocker: string; attacker: string } // block phase (defender), monotonic | { type: 'confirmBlocks' } // damage, then end of turn | { type: 'concede' } // any time, either seat | { type: 'timeout' }; // host-only, for the seat that must act From 038e079ce81e023a3d05c4a82261b8ef499c2eeb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:39:48 -0500 Subject: [PATCH 05/49] [sim-balance] Duel bots (heuristic, MC) and duel simulation harness Engine-agnostic duel bots over a DuelLens, a 40-card deck builder from the 236 sample cards with type/curve-skewed archetypes, a <=4-worker sim runner and DUEL_BALANCE metrics. Runs on a small stand-in duel engine until duel-core's shared/duel alpha lands; then shared/bots/duel-adapter.ts binds it. Co-Authored-By: Claude Opus 5.5 --- scripts/sim/duel-decks.ts | 49 +++++++ scripts/sim/duel-run.ts | 137 ++++++++++++++++++ scripts/sim/duel-sim-types.ts | 18 +++ scripts/sim/duel-standin-adapter.ts | 74 ++++++++++ scripts/sim/duel-standin.ts | 216 ++++++++++++++++++++++++++++ scripts/sim/duel-stats.ts | 156 ++++++++++++++++++++ shared/bots/duel-bots.ts | 194 +++++++++++++++++++++++++ tests/sim-balance-duel.test.ts | 70 +++++++++ 8 files changed, 914 insertions(+) create mode 100644 scripts/sim/duel-decks.ts create mode 100644 scripts/sim/duel-run.ts create mode 100644 scripts/sim/duel-sim-types.ts create mode 100644 scripts/sim/duel-standin-adapter.ts create mode 100644 scripts/sim/duel-standin.ts create mode 100644 scripts/sim/duel-stats.ts create mode 100644 shared/bots/duel-bots.ts create mode 100644 tests/sim-balance-duel.test.ts diff --git a/scripts/sim/duel-decks.ts b/scripts/sim/duel-decks.ts new file mode 100644 index 0000000..388bd49 --- /dev/null +++ b/scripts/sim/duel-decks.ts @@ -0,0 +1,49 @@ +// 40-card sim decks drawn from a card pool (the 236 real sample cards). Every card is unique (one NFT each), +// so decks sample without replacement. Archetypes skew the type or cost mix. Pure, seeded. +import { mulberry32 } from '../../shared/bots/index.ts'; + +export interface PoolCard { id: string; type: string; portal: string; cost: number; keywords: string[]; fame?: number } +export interface SimDeck { id: string; tags: string[]; cards: C[] } + +export const ARCHETYPES = ['random', 'figure-heavy', 'doctrine-heavy', 'event-heavy', 'location-heavy', 'institution-heavy', 'low-curve', 'high-curve'] as const; +export type Archetype = typeof ARCHETYPES[number]; + +function weight(c: PoolCard, arch: Archetype): number { + switch (arch) { + case 'figure-heavy': return c.type === 'Figure' ? 8 : 1; + case 'doctrine-heavy': return c.type === 'Doctrine' ? 8 : 1; + case 'event-heavy': return c.type === 'Event' ? 12 : 1; + case 'location-heavy': return c.type === 'Location' ? 8 : 1; + case 'institution-heavy': return c.type === 'Institution' ? 10 : 1; + case 'low-curve': return c.cost <= 2 ? 8 : c.cost === 3 ? 3 : 0.3; + case 'high-curve': return c.cost >= 5 ? 8 : c.cost === 4 ? 3 : 0.5; + default: return 1; + } +} + +/** Weighted sampling without replacement (Efraimidis–Spirakis keys). */ +export function buildDeck(pool: C[], arch: Archetype, seed: number, size = 40): SimDeck { + const rng = mulberry32(seed); + const keyed = pool.map(c => ({ c, k: Math.pow(rng(), 1 / Math.max(1e-6, weight(c, arch))) })); + keyed.sort((a, b) => b.k - a.k); + const cards = keyed.slice(0, Math.min(size, pool.length)).map(x => x.c); + return { id: `${arch}#${seed}`, tags: deckTags(cards, arch), cards }; +} + +export function deckTags(cards: PoolCard[], arch: string): string[] { + const count = (f: (c: PoolCard) => string) => { const m: Record = {}; for (const c of cards) m[f(c)] = (m[f(c)] ?? 0) + 1; return m; }; + const top = (m: Record) => Object.entries(m).sort((a, b) => b[1] - a[1])[0]?.[0] ?? '?'; + const avg = cards.reduce((t, c) => t + c.cost, 0) / (cards.length || 1); + const curve = avg < 2.6 ? 'low' : avg < 3.4 ? 'mid' : 'high'; + return [`arch:${arch}`, `portal:${top(count(c => c.portal))}`, `curve:${curve}`, `mainType:${top(count(c => c.type))}`]; +} + +/** n decks: half random, the rest cycling through the skewed archetypes. */ +export function deckSet(pool: C[], n: number, seed: number, size = 40): SimDeck[] { + const out: SimDeck[] = []; + for (let i = 0; i < n; i++) { + const arch: Archetype = i % 2 === 0 ? 'random' : ARCHETYPES[1 + ((i >> 1) % (ARCHETYPES.length - 1))]; + out.push(buildDeck(pool, arch, (seed * 7919 + i * 104729) >>> 0, size)); + } + return out; +} diff --git a/scripts/sim/duel-run.ts b/scripts/sim/duel-run.ts new file mode 100644 index 0000000..74cfc33 --- /dev/null +++ b/scripts/sim/duel-run.ts @@ -0,0 +1,137 @@ +// Duel balance simulation. +// npx tsx scripts/sim/duel-run.ts --engine duel --matches 2000 --workers 4 --out sim-out/duel [--rules '{"startingLife":18}'] +// Writes /