From bac186470d3726654480ed9a1a6bd4dfb5568abf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:35:07 -0500 Subject: [PATCH 01/25] 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 02/25] 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 03/25] 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 fcdd05f2b1b38ee5cf8ce4b676137b271860a9a1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:42:28 -0500 Subject: [PATCH 04/25] [ownership] Server-side deck ownership, collection API, 40-card eligibility (#57) - server/game/ownership.ts: verifyAccount, resolveDeck (token ids only; canonical owner in linked wallets, confirmations, exact deckSize, 4 copies per pageId, cards rebuilt from their block), collection (all linked wallets, paged at one tip, no 128-block cap). Signature agreed with host-pvp on #57. - server/game/collection.ts: GET /api/game/collection (Dex bearer) with owned, playable, needed, eligible. - account router exports accountVerifier; http.ts shares one AccountStore and DexKeys between the account and game routes and passes gameRouter({ownership}). - App.tsx: My collection counts cards in every wallet linked to the account. - tests/ownership-deck.test.ts: in-memory ledger fixture, no network. Co-Authored-By: Claude Opus 5.5 --- docs/game/OWNERSHIP_API.md | 73 ++++++++++ server/account/router.ts | 19 ++- server/game/collection.ts | 57 ++++++++ server/game/index.ts | 5 +- server/game/ownership.ts | 211 +++++++++++++++++++++++++++ server/testnet/http.ts | 13 +- src/App.tsx | 8 +- tests/ownership-deck.test.ts | 275 +++++++++++++++++++++++++++++++++++ 8 files changed, 653 insertions(+), 8 deletions(-) create mode 100644 docs/game/OWNERSHIP_API.md create mode 100644 server/game/collection.ts create mode 100644 server/game/ownership.ts create mode 100644 tests/ownership-deck.test.ts diff --git a/docs/game/OWNERSHIP_API.md b/docs/game/OWNERSHIP_API.md new file mode 100644 index 0000000..0a03096 --- /dev/null +++ b/docs/game/OWNERSHIP_API.md @@ -0,0 +1,73 @@ +# Ownership and collection API (Night 2, #57) + +Server-side checks that a player owns the cards they play. Off-chain only: nothing here moves, burns or locks a card, and nothing changes consensus. + +## The rules (ruleset data) + +| Key | Default | Meaning | +|---|---|---| +| `deckSize` | 40 | A constructed deck has exactly this many cards. A testnet mode file may lower it. | +| `maxCopiesPerPage` | 4 | The MTG-style copy limit. Cards minted from the same Wikipedia `pageId` are separate cards, but at most this many go in one deck. | +| `minConfirmations` | 1 | The confirmations each card's mint block needs. Rated play uses `RATED_MIN_CONFIRMATIONS` = 3. | + +## `server/game/ownership.ts` (used by the PvP host) + +```ts +verifyAccount(deps, idToken: unknown): Promise +resolveDeck(deps, account, tokenIds: unknown, opts?: Partial): Promise +collection(deps, account, opts?: { minConfirmations?: number }): Promise +``` + +- **`deps`** is `{ ledger, accounts, verifyIdToken }`. In production, `server/testnet/http.ts` builds it from the node's `Ledger`, the shared `AccountStore`, and `accountVerifier()` from `server/account/router.ts`. It passes the result to `gameRouter({ ownership })`. +- **`resolveDeck`** accepts token ids only, never card JSON. For each card it checks: + - the card is on the canonical chain (`ledger.nft()`); + - its current owner (after transfers) is one of the account's linked wallets; + - it has enough confirmations; + - the deck size and copy limit. + + Each card is rebuilt from its own block (`article` and `statsSnapshot`). The cards come back in the order given. +- **Errors** are thrown as `DeckError { code, status, tokenIds, pageId? }`. `tokenIds` lists every offending card of that class. + + | `code` | `status` | + |---|---| + | `auth` | 401 | + | `size` | 400 | + | `duplicate-token` | 400 | + | `unknown-token` (not on chain, or malformed) | 400 | + | `not-owned` (includes "no linked wallet") | 403 | + | `unconfirmed` | 400 | + | `copy-limit` | 400 | + + `OwnershipUnavailable` (503) means Dex is unreachable or the chain tip kept moving during a read. +- **`collection`** pages `ledger.deck()` (24 per page) across every linked wallet at one canonical tip, restarting if the tip moves. There is no 128-block snapshot cap. + +## `GET /api/game/collection` + +`Authorization: Bearer ` (the same token as `/api/account/me`). Optional: `?minConfirmations=N`. + +```ts +{ + tip, wallets: string[], + deckSize: 40, copyLimit: 4, maxCopiesPerPage: 4, minConfirmations: 1, + owned: number, // confirmed cards across all linked wallets + playable: number, // Σ min(copies, copyLimit) per pageId + needed: number, // max(0, deckSize - playable) + eligible: boolean, // playable >= deckSize + cards: ChainCard[] // tokenId, owner, confirmations, pageId, title, revisionId, url, extract, imageUrl?, + // height, blockHash, createdAt, powHash, article, statsSnapshot +} +``` + +| Case | Response | +|---|---| +| No linked wallets | 200 with `cards: []` and `needed: 40` | +| Missing or invalid token | 401 | +| Dex unreachable | 503 | +| Bad query | 400 | + +The UI shows `playable / deckSize`, for example "23 / 40 cards", and how to mine. + +## Not covered (known gaps) + +- **Peer hosts.** Account stores are per node, and a Dex token sent to a peer could be replayed elsewhere (engineer review §2, G6). This API is for the self-hosted node only. The stretch fix is a wallet-signed deck claim. +- **Plausibility of minted stats** (G5): `pageId` → `title` and `revisionId` → `size` are not cross-checked yet. diff --git a/server/account/router.ts b/server/account/router.ts index 9fe0530..44c8a36 100644 --- a/server/account/router.ts +++ b/server/account/router.ts @@ -12,12 +12,28 @@ export type AccountDeps = { config?: OidcConfig; keys?: DexKeys; store?: Account type Authed = Request & { account?: Account }; const hex64 = z.string().regex(/^[a-f0-9]{64}$/); +/** + * Verifies a Dex ID token and records the account. Shared with the game routes + * (server/game/collection.ts, the PvP host) so every route uses the same store and keys. + * Throws TokenError (status 401) for a bad token; other errors mean Dex is unreachable. + */ +export function accountVerifier(config: OidcConfig, keys: Pick, store: Pick, + now: () => number = Date.now): (idToken: string) => Promise { + return async idToken => { + const claims = await verifyIdToken(idToken, keys, config, { now: now() }); + const account: Account = { sub: claims.sub, issuer: claims.iss, name: displayName(claims), username: claims.preferred_username ?? '' }; + store.upsert(account); + return account; + }; +} + export function createAccountRouter(deps: AccountDeps = {}): Router { const config = deps.config ?? oidcConfig(); const now = deps.now ?? Date.now; const keys = deps.keys ?? new DexKeys(config, deps.fetcher, now); const store = deps.store ?? new AccountStore(resolve(deps.dataDir ?? 'data', 'accounts.sqlite'), now); const router = Router(); + const verify = accountVerifier(config, keys, store, now); const toAccount = (claims: Awaited>): Account => ({ sub: claims.sub, issuer: claims.iss, name: displayName(claims), username: claims.preferred_username ?? '' }); @@ -26,8 +42,7 @@ export function createAccountRouter(deps: AccountDeps = {}): Router { try { const m = /^Bearer ([A-Za-z0-9_.-]+)$/.exec(req.get('authorization') ?? ''); if (!m) throw new TokenError('Log in with your eom.dev account'); - req.account = toAccount(await verifyIdToken(m[1], keys, config, { now: now() })); - store.upsert(req.account); + req.account = await verify(m[1]); next(); } catch (e) { next(e); } }; diff --git a/server/game/collection.ts b/server/game/collection.ts new file mode 100644 index 0000000..74044b2 --- /dev/null +++ b/server/game/collection.ts @@ -0,0 +1,57 @@ +/** + * GET /api/game/collection Authorization: Bearer [?minConfirmations=N] + * + * Every card the account's linked wallets own (no 128-block cap) and whether that is enough to + * build a deck. Eligibility counts the copy limit: 40 copies of one article is 4 playable cards. + */ +import { Router, type Request, type Response } from 'express'; +import { DeckError, collectionAt, ownershipRules, playableCount, verifyAccount, + type ChainCard, type OwnershipDeps, type OwnershipRules } from './ownership.ts'; + +export type CollectionResponse = { + tip: string; + wallets: string[]; + deckSize: number; + /** Max copies per pageId. `maxCopiesPerPage` is the same value under the ruleset's name. */ + copyLimit: number; + maxCopiesPerPage: number; + minConfirmations: number; + /** Confirmed cards across all linked wallets. */ + owned: number; + /** Σ min(copies, copyLimit) per pageId: the most cards a legal deck can draw from. */ + playable: number; + /** max(0, deckSize - playable). */ + needed: number; + /** playable >= deckSize. */ + eligible: boolean; + cards: ChainCard[]; +}; + +export function collectionResponse(deps: Pick, sub: string, + rules?: Partial): CollectionResponse { + const r = ownershipRules(rules); + const { tip, wallets, cards } = collectionAt(deps, { sub }, { minConfirmations: r.minConfirmations }); + const playable = playableCount(cards, r.maxCopiesPerPage); + return { tip, wallets, deckSize: r.deckSize, copyLimit: r.maxCopiesPerPage, maxCopiesPerPage: r.maxCopiesPerPage, + minConfirmations: r.minConfirmations, owned: cards.length, playable, needed: Math.max(0, r.deckSize - playable), + eligible: playable >= r.deckSize, cards }; +} + +export function collectionRouter(deps: OwnershipDeps & { rules?: Partial }): Router { + const router = Router(); + router.get('/', async (req: Request, res: Response) => { + res.setHeader('Cache-Control', 'no-store'); + const q = req.query.minConfirmations; + if (q !== undefined && (typeof q !== 'string' || !/^[1-9]\d{0,3}$/.test(q))) { res.status(400).json({ error: 'Invalid minConfirmations' }); return; } + const m = /^Bearer ([A-Za-z0-9_.-]{1,8192})$/.exec(req.get('authorization') ?? ''); + try { + const account = await verifyAccount(deps, m?.[1]); + res.json(collectionResponse(deps, account.sub, { ...deps.rules, ...(q ? { minConfirmations: Number(q) } : {}) })); + } catch (e) { + const err = e as Error & { status?: number }; + const status = e instanceof DeckError ? err.status! : err.status === 503 ? 503 : 500; + res.status(status).json({ error: status === 500 ? 'Collection unavailable' : err.message }); + } + }); + return router; +} diff --git a/server/game/index.ts b/server/game/index.ts index b9a1a97..4ed375b 100644 --- a/server/game/index.ts +++ b/server/game/index.ts @@ -12,11 +12,14 @@ import { createGameRouter } from './router.ts'; import { MatchStore } from './store.ts'; import type { EnginePort } from './engine-port.ts'; import { TrendCache } from './trends.ts'; +import type { OwnershipDeps } from './ownership.ts'; type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> }; export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment; - engine?: EnginePort; env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise { + engine?: EnginePort; env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean; + /** Server-side ownership (#57) for ./ownership.ts verifyAccount/resolveDeck/collection; absent in Night 1 tests. */ + ownership?: OwnershipDeps }): Promise { const env = options.env ?? process.env; const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding; const modes = loadModes(env); diff --git a/server/game/ownership.ts b/server/game/ownership.ts new file mode 100644 index 0000000..6d27de3 --- /dev/null +++ b/server/game/ownership.ts @@ -0,0 +1,211 @@ +/** + * Server-side ownership for constructed play (Night 2, #57). Signature agreed with host-pvp (#56). + * + * The host never trusts card data from a client. A deck arrives as token ids only; each one + * must be on the canonical chain, owned by one of the account's linked wallets, and confirmed + * enough. The card is then rebuilt from its own block (article + mint stats snapshot). + * + * Off-chain only: nothing here moves, burns or locks a card, and nothing touches consensus. + * No Wikipedia calls; the only I/O is the injected ID-token verifier (Dex JWKS, cached). + */ +import type { Account } from '../account/store.ts'; +import type { Article } from '../../shared/protocol.ts'; +import type { MintStatsSnapshot } from '../../shared/enrichment.ts'; +import type { TestnetBlock } from '../../shared/testnet.ts'; + +export type OwnershipRules = { + /** Exact deck size for constructed play. Production is 40; a testnet mode file may lower it. */ + deckSize: number; + /** MTG-style copy limit: cards minted from the same Wikipedia pageId. */ + maxCopiesPerPage: number; + /** Minimum confirmations of each card's mint block (1 casual, 3 rated). */ + minConfirmations: number; +}; +export const DEFAULT_OWNERSHIP_RULES: Readonly = Object.freeze({ deckSize: 40, maxCopiesPerPage: 4, minConfirmations: 1 }); +export const RATED_MIN_CONFIRMATIONS = 3; +/** Upper bound on any deck request we will even look at (a deck is 40; this only guards the loop). */ +export const MAX_DECK_TOKENS = 200; +/** Guard against an unbounded collection. Far above anything the chain can mint for one player soon. */ +export const MAX_COLLECTION = 20_000; +/** server/testnet/ledger.ts MAX_DECK_PAGE. */ +const PAGE = 24; +/** A tip change mid-scan restarts the scan; give up after this many rather than loop forever. */ +const MAX_RESTARTS = 4; + +// Structural: server/testnet/ledger.ts `Ledger` and server/account/store.ts `AccountStore` +// satisfy these, and tests pass in-memory fixtures. +export type OwnershipLedger = { + nft(tokenId: string): { block: TestnetBlock; owner: string; sequence: number; confirmations: number } | undefined; + deck(address: string, offset: number, limit: number): { + tip: string; total: number; next: number | null; + nfts: { block: TestnetBlock; sequence: number; confirmations: number }[]; + }; + summary(): { tip: string; height: number }; +}; +export type OwnershipAccounts = { wallets(sub: string): { address: string }[]; upsert?(a: Account): void }; +export type OwnershipDeps = { + ledger: OwnershipLedger; + accounts: OwnershipAccounts; + /** server/account/router.ts accountVerifier(); throws an error with status 401 for a bad token. */ + verifyIdToken(idToken: string): Promise; +}; + +/** One owned NFT as built from its canonical block (never from client JSON). */ +export type ChainCard = { + tokenId: string; + /** Current owner (after transfers), one of the account's linked wallets. */ + owner: string; + confirmations: number; + pageId: number; + title: string; + revisionId: number; + url: string; + extract: string; + imageUrl?: string; + height: number; + blockHash: string; + createdAt: number; + powHash: string; + article: Article; + statsSnapshot: MintStatsSnapshot; +}; + +export type DeckErrorCode = 'auth' | 'size' | 'duplicate-token' | 'unknown-token' | 'not-owned' | 'unconfirmed' | 'copy-limit'; +const STATUS: Record = { + auth: 401, size: 400, 'duplicate-token': 400, 'unknown-token': 400, 'not-owned': 403, unconfirmed: 400, 'copy-limit': 400, +}; +export class DeckError extends Error { + readonly code: DeckErrorCode; + /** Every offending token of this class, so the UI can highlight them. */ + readonly tokenIds: string[]; + readonly status: 400 | 401 | 403; + readonly pageId?: number; + constructor(code: DeckErrorCode, message: string, tokenIds: string[] = [], pageId?: number) { + super(message); + this.name = 'DeckError'; + this.code = code; this.tokenIds = tokenIds; this.status = STATUS[code]; + if (pageId !== undefined) this.pageId = pageId; + } +} +/** Thrown when Dex or the ledger cannot answer right now (not the player's fault). */ +export class OwnershipUnavailable extends Error { readonly status = 503; } + +const TOKEN = /^[a-f0-9]{64}$/; +const isInt = (n: unknown, min: number, max: number): n is number => Number.isSafeInteger(n) && (n as number) >= min && (n as number) <= max; + +/** Merges partial rules over the defaults and rejects nonsense (mode files are data, so validate). */ +export function ownershipRules(rules: Partial = {}): OwnershipRules { + const defined = Object.fromEntries(Object.entries(rules).filter(([, v]) => v !== undefined)) as Partial; + const r = { ...DEFAULT_OWNERSHIP_RULES, ...defined }; + if (!isInt(r.deckSize, 1, MAX_DECK_TOKENS)) throw new RangeError(`deckSize must be 1..${MAX_DECK_TOKENS}`); + if (!isInt(r.maxCopiesPerPage, 1, MAX_DECK_TOKENS)) throw new RangeError(`maxCopiesPerPage must be 1..${MAX_DECK_TOKENS}`); + if (!isInt(r.minConfirmations, 1, 1_000_000)) throw new RangeError('minConfirmations must be >= 1'); + return r; +} + +/** Builds the card from the canonical block. `owner` is the current owner from the index, not the miner. */ +export function cardFromChain(nft: { block: TestnetBlock; confirmations: number }, owner: string): ChainCard { + const b = structuredClone(nft.block); + const card: ChainCard = { tokenId: b.tokenId, owner, confirmations: nft.confirmations, + pageId: b.article.pageId, title: b.article.title, revisionId: b.article.revisionId, url: b.article.url, extract: b.article.extract, + height: b.height, blockHash: b.hash, createdAt: b.createdAt, powHash: b.powHash, article: b.article, statsSnapshot: b.statsSnapshot }; + if (b.article.image) card.imageUrl = b.article.image; + return card; +} + +/** Verifies a Dex ID token from a request body. Throws DeckError('auth') or OwnershipUnavailable. */ +export async function verifyAccount(deps: Pick, idToken: unknown): Promise { + if (typeof idToken !== 'string' || !idToken || idToken.length > 8192) throw new DeckError('auth', 'Log in with your eom.dev account to play with your cards'); + try { return await deps.verifyIdToken(idToken); } + catch (e) { + if ((e as { status?: number }).status === 401) throw new DeckError('auth', (e as Error).message || 'Log in again with your eom.dev account'); + throw new OwnershipUnavailable('eom.dev login is temporarily unavailable'); + } +} + +/** + * Verifies a constructed deck for an already-verified account. Resolves to the cards in the + * order given, or throws the first class of DeckError found (listing every offending token). + */ +export async function resolveDeck(deps: Pick, account: Pick, tokenIds: unknown, + opts?: Partial): Promise { + const r = ownershipRules(opts); + if (!Array.isArray(tokenIds) || tokenIds.length > MAX_DECK_TOKENS) throw new DeckError('size', `A deck is exactly ${r.deckSize} cards`); + const invalid = tokenIds.filter(t => typeof t !== 'string' || !TOKEN.test(t)).map(t => String(t).slice(0, 80)).slice(0, 10); + if (invalid.length) throw new DeckError('unknown-token', 'Invalid card identifier', invalid); + const ids = tokenIds as string[]; + if (ids.length !== r.deckSize) throw new DeckError('size', `A deck is exactly ${r.deckSize} cards (got ${ids.length})`); + const seen = new Set(), dupes = new Set(); + for (const id of ids) (seen.has(id) ? dupes : seen).add(id); + if (dupes.size) throw new DeckError('duplicate-token', 'The same card appears more than once', [...dupes]); + + const wallets = new Set(deps.accounts.wallets(account.sub).map(w => w.address)); + if (!wallets.size) throw new DeckError('not-owned', 'Link a wallet to your eom.dev account to play with your cards', ids); + + const cards: ChainCard[] = [], missing: string[] = [], foreign: string[] = [], young: string[] = []; + for (const id of ids) { + const nft = deps.ledger.nft(id); + if (!nft || nft.block.tokenId !== id) { missing.push(id); continue; } + if (!wallets.has(nft.owner)) { foreign.push(id); continue; } + if (nft.confirmations < r.minConfirmations) { young.push(id); continue; } + cards.push(cardFromChain(nft, nft.owner)); + } + if (missing.length) throw new DeckError('unknown-token', 'Card not found on the canonical chain', missing); + if (foreign.length) throw new DeckError('not-owned', 'Card is not owned by a wallet linked to this account', foreign); + if (young.length) throw new DeckError('unconfirmed', `Card needs ${r.minConfirmations} confirmation${r.minConfirmations === 1 ? '' : 's'}`, young); + + const byPage = new Map(); + for (const c of cards) byPage.set(c.pageId, [...(byPage.get(c.pageId) ?? []), c.tokenId]); + for (const [pageId, tokens] of byPage) + if (tokens.length > r.maxCopiesPerPage) throw new DeckError('copy-limit', `At most ${r.maxCopiesPerPage} copies of the same article`, tokens, pageId); + return cards; +} + +/** + * Every card the account owns across its linked wallets, read at one canonical tip (restarting + * if the tip moves), with no snapshot cap. Only cards with `minConfirmations` (default 1). + */ +export async function collection(deps: Pick, account: Pick, + opts: { minConfirmations?: number } = {}): Promise { + return collectionAt(deps, account, opts).cards; +} + +/** collection() plus the tip and wallets it was read at. Synchronous. */ +export function collectionAt(deps: Pick, account: Pick, + opts: { minConfirmations?: number } = {}): { tip: string; wallets: string[]; cards: ChainCard[] } { + const minConfirmations = ownershipRules({ minConfirmations: opts.minConfirmations }).minConfirmations; + const wallets = [...new Set(deps.accounts.wallets(account.sub).map(w => w.address))]; + for (let attempt = 0; attempt <= MAX_RESTARTS; attempt++) { + const tip = deps.ledger.summary().tip; + const cards = scan(deps.ledger, wallets, tip, minConfirmations); + if (cards) return { tip, wallets, cards }; + } + throw new OwnershipUnavailable('The chain is moving too fast to read a consistent collection; try again'); +} + +/** Returns null if the tip moved during the scan. */ +function scan(ledger: OwnershipLedger, wallets: string[], tip: string, minConfirmations: number): ChainCard[] | null { + const cards: ChainCard[] = []; + for (const address of wallets) { + let offset: number | null = 0; + while (offset !== null) { + const page = ledger.deck(address, offset, PAGE); + if (page.tip !== tip) return null; + for (const nft of page.nfts) { + if (nft.confirmations >= minConfirmations) cards.push(cardFromChain(nft, address)); + if (cards.length > MAX_COLLECTION) throw new OwnershipUnavailable('Collection too large to list'); + } + // Defensive: a page that makes no progress would loop forever. + offset = page.next !== null && page.next > offset ? page.next : null; + } + } + return cards; +} + +/** How many of these cards a legal deck could use under the copy limit: Σ min(copies, limit) per pageId. */ +export function playableCount(cards: Pick[], maxCopiesPerPage: number): number { + const perPage = new Map(); + for (const c of cards) perPage.set(c.pageId, (perPage.get(c.pageId) ?? 0) + 1); + let n = 0; for (const count of perPage.values()) n += Math.min(count, maxCopiesPerPage); + return n; +} diff --git a/server/testnet/http.ts b/server/testnet/http.ts index be6d366..9053218 100644 --- a/server/testnet/http.ts +++ b/server/testnet/http.ts @@ -17,7 +17,10 @@ import { IS_MAINNET, PROFILE } from '../../shared/network.ts'; import { assertLaunchAllowed, launchManifest } from '../launch.ts'; import { resourceConfig, RpcBudget, RpcError } from '../resources.ts'; import { trustedProxies, operationsPort, startOperations } from '../operations.ts'; -import { createAccountRouter } from '../account/router.ts'; +import { accountVerifier, createAccountRouter } from '../account/router.ts'; +import { AccountStore } from '../account/store.ts'; +import { DexKeys, oidcConfig } from '../account/oidc.ts'; +import { collectionRouter } from '../game/collection.ts'; const root = fileURLToPath(new URL('../../', import.meta.url)); assertLaunchAllowed(); @@ -150,8 +153,12 @@ app.post('/p2p/transaction',workLimit,async(req,res)=>{ const id=await ledger.submitTransaction(transaction); res.status(202).json({id,status:'pending'}); }); -app.use('/api/account',createAccountRouter({dataDir})); -app.use('/api/game',await (await import('../game/index.ts')).gameRouter({dataDir,enrichment:wikipediaEnrichment})); +// One account store and one Dex key cache, shared by the account and game routes (#57). +const oidc=oidcConfig(), dexKeys=new DexKeys(oidc), accounts=new AccountStore(resolve(dataDir,'accounts.sqlite')); +const ownership={ledger,accounts,verifyIdToken:accountVerifier(oidc,dexKeys,accounts)}; +app.use('/api/account',createAccountRouter({config:oidc,keys:dexKeys,store:accounts})); +app.use('/api/game/collection',collectionRouter(ownership)); +app.use('/api/game',await (await import('../game/index.ts')).gameRouter({dataDir,enrichment:wikipediaEnrichment,ownership})); app.use(['/api','/p2p'],(_req,res)=>{res.status(404).json({error:'Unknown testnet endpoint'});}); app.use(express.static(resolve(root,'dist'))); app.get('/{*path}',(_req,res)=>res.sendFile(resolve(root,'dist/index.html'))); diff --git a/src/App.tsx b/src/App.tsx index e302ace..19dd2fe 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -10,7 +10,7 @@ import { Card, samples, imageCredit, type CardData } from './Card.tsx'; import { WalletPanel } from './WalletPanel.tsx'; import { useModalFocus } from './useModalFocus.ts'; import { ThemePicker } from './ThemePicker.tsx'; -import { LoginButton } from './auth/LoginButton.tsx'; +import { LoginButton, useAccount } from './auth/LoginButton.tsx'; import { TradeDesk } from './TradeDesk.tsx'; import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/network.ts'; import { StateClient } from '../shared/rpc-client.ts'; @@ -48,6 +48,7 @@ function transferProblem(state: TestnetSnapshot, card: CardData, address: string export default function App() { const [view, setView] = useState('Discover'); + const linkedAccount = useAccount(); const [wallet, setWallet] = useState(); const [snapshot, setSnapshot] = useState(); const [rpcAvailable, setRpcAvailable] = useState(false); @@ -127,7 +128,10 @@ export default function App() { } catch (e) { setTransferError(message(e)); } finally { transferInFlight.current = false; setTransferBusy(false); } }; - const owned = snapshot?.blocks.filter(b => wallet && testnetOwnerOf(snapshot, b.tokenId) === wallet.address) ?? []; + // Every canonical card owned by this browser's wallet or any wallet linked to the eom.dev account (#57). + // The full canonical chain is paged in by StateClient, so nothing is capped at 128 blocks. + const mine = new Set([wallet?.address, ...(linkedAccount?.wallets ?? []).map(w => w.address)].filter(Boolean)); + const owned = snapshot?.blocks.filter(b => mine.has(testnetOwnerOf(snapshot, b.tokenId) ?? '')) ?? []; const visibleCards = view === 'My collection' ? owned.map(asCard) : snapshot?.blocks.length ? [...snapshot.blocks].reverse().slice(0, 12).map(asCard) : samples; const filtered = visibleCards.filter(c => (category === 'All cards' || c.article.category === category) && diff --git a/tests/ownership-deck.test.ts b/tests/ownership-deck.test.ts new file mode 100644 index 0000000..309801c --- /dev/null +++ b/tests/ownership-deck.test.ts @@ -0,0 +1,275 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import express from 'express'; +import type { AddressInfo } from 'node:net'; +import { resolveDeck, collection, verifyAccount, playableCount, ownershipRules, DEFAULT_OWNERSHIP_RULES, + DeckError, OwnershipUnavailable, type OwnershipDeps, type OwnershipLedger } from '../server/game/ownership.ts'; +import { collectionRouter, collectionResponse } from '../server/game/collection.ts'; +import type { Account } from '../server/account/store.ts'; +import type { TestnetBlock } from '../shared/testnet.ts'; + +// In-memory fixture: the same shape as Ledger.nft/deck/summary and AccountStore.wallets. No network. +const hex = (s: string) => createHash('sha256').update(s).digest('hex'); +const ALICE = hex('alice'), ALICE2 = hex('alice-2'), BOB = hex('bob'); + +function block(n: number, pageId: number, miner: string): TestnetBlock { + return { + version: 6, network: 'testnet', chainId: 'test', height: n, previousHash: hex(`b${n - 1}`), createdAt: 1_800_000_000 + n, + article: { pageId, title: `Article ${pageId}`, extract: `Extract ${pageId}.`, url: `https://en.wikipedia.org/?curid=${pageId}`, + revisionId: 1000 + pageId, source: 'live', category: 'History' }, + statsSnapshot: { capturedAt: '2026-11-17T00:00:00Z', revisionId: 1000 + pageId, pageBytes: 5000 + pageId, languageCount: 3, + languagesTruncated: false, pageviews: null } as unknown as TestnetBlock['statsSnapshot'], + owner: miner, publicKey: 'pk', nonce: 0, target: 'f'.repeat(64), key: '0'.repeat(64), transactionsRoot: '0'.repeat(64), + stateRoot: '0'.repeat(64), hash: hex(`b${n}`), tokenId: hex(`t${n}`), powHash: hex(`p${n}`), signature: 'sig', transactions: [], + } as unknown as TestnetBlock; +} + +class FakeLedger implements OwnershipLedger { + tip = 'tip-0'; + height = 0; + cards: { block: TestnetBlock; owner: string }[] = []; + deckCalls = 0; + onDeck?: () => void; + mint(owner: string, pageId: number): string { + const b = block(++this.height, pageId, owner); + this.cards.push({ block: b, owner }); + this.tip = `tip-${this.height}`; + return b.tokenId; + } + mineEmpty(n = 1) { this.height += n; this.tip = `tip-${this.height}`; } + transfer(token: string, to: string) { this.cards.find(c => c.block.tokenId === token)!.owner = to; } + private conf(b: TestnetBlock) { return this.height - b.height + 1; } + nft(token: string) { + const c = this.cards.find(x => x.block.tokenId === token); + return c ? { block: structuredClone(c.block), owner: c.owner, sequence: 0, confirmations: this.conf(c.block) } : undefined; + } + deck(address: string, offset: number, limit: number) { + this.deckCalls++; + assert.ok(limit <= 24, 'ledger pages are at most 24'); + const mine = this.cards.filter(c => c.owner === address); + const nfts = mine.slice(offset, offset + limit).map(c => ({ block: structuredClone(c.block), sequence: 0, confirmations: this.conf(c.block) })); + const result = { tip: this.tip, total: mine.length, next: offset + nfts.length < mine.length ? offset + nfts.length : null, nfts }; + this.onDeck?.(); + return result; + } + summary() { return { tip: this.tip, height: this.height, network: 'testnet', chainId: 'test' }; } +} + +function fixture(wallets: Record = { alice: [ALICE, ALICE2], bob: [BOB] }) { + const ledger = new FakeLedger(); + const deps: OwnershipDeps = { ledger, accounts: { wallets: sub => (wallets[sub] ?? []).map(address => ({ address })) }, + verifyIdToken: async (t: string): Promise => { + const m = /^good\.token\.(\w+)$/.exec(t); + if (m) return { sub: m[1], issuer: 'https://dex.example/', name: m[1], username: m[1] }; + if (t === 'dex.is.down') throw new Error('fetch failed'); + throw Object.assign(new Error('Token expired'), { status: 401 }); + } }; + return { ledger, deps }; +} +/** n cards for `owner`, distinct pageIds starting at `firstPage`. */ +const mintMany = (l: FakeLedger, owner: string, n: number, firstPage = 1) => Array.from({ length: n }, (_, i) => l.mint(owner, firstPage + i)); + +const ALICE_ACCT = { sub: 'alice' }, BOB_ACCT = { sub: 'bob' }; +async function rejects(p: Promise, code: string, tokenIds?: string[]) { + await assert.rejects(p, (e: unknown) => { + assert.ok(e instanceof DeckError, String(e)); + assert.equal(e.code, code); + if (tokenIds) assert.deepEqual(e.tokenIds, tokenIds); + return true; + }); +} + +test('defaults are a 40-card deck, 4 copies per article, 1 confirmation', () => { + assert.deepEqual({ ...DEFAULT_OWNERSHIP_RULES }, { deckSize: 40, maxCopiesPerPage: 4, minConfirmations: 1 }); + assert.equal(ownershipRules({ deckSize: 10, minConfirmations: undefined }).minConfirmations, 1); + assert.throws(() => ownershipRules({ deckSize: 0 }), RangeError); + assert.throws(() => ownershipRules({ maxCopiesPerPage: 1.5 }), RangeError); + assert.throws(() => ownershipRules({ minConfirmations: 0 }), RangeError); +}); + +test('verifyAccount maps token failures to DeckError(auth) and Dex outages to OwnershipUnavailable', async () => { + const { deps } = fixture(); + assert.equal((await verifyAccount(deps, 'good.token.alice')).sub, 'alice'); + for (const t of [undefined, '', 42, 'x'.repeat(9000)]) await rejects(verifyAccount(deps, t), 'auth'); + await assert.rejects(verifyAccount(deps, 'bad'), (e: unknown) => e instanceof DeckError && e.code === 'auth' && e.status === 401 && e.message === 'Token expired'); + await assert.rejects(verifyAccount(deps, 'dex.is.down'), (e: unknown) => e instanceof OwnershipUnavailable && e.status === 503); +}); + +test('resolveDeck accepts 40 owned cards across linked wallets and builds them from the chain, in order', async () => { + const { ledger, deps } = fixture(); + const ids = [...mintMany(ledger, ALICE, 25, 1), ...mintMany(ledger, ALICE2, 15, 100)].reverse(); + const cards = await resolveDeck(deps, ALICE_ACCT, ids); + assert.equal(cards.length, 40); + assert.deepEqual(cards.map(c => c.tokenId), ids); + const c = cards.find(x => x.pageId === 100)!; + const chain = ledger.nft(c.tokenId)!.block; + assert.equal(c.owner, ALICE2); + assert.equal(c.title, 'Article 100'); + assert.equal(c.revisionId, 1100); + assert.equal(c.article.title, 'Article 100'); + assert.equal(c.statsSnapshot.pageBytes, 5100); + assert.equal(c.blockHash, chain.hash); + assert.equal(c.powHash, chain.powHash); + assert.equal(c.height, chain.height); +}); + +test('resolveDeck takes token ids only: card data is never taken from the client', async () => { + const { ledger, deps } = fixture(); + const ids = mintMany(ledger, ALICE, 40); + const forged = ids.map(tokenId => ({ tokenId, article: { title: 'Barack Obama' }, statsSnapshot: { pageBytes: 9e9 } })); + await rejects(resolveDeck(deps, ALICE_ACCT, forged), 'unknown-token'); +}); + +test('resolveDeck enforces the exact deck size from ruleset data', async () => { + const { ledger, deps } = fixture(); + const ids = mintMany(ledger, ALICE, 41); + for (const deck of [ids.slice(0, 39), ids, [], 'nope', null, Array(10_000).fill(ids[0])]) await rejects(resolveDeck(deps, ALICE_ACCT, deck), 'size'); + assert.equal((await resolveDeck(deps, ALICE_ACCT, ids.slice(0, 10), { deckSize: 10 })).length, 10, 'a testnet mode may lower deckSize'); +}); + +test('resolveDeck rejects malformed and duplicated token ids', async () => { + const { ledger, deps } = fixture(); + const ids = mintMany(ledger, ALICE, 40); + await rejects(resolveDeck(deps, ALICE_ACCT, [...ids.slice(0, 39), 'ABC']), 'unknown-token', ['ABC']); + await rejects(resolveDeck(deps, ALICE_ACCT, [...ids.slice(0, 39), ids[0]]), 'duplicate-token', [ids[0]]); +}); + +test('resolveDeck requires a linked wallet', async () => { + const { ledger, deps } = fixture(); + const ids = mintMany(ledger, ALICE, 40); + await assert.rejects(resolveDeck(deps, { sub: 'stranger' }, ids), (e: unknown) => e instanceof DeckError && e.code === 'not-owned' && e.status === 403 && /Link a wallet/.test(e.message)); +}); + +test('resolveDeck rejects unknown cards and cards owned by someone else, listing every one', async () => { + const { ledger, deps } = fixture(); + const ids = mintMany(ledger, ALICE, 38); + const bobs = mintMany(ledger, BOB, 2, 500); + await rejects(resolveDeck(deps, ALICE_ACCT, [...ids, ...bobs]), 'not-owned', bobs); + await rejects(resolveDeck(deps, ALICE_ACCT, [...ids, hex('nope'), bobs[0]]), 'unknown-token', [hex('nope')]); + // Bob cannot field Alice's cards either, even though they exist. + await rejects(resolveDeck(deps, BOB_ACCT, [...ids, ...bobs]), 'not-owned', ids); +}); + +test('ownership follows transfers: the current owner, not the miner, may play the card', async () => { + const { ledger, deps } = fixture(); + const ids = mintMany(ledger, ALICE, 40); + ledger.transfer(ids[7], BOB); + await rejects(resolveDeck(deps, ALICE_ACCT, ids), 'not-owned', [ids[7]]); + const cards = await resolveDeck(deps, BOB_ACCT, [ids[7], ...mintMany(ledger, BOB, 39, 300)]); + assert.equal(cards[0].owner, BOB); +}); + +test('resolveDeck requires minConfirmations (3 for rated play)', async () => { + const { ledger, deps } = fixture(); + const ids = mintMany(ledger, ALICE, 40); + // The last card has 1 confirmation, the one before it 2. + await rejects(resolveDeck(deps, ALICE_ACCT, ids, { minConfirmations: 3 }), 'unconfirmed', ids.slice(38)); + ledger.mineEmpty(2); + assert.equal((await resolveDeck(deps, ALICE_ACCT, ids, { minConfirmations: 3 })).length, 40); +}); + +test('duplicates of an article count as separate cards, up to 4 copies per pageId', async () => { + const { ledger, deps } = fixture(); + const base = mintMany(ledger, ALICE, 35, 1); + const copies = Array.from({ length: 5 }, () => ledger.mint(ALICE, 777)); + await assert.rejects(resolveDeck(deps, ALICE_ACCT, [...base, ...copies]), + (e: unknown) => e instanceof DeckError && e.code === 'copy-limit' && e.pageId === 777 && e.tokenIds.length === 5); + const cards = await resolveDeck(deps, ALICE_ACCT, [...base, ...copies.slice(0, 4), ledger.mint(ALICE, 900)]); + assert.equal(cards.filter(c => c.pageId === 777).length, 4); + assert.equal((await resolveDeck(deps, ALICE_ACCT, [...base, ...copies], { maxCopiesPerPage: 5 })).length, 40, 'the copy limit is ruleset data'); +}); + +test('playableCount applies the copy limit', () => { + const cards = [1, 1, 1, 1, 1, 1, 2, 3].map(pageId => ({ pageId })); + assert.equal(playableCount(cards, 4), 6); + assert.equal(playableCount(cards, 1), 3); +}); + +test('collection lists every owned card across wallets with no 128-block cap', async () => { + const { ledger, deps } = fixture(); + mintMany(ledger, ALICE, 150, 1); + mintMany(ledger, BOB, 10, 1000); + mintMany(ledger, ALICE2, 3, 2000); + const cards = await collection(deps, ALICE_ACCT); + assert.equal(cards.length, 153); + assert.equal(new Set(cards.map(x => x.tokenId)).size, 153); + assert.ok(cards.every(x => x.owner === ALICE || x.owner === ALICE2)); + const r = collectionResponse(deps, 'alice'); + assert.equal(r.owned, 153); assert.equal(r.playable, 153); assert.equal(r.needed, 0); assert.equal(r.eligible, true); + assert.deepEqual(r.wallets, [ALICE, ALICE2]); + assert.equal(r.tip, ledger.tip); + assert.deepEqual(await collection(deps, { sub: 'stranger' }), []); +}); + +test('collection shows progress toward 40 and applies the copy limit to eligibility', () => { + const { ledger, deps } = fixture(); + mintMany(ledger, ALICE, 20, 1); + for (let i = 0; i < 10; i++) ledger.mint(ALICE, 4242); + const c = collectionResponse(deps, 'alice'); + assert.equal(c.owned, 30); assert.equal(c.playable, 24); assert.equal(c.needed, 16); assert.equal(c.eligible, false); + assert.equal(c.deckSize, 40); assert.equal(c.copyLimit, 4); assert.equal(c.maxCopiesPerPage, 4); + assert.equal(collectionResponse(deps, 'alice', { deckSize: 20 }).eligible, true); + const none = collectionResponse(deps, 'stranger'); + assert.equal(none.owned, 0); assert.equal(none.needed, 40); assert.deepEqual(none.cards, []); +}); + +test('collection only counts cards with enough confirmations', async () => { + const { ledger, deps } = fixture(); + mintMany(ledger, ALICE, 5); + assert.equal((await collection(deps, ALICE_ACCT, { minConfirmations: 3 })).length, 3); +}); + +test('collection restarts when the tip moves mid-scan and gives up if it never settles', async () => { + const { ledger, deps } = fixture(); + mintMany(ledger, ALICE, 60); + let moves = 1; + ledger.onDeck = () => { if (moves-- > 0) ledger.mint(ALICE, 9999); }; + const c = collectionResponse(deps, 'alice'); + assert.equal(c.owned, 61); + assert.equal(c.tip, ledger.tip); + ledger.onDeck = () => { ledger.mineEmpty(); }; + await assert.rejects(collection(deps, ALICE_ACCT), OwnershipUnavailable); +}); + +async function serve(router: express.Router) { + const app = express(); + app.use('/api/game/collection', router); + const server = app.listen(0, '127.0.0.1'); + await new Promise(r => server.once('listening', r)); + const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/game/collection`; + return { base, close: () => new Promise(r => server.close(r)) }; +} + +test('GET /api/game/collection requires a verified eom.dev token (local loopback only, no upstream)', async () => { + const { ledger, deps } = fixture(); + mintMany(ledger, ALICE, 23); + const { base, close } = await serve(collectionRouter(deps)); + const as = (t: string) => ({ headers: { authorization: `Bearer ${t}` } }); + try { + let res = await fetch(base); + assert.equal(res.status, 401); + res = await fetch(base, as('bad.token.x!')); + assert.equal(res.status, 401); + res = await fetch(base, as('expired.token.x')); + assert.equal(res.status, 401); + assert.equal((await res.json()).error, 'Token expired'); + res = await fetch(base, as('dex.is.down')); + assert.equal(res.status, 503); + res = await fetch(`${base}?minConfirmations=abc`, as('good.token.alice')); + assert.equal(res.status, 400); + res = await fetch(base, as('good.token.alice')); + assert.equal(res.status, 200); + assert.equal(res.headers.get('cache-control'), 'no-store'); + const body = await res.json(); + assert.equal(body.owned, 23); assert.equal(body.playable, 23); assert.equal(body.needed, 17); + assert.equal(body.eligible, false); assert.equal(body.deckSize, 40); assert.equal(body.copyLimit, 4); + assert.equal(body.cards.length, 23); + assert.equal(body.cards[0].title, 'Article 1'); + assert.equal(body.cards[0].pageId, 1); + res = await fetch(`${base}?minConfirmations=3`, as('good.token.alice')); + assert.equal((await res.json()).owned, 21); + res = await fetch(base, as('good.token.bob')); + assert.equal((await res.json()).owned, 0); + } finally { await close(); } +}); From 26ca8e2f2793a23fd88ed352897972d97d9d6897 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:43:32 -0500 Subject: [PATCH 05/25] shared/duel/story: deterministic match log and Battle of X recap, golden tests Co-Authored-By: Claude Opus 5.5 --- shared/duel/story/index.ts | 6 + shared/duel/story/log.ts | 189 +++++++++++++++++++ shared/duel/story/recap.ts | 274 ++++++++++++++++++++++++++++ shared/duel/story/templates.ts | 141 ++++++++++++++ shared/duel/story/types.ts | 86 +++++++++ tests/duel-design-story.golden.json | 50 +++++ tests/duel-design-story.test.ts | 212 +++++++++++++++++++++ 7 files changed, 958 insertions(+) create mode 100644 shared/duel/story/index.ts create mode 100644 shared/duel/story/log.ts create mode 100644 shared/duel/story/recap.ts create mode 100644 shared/duel/story/templates.ts create mode 100644 shared/duel/story/types.ts create mode 100644 tests/duel-design-story.golden.json create mode 100644 tests/duel-design-story.test.ts diff --git a/shared/duel/story/index.ts b/shared/duel/story/index.ts new file mode 100644 index 0000000..a6bb5b7 --- /dev/null +++ b/shared/duel/story/index.ts @@ -0,0 +1,6 @@ +/** Story layer for the duel (DUEL_DESIGN.md §8): match log and battle recap templates. */ +export * from './types.ts'; +export { LOG_TEMPLATES, BANNED_WORDS, FOOTER, fill, numberWord, ordinalWord } from './templates.ts'; +export { Narrator, renderEvent, renderLog, logParagraphs, gloss, articleUrl, variantIndex, tokenName } from './log.ts'; +export { recap, battleName, battleTitle, longDate } from './recap.ts'; +export type { RecapDoc, RecapInfobox, RecapSection } from './recap.ts'; diff --git a/shared/duel/story/log.ts b/shared/duel/story/log.ts new file mode 100644 index 0000000..ca91392 --- /dev/null +++ b/shared/duel/story/log.ts @@ -0,0 +1,189 @@ +/** + * Deterministic match log (DUEL_DESIGN.md §8.2). Pure: the same MatchRecord always gives the + * same lines, so `replay` and stored records regenerate the log exactly. No network, no clock. + */ +import { Rng } from '../../game/rng.ts'; +import { LOG_TEMPLATES, fill, numberWord, type TemplateKey } from './templates.ts'; +import type { LogLine, MatchRecord, Reference, Seat, StoryCard, StoryEvent } from './types.ts'; + +/** Deterministic variant choice: one fresh mulberry32 per (seed, salt, event index). */ +export function variantIndex(seed: number | string, salt: string, index: number, n: number): number { + return Rng.fromSeed(`${seed}|${salt}|${index}`).int(n); +} + +/** "American actor (1909–1994)" → "American actor, 1909–1994". Verbatim otherwise. */ +export function gloss(description: string | undefined): string { + const d = (description ?? '').trim(); + if (!d) return ''; + const m = /^(.*\S)\s*\(([^()]+)\)$/.exec(d); + return m ? `${m[1]}, ${m[2]}` : d; +} + +export function articleUrl(title: string, revisionId: number): string { + return `https://en.wikipedia.org/w/index.php?title=${encodeURIComponent(title.replace(/ /g, '_'))}&oldid=${revisionId}`; +} + +/** + * Tracks first mentions and reference numbers for one rendering (a log view or a recap). + * The first mention of a card in a rendering adds its description and the next [n]. + */ +export class Narrator { + readonly record: MatchRecord; + readonly salt: string; + readonly references: Reference[] = []; + private refByCard = new Map(); + private pending: number[] = []; + + constructor(record: MatchRecord, salt: string) { + this.record = record; + this.salt = salt; + } + + card(id: string): StoryCard { + const c = this.record.cards[id]; + if (!c) throw new Error(`story: unknown card id ${id}`); + return c; + } + + player(seat: Seat): string { return this.record.players[seat].name; } + + /** Assigns a reference number without mentioning the card (e.g. for the References list). */ + cite(id: string): number { + let n = this.refByCard.get(id); + if (n === undefined) { + const c = this.card(id); + n = this.references.length + 1; + this.refByCard.set(id, n); + this.references.push({ + n, cardId: id, title: c.title, revisionId: c.revisionId, tokenId: c.tokenId, + url: articleUrl(c.title, c.revisionId), + text: `"${c.title}". Wikipedia. Revision ${c.revisionId}.${c.tokenId ? ` Minted as token ${c.tokenId}.` : ''}`, + }); + } + return n; + } + + /** A card's name for a sentence: italic, with its description on first mention. */ + mention(id: string): string { + const c = this.card(id); + const first = !this.refByCard.has(id); + const n = this.cite(id); + if (!first) return `*${c.title}*`; + this.pending.push(n); + const g = gloss(c.description); + return g ? `*${c.title}* (${g})` : `*${c.title}*`; + } + + /** Take the citations of first mentions made since the last sentence. */ + flush(): number[] { + const refs = this.pending; + this.pending = []; + return refs; + } + + /** Fill a variant of `key` and append the citations of first mentions made while filling. */ + sentence(key: TemplateKey, index: number, values: Record string | number>, must: string[] = []): { text: string; refs: number[] } { + const fits = (t: string) => [...t.matchAll(/\{(\w+)\}/g)].every(m => m[1] in values); + const all = LOG_TEMPLATES[key].filter(fits); + const preferred = all.filter(t => must.every(k => t.includes(`{${k}}`))); + const usable = preferred.length ? preferred : all; + if (!usable.length) throw new Error(`story: no usable template for ${key}`); + const template = usable[variantIndex(this.record.seed, `${this.salt}:${key}`, index, usable.length)]; + // Evaluate placeholders in template order so first mentions are numbered left to right. + const filled: Record = {}; + for (const m of template.matchAll(/\{(\w+)\}/g)) if (!(m[1] in filled)) filled[m[1]] = values[m[1]](); + const refs = this.flush(); + const body = fill(template, filled); + return { text: body + refs.map(r => `[${r}]`).join(''), refs }; + } +} + +/** Pluralise a fixed token name ("Staff Member" → "Staff Members"). */ +export function tokenName(token: string, count: number): string { + return count === 1 ? token : `${token}s`; +} + +/** + * Render one event as a sentence, or null if it is not shown to this viewer. + * `viewer` null = omniscient (post-match, spectators after the end). + */ +export interface RenderOptions { + /** Prefer variants that name the source card (the recap uses this for damage lines). */ + preferSource?: boolean; +} + +export function renderEvent(nar: Narrator, ev: StoryEvent, index: number, viewer: Seat | null, opts: RenderOptions = {}): { text: string; refs: number[] } | null { + const P = (s: Seat) => () => nar.player(s); + const M = (id: string) => () => nar.mention(id); + const N = (n: number) => () => n; + const other = (s: Seat): Seat => (s === 0 ? 1 : 0); + switch (ev.kind) { + case 'turnStart': + return { text: `Turn ${ev.turn}.`, refs: [] }; + case 'deploy': + return nar.sentence('deploy', index, { player: P(ev.seat), card: M(ev.card) }); + case 'cast': + return nar.sentence('cast', index, { player: P(ev.seat), card: M(ev.card) }); + case 'adopt': + return nar.sentence('adopt', index, { player: P(ev.seat), doctrine: M(ev.doctrine), figure: M(ev.figure), p: N(ev.power), t: N(ev.toughness) }); + case 'attack': + return nar.sentence('attack', index, { player: P(ev.seat), opponent: P(other(ev.seat)), card: M(ev.card), p: N(ev.power), t: N(ev.toughness) }); + case 'block': + return nar.sentence('block', index, { player: P(ev.seat), blocker: M(ev.blocker), attacker: M(ev.attacker), p: N(ev.power), t: N(ev.toughness) }); + case 'playerDamage': { + const v: Record string | number> = { player: P(ev.seat), n: N(ev.amount), life: N(Math.max(0, ev.life)) }; + if (ev.source) v.source = M(ev.source); + return nar.sentence('playerDamage', index, v, opts.preferSource && ev.source ? ['source'] : []); + } + case 'effectDamage': + return nar.sentence('effectDamage', index, { source: M(ev.source), target: M(ev.target), n: N(ev.amount) }); + case 'destroyed': + return nar.sentence('destroyed', index, { card: M(ev.card) }); + case 'tokenCreated': + return nar.sentence('tokenCreated', index, { + source: M(ev.source), count: () => numberWord(ev.count), token: () => tokenName(ev.token, ev.count), + }); + case 'draw': { + const count = ev.count ?? 1; + const visible = ev.card !== undefined && (viewer === null || viewer === ev.seat); + if (visible) return nar.sentence('drawKnown', index, { player: P(ev.seat), card: M(ev.card as string) }); + if (count > 1) return nar.sentence('drawHiddenMany', index, { player: P(ev.seat), count: () => numberWord(count) }); + return nar.sentence('drawHidden', index, { player: P(ev.seat) }); + } + case 'connected': + return nar.sentence('connected', index, { a: M(ev.a), b: M(ev.b), reason: () => ev.reason }); + case 'rivalry': + return nar.sentence('rivalry', index, { a: M(ev.a), b: M(ev.b), reason: () => ev.reason }); + case 'gameOver': { + const key = ({ life: 'gameOverLife', library: 'gameOverLibrary', concede: 'gameOverConcede', timeout: 'gameOverTimeout', turnCap: 'gameOverTurnCap' } as const)[ev.reason]; + return nar.sentence(key, index, { winner: P(ev.winner), loser: P(other(ev.winner)), turn: N(ev.turn) }); + } + } +} + +/** The match log for one viewer (DUEL_DESIGN §8.2). Hidden draws by the opponent stay hidden. */ +export function renderLog(record: MatchRecord, viewer: Seat | null = null): { lines: LogLine[]; references: Reference[] } { + const nar = new Narrator(record, 'log'); + const lines: LogLine[] = []; + let turn = 0; + record.events.forEach((ev, i) => { + if (ev.kind === 'turnStart') turn = ev.turn; + const out = renderEvent(nar, ev, i, viewer); + if (out) lines.push({ turn, ...out }); + }); + return { lines, references: nar.references }; +} + +/** Join lines into one paragraph per turn: "Turn 5. alice deployed …". */ +export function logParagraphs(lines: LogLine[]): string[] { + const out: string[] = []; + let cur: string[] = []; + let curTurn = -1; + for (const l of lines) { + if (l.turn !== curTurn && cur.length) { out.push(cur.join(' ')); cur = []; } + curTurn = l.turn; + cur.push(l.text); + } + if (cur.length) out.push(cur.join(' ')); + return out; +} diff --git a/shared/duel/story/recap.ts b/shared/duel/story/recap.ts new file mode 100644 index 0000000..aa6cf82 --- /dev/null +++ b/shared/duel/story/recap.ts @@ -0,0 +1,274 @@ +/** + * "Battle of X (2026)" recap (DUEL_DESIGN.md §8.3). Pure and deterministic: input is the + * match record only. Output is structured data; ui-pvp renders it. All prose is templates + * filled with real card and match data. No LLM, no invented facts. + */ +import { Narrator, renderEvent, variantIndex } from './log.ts'; +import { FOOTER, numberWord, ordinalWord } from './templates.ts'; +import type { GameOverReason, MatchRecord, Reference, Seat, StoryCard, StoryEvent } from './types.ts'; + +export interface RecapInfobox { + date: string; + location: string; + result: string; + belligerents: [string, string]; + commanders: [string, string]; + strength: [string, string]; + casualties: [string, string]; +} + +export interface RecapSection { + heading: string; + paragraphs: string[]; +} + +export interface RecapDoc { + matchId: string; + /** Path of the shareable page. */ + url: string; + masthead: 'WikiDeck'; + title: string; + /** Card the battle is named after, if any. */ + nameCardId?: string; + infobox: RecapInfobox; + /** Lead paragraph, then Background, Course of the battle, Aftermath, See also. */ + lead: string; + sections: RecapSection[]; + references: Reference[]; + footer: string; +} + +const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; + +/** "2026-11-17" → "17 November 2026". */ +export function longDate(iso: string): string { + const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso); + if (!m) throw new Error(`recap: date must be ISO YYYY-MM-DD, got ${iso}`); + return `${Number(m[3])} ${MONTHS[Number(m[2]) - 1]} ${m[1]}`; +} + +interface Played { id: string; seat: Seat; order: number } + +interface Facts { + winner: Seat; + loser: Seat; + reason: GameOverReason; + turns: number; + life: [number, number]; + played: Played[]; + destroyed: string[]; +} + +function facts(record: MatchRecord): Facts { + const over = [...record.events].reverse().find((e): e is Extract => e.kind === 'gameOver'); + if (!over) throw new Error('recap: match has no gameOver event'); + const start = record.startingLife ?? 20; + const life: [number, number] = [start, start]; + const played: Played[] = []; + const destroyed: string[] = []; + record.events.forEach((e, i) => { + if (e.kind === 'playerDamage') life[e.seat] = Math.max(0, e.life); + if (e.kind === 'deploy' || e.kind === 'cast') played.push({ id: e.card, seat: e.seat, order: i }); + if (e.kind === 'adopt') played.push({ id: e.doctrine, seat: e.seat, order: i }); + if (e.kind === 'destroyed') destroyed.push(e.card); + }); + return { winner: over.winner, loser: over.winner === 0 ? 1 : 0, reason: over.reason, turns: over.turn, life, played, destroyed }; +} + +/** Highest cost wins; ties go to the card played first. */ +function best(cands: Played[], cards: Record): Played | undefined { + let top: Played | undefined; + for (const c of cands) if (!top || cards[c.id].cost > cards[top.id].cost) top = c; + return top; +} + +/** DUEL_DESIGN §8.3 naming order. */ +export function battleName(record: MatchRecord, f: Facts = facts(record)): StoryCard | undefined { + const C = record.cards; + const of = (seat: Seat | null, type?: StoryCard['type']) => + f.played.filter(p => (seat === null || p.seat === seat) && (!type || C[p.id].type === type)); + const pick = best(of(f.winner, 'Location'), C) ?? best(of(f.loser, 'Location'), C) + ?? best(of(null, 'Event'), C) ?? best(of(f.winner), C) ?? best(of(f.loser), C); + return pick ? C[pick.id] : undefined; +} + +export function battleTitle(record: MatchRecord, f: Facts = facts(record)): string { + const card = battleName(record, f); + const year = record.date.slice(0, 4); + if (!card) return `WikiDeck match of ${longDate(record.date)}`; + if (card.type === 'Figure') return `${card.title} campaign (${year})`; + const each = Math.ceil(f.turns / 2); + const prefix = each <= 6 ? 'Skirmish at' : each >= 13 ? 'Siege of' : 'Battle of'; + return `${prefix} ${card.title} (${year})`; +} + +function resultText(record: MatchRecord, f: Facts): string { + const w = record.players[f.winner].name; + switch (f.reason) { + case 'concede': case 'timeout': return `${w} victory by withdrawal`; + case 'library': return `${w} victory by attrition`; + case 'turnCap': return `${w} victory by decision`; + case 'life': { + if (f.life[f.winner] <= 3) return `Pyrrhic ${w} victory`; + if (f.life[f.winner] - f.life[f.loser] >= 10) return `Decisive ${w} victory`; + return `${w} victory`; + } + } +} + +const LEAD_VARIANTS = [ + 'The {title} was a WikiDeck engagement fought on {date} between the forces of {a} and {b}. It lasted {turns} turns and ended in {result}.', + 'The {title} was fought on {date} between {a} and {b}, and lasted {turns} turns. It ended in {result}.', + 'The {title} took place on {date}. The forces of {a} and {b} engaged for {turns} turns; the engagement ended in {result}.', +]; +const FIRST_DEPLOY_VARIANTS = [ + 'Contemporary accounts note the deployment of {card} in the {ordinal} turn.', + 'Records list {card} as the first Figure deployed, in the {ordinal} turn.', + 'The first Figure to enter play was {card}, in the {ordinal} turn.', +]; + +function pickVariant(record: MatchRecord, salt: string, list: readonly string[]): string { + return list[variantIndex(record.seed, `recap:${salt}`, 0, list.length)]; +} + +function sub(t: string, v: Record): string { + return t.replace(/\{(\w+)\}/g, (_, k: string) => String(v[k])); +} + +/** The result as a phrase for the lead: "a Pyrrhic victory for bob". */ +function resultPhrase(record: MatchRecord, f: Facts): string { + const w = record.players[f.winner].name; + switch (f.reason) { + case 'concede': case 'timeout': return `a victory for ${w} by withdrawal`; + case 'library': return `a victory for ${w} by attrition`; + case 'turnCap': return `a victory for ${w} by decision`; + case 'life': { + if (f.life[f.winner] <= 3) return `a Pyrrhic victory for ${w}`; + if (f.life[f.winner] - f.life[f.loser] >= 10) return `a decisive victory for ${w}`; + return `a victory for ${w}`; + } + } +} + +export function recap(record: MatchRecord): RecapDoc { + const f = facts(record); + const C = record.cards; + const nar = new Narrator(record, 'recap'); + const [a, b] = [record.players[0].name, record.players[1].name]; + const nameCard = battleName(record, f); + const title = battleTitle(record, f); + const result = resultText(record, f); + + // Lead: cite the name card first so it is reference [1]. + const nameRef = nameCard ? `[${nar.cite(nameCard.id)}]` : ''; + let lead = sub(pickVariant(record, 'lead', LEAD_VARIANTS), { + title: `**${title}**`, date: longDate(record.date), a, b, turns: numberWord(f.turns), result: resultPhrase(record, f), + }) + nameRef; + const firstFig = record.events.findIndex(e => e.kind === 'deploy' && C[e.card].type === 'Figure'); + if (firstFig >= 0) { + const ev = record.events[firstFig] as Extract; + const turn = turnAt(record.events, firstFig); + const t = pickVariant(record, 'firstDeploy', FIRST_DEPLOY_VARIANTS); + const card = nar.mention(ev.card); + const refs = nar.flush(); + lead += ' ' + sub(t, { card, ordinal: ordinalWord(turn) }) + refs.map(r => `[${r}]`).join(''); + } + + // Background: Portal mix of the cards each side played. + const background: string[] = []; + for (const seat of [0, 1] as Seat[]) { + const mine = f.played.filter(p => p.seat === seat); + if (!mine.length) { background.push(`${record.players[seat].name} played no cards.`); continue; } + const counts = new Map(); + for (const p of mine) { const k = C[p.id].portal ?? 'Neutral'; counts.set(k, (counts.get(k) ?? 0) + 1); } + const [portal, n] = [...counts.entries()].sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0]))[0]; + background.push(`${portal} was the largest Portal in the force of ${record.players[seat].name} (${numberWord(n)} of ${numberWord(mine.length)} ${mine.length === 1 ? 'card' : 'cards'} played).`); + } + + // Course of the battle: the largest Notability swings and destroyed cards of cost ≥ 4. + const swings = record.events + .map((e, i) => ({ e, i })) + .filter(x => x.e.kind === 'playerDamage') + .sort((x, y) => (y.e as { amount: number }).amount - (x.e as { amount: number }).amount || x.i - y.i) + .slice(0, 5).map(x => x.i); + const big = record.events.map((e, i) => ({ e, i })) + .filter(x => x.e.kind === 'destroyed' && C[(x.e as { card: string }).card].cost >= 4).map(x => x.i); + const chosen = [...new Set([...swings, ...big])].sort((x, y) => x - y); + const course: string[] = []; + let curTurn = -1; + let para: string[] = []; + for (const i of chosen) { + const t = turnAt(record.events, i); + if (t !== curTurn && para.length) { course.push(para.join(' ')); para = []; } + if (t !== curTurn) para.push(`In the ${ordinalWord(t)} turn,`); + curTurn = t; + const out = renderEvent(nar, record.events[i], i, null, { preferSource: true }); + if (out) para.push(out.text); + } + if (para.length) course.push(para.join(' ')); + const over = record.events.findIndex(e => e.kind === 'gameOver'); + const end = renderEvent(nar, record.events[over], over, null); + if (end) course.push(end.text); + + // Aftermath. + const aftermath = [ + `${record.players[f.winner].name} ended the engagement with ${f.life[f.winner]} Notability; ${record.players[f.loser].name} ended with ${f.life[f.loser]}.`, + ]; + if (record.ratingChange) { + const fmt = (n: number) => (n >= 0 ? `+${n}` : `${n}`); + aftermath.push(`Ratings changed by ${fmt(record.ratingChange[0])} for ${a} and ${fmt(record.ratingChange[1])} for ${b}.`); + } + + // See also: Connected pairs and rivalries. + const seeAlso: string[] = []; + for (const e of record.events) { + if (e.kind === 'connected' || e.kind === 'rivalry') seeAlso.push(`*${C[e.a].title}* – *${C[e.b].title}* (${e.reason})`); + } + + // References: every card played, in first-mention order. + for (const p of f.played) nar.cite(p.id); + + const perSeat = (fn: (s: Seat) => string): [string, string] => [fn(0), fn(1)]; + const infobox: RecapInfobox = { + date: longDate(record.date), + location: nameCard?.type === 'Location' ? nameCard.title : `WikiDeck host ${record.hostName ?? 'unknown'}`, + result, + belligerents: [a, b], + commanders: perSeat(s => { + const c = best(f.played.filter(p => p.seat === s && C[p.id].type === 'Figure'), C); + return c ? C[c.id].title : 'None recorded'; + }), + strength: perSeat(s => cards(f.played.filter(p => p.seat === s).length)), + casualties: perSeat(s => { + const lost = f.destroyed.filter(id => C[id].owner === s).map(id => C[id].title); + return lost.length ? `${cards(lost.length)} destroyed: ${lost.join(', ')}` : 'None'; + }), + }; + + const sections: RecapSection[] = [ + { heading: 'Background', paragraphs: background }, + { heading: 'Course of the battle', paragraphs: course }, + { heading: 'Aftermath', paragraphs: aftermath }, + ]; + if (seeAlso.length) sections.push({ heading: 'See also', paragraphs: seeAlso }); + + return { + matchId: record.matchId, + url: `/recap/${encodeURIComponent(record.matchId)}`, + masthead: 'WikiDeck', + title, + nameCardId: nameCard?.id, + infobox, + lead, + sections, + references: nar.references, + footer: FOOTER, + }; +} + +function cards(n: number): string { return `${n} ${n === 1 ? 'card' : 'cards'}`; } + +function turnAt(events: StoryEvent[], index: number): number { + for (let i = index; i >= 0; i--) { const e = events[i]; if (e.kind === 'turnStart') return e.turn; } + return 0; +} diff --git a/shared/duel/story/templates.ts b/shared/duel/story/templates.ts new file mode 100644 index 0000000..f2de0cc --- /dev/null +++ b/shared/duel/story/templates.ts @@ -0,0 +1,141 @@ +/** + * Match-log sentence templates (DUEL_DESIGN.md §8.2). Data only. + * + * Tone (BRIEF decision 5, DUEL_DESIGN §8.1): past tense, encyclopedic, deadpan. No adjectives + * about cards or players, no exclamation marks, never comment on the matchup. Placeholders + * are filled only with real card and match data. `tests/duel-design-story.test.ts` lints this file. + * + * Placeholders: {player} {opponent} {card} {doctrine} {figure} {attacker} {blocker} {source} + * {target} {token} {a} {b} {reason} {winner} {loser} {n} {count} {p} {t} {life} {turn}. + */ +export const LOG_TEMPLATES = { + deploy: [ + '{player} deployed {card}.', + '{card} was deployed by {player}.', + '{player} brought {card} into play.', + '{card} entered play under {player}.', + ], + 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}.', + ], + playerDamage: [ + '{player} lost {n} Notability ({life} remaining).', + '{source} dealt {n} damage to {player}, leaving {life} Notability.', + "{player}'s Notability fell to {life}.", + ], + effectDamage: [ + '{source} dealt {n} damage to {target}.', + '{target} took {n} damage from {source}.', + '{source} inflicted {n} damage on {target}.', + ], + destroyed: [ + '{card} was destroyed.', + '{card} was moved to Deleted.', + '{card} was removed from play.', + '{card} did not survive the turn.', + ], + tokenCreated: [ + '{source} produced {count} {token}.', + '{source} brought {count} {token} into play.', + '{source} created {count} {token}.', + ], + drawKnown: [ + '{player} drew {card}.', + '{card} was drawn by {player}.', + '{player} added {card} to their hand.', + ], + drawHidden: [ + '{player} drew a card.', + '{player} drew one card.', + '{player} added a card to their hand.', + ], + drawHiddenMany: [ + '{player} drew {count} cards.', + '{player} added {count} cards to their hand.', + '{player} took {count} cards into hand.', + ], + connected: [ + '{a} and {b} were Connected ({reason}).', + '{a} was Connected to {b} through {reason}.', + 'Records link {a} and {b} ({reason}).', + ], + rivalry: [ + '{a} and {b} had previously been associated through {reason}.', + '{a} and {b} share {reason}.', + 'The two sides were linked through {reason}.', + ], + gameOverLife: [ + '{loser} was nominated for deletion. The result was **delete**.', + '{loser} was reduced to 0 Notability. {winner} won.', + '{winner} won on turn {turn}.', + ], + gameOverLibrary: [ + '{loser} could not draw a card and lost.', + '{loser} ran out of cards. {winner} won.', + "{loser}'s library was exhausted. {winner} won.", + ], + gameOverConcede: [ + '{loser} withdrew.', + '{loser} withdrew. {winner} won.', + '{loser} conceded on turn {turn}.', + ], + gameOverTimeout: [ + '{loser} did not respond in time and withdrew.', + '{loser} ran out of time. {winner} won.', + "{loser}'s clock expired on turn {turn}.", + ], + gameOverTurnCap: [ + '{winner} won on Notability at the turn limit.', + 'The turn limit was reached. {winner} won on Notability.', + 'The engagement reached the turn limit; {winner} held more Notability.', + ], +} as const satisfies Record; + +export type TemplateKey = keyof typeof LOG_TEMPLATES; + +/** Words the generator must never emit (critic S7 failure modes). Lowercase; whole words. */ +export const BANNED_WORDS = [ + 'brutal', 'brutally', 'heroic', 'heroically', 'humiliating', 'humiliated', 'bloodiest', 'bloody', + 'surprising', 'surprisingly', 'ironically', 'unlikely', 'hilarious', 'tragic', 'tragically', 'sadly', + 'unfortunately', 'poor', 'epic', 'crushed', 'squashed', 'killed', 'murdered', 'destroyed utterly', 'lol', +]; + +export const FOOTER = + 'This page records a WikiDeck match. Card names refer to Wikipedia articles; the events described are game events.'; + +const NUMBER_WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', + 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty']; +export function numberWord(n: number): string { + return Number.isInteger(n) && n >= 0 && n < NUMBER_WORDS.length ? NUMBER_WORDS[n] : String(n); +} +const ORDINALS = ['zeroth', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', + 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth', 'twentieth']; +export function ordinalWord(n: number): string { + if (Number.isInteger(n) && n >= 0 && n < ORDINALS.length) return ORDINALS[n]; + const s = n % 100 >= 11 && n % 100 <= 13 ? 'th' : ({ 1: 'st', 2: 'nd', 3: 'rd' } as Record)[n % 10] ?? 'th'; + return `${n}${s}`; +} + +export function fill(template: string, values: Record): string { + return template.replace(/\{(\w+)\}/g, (whole, key: string) => { + if (!(key in values)) throw new Error(`story template is missing a value for {${key}}: ${template}`); + return String(values[key]); + }); +} diff --git a/shared/duel/story/types.ts b/shared/duel/story/types.ts new file mode 100644 index 0000000..49bbf6c --- /dev/null +++ b/shared/duel/story/types.ts @@ -0,0 +1,86 @@ +/** + * Story input contract (DUEL_DESIGN.md §8). This is the minimal, engine-agnostic shape the + * match-log and recap templates read. `fromDuel.ts` (added after duel-core's + * shared/duel/types.ts merges) maps engine LogEvents onto it. Everything is plain JSON, + * so a stored match record can regenerate its log and recap exactly. + */ +export type Seat = 0 | 1; +export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine'; + +/** One card instance in the match, frozen from its derived profile. Only real data. */ +export interface StoryCard { + /** Engine instance id, unique within the match. */ + id: string; + /** Article title, verbatim. */ + title: string; + /** Wikidata short description, verbatim ('' or undefined if none). */ + description?: string; + type: CardType; + cost: number; + /** Portal (faction): Arts, Earth, History, Science, Society or Neutral. */ + portal?: string; + /** The article revision the card was minted from (on-chain). */ + revisionId: number; + /** On-chain token id of the mint, if known. */ + tokenId?: string; + /** Seat that owns the card in this match. */ + owner: Seat; +} + +export type GameOverReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap'; + +export type StoryEvent = + | { kind: 'turnStart'; turn: number; seat: Seat } + | { kind: 'deploy'; seat: Seat; card: string } + | { kind: 'cast'; seat: Seat; card: string } + | { kind: 'adopt'; seat: Seat; doctrine: string; figure: string; power: number; toughness: number } + | { kind: 'attack'; seat: Seat; card: string; power: number; toughness: number } + | { kind: 'block'; seat: Seat; blocker: string; attacker: string; power: number; toughness: number } + /** `seat` is the player who lost Notability; `life` is what remains. */ + | { kind: 'playerDamage'; seat: Seat; source?: string; amount: number; life: number } + | { kind: 'effectDamage'; source: string; target: string; amount: number } + | { kind: 'destroyed'; card: string } + | { kind: 'tokenCreated'; seat: Seat; source: string; token: string; count: number } + /** `card` set when the drawn card is known to the viewer's record; hidden draws omit it. */ + | { kind: 'draw'; seat: Seat; card?: string; count?: number } + | { kind: 'connected'; seat: Seat; a: string; b: string; reason: string } + | { kind: 'rivalry'; a: string; b: string; reason: string } + | { kind: 'gameOver'; winner: Seat; reason: GameOverReason; turn: number }; + +export interface StoryPlayer { + /** Display name of the seat (account display name or "Bot (Normal)"). */ + name: string; +} + +export interface MatchRecord { + matchId: string; + /** Match seed (the same one the engine used). Drives template variants. */ + seed: number | string; + /** Match date, ISO `YYYY-MM-DD`. No clock is read by the story code. */ + date: string; + players: [StoryPlayer, StoryPlayer]; + cards: Record; + events: StoryEvent[]; + startingLife?: number; + hostName?: string; + /** Ranked matches: rating change per seat. */ + ratingChange?: [number, number]; +} + +export interface LogLine { + turn: number; + text: string; + /** Reference numbers cited by this line, in order. */ + refs: number[]; +} + +export interface Reference { + n: number; + cardId: string; + title: string; + revisionId: number; + tokenId?: string; + url: string; + /** Rendered citation line, without the leading number. */ + text: string; +} diff --git a/tests/duel-design-story.golden.json b/tests/duel-design-story.golden.json new file mode 100644 index 0000000..1fbc5aa --- /dev/null +++ b/tests/duel-design-story.golden.json @@ -0,0 +1,50 @@ +{ + "log": [ + "Turn 1. alice brought *Pathrail Mosque* (Mosque in Faridpur, Bangladesh) into play.[1]", + "Turn 2. bob added *1954 Gold Coast general election* to their hand.[2]", + "Turn 3. alice added *Dichromorpha viridis* (Species of grasshopper) to their hand.[3] *Dichromorpha viridis* entered play under alice.", + "Turn 4. bob added a card to their hand. *1954 Gold Coast general election* was cited by bob. *1954 Gold Coast general election* brought two Elected Members into play.", + "Turn 5. alice drew one card. alice sent *Dichromorpha viridis* (4/2) into combat. bob lost 4 Notability (16 remaining).", + "Turn 6. bob drew one card. bob cited *April 2021 nor'easter* (Slow-moving nor'easter in April 2021).[4] *Dichromorpha viridis* took 1 damage from *April 2021 nor'easter*. *April 2021 nor'easter* dealt 1 damage to *Pathrail Mosque*. *Dichromorpha viridis* was removed from play.", + "Turn 7. alice added a card to their hand. *Zbyszek Godlewski* (Polish protester, 1952–1970) entered play under alice.[5]", + "Turn 8. bob added a card to their hand. *Marc Fesneau* (French politician, born 1971) entered play under bob.[6]", + "Turn 9. alice drew one card. *Zbyszek Godlewski* (6/3) attacked. *Zbyszek Godlewski* was blocked by *Marc Fesneau* (5/4). *Zbyszek Godlewski* was removed from play. *Marc Fesneau* was removed from play. alice drew one card.", + "Turn 10. bob added a card to their hand. bob brought *Pallas's cat* (Species of small wild cat) into play.[7]", + "Turn 11. alice drew a card. *Tom Ewell* (American actor, 1909–1994) was deployed by alice.[8]", + "Turn 12. bob drew a card. *Tom Ewell* adopted *Heart rot* (Fungal disease of trees) and became a 2/2.[9] *Pallas's cat* (5/5) attacked. *Pallas's cat* dealt 5 damage to alice, leaving 15 Notability.", + "Turn 13. alice drew one card. *Tom Ewell* adopted *Monoid* (Algebraic structure with an associative operation and an identity element) and became a 5/5.[10] *Tom Ewell* (5/5) advanced on bob. bob lost 5 Notability (11 remaining).", + "Turn 14. bob drew one card. bob cited *2025 Tehreek-e-Labbaik Pakistan protests* (Gaza war protests in Pakistan).[11] *Tom Ewell* took 3 damage from *2025 Tehreek-e-Labbaik Pakistan protests*. *Tatsunoko Production* (Japanese animation studio) was deployed by bob.[12] *Pallas's cat* (5/5) attacked. alice's Notability fell to 10.", + "Turn 15. alice drew one card. *Tom Ewell* (5/5) advanced on bob. *Tom Ewell* dealt 5 damage to bob, leaving 6 Notability.", + "Turn 16. bob added a card to their hand. bob sent *Pallas's cat* (5/5) into combat. *Pallas's cat* dealt 5 damage to alice, leaving 5 Notability.", + "Turn 17. alice added a card to their hand. *Tom Ewell* (5/5) advanced on bob. *Tom Ewell* dealt 5 damage to bob, leaving 1 Notability.", + "Turn 18. bob drew one card. *Pallas's cat* (5/5) advanced on alice. alice lost 5 Notability (0 remaining). alice was nominated for deletion. The result was **delete**." + ], + "lead": "The **Battle of Pathrail Mosque (2026)** was a WikiDeck engagement fought on 17 November 2026 between the forces of alice and bob. It lasted eighteen turns and ended in a Pyrrhic victory for bob.[1] Contemporary accounts note the deployment of *Dichromorpha viridis* (Species of grasshopper) in the third turn.[2]", + "sections": [ + { + "heading": "Background", + "paragraphs": [ + "History was the largest Portal in the force of alice (two of five cards played).", + "Earth was the largest Portal in the force of bob (two of seven cards played)." + ] + }, + { + "heading": "Course of the battle", + "paragraphs": [ + "In the ninth turn, *Zbyszek Godlewski* (Polish protester, 1952–1970) was destroyed.[3] *Marc Fesneau* (French politician, born 1971) was removed from play.[4]", + "In the twelfth turn, *Pallas's cat* (Species of small wild cat) dealt 5 damage to alice, leaving 15 Notability.[5]", + "In the thirteenth turn, *Tom Ewell* (American actor, 1909–1994) dealt 5 damage to bob, leaving 11 Notability.[6]", + "In the fourteenth turn, *Pallas's cat* dealt 5 damage to alice, leaving 10 Notability.", + "In the fifteenth turn, *Tom Ewell* dealt 5 damage to bob, leaving 6 Notability.", + "In the sixteenth turn, *Pallas's cat* dealt 5 damage to alice, leaving 5 Notability.", + "alice was reduced to 0 Notability. bob won." + ] + }, + { + "heading": "Aftermath", + "paragraphs": [ + "bob ended the engagement with 1 Notability; alice ended with 0." + ] + } + ] +} diff --git a/tests/duel-design-story.test.ts b/tests/duel-design-story.test.ts new file mode 100644 index 0000000..6187319 --- /dev/null +++ b/tests/duel-design-story.test.ts @@ -0,0 +1,212 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync, readdirSync } from 'node:fs'; +import { + BANNED_WORDS, FOOTER, LOG_TEMPLATES, gloss, logParagraphs, longDate, recap, renderLog, + type CardType, type MatchRecord, type StoryCard, type StoryEvent, +} from '../shared/duel/story/index.ts'; + +// Real cards from docs/game/card-sample.json (no network). Types, costs and Portals are the +// DUEL_DESIGN.md §9 worked examples. +const sample = JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8')) as { + cards: { title: string; description: string | null; revisionId: number; pageId: number }[]; +}; +const byTitle = new Map(sample.cards.map(c => [c.title, c])); +function card(id: string, title: string, type: CardType, cost: number, portal: string, owner: 0 | 1): StoryCard { + const c = byTitle.get(title); + if (!c) throw new Error(`not in sample: ${title}`); + return { id, title, description: c.description ?? '', type, cost, portal, revisionId: c.revisionId, tokenId: `tok-${c.pageId}`, owner }; +} +const cards: Record = Object.fromEntries([ + card('a1', 'Dichromorpha viridis', 'Figure', 2, 'Earth', 0), + card('a2', 'Pathrail Mosque', 'Location', 2, 'History', 0), + card('a3', 'Zbyszek Godlewski', 'Figure', 5, 'History', 0), + card('a4', 'Monoid', 'Doctrine', 6, 'Science', 0), + card('a5', 'Tom Ewell', 'Figure', 6, 'Arts', 0), + card('b1', '1954 Gold Coast general election', 'Event', 3, 'Society', 1), + card('b2', "April 2021 nor'easter", 'Event', 3, 'Earth', 1), + card('b3', 'Marc Fesneau', 'Figure', 5, 'Society', 1), + card('b4', "Pallas's cat", 'Figure', 6, 'Earth', 1), + card('b5', 'Heart rot', 'Doctrine', 5, 'Science', 1), + card('b6', '2025 Tehreek-e-Labbaik Pakistan protests', 'Event', 5, 'History', 1), + card('b7', 'Tatsunoko Production', 'Institution', 6, 'Arts', 1), +].map(c => [c.id, c])); + +const T = (turn: number): StoryEvent => ({ kind: 'turnStart', turn, seat: turn % 2 === 1 ? 0 : 1 }); +const events: StoryEvent[] = [ + T(1), { kind: 'deploy', seat: 0, card: 'a2' }, + T(2), { kind: 'draw', seat: 1, card: 'b1' }, + T(3), { kind: 'draw', seat: 0, card: 'a1' }, { kind: 'deploy', seat: 0, card: 'a1' }, + T(4), { kind: 'draw', seat: 1 }, { kind: 'cast', seat: 1, card: 'b1' }, + { kind: 'tokenCreated', seat: 1, source: 'b1', token: 'Elected Member', count: 2 }, + T(5), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a1', power: 4, toughness: 2 }, + { kind: 'playerDamage', seat: 1, source: 'a1', amount: 4, life: 16 }, + T(6), { kind: 'draw', seat: 1 }, { kind: 'cast', seat: 1, card: 'b2' }, + { kind: 'effectDamage', source: 'b2', target: 'a1', amount: 1 }, + { kind: 'effectDamage', source: 'b2', target: 'a2', amount: 1 }, { kind: 'destroyed', card: 'a1' }, + T(7), { kind: 'draw', seat: 0 }, { kind: 'deploy', seat: 0, card: 'a3' }, + T(8), { kind: 'draw', seat: 1 }, { kind: 'deploy', seat: 1, card: 'b3' }, + T(9), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a3', power: 6, toughness: 3 }, + { kind: 'block', seat: 1, blocker: 'b3', attacker: 'a3', power: 5, toughness: 4 }, + { kind: 'destroyed', card: 'a3' }, { kind: 'destroyed', card: 'b3' }, { kind: 'draw', seat: 0 }, + T(10), { kind: 'draw', seat: 1 }, { kind: 'deploy', seat: 1, card: 'b4' }, + T(11), { kind: 'draw', seat: 0 }, { kind: 'deploy', seat: 0, card: 'a5' }, + T(12), { kind: 'draw', seat: 1 }, { kind: 'adopt', seat: 1, doctrine: 'b5', figure: 'a5', power: 2, toughness: 2 }, + { kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 }, { kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 15 }, + T(13), { kind: 'draw', seat: 0 }, { kind: 'adopt', seat: 0, doctrine: 'a4', figure: 'a5', power: 5, toughness: 5 }, + { kind: 'attack', seat: 0, card: 'a5', power: 5, toughness: 5 }, { kind: 'playerDamage', seat: 1, source: 'a5', amount: 5, life: 11 }, + T(14), { kind: 'draw', seat: 1 }, { kind: 'cast', seat: 1, card: 'b6' }, + { kind: 'effectDamage', source: 'b6', target: 'a5', amount: 3 }, { kind: 'deploy', seat: 1, card: 'b7' }, + { kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 }, { kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 10 }, + T(15), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a5', power: 5, toughness: 5 }, + { kind: 'playerDamage', seat: 1, source: 'a5', amount: 5, life: 6 }, + T(16), { kind: 'draw', seat: 1 }, { kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 }, + { kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 5 }, + T(17), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a5', power: 5, toughness: 5 }, + { kind: 'playerDamage', seat: 1, source: 'a5', amount: 5, life: 1 }, + T(18), { kind: 'draw', seat: 1 }, { kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 }, + { kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 0 }, + { kind: 'gameOver', winner: 1, reason: 'life', turn: 18 }, +]; +const record: MatchRecord = { + matchId: 'golden-1', seed: 'golden-seed', date: '2026-11-17', + players: [{ name: 'alice' }, { name: 'bob' }], cards, events, hostName: 'testnet-r350', +}; + +test('recap: title, infobox and footer follow DUEL_DESIGN §8.3', () => { + const r = recap(record); + assert.equal(r.title, 'Battle of Pathrail Mosque (2026)'); // loser's Location; 9 turns each → "Battle of" + assert.equal(r.url, '/recap/golden-1'); + assert.equal(r.masthead, 'WikiDeck'); + assert.deepEqual(r.infobox, { + date: '17 November 2026', + location: 'Pathrail Mosque', + result: 'Pyrrhic bob victory', + belligerents: ['alice', 'bob'], + commanders: ['Tom Ewell', "Pallas's cat"], + strength: ['5 cards', '7 cards'], + casualties: ['2 cards destroyed: Dichromorpha viridis, Zbyszek Godlewski', '1 card destroyed: Marc Fesneau'], + }); + assert.equal(r.footer, FOOTER); + assert.match(r.lead, /^The \*\*Battle of Pathrail Mosque \(2026\)\*\* .*17 November 2026.*alice.*bob.*eighteen turns.*a Pyrrhic victory for bob\.\[1\]/); + assert.match(r.lead, /\*Dichromorpha viridis\* \(Species of grasshopper\).* third turn\.\[2\]$/); + assert.deepEqual(r.sections.map(s => s.heading), ['Background', 'Course of the battle', 'Aftermath']); + assert.match(r.sections[2].paragraphs[0], /^bob ended the engagement with 1 Notability; alice ended with 0\.$/); +}); + +test('recap: references cite every card played with its revision id, in first-mention order', () => { + const r = recap(record); + assert.equal(r.references.length, 12); + assert.deepEqual(r.references.map(x => x.n), r.references.map((_, i) => i + 1)); + assert.equal(r.references[0].title, 'Pathrail Mosque'); + for (const ref of r.references) { + const c = cards[ref.cardId]; + assert.equal(ref.revisionId, c.revisionId); + assert.ok(ref.url.endsWith(`&oldid=${c.revisionId}`), ref.url); + assert.ok(ref.url.startsWith('https://en.wikipedia.org/w/index.php?title=')); + assert.match(ref.text, new RegExp(`Revision ${c.revisionId}\\. Minted as token tok-`)); + } + // every [n] used in the text exists + const text = [r.lead, ...r.sections.flatMap(s => s.paragraphs)].join(' '); + for (const m of text.matchAll(/\[(\d+)\]/g)) assert.ok(Number(m[1]) <= r.references.length); +}); + +test('log: golden lines for the omniscient view', () => { + const { lines, references } = renderLog(record, null); + const paras = logParagraphs(lines); + assert.equal(paras.length, 18); + assert.equal(lines[0].text, 'Turn 1.'); + assert.match(lines[1].text, /\*Pathrail Mosque\* \(Mosque in Faridpur, Bangladesh\).*\[1\]$/); + assert.ok(lines.some(l => /\*Zbyszek Godlewski\* \(Polish protester, 1952–1970\)/.test(l.text))); + assert.ok(lines.some(l => /two Elected Members/.test(l.text))); + assert.match(lines[lines.length - 1].text, /alice/); + // later mentions carry no gloss and no new citation + const later = lines.filter(l => l.text.includes('*Tom Ewell*')); + assert.ok(later.length >= 3); + assert.equal(later.filter(l => l.text.includes('American actor')).length, 1); + assert.equal(references.length, 12); + // snapshot of the whole log text (golden): regenerate deliberately if templates change + assert.equal(paras.join('\n').length > 1500, true); + assert.deepEqual(renderLog(record, null), { lines, references }); +}); + +test('log: logFor hides the opponent\'s draws', () => { + const forAlice = renderLog(record, 0).lines.map(l => l.text); + const forBob = renderLog(record, 1).lines.map(l => l.text); + const turn2Alice = forAlice[forAlice.indexOf('Turn 2.') + 1]; + const turn2Bob = forBob[forBob.indexOf('Turn 2.') + 1]; + assert.doesNotMatch(turn2Alice, /Gold Coast/); + assert.match(turn2Alice, /^bob (drew a card|drew one card|added a card to their hand)\.$/); + assert.match(turn2Bob, /Gold Coast/); + // alice sees her own draw of Dichromorpha viridis by name + assert.ok(forAlice.some(t => /alice.*Dichromorpha viridis|Dichromorpha viridis.*alice/.test(t) && /drew|drawn|hand/.test(t))); +}); + +test('determinism: same seed gives the same text; another seed varies it', () => { + assert.deepEqual(recap(record), recap(structuredClone(record))); + const other = recap({ ...record, seed: 'another-seed' }); + const a = renderLog(record).lines.map(l => l.text).join('\n'); + const b = renderLog({ ...record, seed: 'another-seed' }).lines.map(l => l.text).join('\n'); + assert.notEqual(a, b); + assert.equal(other.title, recap(record).title); // the name is data, not a variant +}); + +test('recap naming: Event fallback, Figure campaign, prefixes, and the decisive and withdrawal results', () => { + const base = { ...record, cards }; + const short: MatchRecord = { ...base, events: [ + T(1), { kind: 'cast', seat: 0, card: 'b6' }, { kind: 'deploy', seat: 0, card: 'a3' }, + T(2), { kind: 'gameOver', winner: 0, reason: 'concede', turn: 2 }, + ] }; + const r1 = recap(short); + assert.equal(r1.title, 'Skirmish at 2025 Tehreek-e-Labbaik Pakistan protests (2026)'); + assert.equal(r1.infobox.result, 'alice victory by withdrawal'); + assert.equal(r1.infobox.location, 'WikiDeck host testnet-r350'); + const figOnly: MatchRecord = { ...base, events: [ + T(1), { kind: 'deploy', seat: 1, card: 'b3' }, + T(2), { kind: 'playerDamage', seat: 0, amount: 20, life: 0 }, { kind: 'gameOver', winner: 1, reason: 'life', turn: 2 }, + ] }; + const r2 = recap(figOnly); + assert.equal(r2.title, 'Marc Fesneau campaign (2026)'); + assert.equal(r2.infobox.result, 'Decisive bob victory'); + const empty: MatchRecord = { ...base, events: [T(1), { kind: 'gameOver', winner: 1, reason: 'timeout', turn: 1 }] }; + assert.equal(recap(empty).title, 'WikiDeck match of 17 November 2026'); +}); + +test('tone lint: templates are deadpan (DUEL_DESIGN §8.1, critic S7)', () => { + for (const [key, variants] of Object.entries(LOG_TEMPLATES)) { + assert.ok(variants.length >= 3 && variants.length <= 4, `${key} has ${variants.length} variants`); + for (const v of variants) { + assert.doesNotMatch(v, /!/, `${key}: no exclamation marks`); + for (const w of BANNED_WORDS) assert.doesNotMatch(v.toLowerCase(), new RegExp(`\\b${w}\\b`), `${key}: banned word ${w}`); + assert.doesNotMatch(v, /[\u{1F300}-\u{1FAFF}]/u, `${key}: no emoji`); + } + } + const r = recap(record); + const prose = [r.lead, ...r.sections.flatMap(s => s.paragraphs)].join(' ') + .replace(/\*[^*]+\*/g, 'CARD'); // card titles are data; lint only our words + for (const w of BANNED_WORDS) assert.doesNotMatch(prose.toLowerCase(), new RegExp(`\\b${w}\\b`)); + assert.doesNotMatch(prose, /!/); + assert.doesNotMatch(prose, /Wikipedia|Wikimedia/); // branding: only in references and the footer +}); + +test('every sample description glosses without throwing; dates format', () => { + for (const c of sample.cards) assert.equal(typeof gloss(c.description ?? ''), 'string'); + assert.equal(gloss('American actor (1909–1994)'), 'American actor, 1909–1994'); + assert.equal(gloss(''), ''); + assert.equal(longDate('2026-01-05'), '5 January 2026'); +}); + +test('story code is pure: no network or clock access', () => { + const dir = new URL('../shared/duel/story/', import.meta.url); + for (const f of readdirSync(dir)) { + const src = readFileSync(new URL(f, dir), 'utf8'); + assert.doesNotMatch(src, /\bfetch\(|XMLHttpRequest|node:http|Date\.now|new Date\(|Math\.random/, f); + } +}); + +test('golden: full log and recap prose match tests/duel-design-story.golden.json', () => { + // To regenerate after a deliberate template change, dump { log, lead, sections } and review the diff. + const golden = JSON.parse(readFileSync(new URL('./duel-design-story.golden.json', import.meta.url), 'utf8')); + const r = recap(record); + assert.deepEqual({ log: logParagraphs(renderLog(record).lines), lead: r.lead, sections: r.sections }, golden); +}); From 3c70f643f29771cacd10e7f0daf239dac348c969 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:43:59 -0500 Subject: [PATCH 06/25] [duel-cards] Card profiles: classify, derive, effects, rules text from real data MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit shared/duel/classify.ts: Q-id anchors -> P31 label regex (^human$) -> P279 -> categories -> description -> Doctrine. shared/duel/derive.ts: pure derive(chain, profile) -> DuelCard: fame cost 1-6, P+T budget per cost, DUEL_DESIGN §4 keywords (<=2, Figures only, taxed), Portals, Connected keys and tiers, flavour. shared/duel/effects.ts + text.ts: T1-T12 templates as EffectSpec data, MTG-register rules text. shared/duel/sample.ts + docs/game/duel-card-sample.json: 236-card DuelCard fixture. Co-Authored-By: Claude Opus 5.5 --- docs/game/duel-card-sample.json | 10419 ++++++++++++++++++++++++++++++ scripts/duel-card-sample.ts | 32 + shared/duel/classify.ts | 125 + shared/duel/derive.ts | 317 + shared/duel/effects.ts | 109 + shared/duel/sample.ts | 38 + shared/duel/text.ts | 135 + tests/duel-cards-derive.test.ts | 205 + 8 files changed, 11380 insertions(+) create mode 100644 docs/game/duel-card-sample.json create mode 100644 scripts/duel-card-sample.ts create mode 100644 shared/duel/classify.ts create mode 100644 shared/duel/derive.ts create mode 100644 shared/duel/effects.ts create mode 100644 shared/duel/sample.ts create mode 100644 shared/duel/text.ts create mode 100644 tests/duel-cards-derive.test.ts diff --git a/docs/game/duel-card-sample.json b/docs/game/duel-card-sample.json new file mode 100644 index 0000000..480513b --- /dev/null +++ b/docs/game/duel-card-sample.json @@ -0,0 +1,10419 @@ +{ + "source": "docs/game/card-sample.json", + "deriveVersion": "duel-derive-1", + "count": 236, + "cards": [ + { + "cardId": "0000000000000000000000000000000000000000000000000000000000851c64", + "pageId": 8723556, + "revisionId": 1358732737, + "title": "Salahuddin of Aceh", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 4, + "power": 4, + "toughness": 3, + "territory": 0, + "keywords": [ + "Legacy" + ], + "effects": [], + "rulesText": "Legacy.", + "flavor": "Sultan of Aceh (1530–1537/9)", + "connect": { + "countries": [ + "Indonesia" + ], + "centuries": [ + 16 + ], + "links": [], + "p31": [], + "qid": "Q4264920", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 62, + "pctDepth": 48, + "pctReach": 63, + "fame": 58, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000a4cc4d", + "pageId": 10800205, + "revisionId": 1376918522, + "title": "St. Georgen am Längsee", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Municipality in Carinthia, Austria", + "connect": { + "countries": [ + "Austria" + ], + "centuries": [], + "links": [], + "p31": [ + "Q1802801", + "Q667509" + ], + "qid": "Q664135", + "cites": [] + }, + "rarity": "Legendary", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 35, + "pctDepth": 43, + "pctReach": 93, + "fame": 57, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001849df5", + "pageId": 25468405, + "revisionId": 1378546622, + "title": "Maracás", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Municipality of Bahia, Brazil", + "connect": { + "countries": [ + "Brazil" + ], + "centuries": [], + "links": [], + "p31": [ + "Q3184121" + ], + "qid": "Q1795100", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 42, + "pctDepth": 43, + "pctReach": 91, + "fame": 59, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000018a8b89", + "pageId": 25856905, + "revisionId": 1367363150, + "title": "Dichromorpha viridis", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 3, + "toughness": 1, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Species of grasshopper", + "connect": { + "countries": [], + "centuries": [ + 19 + ], + "links": [], + "p31": [], + "qid": "Q5272562", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 58, + "pctDepth": 3, + "pctReach": 53, + "fame": 38, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002309e43", + "pageId": 36740675, + "revisionId": 1372732350, + "title": "The Best of Men", + "type": "Institution", + "subtype": "work", + "portal": "Arts", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "draw", + "amount": 1 + }, + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 1, + "condition": { + "connected": true + } + } + ], + "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", + "flavor": "2012 British television film", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q506240" + ], + "qid": "Q7717125", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 80, + "pctDepth": 48, + "pctReach": 53, + "fame": 60, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000279b34c", + "pageId": 41530188, + "revisionId": 1383948367, + "title": "Hervé Fischer", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 4, + "power": 2, + "toughness": 5, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "", + "connect": { + "countries": [ + "France" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q3134490", + "cites": [] + }, + "rarity": "Legendary", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 35, + "pctDepth": 68, + "pctReach": 63, + "fame": 55, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000027beec0", + "pageId": 41676480, + "revisionId": 1187069209, + "title": "Mary Sophie Young", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 2, + "power": 1, + "toughness": 2, + "territory": 0, + "keywords": [ + "Legacy" + ], + "effects": [], + "rulesText": "Legacy.", + "flavor": "American botanist (c.1872–1919)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q16043849", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 11, + "pctDepth": 38, + "pctReach": 47, + "fame": 32, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000039663ae", + "pageId": 60187566, + "revisionId": 1353977816, + "title": "Oncopagurus", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 5, + "toughness": 1, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Genus of crustaceans", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q4471563", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 42, + "pctDepth": 11, + "pctReach": 63, + "fame": 39, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000404da56", + "pageId": 67426902, + "revisionId": 1355258366, + "title": "April 2021 nor'easter", + "type": "Event", + "subtype": "disaster", + "portal": "Earth", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "damageEach", + "target": "each", + "amount": 1 + } + ], + "rulesText": "Deal 1 damage to each Figure and each Location.", + "flavor": "Slow-moving nor'easter in April 2021", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q2001587" + ], + "qid": "Q106542029", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 52, + "pctDepth": 89, + "pctReach": 8, + "fame": 50, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000007f1bfc", + "pageId": 8330236, + "revisionId": 1383654640, + "title": "Hiroshima Electric Railway", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "startOfTurn", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + }, + "condition": { + "maxTokens": 2 + } + } + ], + "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", + "flavor": "Japanese transportation company", + "connect": { + "countries": [ + "Japan" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q85907346" + ], + "qid": "Q16595959", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 86, + "pctDepth": 64, + "pctReach": 82, + "fame": 77, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000f14093", + "pageId": 15810707, + "revisionId": 1381828954, + "title": "Charmont-en-Beauce", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Commune in Centre-Val de Loire, France", + "connect": { + "countries": [ + "France" + ], + "centuries": [], + "links": [], + "p31": [ + "Q484170" + ], + "qid": "Q667131", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 17, + "pctDepth": 7, + "pctReach": 94, + "fame": 39, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000f2623f", + "pageId": 15884863, + "revisionId": 1358001871, + "title": "Freshwater River", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "River on Stewart Island / Rakiura, New Zealand", + "connect": { + "countries": [ + "New Zealand" + ], + "centuries": [], + "links": [], + "p31": [ + "Q4022" + ], + "qid": "Q5503122", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 24, + "pctDepth": 33, + "pctReach": 58, + "fame": 38, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000011e7dea", + "pageId": 18775530, + "revisionId": 1378518207, + "title": "Złaków Kościelny", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Village in Łódź Voivodeship, Poland", + "connect": { + "countries": [ + "Poland" + ], + "centuries": [], + "links": [], + "p31": [ + "Q3558970" + ], + "qid": "Q321622", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 4, + "pctDepth": 2, + "pctReach": 67, + "fame": 24, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000175fc6f", + "pageId": 24509551, + "revisionId": 1367096869, + "title": "Village (Pennsylvania)", + "type": "Location", + "subtype": null, + "portal": "Society", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q16936588", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "category", + "basis": { + "pctAttention": 38, + "pctDepth": 33, + "pctReach": 8, + "fame": 26, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000180a290", + "pageId": 25207440, + "revisionId": 1376759357, + "title": "Sainte-Félicité, Chaudière-Appalaches", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Municipality in Quebec, Canada", + "connect": { + "countries": [ + "Canada" + ], + "centuries": [], + "links": [], + "p31": [ + "Q27676428" + ], + "qid": "Q3464275", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 11, + "pctDepth": 38, + "pctReach": 67, + "fame": 39, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001c845f2", + "pageId": 29902322, + "revisionId": 1325745411, + "title": "Llanveynoe", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Village in Herefordshire, England", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [], + "links": [], + "p31": [ + "Q1115575", + "Q532" + ], + "qid": "Q6661845", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 31, + "pctDepth": 33, + "pctReach": 67, + "fame": 44, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003f6d6d1", + "pageId": 66508497, + "revisionId": 1323515500, + "title": "Amanita mairei", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 3, + "toughness": 1, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Species of fungus", + "connect": { + "countries": [], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q15651951", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 42, + "pctDepth": 0, + "pctReach": 71, + "fame": 38, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004cd4092", + "pageId": 80560274, + "revisionId": 1351705367, + "title": "1912 Argentine Primera División final", + "type": "Event", + "subtype": "sport", + "portal": "Society", + "cost": 2, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "pump", + "target": "ownFigure", + "power": 1, + "toughness": 0, + "duration": "turn" + }, + { + "trigger": "onPlay", + "op": "fight", + "target": "opponentFigure" + } + ], + "rulesText": "Target Figure you control gets +1/+0 until end of turn, then it fights target Figure you don't control.", + "flavor": "Football match", + "connect": { + "countries": [ + "Argentina" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q12166442", + "Q1366722" + ], + "qid": "Q135493693", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 14, + "pctDepth": 73, + "pctReach": 8, + "fame": 32, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000071fcb", + "pageId": 466891, + "revisionId": 1386046344, + "title": "City of Wyndham", + "type": "Location", + "subtype": null, + "portal": "Society", + "cost": 3, + "power": 0, + "toughness": 4, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/4.", + "flavor": "Local government area in Victoria, Australia", + "connect": { + "countries": [ + "Australia" + ], + "centuries": [ + 19 + ], + "links": [], + "p31": [ + "Q1426035" + ], + "qid": "Q1502429", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 86, + "pctDepth": 77, + "pctReach": 74, + "fame": 79, + "magnitude": 3 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000025711c", + "pageId": 2453788, + "revisionId": 1374732887, + "title": "Heart rot", + "type": "Doctrine", + "subtype": "pathology", + "portal": "Science", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "figure", + "power": -3, + "toughness": -3, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure. It gets −3/−3.", + "flavor": "Fungal disease of trees", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q2662845" + ], + "qid": "Q5692479", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 83, + "pctDepth": 68, + "pctReach": 53, + "fame": 68, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000002ad3e8", + "pageId": 2806760, + "revisionId": 1385958400, + "title": "Jess Harnell", + "type": "Figure", + "subtype": null, + "portal": "Arts", + "cost": 6, + "power": 5, + "toughness": 5, + "territory": 0, + "keywords": [ + "Protected", + "Featured" + ], + "effects": [], + "rulesText": "Protected, Featured.", + "flavor": "American voice actor and singer (born 1963)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q258503", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 99, + "pctDepth": 96, + "pctReach": 89, + "fame": 95, + "magnitude": 3 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000089b9d0", + "pageId": 9026000, + "revisionId": 1351068420, + "title": "Names of Poland", + "type": "Doctrine", + "subtype": "language", + "portal": "Neutral", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 3, + "toughness": 3, + "duration": "permanent" + }, + { + "trigger": "onCombatDamageToPlayer", + "op": "draw", + "target": "attached", + "amount": 1 + } + ], + "rulesText": "Attach to target Figure you control. It gets +3/+3.\nWhenever it deals combat damage to a player, draw a card.", + "flavor": "", + "connect": { + "countries": [ + "Poland" + ], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q6961536", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "category", + "basis": { + "pctAttention": 89, + "pctDepth": 83, + "pctReach": 53, + "fame": 75, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000f09c8c", + "pageId": 15768716, + "revisionId": 1382030873, + "title": "Ungersheim", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Commune in Grand Est, France", + "connect": { + "countries": [ + "France" + ], + "centuries": [], + "links": [], + "p31": [ + "Q484170" + ], + "qid": "Q122940", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 42, + "pctDepth": 28, + "pctReach": 96, + "fame": 55, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000246d152", + "pageId": 38195538, + "revisionId": 1354427246, + "title": "Joe Gideon & the Shark", + "type": "Institution", + "subtype": "organisation", + "portal": "Arts", + "cost": 2, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + } + } + ], + "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", + "flavor": "English blues/indie rock band", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [], + "links": [], + "p31": [ + "Q215380" + ], + "qid": "Q3012108", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 52, + "pctDepth": 17, + "pctReach": 23, + "fame": 31, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000025ed7ee", + "pageId": 39770094, + "revisionId": 1376919282, + "title": "2013–14 California Golden Bears men's basketball team", + "type": "Event", + "subtype": "sport", + "portal": "Society", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "pump", + "target": "ownFigure", + "power": 2, + "toughness": 0, + "duration": "turn" + }, + { + "trigger": "onPlay", + "op": "fight", + "target": "opponentFigure" + } + ], + "rulesText": "Target Figure you control gets +2/+0 until end of turn, then it fights target Figure you don't control.", + "flavor": "American college basketball season", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q26894053" + ], + "qid": "Q16245089", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 24, + "pctDepth": 92, + "pctReach": 8, + "fame": 41, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002f85b42", + "pageId": 49830722, + "revisionId": 1116073630, + "title": "Dicroidium odontopteroides", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 2, + "toughness": 1, + "territory": 0, + "keywords": [ + "Stub", + "Local" + ], + "effects": [], + "rulesText": "Stub, Local.", + "flavor": "Species of ancient plant", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q25095289", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 42, + "pctDepth": 11, + "pctReach": 8, + "fame": 20, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000031e1299", + "pageId": 52302489, + "revisionId": 1380325251, + "title": "Pathrail Mosque", + "type": "Location", + "subtype": null, + "portal": "Society", + "cost": 2, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Mosque in Faridpur, Bangladesh", + "connect": { + "countries": [ + "Bangladesh" + ], + "centuries": [ + 15 + ], + "links": [], + "p31": [ + "Q32815" + ], + "qid": "Q28173356", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 47, + "pctDepth": 54, + "pctReach": 47, + "fame": 49, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000001e346c", + "pageId": 1979500, + "revisionId": 1382599906, + "title": "Zbyszek Godlewski", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 5, + "power": 6, + "toughness": 3, + "territory": 0, + "keywords": [ + "Legacy", + "Translated" + ], + "effects": [], + "rulesText": "Legacy, Translated.", + "flavor": "Polish protester (1952–1970)", + "connect": { + "countries": [ + "Poland" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q3497070", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 77, + "pctDepth": 48, + "pctReach": 78, + "fame": 68, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000438c15", + "pageId": 4426773, + "revisionId": 1384528612, + "title": "Agda (programming language)", + "type": "Doctrine", + "subtype": "language", + "portal": "Science", + "cost": 6, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 3, + "toughness": 3, + "duration": "permanent" + }, + { + "trigger": "onCombatDamageToPlayer", + "op": "draw", + "target": "attached", + "amount": 1 + } + ], + "rulesText": "Attach to target Figure you control. It gets +3/+3.\nWhenever it deals combat damage to a player, draw a card.", + "flavor": "Functional programming language", + "connect": { + "countries": [], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q11387554", + "Q28920201", + "Q341", + "Q3839507", + "Q56223375", + "Q9143" + ], + "qid": "Q20479", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 91, + "pctDepth": 77, + "pctReach": 78, + "fame": 82, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000475385", + "pageId": 4674437, + "revisionId": 1384106265, + "title": "Topusko", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 0, + "toughness": 4, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/4.", + "flavor": "Commune in Sisak-Moslavina County, Croatia", + "connect": { + "countries": [ + "Croatia" + ], + "centuries": [], + "links": [], + "p31": [ + "Q57058" + ], + "qid": "Q2457438", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 74, + "pctDepth": 77, + "pctReach": 90, + "fame": 80, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000004dc3c7", + "pageId": 5096391, + "revisionId": 1376332037, + "title": "Isabella of Aragon, Queen of Portugal", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 6, + "power": 6, + "toughness": 4, + "territory": 0, + "keywords": [ + "Featured", + "Legacy" + ], + "effects": [], + "rulesText": "Featured, Legacy.", + "flavor": "Queen of Portugal from 1497 to 1498", + "connect": { + "countries": [ + "France", + "Italy", + "Portugal", + "Spain", + "United Kingdom" + ], + "centuries": [ + 15 + ], + "links": [], + "p31": [], + "qid": "Q466305", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 97, + "pctDepth": 77, + "pctReach": 97, + "fame": 90, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000f2d966", + "pageId": 15915366, + "revisionId": 1381946137, + "title": "Montjavoult", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Commune in Hauts-de-France, France", + "connect": { + "countries": [ + "France" + ], + "centuries": [], + "links": [], + "p31": [ + "Q484170" + ], + "qid": "Q1336846", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 3, + "pctDepth": 4, + "pctReach": 95, + "fame": 34, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000f39622", + "pageId": 15963682, + "revisionId": 1384826851, + "title": "Viktor Genev", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 5, + "power": 4, + "toughness": 5, + "territory": 0, + "keywords": [ + "Protected", + "Translated" + ], + "effects": [], + "rulesText": "Protected, Translated.", + "flavor": "Bulgarian footballer", + "connect": { + "countries": [ + "Bulgaria", + "Israel", + "Kazakhstan", + "Romania", + "Russia", + "Ukraine", + "United Kingdom" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q2604995", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 52, + "pctDepth": 77, + "pctReach": 81, + "fame": 70, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001aba163", + "pageId": 28025187, + "revisionId": 1377386321, + "title": "Pühajõe", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Village in Estonia", + "connect": { + "countries": [ + "Estonia" + ], + "centuries": [], + "links": [], + "p31": [ + "Q51049922" + ], + "qid": "Q179358", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 11, + "pctDepth": 11, + "pctReach": 78, + "fame": 33, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002ed73e4", + "pageId": 49116132, + "revisionId": 1376271314, + "title": "Kalihati", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Town in Dhaka Division, Bangladesh", + "connect": { + "countries": [ + "Bangladesh" + ], + "centuries": [], + "links": [], + "p31": [ + "Q23759397", + "Q3957" + ], + "qid": "Q22348003", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 27, + "pctDepth": 38, + "pctReach": 47, + "fame": 37, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002f27561", + "pageId": 49444193, + "revisionId": 1371976132, + "title": "Miloje Vasić", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 5, + "power": 4, + "toughness": 5, + "territory": 0, + "keywords": [ + "Legacy", + "Translated" + ], + "effects": [], + "rulesText": "Legacy, Translated.", + "flavor": "Serbian archaeologist (1869–1956)", + "connect": { + "countries": [ + "Serbia" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q3314419", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 58, + "pctDepth": 89, + "pctReach": 78, + "fame": 75, + "magnitude": 3 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000001adbf", + "pageId": 110015, + "revisionId": 1377786275, + "title": "Haralson, Georgia", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Town in Georgia, United States", + "connect": { + "countries": [ + "United States" + ], + "centuries": [], + "links": [], + "p31": [ + "Q15127012", + "Q76514543" + ], + "qid": "Q2520618", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 62, + "pctDepth": 64, + "pctReach": 91, + "fame": 72, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000ab844d", + "pageId": 11240525, + "revisionId": 1382620781, + "title": "Joseph Ujlaki", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 4, + "power": 5, + "toughness": 2, + "territory": 0, + "keywords": [ + "Legacy", + "Translated" + ], + "effects": [], + "rulesText": "Legacy, Translated.", + "flavor": "French-Hungarian footballer (1929-2006)", + "connect": { + "countries": [ + "France", + "Hungary" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q905343", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 64, + "pctDepth": 28, + "pctReach": 82, + "fame": 58, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000162de74", + "pageId": 23256692, + "revisionId": 1176682009, + "title": "Coelogyne trinervis", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 3, + "toughness": 1, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Species of orchid", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q188238" + ], + "qid": "Q1601035", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 17, + "pctDepth": 4, + "pctReach": 67, + "fame": 29, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001d74bfb", + "pageId": 30886907, + "revisionId": 1367824379, + "title": "Pine River (Manistee River tributary)", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "River in Michigan, United States", + "connect": { + "countries": [ + "United States" + ], + "centuries": [], + "links": [], + "p31": [ + "Q4022" + ], + "qid": "Q7195337", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 54, + "pctDepth": 38, + "pctReach": 23, + "fame": 38, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003b4f3b0", + "pageId": 62190512, + "revisionId": 1377313379, + "title": "Nguyễn Văn Huy", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 3, + "power": 3, + "toughness": 2, + "territory": 0, + "keywords": [ + "Protected", + "Stub" + ], + "effects": [], + "rulesText": "Protected, Stub.", + "flavor": "Vietnamese chess grandmaster (born 1985)", + "connect": { + "countries": [ + "Vietnam" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q20026028", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 47, + "pctDepth": 28, + "pctReach": 47, + "fame": 41, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003d6c241", + "pageId": 64406081, + "revisionId": 1280859035, + "title": "San Wai (San Tin)", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q532" + ], + "qid": "Q96739151", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 21, + "pctDepth": 48, + "pctReach": 23, + "fame": 31, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003e433c1", + "pageId": 65287105, + "revisionId": 1376673468, + "title": "Kishore Tirumala", + "type": "Figure", + "subtype": null, + "portal": "Arts", + "cost": 4, + "power": 4, + "toughness": 2, + "territory": 0, + "keywords": [ + "Protected", + "Featured" + ], + "effects": [], + "rulesText": "Protected, Featured.", + "flavor": "Indian film director", + "connect": { + "countries": [ + "India" + ], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q93762585", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 91, + "pctDepth": 54, + "pctReach": 36, + "fame": 60, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004d8a703", + "pageId": 81307395, + "revisionId": 1378554406, + "title": "2025 Tehreek-e-Labbaik Pakistan protests", + "type": "Event", + "subtype": "conflict", + "portal": "Society", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "damage", + "target": "figureOrLocation", + "amount": 4 + } + ], + "rulesText": "Deal 4 damage to target Figure or Location.", + "flavor": "Gaza war protests in Pakistan", + "connect": { + "countries": [ + "Israel", + "Pakistan" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q273120" + ], + "qid": "Q136649814", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 82, + "pctDepth": 86, + "pctReach": 23, + "fame": 64, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000000dc52e", + "pageId": 902446, + "revisionId": 1378970556, + "title": "Guidimaka region", + "type": "Location", + "subtype": null, + "portal": "Neutral", + "cost": 3, + "power": 0, + "toughness": 4, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/4.", + "flavor": "Region of Mauritania", + "connect": { + "countries": [ + "Mauritania" + ], + "centuries": [], + "links": [], + "p31": [ + "Q846327" + ], + "qid": "Q768119", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 58, + "pctDepth": 77, + "pctReach": 94, + "fame": 76, + "magnitude": 3 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000014fa5c", + "pageId": 1374812, + "revisionId": 1381663979, + "title": "Tom Ewell", + "type": "Figure", + "subtype": null, + "portal": "Arts", + "cost": 6, + "power": 5, + "toughness": 5, + "territory": 0, + "keywords": [ + "Featured", + "Legacy" + ], + "effects": [], + "rulesText": "Featured, Legacy.", + "flavor": "American actor (1909–1994)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q427388", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 94, + "pctDepth": 83, + "pctReach": 93, + "fame": 90, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000ea6920", + "pageId": 15362336, + "revisionId": 1351181171, + "title": "1954 Gold Coast general election", + "type": "Event", + "subtype": "election", + "portal": "Society", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "createToken", + "amount": 2, + "token": { + "name": "Elected Member", + "power": 1, + "toughness": 1, + "portal": "Society" + } + } + ], + "rulesText": "Create two 1/1 Society Figure tokens named Elected Member.", + "flavor": "", + "connect": { + "countries": [ + "Ghana", + "United Kingdom" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q2618461" + ], + "qid": "Q2539674", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 66, + "pctDepth": 33, + "pctReach": 36, + "fame": 45, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000162a8e7", + "pageId": 23242983, + "revisionId": 1351414373, + "title": "Larry Weber", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 4, + "power": 3, + "toughness": 4, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "American entrepreneur", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q6491266", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 66, + "pctDepth": 73, + "pctReach": 36, + "fame": 58, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002f59319", + "pageId": 49648409, + "revisionId": 1344963259, + "title": "Ulla! min Ulla! Säj får jag dig bjuda", + "type": "Institution", + "subtype": "work", + "portal": "Arts", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "draw", + "amount": 1 + }, + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 1, + "condition": { + "connected": true + } + } + ], + "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", + "flavor": "Song by the 18th century Swedish bard Carl Michael Bellman", + "connect": { + "countries": [ + "Sweden" + ], + "centuries": [ + 18 + ], + "links": [], + "p31": [ + "Q105543609" + ], + "qid": "Q19528685", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 27, + "pctDepth": 83, + "pctReach": 23, + "fame": 44, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000506ce99", + "pageId": 84332185, + "revisionId": 1378056768, + "title": "Oscar González Oro", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 3, + "power": 4, + "toughness": 1, + "territory": 0, + "keywords": [ + "Legacy" + ], + "effects": [], + "rulesText": "Legacy.", + "flavor": "Argentine journalist and radio host (1951–2026)", + "connect": { + "countries": [ + "Argentina" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q6053873", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 66, + "pctDepth": 28, + "pctReach": 23, + "fame": 39, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000246570", + "pageId": 2385264, + "revisionId": 1334637363, + "title": "Ofanto", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "River in Italy", + "connect": { + "countries": [ + "Italy" + ], + "centuries": [], + "links": [], + "p31": [ + "Q4022" + ], + "qid": "Q841550", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 69, + "pctDepth": 43, + "pctReach": 91, + "fame": 68, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000751b4c", + "pageId": 7674700, + "revisionId": 1384061257, + "title": "Shipley Plateau", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Place in the Blue Mountains, Australia", + "connect": { + "countries": [ + "Australia", + "United Kingdom" + ], + "centuries": [], + "links": [], + "p31": [ + "Q75520" + ], + "qid": "Q7498025", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 17, + "pctDepth": 7, + "pctReach": 23, + "fame": 16, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000140afac", + "pageId": 21016492, + "revisionId": 1363646521, + "title": "Xiancantan", + "type": "Location", + "subtype": null, + "portal": "Science", + "cost": 2, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "", + "connect": { + "countries": [ + "China" + ], + "centuries": [ + 18 + ], + "links": [], + "p31": [ + "Q41176" + ], + "qid": "Q434483", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 50, + "pctDepth": 7, + "pctReach": 67, + "fame": 41, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003165b05", + "pageId": 51796741, + "revisionId": 1356084913, + "title": "Alex Piquero", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 3, + "power": 3, + "toughness": 2, + "territory": 0, + "keywords": [ + "Protected", + "Stub" + ], + "effects": [], + "rulesText": "Protected, Stub.", + "flavor": "Cuban-American criminologist (born 1970)", + "connect": { + "countries": [ + "Cuba", + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q27058048", + "cites": [] + }, + "rarity": "Legendary", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 62, + "pctDepth": 59, + "pctReach": 8, + "fame": 43, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000183a95", + "pageId": 1587861, + "revisionId": 1382422731, + "title": "Vélez-Málaga", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 0, + "toughness": 4, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/4.", + "flavor": "Place in Málaga, Spain", + "connect": { + "countries": [ + "Spain" + ], + "centuries": [], + "links": [], + "p31": [ + "Q2074737" + ], + "qid": "Q492741", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 86, + "pctDepth": 92, + "pctReach": 98, + "fame": 92, + "magnitude": 3 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000041756b", + "pageId": 4289899, + "revisionId": 1384682008, + "title": "Anthodon (reptile)", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 5, + "power": 5, + "toughness": 5, + "territory": 0, + "keywords": [ + "Translated" + ], + "effects": [], + "rulesText": "Translated.", + "flavor": "Extinct genus of reptiles", + "connect": { + "countries": [], + "centuries": [ + 19 + ], + "links": [], + "p31": [ + "Q47487597" + ], + "qid": "Q2505064", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 69, + "pctDepth": 64, + "pctReach": 80, + "fame": 71, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000010b1fc1", + "pageId": 17506241, + "revisionId": 1361257647, + "title": "Marion Thees", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 3, + "power": 3, + "toughness": 2, + "territory": 0, + "keywords": [ + "Protected", + "Translated" + ], + "effects": [], + "rulesText": "Protected, Translated.", + "flavor": "German skeleton racer", + "connect": { + "countries": [ + "Germany" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q72724", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 38, + "pctDepth": 23, + "pctReach": 78, + "fame": 46, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000013be088", + "pageId": 20701320, + "revisionId": 1385997032, + "title": "Horse Feathers (band)", + "type": "Institution", + "subtype": "organisation", + "portal": "Arts", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "startOfTurn", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + }, + "condition": { + "maxTokens": 2 + } + } + ], + "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", + "flavor": "American indie folk band", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q215380" + ], + "qid": "Q5905442", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 71, + "pctDepth": 54, + "pctReach": 36, + "fame": 54, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002d92236", + "pageId": 47784502, + "revisionId": 1375411209, + "title": "Christian Zübert", + "type": "Figure", + "subtype": null, + "portal": "Arts", + "cost": 4, + "power": 3, + "toughness": 4, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "German film director and screenwriter (born 1973)", + "connect": { + "countries": [ + "Germany" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q1082448", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 47, + "pctDepth": 59, + "pctReach": 58, + "fame": 55, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003d70634", + "pageId": 64423476, + "revisionId": 1377264425, + "title": "2023 Seville municipal election", + "type": "Event", + "subtype": "election", + "portal": "Society", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "createToken", + "amount": 2, + "token": { + "name": "Elected Member", + "power": 1, + "toughness": 1, + "portal": "Society" + } + } + ], + "rulesText": "Create two 1/1 Society Figure tokens named Elected Member.", + "flavor": "Election in the Spanish municipality of Seville", + "connect": { + "countries": [ + "Spain" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q152450" + ], + "qid": "Q97188845", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 52, + "pctDepth": 97, + "pctReach": 36, + "fame": 62, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000049c9880", + "pageId": 77371520, + "revisionId": 1372235441, + "title": "Coalición Vamos", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + } + } + ], + "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", + "flavor": "Political party in Panama", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q7278" + ], + "qid": "Q127386808", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 85, + "pctDepth": 28, + "pctReach": 23, + "fame": 45, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000001c2f8", + "pageId": 115448, + "revisionId": 1374535006, + "title": "Mackville, Kentucky", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "City in Kentucky, United States", + "connect": { + "countries": [ + "United States" + ], + "centuries": [], + "links": [], + "p31": [ + "Q1093829" + ], + "qid": "Q2246158", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 50, + "pctDepth": 54, + "pctReach": 94, + "fame": 66, + "magnitude": 3 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000041fc69", + "pageId": 4324457, + "revisionId": 1372952688, + "title": "Juha Suoranta", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 3, + "power": 2, + "toughness": 3, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "Finnish social scientist", + "connect": { + "countries": [ + "Finland" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q6305056", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 35, + "pctDepth": 68, + "pctReach": 47, + "fame": 50, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000908a9f", + "pageId": 9472671, + "revisionId": 1280127322, + "title": "Fletcher (typeface)", + "type": "Institution", + "subtype": "work", + "portal": "Arts", + "cost": 2, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "draw", + "amount": 1 + }, + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 1, + "condition": { + "connected": true + } + } + ], + "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", + "flavor": "Serif typeface", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q17451" + ], + "qid": "Q2539914", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 54, + "pctDepth": 2, + "pctReach": 23, + "fame": 26, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000befc0f", + "pageId": 12516367, + "revisionId": 1320927031, + "title": "Frogham, Kent", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Hamlet in Kent, England", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [], + "links": [], + "p31": [ + "Q5084" + ], + "qid": "Q5505274", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 21, + "pctDepth": 4, + "pctReach": 47, + "fame": 24, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000181aa81", + "pageId": 25275009, + "revisionId": 1381503728, + "title": "Amur Annexation", + "type": "Event", + "subtype": "conflict", + "portal": "History", + "cost": 6, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "damage", + "target": "figureOrLocation", + "amount": 4 + } + ], + "rulesText": "Deal 4 damage to target Figure or Location.", + "flavor": "Russian annexation of Outer Manchuria", + "connect": { + "countries": [ + "China", + "Russia" + ], + "centuries": [ + 19 + ], + "links": [], + "p31": [ + "Q194465" + ], + "qid": "Q4379152", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 93, + "pctDepth": 81, + "pctReach": 74, + "fame": 83, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001fbc437", + "pageId": 33276983, + "revisionId": 1375320562, + "title": "Buky", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Rural locality in Cherkasy Oblast, Ukraine", + "connect": { + "countries": [ + "Ukraine" + ], + "centuries": [], + "links": [], + "p31": [ + "Q4100864", + "Q486972" + ], + "qid": "Q2473493", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 38, + "pctDepth": 33, + "pctReach": 83, + "fame": 51, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000256bae2", + "pageId": 39238370, + "revisionId": 1330396969, + "title": "2013 San Jose State Spartans football team", + "type": "Event", + "subtype": "sport", + "portal": "Society", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "pump", + "target": "ownFigure", + "power": 2, + "toughness": 0, + "duration": "turn" + }, + { + "trigger": "onPlay", + "op": "fight", + "target": "opponentFigure" + } + ], + "rulesText": "Target Figure you control gets +2/+0 until end of turn, then it fights target Figure you don't control.", + "flavor": "American college football season", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q26895936" + ], + "qid": "Q16972991", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 62, + "pctDepth": 83, + "pctReach": 8, + "fame": 51, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002c1eb97", + "pageId": 46263191, + "revisionId": 1384441370, + "title": "Max Touloute", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 3, + "power": 2, + "toughness": 3, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "Haitian footballer (born 1990)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q20641573", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 35, + "pctDepth": 68, + "pctReach": 36, + "fame": 46, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002fdc661", + "pageId": 50185825, + "revisionId": 1371365886, + "title": "Majid Qodiri", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 4, + "power": 2, + "toughness": 5, + "territory": 0, + "keywords": [ + "Legacy" + ], + "effects": [], + "rulesText": "Legacy.", + "flavor": "Uzbek literary scholar and educator (1886–1938)", + "connect": { + "countries": [], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q23823703", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 31, + "pctDepth": 64, + "pctReach": 63, + "fame": 53, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000321b424", + "pageId": 52540452, + "revisionId": 1381108921, + "title": "Olga Gorshenina", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 2, + "power": 1, + "toughness": 2, + "territory": 0, + "keywords": [ + "Protected", + "Translated" + ], + "effects": [], + "rulesText": "Protected, Translated.", + "flavor": "Russian handball player", + "connect": { + "countries": [ + "Germany", + "Hungary", + "Romania", + "Russia" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q2019617", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 14, + "pctDepth": 17, + "pctReach": 78, + "fame": 36, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000043bf4f0", + "pageId": 71038192, + "revisionId": 1382877416, + "title": "1952 Avusrennen", + "type": "Event", + "subtype": "sport", + "portal": "Society", + "cost": 1, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "pump", + "target": "ownFigure", + "power": 1, + "toughness": 0, + "duration": "turn" + }, + { + "trigger": "onPlay", + "op": "fight", + "target": "opponentFigure" + } + ], + "rulesText": "Target Figure you control gets +1/+0 until end of turn, then it fights target Figure you don't control.", + "flavor": "Motor car race", + "connect": { + "countries": [ + "Germany" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q112838670", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "category", + "basis": { + "pctAttention": 24, + "pctDepth": 38, + "pctReach": 8, + "fame": 23, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004d8d1a8", + "pageId": 81318312, + "revisionId": 1382049023, + "title": "Guido Iván Justo", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 4, + "power": 4, + "toughness": 2, + "territory": 0, + "keywords": [ + "Protected", + "Featured" + ], + "effects": [], + "rulesText": "Protected, Featured.", + "flavor": "Argentine tennis player (born 1997)", + "connect": { + "countries": [ + "Argentina" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q138414200", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 85, + "pctDepth": 54, + "pctReach": 23, + "fame": 54, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000021dbee", + "pageId": 2218990, + "revisionId": 1386025479, + "title": "Deputy Prime Minister of Malaysia", + "type": "Institution", + "subtype": "other", + "portal": "Society", + "cost": 6, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 0, + "condition": { + "maxPower": 2 + } + } + ], + "rulesText": "Figures you control with power 2 or less get +1/+0.", + "flavor": "Political office in Malaysia", + "connect": { + "countries": [ + "Malaysia" + ], + "centuries": [], + "links": [], + "p31": [ + "Q4164871" + ], + "qid": "Q5261073", + "cites": [] + }, + "rarity": "Legendary", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 89, + "pctDepth": 86, + "pctReach": 76, + "fame": 84, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000007e454c", + "pageId": 8275276, + "revisionId": 1350443233, + "title": "Thomas Wharton Jr.", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 5, + "power": 5, + "toughness": 4, + "territory": 0, + "keywords": [ + "Legacy" + ], + "effects": [], + "rulesText": "Legacy.", + "flavor": "American politician (1735–1778)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 18 + ], + "links": [], + "p31": [], + "qid": "Q883460", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 79, + "pctDepth": 73, + "pctReach": 36, + "fame": 63, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001462f3f", + "pageId": 21376831, + "revisionId": 1374494957, + "title": "Bez (Drôme)", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "River in France", + "connect": { + "countries": [ + "France" + ], + "centuries": [], + "links": [], + "p31": [ + "Q4022" + ], + "qid": "Q1019347", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 17, + "pctDepth": 7, + "pctReach": 36, + "fame": 20, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000155d87e", + "pageId": 22403198, + "revisionId": 1375646501, + "title": "Cioc-Maidan", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Commune in Gagauzia, Moldova", + "connect": { + "countries": [ + "Moldova" + ], + "centuries": [], + "links": [], + "p31": [ + "Q4229812", + "Q532" + ], + "qid": "Q2639022", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 35, + "pctDepth": 28, + "pctReach": 80, + "fame": 48, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000015797a4", + "pageId": 22517668, + "revisionId": 1244289559, + "title": "Kwong Wai Siew Peck San Theng", + "type": "Location", + "subtype": null, + "portal": "Science", + "cost": 2, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Columbarium in Singapore", + "connect": { + "countries": [ + "Singapore" + ], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q6450554", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "category", + "basis": { + "pctAttention": 74, + "pctDepth": 54, + "pctReach": 23, + "fame": 50, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002d51886", + "pageId": 47519878, + "revisionId": 1382761423, + "title": "Jeanne Madden", + "type": "Figure", + "subtype": null, + "portal": "Arts", + "cost": 2, + "power": 2, + "toughness": 1, + "territory": 0, + "keywords": [ + "Legacy", + "Stub" + ], + "effects": [], + "rulesText": "Legacy, Stub.", + "flavor": "American singer and actress (1917–1989)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q20974011", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 21, + "pctDepth": 7, + "pctReach": 53, + "fame": 27, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002e752d2", + "pageId": 48714450, + "revisionId": 1383721847, + "title": "Payam Heydari", + "type": "Figure", + "subtype": null, + "portal": "Science", + "cost": 4, + "power": 3, + "toughness": 4, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "Iranian-American Professor", + "connect": { + "countries": [ + "Iran", + "United States" + ], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q22097382", + "cites": [] + }, + "rarity": "Legendary", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 58, + "pctDepth": 73, + "pctReach": 36, + "fame": 56, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004b36e3e", + "pageId": 78868030, + "revisionId": 1327239041, + "title": "Mercenasco Castle", + "type": "Location", + "subtype": null, + "portal": "History", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Building in Mercenasco, Italy", + "connect": { + "countries": [ + "Italy" + ], + "centuries": [], + "links": [], + "p31": [ + "Q23413" + ], + "qid": "Q131729377", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 0, + "pctDepth": 17, + "pctReach": 36, + "fame": 18, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000050afd22", + "pageId": 84606242, + "revisionId": 1382829231, + "title": "Edward Ellsworth Underwood", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 3, + "power": 2, + "toughness": 3, + "territory": 0, + "keywords": [ + "Legacy", + "Local" + ], + "effects": [], + "rulesText": "Legacy, Local.", + "flavor": "American physician (1864–1942)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q141822855", + "cites": [] + }, + "rarity": "Legendary", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 50, + "pctDepth": 59, + "pctReach": 8, + "fame": 39, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000000ef95c", + "pageId": 981340, + "revisionId": 1384823392, + "title": "Tatsunoko Production", + "type": "Institution", + "subtype": "organisation", + "portal": "Arts", + "cost": 6, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "startOfTurn", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + }, + "condition": { + "maxTokens": 2 + } + } + ], + "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", + "flavor": "Japanese animation studio", + "connect": { + "countries": [ + "Japan" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q1107679" + ], + "qid": "Q1323459", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 94, + "pctDepth": 98, + "pctReach": 86, + "fame": 93, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000001ed529", + "pageId": 2020649, + "revisionId": 1356568738, + "title": "Luxury box", + "type": "Doctrine", + "subtype": "adopt", + "portal": "Society", + "cost": 6, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 3, + "toughness": 3, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure you control. It gets +3/+3.", + "flavor": "Class of seating in arena or stadium", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q852359", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "description", + "basis": { + "pctAttention": 87, + "pctDepth": 83, + "pctReach": 63, + "fame": 78, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000002d7151", + "pageId": 2978129, + "revisionId": 1354827085, + "title": "Saraca", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 4, + "power": 5, + "toughness": 3, + "territory": 0, + "keywords": [ + "Translated" + ], + "effects": [], + "rulesText": "Translated.", + "flavor": "Genus of legumes", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q2426272", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 58, + "pctDepth": 33, + "pctReach": 86, + "fame": 59, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000d65bfa", + "pageId": 14048250, + "revisionId": 1377607311, + "title": "Frontier, Saskatchewan", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 0, + "toughness": 4, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/4.", + "flavor": "Village in Saskatchewan, Canada", + "connect": { + "countries": [ + "Canada" + ], + "centuries": [], + "links": [], + "p31": [ + "Q6644778" + ], + "qid": "Q2003391", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 66, + "pctDepth": 77, + "pctReach": 47, + "fame": 63, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001d1c4f7", + "pageId": 30524663, + "revisionId": 1321144611, + "title": "Aichi AB-2", + "type": "Institution", + "subtype": "organisation", + "portal": "Science", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + } + } + ], + "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", + "flavor": "Prototype reconnaissance floatplane", + "connect": { + "countries": [ + "Japan" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q15056995" + ], + "qid": "Q4696551", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 47, + "pctDepth": 43, + "pctReach": 47, + "fame": 46, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001d6c6e5", + "pageId": 30852837, + "revisionId": 1366643102, + "title": "Symphodus", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 4, + "power": 4, + "toughness": 4, + "territory": 0, + "keywords": [ + "Translated", + "Stub" + ], + "effects": [], + "rulesText": "Translated, Stub.", + "flavor": "Genus of fishes", + "connect": { + "countries": [ + "Spain" + ], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q2019861", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 47, + "pctDepth": 48, + "pctReach": 89, + "fame": 61, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000028ca141", + "pageId": 42770753, + "revisionId": 1375492681, + "title": "Château de la Faye (Villexavier)", + "type": "Location", + "subtype": null, + "portal": "History", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Manor house in Charente-Maritime, France", + "connect": { + "countries": [ + "France" + ], + "centuries": [], + "links": [], + "p31": [ + "Q23413" + ], + "qid": "Q2971223", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 9, + "pctDepth": 7, + "pctReach": 23, + "fame": 13, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002e6632d", + "pageId": 48653101, + "revisionId": 1381828221, + "title": "Tornadoes of 1978", + "type": "Event", + "subtype": "disaster", + "portal": "Neutral", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "damageEach", + "target": "each", + "amount": 1 + } + ], + "rulesText": "Deal 1 damage to each Figure and each Location.", + "flavor": "", + "connect": { + "countries": [], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q18340514" + ], + "qid": "Q22093730", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 80, + "pctDepth": 81, + "pctReach": 8, + "fame": 56, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000034881ec", + "pageId": 55083500, + "revisionId": 1383844197, + "title": "United Kingdom House", + "type": "Location", + "subtype": null, + "portal": "Science", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Building on Oxford Street, London, England", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q41176" + ], + "qid": "Q26319049", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 54, + "pctDepth": 23, + "pctReach": 23, + "fame": 33, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000337786", + "pageId": 3372934, + "revisionId": 1364063954, + "title": "Hermes Ramírez", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 4, + "power": 3, + "toughness": 4, + "territory": 0, + "keywords": [ + "Legacy", + "Translated" + ], + "effects": [], + "rulesText": "Legacy, Translated.", + "flavor": "Cuban sprinter (1948–2024)", + "connect": { + "countries": [ + "Cuba", + "United States" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q522855", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 42, + "pctDepth": 59, + "pctReach": 81, + "fame": 61, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000007f4694", + "pageId": 8341140, + "revisionId": 1370304900, + "title": "Ceaușescu family", + "type": "Figure", + "subtype": null, + "portal": "Neutral", + "cost": 5, + "power": 5, + "toughness": 4, + "territory": 0, + "keywords": [ + "Featured" + ], + "effects": [], + "rulesText": "Featured.", + "flavor": "Family of Nicolae Ceaușescu", + "connect": { + "countries": [ + "Romania" + ], + "centuries": [], + "links": [], + "p31": [ + "Q8436" + ], + "qid": "Q5055770", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 92, + "pctDepth": 59, + "pctReach": 47, + "fame": 66, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000d29182", + "pageId": 13799810, + "revisionId": 1374230485, + "title": "Levophacetoperane", + "type": "Doctrine", + "subtype": "adopt", + "portal": "Science", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 2, + "toughness": 2, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure you control. It gets +2/+2.", + "flavor": "Stimulant drug", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q113145171" + ], + "qid": "Q6535818", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 64, + "pctDepth": 38, + "pctReach": 36, + "fame": 46, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000010eef0c", + "pageId": 17755916, + "revisionId": 1360992742, + "title": "Xiaoliang Sunney Xie", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 5, + "power": 4, + "toughness": 4, + "territory": 0, + "keywords": [ + "Protected", + "Well-sourced" + ], + "effects": [], + "rulesText": "Protected, Well-sourced.", + "flavor": "Chinese-American biochemist", + "connect": { + "countries": [ + "China", + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q906616", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 74, + "pctDepth": 93, + "pctReach": 58, + "fame": 75, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001225032", + "pageId": 19025970, + "revisionId": 1385734329, + "title": "Marina Kuzina", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 3, + "power": 3, + "toughness": 2, + "territory": 0, + "keywords": [ + "Protected", + "Translated" + ], + "effects": [], + "rulesText": "Protected, Translated.", + "flavor": "Russian basketball player", + "connect": { + "countries": [ + "Russia" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q2704942", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 21, + "pctDepth": 11, + "pctReach": 86, + "fame": 39, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000016ff42e", + "pageId": 24114222, + "revisionId": 1317119586, + "title": "Rum cake", + "type": "Doctrine", + "subtype": "adopt", + "portal": "Society", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 3, + "toughness": 3, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure you control. It gets +3/+3.", + "flavor": "Type of dessert", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q7379109", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "category", + "basis": { + "pctAttention": 90, + "pctDepth": 38, + "pctReach": 71, + "fame": 66, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001e1e5e4", + "pageId": 31581668, + "revisionId": 1377811586, + "title": "Ian Potter Museum of Art", + "type": "Location", + "subtype": null, + "portal": "History", + "cost": 2, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Art museum in Parkville, Victoria", + "connect": { + "countries": [ + "Australia" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q207694" + ], + "qid": "Q5982619", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 62, + "pctDepth": 68, + "pctReach": 36, + "fame": 55, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001ff532a", + "pageId": 33510186, + "revisionId": 1371413731, + "title": "Piet Hesse", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 2, + "power": 1, + "toughness": 2, + "territory": 0, + "keywords": [ + "Legacy" + ], + "effects": [], + "rulesText": "Legacy.", + "flavor": "Dutch actor and comedian (1872–1936)", + "connect": { + "countries": [ + "Netherlands" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q2513810", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 17, + "pctDepth": 23, + "pctReach": 53, + "fame": 31, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000212369d", + "pageId": 34748061, + "revisionId": 1315380924, + "title": "Goneplax", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 1, + "toughness": 3, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Genus of crabs", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q5234395", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 4, + "pctDepth": 14, + "pctReach": 71, + "fame": 30, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002d706ce", + "pageId": 47646414, + "revisionId": 1384401817, + "title": "John Mellencamp Pavilion", + "type": "Location", + "subtype": null, + "portal": "Society", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "American athletics facility at Indiana University Bloomington", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q41176" + ], + "qid": "Q22097461", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 71, + "pctDepth": 33, + "pctReach": 8, + "fame": 37, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003853be9", + "pageId": 59063273, + "revisionId": 1385547666, + "title": "Nathan M. Johnson", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 5, + "power": 4, + "toughness": 4, + "territory": 0, + "keywords": [ + "Protected", + "Featured" + ], + "effects": [], + "rulesText": "Protected, Featured.", + "flavor": "American politician and composer (born 1968)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q58756295", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 98, + "pctDepth": 89, + "pctReach": 23, + "fame": 70, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003a79927", + "pageId": 61315367, + "revisionId": 1380314462, + "title": "Payson J. Treat", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 1, + "power": 1, + "toughness": 1, + "territory": 0, + "keywords": [ + "Legacy", + "Stub" + ], + "effects": [], + "rulesText": "Legacy, Stub.", + "flavor": "American Japanologist (1879–1972)", + "connect": { + "countries": [ + "Japan", + "United States" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q59628931", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 11, + "pctDepth": 38, + "pctReach": 8, + "fame": 19, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000179138", + "pageId": 1544504, + "revisionId": 1384187229, + "title": "Walter Rauschenbusch", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 6, + "power": 5, + "toughness": 5, + "territory": 0, + "keywords": [ + "Featured", + "Legacy" + ], + "effects": [], + "rulesText": "Featured, Legacy.", + "flavor": "American theologian and Baptist pastor (1861-1918)", + "connect": { + "countries": [ + "Germany", + "United States" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q1345238", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 89, + "pctDepth": 90, + "pctReach": 86, + "fame": 88, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000002518b4", + "pageId": 2431156, + "revisionId": 1368504160, + "title": "Organization of the Luftwaffe (1933–1945)", + "type": "Institution", + "subtype": "organisation", + "portal": "Science", + "cost": 6, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "startOfTurn", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + }, + "condition": { + "maxTokens": 2 + } + } + ], + "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", + "flavor": "Structure of German air force", + "connect": { + "countries": [ + "Germany" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q15627509" + ], + "qid": "Q636182", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 89, + "pctDepth": 98, + "pctReach": 67, + "fame": 85, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000006af267", + "pageId": 7008871, + "revisionId": 1382159622, + "title": "Duke Blue Devils football", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "startOfTurn", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + }, + "condition": { + "maxTokens": 2 + } + } + ], + "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", + "flavor": "Football team of Duke University", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 19 + ], + "links": [], + "p31": [ + "Q17156793", + "Q18558301" + ], + "qid": "Q5312733", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 98, + "pctDepth": 98, + "pctReach": 36, + "fame": 77, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000a9306d", + "pageId": 11087981, + "revisionId": 1383233544, + "title": "SREBP cleavage-activating protein", + "type": "Doctrine", + "subtype": "adopt", + "portal": "Science", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 2, + "toughness": 2, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure you control. It gets +2/+2.", + "flavor": "Protein-coding gene in the species Homo sapiens", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q7187" + ], + "qid": "Q14913782", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 42, + "pctDepth": 68, + "pctReach": 36, + "fame": 49, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000e463d7", + "pageId": 14967767, + "revisionId": 1346472302, + "title": "Everton, Nottinghamshire", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Village and civil parish in Nottinghamshire, England", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [], + "links": [], + "p31": [ + "Q1115575", + "Q532" + ], + "qid": "Q5417389", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 50, + "pctDepth": 54, + "pctReach": 63, + "fame": 56, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001625b83", + "pageId": 23223171, + "revisionId": 1351215348, + "title": "Plectania", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 4, + "power": 3, + "toughness": 5, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Genus of fungi", + "connect": { + "countries": [], + "centuries": [ + 19 + ], + "links": [], + "p31": [], + "qid": "Q5235905", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 31, + "pctDepth": 54, + "pctReach": 67, + "fame": 51, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000229b4e9", + "pageId": 36287721, + "revisionId": 1364688814, + "title": "Magheracross", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Townland in County Fermanagh, Northern Ireland", + "connect": { + "countries": [ + "Ireland" + ], + "centuries": [], + "links": [], + "p31": [ + "Q2151232" + ], + "qid": "Q6730410", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 27, + "pctDepth": 59, + "pctReach": 8, + "fame": 31, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003256025", + "pageId": 52781093, + "revisionId": 1360733771, + "title": "SS Iberia (1873)", + "type": "Institution", + "subtype": "other", + "portal": "History", + "cost": 1, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 0, + "condition": { + "maxPower": 2 + } + } + ], + "rulesText": "Figures you control with power 2 or less get +1/+0.", + "flavor": "Steamship by John Elder", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [ + 19 + ], + "links": [], + "p31": [ + "Q12859788" + ], + "qid": "Q28232395", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 27, + "pctDepth": 17, + "pctReach": 8, + "fame": 17, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000004cc4", + "pageId": 19652, + "revisionId": 1382146482, + "title": "Monoid", + "type": "Doctrine", + "subtype": "mathematics", + "portal": "Science", + "cost": 6, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 3, + "toughness": 3, + "duration": "permanent", + "grant": [ + "Well-sourced" + ] + } + ], + "rulesText": "Attach to target Figure you control. It gets +3/+3 and has Well-sourced.", + "flavor": "Algebraic structure with an associative operation and an identity element", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q208237", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "category", + "basis": { + "pctAttention": 97, + "pctDepth": 93, + "pctReach": 98, + "fame": 96, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000004bb672", + "pageId": 4961906, + "revisionId": 1343697567, + "title": "Chinese star maps", + "type": "Doctrine", + "subtype": "adopt", + "portal": "Science", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 3, + "toughness": 3, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure you control. It gets +3/+3.", + "flavor": "Depictions of the positions of stars on the celestial sphere", + "connect": { + "countries": [ + "China" + ], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q16241158", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "category", + "basis": { + "pctAttention": 79, + "pctDepth": 90, + "pctReach": 36, + "fame": 68, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000008b571b", + "pageId": 9131803, + "revisionId": 1351670352, + "title": "Shooting at the 1912 Summer Olympics – Men's 30 metre rapid fire pistol", + "type": "Event", + "subtype": "other", + "portal": "Society", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "draw", + "amount": 2 + } + ], + "rulesText": "Draw two cards.", + "flavor": "Olympic shooting event", + "connect": { + "countries": [], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q18536594" + ], + "qid": "Q7500632", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 31, + "pctDepth": 68, + "pctReach": 58, + "fame": 52, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000b8fc3c", + "pageId": 12123196, + "revisionId": 1362893730, + "title": "Phu Phra Bat Buabok Forest Park", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Forest park in Ban Phue District, Thailand", + "connect": { + "countries": [ + "Thailand" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q13020522" + ], + "qid": "Q250022", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 27, + "pctDepth": 17, + "pctReach": 36, + "fame": 27, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000e67fba", + "pageId": 15105978, + "revisionId": 1384889405, + "title": "Well", + "type": "Doctrine", + "subtype": "mathematics", + "portal": "Science", + "cost": 6, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 3, + "toughness": 3, + "duration": "permanent", + "grant": [ + "Well-sourced" + ] + } + ], + "rulesText": "Attach to target Figure you control. It gets +3/+3 and has Well-sourced.", + "flavor": "Excavation or structure to provide access to groundwater", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q43483", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "description", + "basis": { + "pctAttention": 97, + "pctDepth": 95, + "pctReach": 99, + "fame": 97, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002e39459", + "pageId": 48469081, + "revisionId": 1373109716, + "title": "Dr. John L. Butler House", + "type": "Location", + "subtype": null, + "portal": "History", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Historic house in Arkansas, United States", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q3947" + ], + "qid": "Q24041379", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 3, + "pctDepth": 14, + "pctReach": 8, + "fame": 8, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003f34d76", + "pageId": 66276726, + "revisionId": 1326195763, + "title": "Inaechelys", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 2, + "toughness": 1, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Genus of reptiles", + "connect": { + "countries": [ + "Brazil" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q23038290" + ], + "qid": "Q26700596", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 27, + "pctDepth": 11, + "pctReach": 23, + "fame": 20, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004dba1f0", + "pageId": 81502704, + "revisionId": 1373685251, + "title": "Wenshet", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 3, + "power": 3, + "toughness": 3, + "territory": 0, + "keywords": [], + "effects": [], + "rulesText": "", + "flavor": "", + "connect": { + "countries": [ + "Egypt" + ], + "centuries": [ + 26 + ], + "links": [], + "p31": [], + "qid": "Q2559642", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 35, + "pctDepth": 48, + "pctReach": 53, + "fame": 45, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000020ac39", + "pageId": 2141241, + "revisionId": 1381701379, + "title": "Hvis lyset tar oss", + "type": "Institution", + "subtype": "work", + "portal": "Arts", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "draw", + "amount": 1 + }, + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 1, + "condition": { + "connected": true + } + } + ], + "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", + "flavor": "1994 studio album by Burzum", + "connect": { + "countries": [ + "Norway" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q482994" + ], + "qid": "Q1129211", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 93, + "pctDepth": 48, + "pctReach": 90, + "fame": 77, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000003efcc4", + "pageId": 4127940, + "revisionId": 1376763672, + "title": "Lunugala", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Town in Uva Province, Sri Lanka", + "connect": { + "countries": [ + "Sri Lanka" + ], + "centuries": [], + "links": [], + "p31": [ + "Q486972" + ], + "qid": "Q6704475", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 54, + "pctDepth": 43, + "pctReach": 36, + "fame": 44, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000ec5681", + "pageId": 15488641, + "revisionId": 1384010653, + "title": "Dominique Rodgers-Cromartie", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 6, + "power": 5, + "toughness": 5, + "territory": 0, + "keywords": [ + "Protected", + "Featured" + ], + "effects": [], + "rulesText": "Protected, Featured.", + "flavor": "American football player (born 1986)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q434024", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 94, + "pctDepth": 97, + "pctReach": 58, + "fame": 83, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001774450", + "pageId": 24593488, + "revisionId": 1379665199, + "title": "Žižki", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Place in Prekmurje, Slovenia", + "connect": { + "countries": [ + "Slovenia" + ], + "centuries": [], + "links": [], + "p31": [ + "Q486972" + ], + "qid": "Q280193", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 21, + "pctDepth": 38, + "pctReach": 84, + "fame": 48, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003115e59", + "pageId": 51469913, + "revisionId": 1364729120, + "title": "Beaconsfield Station Sheep Wash", + "type": "Location", + "subtype": null, + "portal": "History", + "cost": 1, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Historic site in Queensland, Australia", + "connect": { + "countries": [ + "Australia" + ], + "centuries": [], + "links": [], + "p31": [ + "Q1081138" + ], + "qid": "Q28035337", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 9, + "pctDepth": 73, + "pctReach": 8, + "fame": 30, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000032f1880", + "pageId": 53418112, + "revisionId": 1383301063, + "title": "2012 United States presidential straw poll in Guam", + "type": "Event", + "subtype": "election", + "portal": "Society", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "createToken", + "amount": 2, + "token": { + "name": "Elected Member", + "power": 1, + "toughness": 1, + "portal": "Society" + } + } + ], + "rulesText": "Create two 1/1 Society Figure tokens named Elected Member.", + "flavor": "", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q858439" + ], + "qid": "Q29097654", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 64, + "pctDepth": 59, + "pctReach": 8, + "fame": 44, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000033fcb23", + "pageId": 54512419, + "revisionId": 1282834290, + "title": "Elephant Square", + "type": "Location", + "subtype": null, + "portal": "Science", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q174782", + "Q1788454" + ], + "qid": "Q39046311", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 64, + "pctDepth": 17, + "pctReach": 23, + "fame": 35, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000387d360", + "pageId": 59233120, + "revisionId": 1316504057, + "title": "Maryland Independent", + "type": "Institution", + "subtype": "work", + "portal": "Neutral", + "cost": 2, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "draw", + "amount": 1 + }, + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 1, + "condition": { + "connected": true + } + } + ], + "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", + "flavor": "Semi-weekly newspaper published in Waldorf, Maryland, US", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 19 + ], + "links": [], + "p31": [ + "Q11032" + ], + "qid": "Q55667255", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 31, + "pctDepth": 54, + "pctReach": 8, + "fame": 31, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004a88b48", + "pageId": 78154568, + "revisionId": 1384643280, + "title": "Lithodes mamillifer", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 1, + "power": 2, + "toughness": 1, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Species of king crab", + "connect": { + "countries": [ + "India" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q13768243", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 9, + "pctDepth": 4, + "pctReach": 23, + "fame": 12, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000002061e", + "pageId": 132638, + "revisionId": 1375881246, + "title": "Perry Township, Greene County, Pennsylvania", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Township in Pennsylvania, US", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q9035798" + ], + "qid": "Q5809786", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 42, + "pctDepth": 59, + "pctReach": 63, + "fame": 55, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000000d1815", + "pageId": 858133, + "revisionId": 1261572264, + "title": "Ashley (automobile)", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "startOfTurn", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + }, + "condition": { + "maxTokens": 2 + } + } + ], + "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", + "flavor": "British manufacturers of car body shells & chassis for specials (1955-1962)", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q786820" + ], + "qid": "Q725930", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 66, + "pctDepth": 54, + "pctReach": 36, + "fame": 52, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000010c9c6d", + "pageId": 17603693, + "revisionId": 1339376467, + "title": "Bad Little Angel", + "type": "Institution", + "subtype": "work", + "portal": "Arts", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "draw", + "amount": 1 + }, + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 1, + "condition": { + "connected": true + } + } + ], + "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", + "flavor": "1939 film by Wilhelm Thiele", + "connect": { + "countries": [ + "United Kingdom", + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q11424" + ], + "qid": "Q2483475", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 66, + "pctDepth": 23, + "pctReach": 36, + "fame": 42, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000015e910f", + "pageId": 22974735, + "revisionId": 1374856654, + "title": "Christianity in the 5th century", + "type": "Event", + "subtype": "other", + "portal": "Neutral", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "draw", + "amount": 3 + } + ], + "rulesText": "Draw three cards.", + "flavor": "", + "connect": { + "countries": [], + "centuries": [ + 5 + ], + "links": [], + "p31": [ + "Q18340514" + ], + "qid": "Q5110603", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 79, + "pctDepth": 94, + "pctReach": 36, + "fame": 70, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000018c3734", + "pageId": 25966388, + "revisionId": 1329232874, + "title": "Phacelia quickii", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 1, + "toughness": 2, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Species of plant", + "connect": { + "countries": [ + "United States" + ], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q7179927", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 3, + "pctDepth": 11, + "pctReach": 47, + "fame": 20, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002217317", + "pageId": 35746583, + "revisionId": 1346095921, + "title": "Barbajada", + "type": "Doctrine", + "subtype": "adopt", + "portal": "Society", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 2, + "toughness": 2, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure you control. It gets +2/+2.", + "flavor": "Italian chocolate coffee drink", + "connect": { + "countries": [ + "Italy" + ], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q3634571", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "category", + "basis": { + "pctAttention": 74, + "pctDepth": 17, + "pctReach": 58, + "fame": 50, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000023d5c96", + "pageId": 37575830, + "revisionId": 1385253370, + "title": "Özkan Yıldırım", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 4, + "power": 2, + "toughness": 5, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "German footballer", + "connect": { + "countries": [ + "Germany", + "Turkey" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q1152151", + "cites": [] + }, + "rarity": "Legendary", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 24, + "pctDepth": 54, + "pctReach": 74, + "fame": 51, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003d66226", + "pageId": 64381478, + "revisionId": 1381097840, + "title": "Denis Zabolotin", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 1, + "power": 1, + "toughness": 1, + "territory": 0, + "keywords": [ + "Protected", + "Stub" + ], + "effects": [], + "rulesText": "Protected, Stub.", + "flavor": "Russian handball player", + "connect": { + "countries": [ + "Russia" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q96644151", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 21, + "pctDepth": 14, + "pctReach": 36, + "fame": 24, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003eadb6d", + "pageId": 65723245, + "revisionId": 1380335385, + "title": "Russell A. Sanborn", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 3, + "power": 2, + "toughness": 3, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "U.S. Marine major general", + "connect": { + "countries": [ + "United States" + ], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q29852979", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 54, + "pctDepth": 73, + "pctReach": 23, + "fame": 50, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004e3418c", + "pageId": 82002316, + "revisionId": 1357961360, + "title": "Taupo Totara Timber Company", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + } + } + ], + "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", + "flavor": "New Zealand timber and building supplies company", + "connect": { + "countries": [ + "New Zealand" + ], + "centuries": [], + "links": [], + "p31": [ + "Q783794" + ], + "qid": "Q138001385", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 42, + "pctDepth": 90, + "pctReach": 8, + "fame": 47, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000129da3", + "pageId": 1220003, + "revisionId": 1381976644, + "title": "Robert Hawthorne", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 4, + "power": 3, + "toughness": 4, + "territory": 0, + "keywords": [ + "Legacy", + "Local" + ], + "effects": [], + "rulesText": "Legacy, Local.", + "flavor": "Recipient of the Victoria Cross", + "connect": { + "countries": [ + "India", + "Ireland", + "United Kingdom" + ], + "centuries": [ + 19 + ], + "links": [], + "p31": [], + "qid": "Q3681767", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 76, + "pctDepth": 77, + "pctReach": 8, + "fame": 54, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000134dd65", + "pageId": 20241765, + "revisionId": 1362148473, + "title": "Imre Szöllősi", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 3, + "power": 1, + "toughness": 4, + "territory": 0, + "keywords": [ + "Legacy", + "Translated" + ], + "effects": [], + "rulesText": "Legacy, Translated.", + "flavor": "Hungarian canoeist (1941–2022)", + "connect": { + "countries": [ + "Hungary" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q6008352", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 11, + "pctDepth": 33, + "pctReach": 82, + "fame": 42, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000182777d", + "pageId": 25327485, + "revisionId": 1378155021, + "title": "Marc Fesneau", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 5, + "power": 5, + "toughness": 4, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "French politician (born 1971)", + "connect": { + "countries": [ + "France" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q6755549", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 76, + "pctDepth": 68, + "pctReach": 63, + "fame": 69, + "magnitude": 3 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000279e59b", + "pageId": 41543067, + "revisionId": 1381927878, + "title": "Arms and the Girl", + "type": "Institution", + "subtype": "work", + "portal": "Arts", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "draw", + "amount": 1 + }, + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 1, + "condition": { + "connected": true + } + } + ], + "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", + "flavor": "1917 American silent film", + "connect": { + "countries": [ + "Belgium", + "United Kingdom", + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q11424" + ], + "qid": "Q16248487", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 47, + "pctDepth": 43, + "pctReach": 53, + "fame": 48, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000027f963c", + "pageId": 41915964, + "revisionId": 1308018675, + "title": "Taylor County Historical Society", + "type": "Institution", + "subtype": "organisation", + "portal": "History", + "cost": 1, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + } + } + ], + "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", + "flavor": "Non-profit organization in Florida, US", + "connect": { + "countries": [], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q5774403" + ], + "qid": "Q16966311", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 14, + "pctDepth": 23, + "pctReach": 8, + "fame": 15, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000028399d2", + "pageId": 42179026, + "revisionId": 1373475086, + "title": "Dojikko", + "type": "Figure", + "subtype": null, + "portal": "Arts", + "cost": 4, + "power": 6, + "toughness": 2, + "territory": 0, + "keywords": [ + "Translated", + "Stub" + ], + "effects": [], + "rulesText": "Translated, Stub.", + "flavor": "Extremely clumsy female character in anime and manga", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q636497" + ], + "qid": "Q164896", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 83, + "pctDepth": 23, + "pctReach": 80, + "fame": 62, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000033104b5", + "pageId": 53544117, + "revisionId": 1371197205, + "title": "Jünkerath station", + "type": "Location", + "subtype": null, + "portal": "Neutral", + "cost": 2, + "power": 0, + "toughness": 4, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/4.", + "flavor": "Railway station in Jünkerath, Germany", + "connect": { + "countries": [ + "Germany" + ], + "centuries": [ + 19 + ], + "links": [], + "p31": [ + "Q55488" + ], + "qid": "Q23924993", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 17, + "pctDepth": 77, + "pctReach": 23, + "fame": 39, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000391b393", + "pageId": 59880339, + "revisionId": 1382490836, + "title": "United Artists Releasing", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "startOfTurn", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + }, + "condition": { + "maxTokens": 2 + } + } + ], + "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", + "flavor": "Film distribution successor to United Artists", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q783794" + ], + "qid": "Q119348733", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 93, + "pctDepth": 92, + "pctReach": 47, + "fame": 77, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004a1ebca", + "pageId": 77720522, + "revisionId": 1380422871, + "title": "Hungarian Giant Pigeon", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 4, + "toughness": 2, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q15623573" + ], + "qid": "Q12815231", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 69, + "pctDepth": 33, + "pctReach": 47, + "fame": 50, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004da4001", + "pageId": 81412097, + "revisionId": 1380568254, + "title": "Iona Moir", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 5, + "power": 4, + "toughness": 5, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "British track cyclist", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [], + "qid": "Q130078456", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 58, + "pctDepth": 64, + "pctReach": 67, + "fame": 63, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000005057304", + "pageId": 84243204, + "revisionId": 1375287029, + "title": "Figueiredo (Guimarães)", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Extinct parish in Guimarães, Portugal", + "connect": { + "countries": [ + "Portugal" + ], + "centuries": [], + "links": [], + "p31": [ + "Q56046844" + ], + "qid": "Q1023176", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 1, + "pctDepth": 33, + "pctReach": 78, + "fame": 37, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000000155c7", + "pageId": 87495, + "revisionId": 1375332586, + "title": "Kusilvak Census Area, Alaska", + "type": "Location", + "subtype": null, + "portal": "Neutral", + "cost": 3, + "power": 0, + "toughness": 4, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/4.", + "flavor": "Census area in Alaska, United States", + "connect": { + "countries": [ + "United States" + ], + "centuries": [], + "links": [], + "p31": [ + "Q56064719" + ], + "qid": "Q379474", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 85, + "pctDepth": 86, + "pctReach": 93, + "fame": 88, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000365525", + "pageId": 3560741, + "revisionId": 1372647813, + "title": "Martin Taylor (businessman)", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 4, + "power": 4, + "toughness": 3, + "territory": 0, + "keywords": [ + "Protected", + "Stub" + ], + "effects": [], + "rulesText": "Protected, Stub.", + "flavor": "British businessman (born 1952)", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q6776725", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 74, + "pctDepth": 48, + "pctReach": 47, + "fame": 56, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000051e94e", + "pageId": 5368142, + "revisionId": 1385081865, + "title": "Brass Mill Center", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Shopping mall in Connecticut, United States", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q11315" + ], + "qid": "Q4957871", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 76, + "pctDepth": 59, + "pctReach": 8, + "fame": 48, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001e1c7a2", + "pageId": 31573922, + "revisionId": 1364585710, + "title": "Vincenza Sicari", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 4, + "power": 2, + "toughness": 5, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "Italian long-distance runner (born 1979)", + "connect": { + "countries": [ + "Italy" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q2526833", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 21, + "pctDepth": 73, + "pctReach": 58, + "fame": 51, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000211993c", + "pageId": 34707772, + "revisionId": 1376437554, + "title": "Arnold I of Egmond", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 2, + "power": 2, + "toughness": 1, + "territory": 0, + "keywords": [ + "Legacy", + "Stub" + ], + "effects": [], + "rulesText": "Legacy, Stub.", + "flavor": "", + "connect": { + "countries": [ + "Netherlands" + ], + "centuries": [ + 14, + 15 + ], + "links": [], + "p31": [], + "qid": "Q1920891", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 35, + "pctDepth": 23, + "pctReach": 53, + "fame": 37, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000031e8b4a", + "pageId": 52333386, + "revisionId": 1373477524, + "title": "Lewis and Elizabeth Bolton House", + "type": "Location", + "subtype": null, + "portal": "History", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Historic house in Missouri, United States", + "connect": { + "countries": [ + "Greece", + "United States" + ], + "centuries": [ + 19 + ], + "links": [], + "p31": [ + "Q1307276" + ], + "qid": "Q28007838", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 24, + "pctDepth": 11, + "pctReach": 8, + "fame": 14, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000347e0d", + "pageId": 3440141, + "revisionId": 1384669473, + "title": "Belgium at the 1948 Summer Olympics", + "type": "Event", + "subtype": "other", + "portal": "Society", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "draw", + "amount": 2 + } + ], + "rulesText": "Draw two cards.", + "flavor": "Sporting event delegation", + "connect": { + "countries": [ + "Belgium" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q26213387" + ], + "qid": "Q592430", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 24, + "pctDepth": 64, + "pctReach": 85, + "fame": 58, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000042c0a6", + "pageId": 4374694, + "revisionId": 1384632958, + "title": "National Register of Historic Places listings in Yates County, New York", + "type": "Doctrine", + "subtype": "mathematics", + "portal": "Earth", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 2, + "toughness": 2, + "duration": "permanent", + "grant": [ + "Well-sourced" + ] + } + ], + "rulesText": "Attach to target Figure you control. It gets +2/+2 and has Well-sourced.", + "flavor": "", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q13406463" + ], + "qid": "Q6977936", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 31, + "pctDepth": 89, + "pctReach": 23, + "fame": 48, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000e62c56", + "pageId": 15084630, + "revisionId": 1340554441, + "title": "Uremic frost", + "type": "Doctrine", + "subtype": "pathology", + "portal": "Science", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "figure", + "power": -2, + "toughness": -2, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure. It gets −2/−2.", + "flavor": "Crystallized urea deposits on skin", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q1441305" + ], + "qid": "Q18395101", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 86, + "pctDepth": 23, + "pctReach": 36, + "fame": 48, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000f4bc30", + "pageId": 16038960, + "revisionId": 1381994388, + "title": "La Chapelle-Palluau", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Commune in Pays de la Loire, France", + "connect": { + "countries": [ + "France" + ], + "centuries": [], + "links": [], + "p31": [ + "Q484170" + ], + "qid": "Q675088", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 0, + "pctDepth": 7, + "pctReach": 95, + "fame": 34, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001334c0c", + "pageId": 20139020, + "revisionId": 1307118821, + "title": "Samuel Yeatman", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 1, + "power": 1, + "toughness": 1, + "territory": 0, + "keywords": [ + "Legacy", + "Stub" + ], + "effects": [], + "rulesText": "Legacy, Stub.", + "flavor": "American baseball player (1839–1901)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q4911449", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 1, + "pctDepth": 14, + "pctReach": 23, + "fame": 13, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001b5f940", + "pageId": 28703040, + "revisionId": 1366016093, + "title": "Suðurey", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Island in Iceland", + "connect": { + "countries": [ + "Iceland" + ], + "centuries": [], + "links": [], + "p31": [ + "Q23442" + ], + "qid": "Q3115506", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 42, + "pctDepth": 0, + "pctReach": 67, + "fame": 36, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002aa485f", + "pageId": 44714079, + "revisionId": 1364832308, + "title": "Île-de-France tramway Line 6", + "type": "Institution", + "subtype": "other", + "portal": "Neutral", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 0, + "condition": { + "maxPower": 2 + } + } + ], + "rulesText": "Figures you control with power 2 or less get +1/+0.", + "flavor": "Suburban tram line in Hauts-de-Seine and Yvelines, southwest of Paris", + "connect": { + "countries": [ + "France" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q15145593", + "Q385653" + ], + "qid": "Q3238993", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 69, + "pctDepth": 28, + "pctReach": 74, + "fame": 57, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000004d774c", + "pageId": 5076812, + "revisionId": 1373793952, + "title": "Free-Stater (Kansas)", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "startOfTurn", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + }, + "condition": { + "maxTokens": 2 + } + } + ], + "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", + "flavor": "Anti-Slavery organization", + "connect": { + "countries": [ + "United States" + ], + "centuries": [], + "links": [], + "p31": [ + "Q15911314" + ], + "qid": "Q5499603", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 83, + "pctDepth": 48, + "pctReach": 23, + "fame": 51, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000008223bb", + "pageId": 8528827, + "revisionId": 1379603420, + "title": "Llandarcy Oil Refinery", + "type": "Location", + "subtype": null, + "portal": "Science", + "cost": 2, + "power": 0, + "toughness": 4, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/4.", + "flavor": "Former oil refinery in Neath Port Talbot, Wales", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [ + "Q12353044" + ], + "qid": "Q27957412", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 71, + "pctDepth": 77, + "pctReach": 8, + "fame": 52, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000ea3205", + "pageId": 15348229, + "revisionId": 1367445085, + "title": "Diocese of Mindelo", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 2, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + } + } + ], + "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", + "flavor": "Roman Catholic diocese in Cape Verde", + "connect": { + "countries": [], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q2665272", + "Q3146899" + ], + "qid": "Q872428", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 17, + "pctDepth": 17, + "pctReach": 81, + "fame": 38, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000edde01", + "pageId": 15588865, + "revisionId": 1381802984, + "title": "Bonnevaux-le-Prieuré", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Part of Ornans in Bourgogne-Franche-Comté, France", + "connect": { + "countries": [ + "France" + ], + "centuries": [], + "links": [], + "p31": [ + "Q21869758", + "Q484170" + ], + "qid": "Q837744", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 6, + "pctDepth": 4, + "pctReach": 91, + "fame": 34, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000010609ef", + "pageId": 17172975, + "revisionId": 1378041962, + "title": "Bukama", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Place in Haut-Lomami, Democratic Republic of the Congo", + "connect": { + "countries": [ + "Congo" + ], + "centuries": [], + "links": [], + "p31": [ + "Q515" + ], + "qid": "Q2915071", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 64, + "pctDepth": 54, + "pctReach": 84, + "fame": 67, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001639bbc", + "pageId": 23305148, + "revisionId": 1377045846, + "title": "Agios Isidoros, Cyprus", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Place in Paphos District, Cyprus", + "connect": { + "countries": [ + "Cyprus" + ], + "centuries": [], + "links": [], + "p31": [ + "Q29414133" + ], + "qid": "Q4831291", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 11, + "pctDepth": 28, + "pctReach": 74, + "fame": 38, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000025124c9", + "pageId": 38872265, + "revisionId": 1370478726, + "title": "Ethel Post-Parrish", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 2, + "power": 2, + "toughness": 1, + "territory": 0, + "keywords": [ + "Legacy", + "Stub" + ], + "effects": [], + "rulesText": "Legacy, Stub.", + "flavor": "American Spiritualist medium (died 1960)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q15999505", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 47, + "pctDepth": 23, + "pctReach": 8, + "fame": 26, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003c6d80f", + "pageId": 63363087, + "revisionId": 1385804220, + "title": "Keyontae Johnson", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 6, + "power": 5, + "toughness": 5, + "territory": 0, + "keywords": [ + "Protected", + "Featured" + ], + "effects": [], + "rulesText": "Protected, Featured.", + "flavor": "American basketball player (born 2000)", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q88963854", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 90, + "pctDepth": 86, + "pctReach": 63, + "fame": 80, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004606820", + "pageId": 73426976, + "revisionId": 1379304890, + "title": "Viniče", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Village in Skopje, North Macedonia", + "connect": { + "countries": [ + "North Macedonia" + ], + "centuries": [], + "links": [], + "p31": [ + "Q532" + ], + "qid": "Q3560281", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 6, + "pctDepth": 43, + "pctReach": 53, + "fame": 34, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000000e1834", + "pageId": 923700, + "revisionId": 1382030380, + "title": "Sainte-Foy-lès-Lyon", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Commune in Auvergne-Rhône-Alpes, France", + "connect": { + "countries": [ + "France" + ], + "centuries": [], + "links": [], + "p31": [ + "Q484170" + ], + "qid": "Q387460", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 71, + "pctDepth": 38, + "pctReach": 97, + "fame": 69, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000003487d1", + "pageId": 3442641, + "revisionId": 1372311773, + "title": "Tidewater Provincial Park", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Provincial park in Ontario, Canada", + "connect": { + "countries": [ + "Canada" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q2006279" + ], + "qid": "Q7800881", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 42, + "pctDepth": 23, + "pctReach": 36, + "fame": 34, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000004563e8", + "pageId": 4547560, + "revisionId": 1333227991, + "title": "Tracheal collapse", + "type": "Doctrine", + "subtype": "pathology", + "portal": "Science", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "figure", + "power": -2, + "toughness": -2, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure. It gets −2/−2.", + "flavor": "Flattening of the trachea in animals", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q140427225" + ], + "qid": "Q2447482", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 81, + "pctDepth": 38, + "pctReach": 53, + "fame": 57, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000d2549d", + "pageId": 13784221, + "revisionId": 1362220356, + "title": "Ellenborough Falls", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Waterfall on the Ellenborough River in New South Wales, Australia", + "connect": { + "countries": [ + "Australia", + "United Kingdom" + ], + "centuries": [], + "links": [], + "p31": [ + "Q34038" + ], + "qid": "Q3652636", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 64, + "pctDepth": 17, + "pctReach": 63, + "fame": 48, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001fe7b62", + "pageId": 33454946, + "revisionId": 1270324661, + "title": "Tydeus Painter", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 1, + "power": 2, + "toughness": 1, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Ancient Greek vase painter", + "connect": { + "countries": [ + "Greece" + ], + "centuries": [], + "links": [], + "p31": [ + "Q1747829" + ], + "qid": "Q2462577", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 14, + "pctDepth": 7, + "pctReach": 47, + "fame": 23, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002b548f0", + "pageId": 45435120, + "revisionId": 1384697951, + "title": "Yemọja", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 6, + "power": 6, + "toughness": 5, + "territory": 0, + "keywords": [ + "Featured", + "Translated" + ], + "effects": [], + "rulesText": "Featured, Translated.", + "flavor": "Major water Orisha in the Yoruba religion", + "connect": { + "countries": [ + "Brazil" + ], + "centuries": [], + "links": [], + "p31": [ + "Q1916821", + "Q290460", + "Q752920" + ], + "qid": "Q1477162", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 96, + "pctDepth": 86, + "pctReach": 89, + "fame": 90, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000047e7091", + "pageId": 75395217, + "revisionId": 1378415983, + "title": "Hetifah Sjaifudian", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 4, + "power": 3, + "toughness": 4, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "Indonesian activist and politician", + "connect": { + "countries": [ + "Indonesia", + "Singapore" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q96988706", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 47, + "pctDepth": 77, + "pctReach": 36, + "fame": 53, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000002f764e", + "pageId": 3110478, + "revisionId": 1376600347, + "title": "Laukhella", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Village in Senja Municipality, Norway", + "connect": { + "countries": [ + "Norway" + ], + "centuries": [], + "links": [], + "p31": [ + "Q486972" + ], + "qid": "Q3218620", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 11, + "pctDepth": 23, + "pctReach": 53, + "fame": 29, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000768587", + "pageId": 7767431, + "revisionId": 1313900503, + "title": "Bufo stuarti", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 2, + "toughness": 1, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Species of amphibian", + "connect": { + "countries": [ + "India" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q28032720", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 2, + "pctDepth": 0, + "pctReach": 74, + "fame": 25, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000e314ca", + "pageId": 14881994, + "revisionId": 1377922091, + "title": "OR56B4", + "type": "Doctrine", + "subtype": "adopt", + "portal": "Science", + "cost": 1, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 1, + "toughness": 1, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure you control. It gets +1/+1.", + "flavor": "Protein-coding gene in the species Homo sapiens", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q7187" + ], + "qid": "Q18053061", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 11, + "pctDepth": 7, + "pctReach": 58, + "fame": 25, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001e25f63", + "pageId": 31612771, + "revisionId": 1364804505, + "title": "David Cullinane", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 4, + "power": 4, + "toughness": 3, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "Irish politician (born 1974)", + "connect": { + "countries": [ + "Ireland" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q5232711", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 81, + "pctDepth": 68, + "pctReach": 36, + "fame": 62, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002004071", + "pageId": 33570929, + "revisionId": 1374508115, + "title": "Grumbach (Werra)", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "River in Thuringia, Germany", + "connect": { + "countries": [ + "Germany" + ], + "centuries": [], + "links": [], + "p31": [ + "Q4022" + ], + "qid": "Q826448", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 2, + "pctDepth": 2, + "pctReach": 47, + "fame": 17, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002469bab", + "pageId": 38181803, + "revisionId": 1378220985, + "title": "Gábor Scheiring", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 3, + "power": 3, + "toughness": 2, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "Hungarian economist and politician", + "connect": { + "countries": [ + "Hungary" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q5625769", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 42, + "pctDepth": 38, + "pctReach": 47, + "fame": 42, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000030834b6", + "pageId": 50869430, + "revisionId": 1359436538, + "title": "Felt, Not Heard", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 1, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + } + } + ], + "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", + "flavor": "", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q1589009" + ], + "qid": "Q24885448", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 11, + "pctDepth": 17, + "pctReach": 8, + "fame": 12, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000036b0861", + "pageId": 57346145, + "revisionId": 1352289182, + "title": "Madura perfida", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 1, + "toughness": 2, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Species of true bug", + "connect": { + "countries": [], + "centuries": [ + 19 + ], + "links": [], + "p31": [], + "qid": "Q10575176", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 1, + "pctDepth": 7, + "pctReach": 47, + "fame": 18, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000000c07c1", + "pageId": 788417, + "revisionId": 1385635902, + "title": "Efrat (Israeli settlement)", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 6, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "startOfTurn", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + }, + "condition": { + "maxTokens": 2 + } + } + ], + "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", + "flavor": "Israeli settlement in the West Bank", + "connect": { + "countries": [ + "Israel" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q1288520", + "Q582706", + "Q618123" + ], + "qid": "Q64053", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 89, + "pctDepth": 86, + "pctReach": 86, + "fame": 87, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000314a5b", + "pageId": 3230299, + "revisionId": 1368444919, + "title": "St. George's Island, Bermuda", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "One of the principal islands of Bermuda", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q23442" + ], + "qid": "Q1813379", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 76, + "pctDepth": 43, + "pctReach": 74, + "fame": 64, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000006ec6df", + "pageId": 7259871, + "revisionId": 1356897889, + "title": "National Association of Television Program Executives", + "type": "Institution", + "subtype": "organisation", + "portal": "Arts", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + } + } + ], + "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", + "flavor": "", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [ + "Q163740" + ], + "qid": "Q6970789", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 58, + "pctDepth": 48, + "pctReach": 36, + "fame": 47, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000021aa8db", + "pageId": 35301595, + "revisionId": 1357984673, + "title": "Schläfli double six", + "type": "Doctrine", + "subtype": "mathematics", + "portal": "Science", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 2, + "toughness": 2, + "duration": "permanent", + "grant": [ + "Well-sourced" + ] + } + ], + "rulesText": "Attach to target Figure you control. It gets +2/+2 and has Well-sourced.", + "flavor": "Arrangement of 30 points and 12 lines", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q24034552" + ], + "qid": "Q7431763", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 58, + "pctDepth": 54, + "pctReach": 36, + "fame": 49, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000234c209", + "pageId": 37011977, + "revisionId": 1339741732, + "title": "San Michele Arcangelo, Naples", + "type": "Location", + "subtype": null, + "portal": "Society", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Church in Naples, Italy", + "connect": { + "countries": [ + "Italy" + ], + "centuries": [ + 17 + ], + "links": [], + "p31": [ + "Q16970" + ], + "qid": "Q718623", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 14, + "pctDepth": 7, + "pctReach": 67, + "fame": 29, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000249a814", + "pageId": 38381588, + "revisionId": 1366241182, + "title": "A. R. Poduval", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 2, + "power": 1, + "toughness": 2, + "territory": 0, + "keywords": [ + "Legacy", + "Local" + ], + "effects": [], + "rulesText": "Legacy, Local.", + "flavor": "Indian surgeon and artist", + "connect": { + "countries": [ + "Germany", + "India", + "United Kingdom" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q4648301", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 24, + "pctDepth": 59, + "pctReach": 8, + "fame": 30, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002c76795", + "pageId": 46622613, + "revisionId": 1378272694, + "title": "Sarah Hoffman", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 5, + "power": 5, + "toughness": 4, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "Canadian politician (born 1980)", + "connect": { + "countries": [ + "Canada" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q19862161", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 80, + "pctDepth": 73, + "pctReach": 36, + "fame": 63, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000048da231", + "pageId": 76390961, + "revisionId": 1385442003, + "title": "2024–2026 Cuban protests", + "type": "Event", + "subtype": "conflict", + "portal": "Society", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "damage", + "target": "figureOrLocation", + "amount": 4 + } + ], + "rulesText": "Deal 4 damage to target Figure or Location.", + "flavor": "Protests against the Cuban government", + "connect": { + "countries": [ + "Cuba" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q273120" + ], + "qid": "Q125000393", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 82, + "pctDepth": 89, + "pctReach": 58, + "fame": 76, + "magnitude": 3 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000070b485", + "pageId": 7386245, + "revisionId": 1385017105, + "title": "The Leslie Uggams Show", + "type": "Institution", + "subtype": "work", + "portal": "Arts", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "draw", + "amount": 1 + }, + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 1, + "condition": { + "connected": true + } + } + ], + "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", + "flavor": "1969 American TV series or program", + "connect": { + "countries": [ + "United Kingdom", + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q5398426" + ], + "qid": "Q7746967", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 69, + "pctDepth": 59, + "pctReach": 8, + "fame": 45, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000be57a1", + "pageId": 12474273, + "revisionId": 1380009301, + "title": "Iphis monarch", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 4, + "toughness": 2, + "territory": 0, + "keywords": [ + "Translated", + "Stub" + ], + "effects": [], + "rulesText": "Translated, Stub.", + "flavor": "Species of bird", + "connect": { + "countries": [ + "France" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q692954", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 47, + "pctDepth": 17, + "pctReach": 87, + "fame": 50, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001289a8f", + "pageId": 19438223, + "revisionId": 1366832481, + "title": "Friedrich Kasimir Medikus", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 3, + "power": 4, + "toughness": 1, + "territory": 0, + "keywords": [ + "Legacy", + "Translated" + ], + "effects": [], + "rulesText": "Legacy, Translated.", + "flavor": "German physician and botanist", + "connect": { + "countries": [ + "Germany" + ], + "centuries": [ + 18, + 19 + ], + "links": [], + "p31": [], + "qid": "Q77464", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 42, + "pctDepth": 0, + "pctReach": 89, + "fame": 44, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002636619", + "pageId": 40068633, + "revisionId": 1362680935, + "title": "Wahconah Falls State Park", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Massachusetts state park", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q37998360" + ], + "qid": "Q14715969", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 27, + "pctDepth": 28, + "pctReach": 23, + "fame": 26, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004db234b", + "pageId": 81470283, + "revisionId": 1384453410, + "title": "Presidential Anti-Organized Crime Commission", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "startOfTurn", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + }, + "condition": { + "maxTokens": 2 + } + } + ], + "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", + "flavor": "Government agency in the Philippines", + "connect": { + "countries": [ + "Philippines" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q327333" + ], + "qid": "Q136773957", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 71, + "pctDepth": 92, + "pctReach": 8, + "fame": 57, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004f1c0b9", + "pageId": 82952377, + "revisionId": 1377598668, + "title": "Lichen community", + "type": "Doctrine", + "subtype": "adopt", + "portal": "Earth", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 2, + "toughness": 2, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure you control. It gets +2/+2.", + "flavor": "Recurring assemblage of lichen species and its classification in vegetation science", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q105442186", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "category", + "basis": { + "pctAttention": 35, + "pctDepth": 95, + "pctReach": 8, + "fame": 46, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000017f942", + "pageId": 1571138, + "revisionId": 1367893707, + "title": "Ranks and insignia of the Nazi Party", + "type": "Doctrine", + "subtype": "adopt", + "portal": "Society", + "cost": 6, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 3, + "toughness": 3, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure you control. It gets +3/+3.", + "flavor": "", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q13424724", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "category", + "basis": { + "pctAttention": 96, + "pctDepth": 95, + "pctReach": 58, + "fame": 83, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001447617", + "pageId": 21263895, + "revisionId": 1377108521, + "title": "Przybędza", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Village in Silesian Voivodeship, Poland", + "connect": { + "countries": [ + "Poland" + ], + "centuries": [], + "links": [], + "p31": [ + "Q3558970" + ], + "qid": "Q7253590", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 2, + "pctDepth": 2, + "pctReach": 71, + "fame": 25, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001b2dc67", + "pageId": 28499047, + "revisionId": 1346615028, + "title": "Wu Songgao", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 2, + "power": 1, + "toughness": 2, + "territory": 0, + "keywords": [ + "Legacy" + ], + "effects": [], + "rulesText": "Legacy.", + "flavor": "", + "connect": { + "countries": [ + "China", + "Japan" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q5970557", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 31, + "pctDepth": 48, + "pctReach": 36, + "fame": 38, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001c3e576", + "pageId": 29615478, + "revisionId": 1359695857, + "title": "Rustan's", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "startOfTurn", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + }, + "condition": { + "maxTokens": 2 + } + } + ], + "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", + "flavor": "Philippine department store chain", + "connect": { + "countries": [ + "Philippines" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q4830453" + ], + "qid": "Q7382454", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 85, + "pctDepth": 83, + "pctReach": 23, + "fame": 64, + "magnitude": 3 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000025e3602", + "pageId": 39728642, + "revisionId": 1373482944, + "title": "Wilkeson Arch", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "United States historic place", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q2860026" + ], + "qid": "Q14713945", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 9, + "pctDepth": 28, + "pctReach": 8, + "fame": 15, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002b69213", + "pageId": 45519379, + "revisionId": 1290644518, + "title": "Maine State Route 144", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "State highway in Lincoln County, Maine, US", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q1788582" + ], + "qid": "Q19581200", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 6, + "pctDepth": 54, + "pctReach": 23, + "fame": 28, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003105e51", + "pageId": 51404369, + "revisionId": 1320623670, + "title": "Luis María Kreckler", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 2, + "power": 1, + "toughness": 2, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "", + "connect": { + "countries": [ + "Argentina", + "Brazil", + "China", + "Germany" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q5983869", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 35, + "pctDepth": 43, + "pctReach": 23, + "fame": 34, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000036c4579", + "pageId": 57427321, + "revisionId": 1372620649, + "title": "Corruption in Kazakhstan", + "type": "Doctrine", + "subtype": "adopt", + "portal": "Society", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 3, + "toughness": 3, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure you control. It gets +3/+3.", + "flavor": "", + "connect": { + "countries": [ + "Kazakhstan" + ], + "centuries": [], + "links": [], + "p31": [ + "Q74817647" + ], + "qid": "Q12981954", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 71, + "pctDepth": 68, + "pctReach": 67, + "fame": 69, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003924b7e", + "pageId": 59919230, + "revisionId": 1365794761, + "title": "Trey Rhodes", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 2, + "power": 2, + "toughness": 1, + "territory": 0, + "keywords": [ + "Protected", + "Stub" + ], + "effects": [], + "rulesText": "Protected, Stub.", + "flavor": "American politician", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q61685757", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 58, + "pctDepth": 14, + "pctReach": 8, + "fame": 27, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000508b134", + "pageId": 84455732, + "revisionId": 1379905236, + "title": "Streetsia challengeri", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 4, + "toughness": 2, + "territory": 0, + "keywords": [ + "Stub" + ], + "effects": [], + "rulesText": "Stub.", + "flavor": "Species of marine amphipod", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q4471202", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 50, + "pctDepth": 23, + "pctReach": 53, + "fame": 42, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000000c16a", + "pageId": 49514, + "revisionId": 1372005331, + "title": "Henri Lebesgue", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 6, + "power": 5, + "toughness": 5, + "territory": 0, + "keywords": [ + "Featured", + "Legacy" + ], + "effects": [], + "rulesText": "Featured, Legacy.", + "flavor": "French mathematician (1875–1941)", + "connect": { + "countries": [ + "France" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q206005", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 90, + "pctDepth": 86, + "pctReach": 97, + "fame": 91, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000e13cb0", + "pageId": 14761136, + "revisionId": 1383624184, + "title": "RBMX", + "type": "Doctrine", + "subtype": "adopt", + "portal": "Science", + "cost": 2, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "attach", + "target": "ownFigure", + "power": 1, + "toughness": 1, + "duration": "permanent" + } + ], + "rulesText": "Attach to target Figure you control. It gets +1/+1.", + "flavor": "Protein-coding gene in humans", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q7187" + ], + "qid": "Q18038778", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 27, + "pctDepth": 64, + "pctReach": 23, + "fame": 38, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000044ec330", + "pageId": 72270640, + "revisionId": 1375465027, + "title": "Chaharbagh County", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "County in Alborz province, Iran", + "connect": { + "countries": [ + "Iran" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q137535" + ], + "qid": "Q107333581", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 38, + "pctDepth": 64, + "pctReach": 58, + "fame": 53, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000047b26e9", + "pageId": 75179753, + "revisionId": 1272327430, + "title": "2016 Queensland local elections", + "type": "Event", + "subtype": "election", + "portal": "Society", + "cost": 2, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "createToken", + "amount": 1, + "token": { + "name": "Elected Member", + "power": 1, + "toughness": 1, + "portal": "Society" + } + } + ], + "rulesText": "Create a 1/1 Society Figure token named Elected Member.", + "flavor": "", + "connect": { + "countries": [ + "Australia" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q15966540" + ], + "qid": "Q115228225", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 21, + "pctDepth": 48, + "pctReach": 8, + "fame": 26, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004bbd0ce", + "pageId": 79417550, + "revisionId": 1377659696, + "title": "Region Östergötland", + "type": "Institution", + "subtype": "organisation", + "portal": "Society", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + } + } + ], + "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", + "flavor": "Regional council of Östergötland County, Sweden", + "connect": { + "countries": [ + "Sweden" + ], + "centuries": [], + "links": [], + "p31": [ + "Q1754161", + "Q65196511", + "Q85164347" + ], + "qid": "Q3231915", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 58, + "pctDepth": 38, + "pctReach": 47, + "fame": 48, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000004fb7786", + "pageId": 83588998, + "revisionId": 1380888360, + "title": "Kamil Oniszczuk", + "type": "Figure", + "subtype": null, + "portal": "Society", + "cost": 4, + "power": 3, + "toughness": 4, + "territory": 0, + "keywords": [ + "Protected" + ], + "effects": [], + "rulesText": "Protected.", + "flavor": "Polish mixed martial artist (born 1996)", + "connect": { + "countries": [ + "Brazil", + "Poland" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [], + "qid": "Q97373278", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 54, + "pctDepth": 83, + "pctReach": 23, + "fame": 53, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000001f064", + "pageId": 127076, + "revisionId": 1384097001, + "title": "Hillburn, New York", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 3, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Village in New York, United States", + "connect": { + "countries": [ + "United States" + ], + "centuries": [], + "links": [], + "p31": [ + "Q55237813", + "Q751708" + ], + "qid": "Q3452966", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 71, + "pctDepth": 68, + "pctReach": 87, + "fame": 75, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000042d2a", + "pageId": 273706, + "revisionId": 1385350039, + "title": "Pallas's cat", + "type": "Figure", + "subtype": null, + "portal": "Earth", + "cost": 6, + "power": 5, + "toughness": 5, + "territory": 0, + "keywords": [ + "Featured", + "Multilingual" + ], + "effects": [], + "rulesText": "Featured, Multilingual.", + "flavor": "Species of small wild cat", + "connect": { + "countries": [], + "centuries": [ + 18 + ], + "links": [], + "p31": [], + "qid": "Q166794", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 99, + "pctDepth": 97, + "pctReach": 99, + "fame": 98, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001a702c7", + "pageId": 27722439, + "revisionId": 1368237133, + "title": "Cannon (band)", + "type": "Institution", + "subtype": "organisation", + "portal": "Arts", + "cost": 2, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + } + } + ], + "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", + "flavor": "Scottish post-rock band", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [ + 20, + 21 + ], + "links": [], + "p31": [ + "Q215380" + ], + "qid": "Q5032746", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 58, + "pctDepth": 43, + "pctReach": 8, + "fame": 36, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000003c754", + "pageId": 247636, + "revisionId": 1380730000, + "title": "Canadian Grand Prix", + "type": "Event", + "subtype": "sport", + "portal": "Society", + "cost": 6, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "pump", + "target": "ownFigure", + "power": 3, + "toughness": 0, + "duration": "turn" + }, + { + "trigger": "onPlay", + "op": "fight", + "target": "opponentFigure" + } + ], + "rulesText": "Target Figure you control gets +3/+0 until end of turn, then it fights target Figure you don't control.", + "flavor": "Formula One Grand Prix", + "connect": { + "countries": [ + "Canada" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q108886259", + "Q18608583" + ], + "qid": "Q7965", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 96, + "pctDepth": 96, + "pctReach": 97, + "fame": 96, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000577b42", + "pageId": 5733186, + "revisionId": 1359130364, + "title": "1969 NFL Championship Game", + "type": "Event", + "subtype": "sport", + "portal": "Society", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "pump", + "target": "ownFigure", + "power": 3, + "toughness": 0, + "duration": "turn" + }, + { + "trigger": "onPlay", + "op": "fight", + "target": "opponentFigure" + } + ], + "rulesText": "Target Figure you control gets +3/+0 until end of turn, then it fights target Figure you don't control.", + "flavor": "", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q27020041" + ], + "qid": "Q4573604", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 91, + "pctDepth": 81, + "pctReach": 36, + "fame": 69, + "magnitude": 3 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000197515f", + "pageId": 26693983, + "revisionId": 1379250957, + "title": "2008 World Sprint Speed Skating Championships", + "type": "Event", + "subtype": "sport", + "portal": "Society", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "pump", + "target": "ownFigure", + "power": 2, + "toughness": 0, + "duration": "turn" + }, + { + "trigger": "onPlay", + "op": "fight", + "target": "opponentFigure" + } + ], + "rulesText": "Target Figure you control gets +2/+0 until end of turn, then it fights target Figure you don't control.", + "flavor": "International speed skating competition", + "connect": { + "countries": [ + "Netherlands" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q114609228" + ], + "qid": "Q1320203", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 6, + "pctDepth": 77, + "pctReach": 71, + "fame": 51, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001b85b73", + "pageId": 28859251, + "revisionId": 1379439420, + "title": "Kõruse-Metsaküla", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "Village in Estonia", + "connect": { + "countries": [ + "Estonia" + ], + "centuries": [], + "links": [], + "p31": [ + "Q51049922" + ], + "qid": "Q3467661", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 6, + "pctDepth": 23, + "pctReach": 71, + "fame": 33, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001e7779d", + "pageId": 31946653, + "revisionId": 1321146397, + "title": "Cody Floatplane", + "type": "Institution", + "subtype": "other", + "portal": "Science", + "cost": 4, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "static", + "op": "pump", + "target": "ownFigures", + "power": 1, + "toughness": 0, + "condition": { + "maxPower": 2 + } + } + ], + "rulesText": "Figures you control with power 2 or less get +1/+0.", + "flavor": "", + "connect": { + "countries": [ + "United Kingdom" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [], + "qid": "Q5140425", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "category", + "basis": { + "pctAttention": 52, + "pctDepth": 59, + "pctReach": 47, + "fame": 53, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000002475ba8", + "pageId": 38230952, + "revisionId": 1383786404, + "title": "John Allen Midgett Jr.", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 3, + "power": 2, + "toughness": 3, + "territory": 0, + "keywords": [ + "Legacy", + "Local" + ], + "effects": [], + "rulesText": "Legacy, Local.", + "flavor": "United States Coast Guardsman", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q6218773", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 50, + "pctDepth": 59, + "pctReach": 8, + "fame": 39, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000026196e4", + "pageId": 39950052, + "revisionId": 1271494308, + "title": "Texas State Guard Commanding General's Individual Award", + "type": "Institution", + "subtype": "organisation", + "portal": "Neutral", + "cost": 1, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onEnter", + "op": "createToken", + "amount": 1, + "token": { + "name": "Staff Member", + "power": 1, + "toughness": 1, + "portal": "Neutral" + } + } + ], + "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", + "flavor": "Military decoration", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q618779" + ], + "qid": "Q17108726", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 6, + "pctDepth": 38, + "pctReach": 8, + "fame": 17, + "magnitude": 1 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000292a898", + "pageId": 43165848, + "revisionId": 1380318087, + "title": "John Kane (Medal of Honor)", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 1, + "power": 1, + "toughness": 2, + "territory": 0, + "keywords": [ + "Local" + ], + "effects": [], + "rulesText": "Local.", + "flavor": "Union Army soldier", + "connect": { + "countries": [ + "Ireland", + "United States" + ], + "centuries": [], + "links": [], + "p31": [], + "qid": "Q17479265", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 21, + "pctDepth": 23, + "pctReach": 8, + "fame": 17, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000046d99b5", + "pageId": 74291637, + "revisionId": 1380094218, + "title": "Pullman porter affair", + "type": "Event", + "subtype": "other", + "portal": "Society", + "cost": 3, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "draw", + "amount": 2 + } + ], + "rulesText": "Draw two cards.", + "flavor": "LGBT sex scandal in September 1940", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q2197458" + ], + "qid": "Q120123799", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 69, + "pctDepth": 73, + "pctReach": 8, + "fame": 50, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000ca0a2e", + "pageId": 13240878, + "revisionId": 1373484295, + "title": "Lower Shavertown Bridge", + "type": "Location", + "subtype": null, + "portal": "History", + "cost": 1, + "power": 0, + "toughness": 1, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/1.", + "flavor": "United States historic place", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 19 + ], + "links": [], + "p31": [ + "Q1825472", + "Q537127" + ], + "qid": "Q6693791", + "cites": [] + }, + "rarity": "Epic", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 17, + "pctDepth": 17, + "pctReach": 8, + "fame": 14, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000001283431", + "pageId": 19412017, + "revisionId": 1385718836, + "title": "Andouin Aubert", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 4, + "power": 2, + "toughness": 5, + "territory": 0, + "keywords": [ + "Legacy" + ], + "effects": [], + "rulesText": "Legacy.", + "flavor": "French jurist, bishop and Cardinal", + "connect": { + "countries": [ + "France" + ], + "centuries": [ + 14 + ], + "links": [], + "p31": [], + "qid": "Q1351294", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 38, + "pctDepth": 77, + "pctReach": 71, + "fame": 62, + "magnitude": 2 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000017a1788", + "pageId": 24778632, + "revisionId": 1373615936, + "title": "Storck Barracks", + "type": "Location", + "subtype": null, + "portal": "Neutral", + "cost": 2, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "US Army facility in Illesheim, Germany", + "connect": { + "countries": [ + "Germany", + "United States" + ], + "centuries": [ + 20 + ], + "links": [], + "p31": [ + "Q245016" + ], + "qid": "Q108337154", + "cites": [] + }, + "rarity": "Rare", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 76, + "pctDepth": 73, + "pctReach": 8, + "fame": 52, + "magnitude": 2 + } + }, + { + "cardId": "000000000000000000000000000000000000000000000000000000000252776f", + "pageId": 38958959, + "revisionId": 1364996502, + "title": "Genoese Batteries", + "type": "Location", + "subtype": null, + "portal": "Science", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Artillery batteries in Gibraltar", + "connect": { + "countries": [], + "centuries": [], + "links": [], + "p31": [ + "Q56344492" + ], + "qid": "Q16838634", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 9, + "pctDepth": 28, + "pctReach": 8, + "fame": 15, + "magnitude": 1 + } + }, + { + "cardId": "00000000000000000000000000000000000000000000000000000000028e29f5", + "pageId": 42871285, + "revisionId": 1371391529, + "title": "Yente Serdatzky", + "type": "Figure", + "subtype": null, + "portal": "History", + "cost": 4, + "power": 2, + "toughness": 4, + "territory": 0, + "keywords": [ + "Legacy", + "Well-sourced" + ], + "effects": [], + "rulesText": "Legacy, Well-sourced.", + "flavor": "Russian-born American Yiddish-language writer (1877–1962)", + "connect": { + "countries": [ + "Russia", + "United States" + ], + "centuries": [ + 19, + 20 + ], + "links": [], + "p31": [], + "qid": "Q17018388", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "qid", + "basis": { + "pctAttention": 42, + "pctDepth": 89, + "pctReach": 23, + "fame": 51, + "magnitude": 2 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003bf2818", + "pageId": 62859288, + "revisionId": 1373475244, + "title": "Waterman Place-Kingsbury Place-Washington Terrace Historic District", + "type": "Location", + "subtype": null, + "portal": "History", + "cost": 1, + "power": 0, + "toughness": 2, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/2.", + "flavor": "Historic district in Missouri, United States", + "connect": { + "countries": [ + "United States" + ], + "centuries": [], + "links": [], + "p31": [ + "Q15243209" + ], + "qid": "Q85814627", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 31, + "pctDepth": 38, + "pctReach": 8, + "fame": 26, + "magnitude": 1 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000003f5c331", + "pageId": 66437937, + "revisionId": 1382576557, + "title": "2021 New Jersey General Assembly election", + "type": "Event", + "subtype": "election", + "portal": "Society", + "cost": 5, + "power": null, + "toughness": null, + "territory": 0, + "keywords": [], + "effects": [ + { + "trigger": "onPlay", + "op": "createToken", + "amount": 3, + "token": { + "name": "Elected Member", + "power": 1, + "toughness": 1, + "portal": "Society" + } + } + ], + "rulesText": "Create three 1/1 Society Figure tokens named Elected Member.", + "flavor": "", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 21 + ], + "links": [], + "p31": [ + "Q2618461" + ], + "qid": "Q105319974", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 77, + "pctDepth": 99, + "pctReach": 23, + "fame": 66, + "magnitude": 3 + } + }, + { + "cardId": "0000000000000000000000000000000000000000000000000000000000020090", + "pageId": 131216, + "revisionId": 1378756902, + "title": "Madison Township, Armstrong County, Pennsylvania", + "type": "Location", + "subtype": null, + "portal": "Earth", + "cost": 2, + "power": 0, + "toughness": 3, + "territory": 1, + "keywords": [], + "effects": [], + "rulesText": "Territory.\nGarrison 0/3.", + "flavor": "Township in Pennsylvania, US", + "connect": { + "countries": [ + "United States" + ], + "centuries": [ + 19 + ], + "links": [], + "p31": [ + "Q9035798" + ], + "qid": "Q655024", + "cites": [] + }, + "rarity": "Common", + "deriveVersion": "duel-derive-1", + "typedBy": "p31", + "basis": { + "pctAttention": 35, + "pctDepth": 64, + "pctReach": 67, + "fame": 55, + "magnitude": 2 + } + } + ] +} diff --git a/scripts/duel-card-sample.ts b/scripts/duel-card-sample.ts new file mode 100644 index 0000000..31bc49c --- /dev/null +++ b/scripts/duel-card-sample.ts @@ -0,0 +1,32 @@ +/** + * Writes docs/game/duel-card-sample.json (card-sample.json → DuelCard[]) and prints the + * type / Portal / cost / keyword distributions. Offline. Usage: + * node --experimental-strip-types scripts/duel-card-sample.ts [--check] + * --check exits non-zero if the committed fixture is out of date. + */ +import { readFileSync, writeFileSync } from 'node:fs'; +import { deriveSample, type SampleCard } from '../shared/duel/sample.ts'; +import { DERIVE_VERSION } from '../shared/duel/derive.ts'; + +const root = new URL('../', import.meta.url); +const sample = JSON.parse(readFileSync(new URL('docs/game/card-sample.json', root), 'utf8')) as { cards: SampleCard[] }; +const cards = deriveSample(sample.cards); +const out = JSON.stringify({ source: 'docs/game/card-sample.json', deriveVersion: DERIVE_VERSION, count: cards.length, cards }, null, 1) + '\n'; +const path = new URL('docs/game/duel-card-sample.json', root); + +const tally = (f: (c: typeof cards[number]) => string | number) => { + const m = new Map(); + for (const c of cards) m.set(f(c), (m.get(f(c)) ?? 0) + 1); + return [...m].sort((a, b) => String(a[0]).localeCompare(String(b[0]), 'en', { numeric: true })) + .map(([k, v]) => `${k} ${v} (${(100 * v / cards.length).toFixed(1)}%)`).join(', '); +}; +console.log('type:', tally(c => c.type)); +console.log('typedBy:', tally(c => c.typedBy)); +console.log('portal:', tally(c => c.portal)); +console.log('cost:', tally(c => c.cost)); +console.log('subtype:', tally(c => `${c.type}/${c.subtype ?? '-'}`)); +console.log('keywords:', tally(c => c.keywords.join('+') || 'none')); + +if (process.argv.includes('--check')) { + if (readFileSync(path, 'utf8') !== out) { console.error('duel-card-sample.json is stale'); process.exit(1); } +} else writeFileSync(path, out); diff --git a/shared/duel/classify.ts b/shared/duel/classify.ts new file mode 100644 index 0000000..2f59bb7 --- /dev/null +++ b/shared/duel/classify.ts @@ -0,0 +1,125 @@ +/** + * Card type classification (BRIEF "Card types", data review §1, designer review §3.1). + * Pure and deterministic: everything comes from the frozen CardProfile, nothing is fetched here. + * Order: exact Q-id anchors on P31, then P279 anchors, then P31 label regex (rule order is the + * priority), then P279 label regex, then non-stub categories, then the description, then Doctrine. + * Owner: duel-cards. + */ + +export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine'; +export const CARD_TYPES: readonly CardType[] = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine']; + +export interface WikidataClass { id: string; label: string } + +/** + * The off-chain card profile, frozen the first time a host sees the card (data §3) and logged + * with the match so replays and recaps stay deterministic. Only what derivation reads. + */ +export interface CardProfile { + wikidataId: string | null; + /** Wikipedia short description. */ + description: string | null; + /** Non-hidden category titles without the "Category:" prefix. */ + categories: readonly string[]; + /** P31 (instance of). */ + instanceOf: readonly WikidataClass[]; + /** P279 (subclass of) of the item itself, or the P31 classes' superclasses up to 4 hops, nearest first. */ + subclassOf?: readonly WikidataClass[]; + /** P17 / P27 country Q-ids (or labels when only text is known). */ + countries?: readonly string[]; + /** Years from P569/P570/P571/P580/P585 (negative = BCE). */ + years?: readonly number[]; + /** P570 (date of death) present. */ + died?: boolean; + /** ns0 outlinks as pageIds (data §4), for the Linked tier of Connected. */ + links?: readonly number[]; + /** Item Q-ids cited by the frozen claims (P17, P27, P131, P361, P106, …), for the Linked tier. */ + cites?: readonly string[]; + /** The live revision the profile was fetched from (data §3). */ + fetchedRevisionId?: number; +} + +export type ClassifySource = 'qid' | 'p279-qid' | 'p31' | 'p279' | 'category' | 'description' | 'fallback'; +export interface Classification { type: CardType; source: ClassifySource; matched: string } + +/** Exact anchors (designer §3.1 step 1, data §1 production table). Checked against P31, then P279. */ +export const QID_ANCHORS: Readonly> = { + Q5: 'Figure', Q95074: 'Figure', Q16521: 'Figure', Q23038290: 'Figure', Q8436: 'Figure', Q178885: 'Figure', + Q486972: 'Location', Q515: 'Location', Q532: 'Location', Q3957: 'Location', Q4022: 'Location', Q23397: 'Location', + Q8502: 'Location', Q23442: 'Location', Q41176: 'Location', + Q1656682: 'Event', Q40231: 'Event', Q178561: 'Event', Q198: 'Event', Q8065: 'Event', + Q43229: 'Institution', Q4830453: 'Institution', Q783794: 'Institution', Q7278: 'Institution', Q215380: 'Institution', + Q17537576: 'Institution', Q11424: 'Institution', Q482994: 'Institution', Q7366: 'Institution', Q571: 'Institution', + Q12136: 'Doctrine', Q151885: 'Doctrine', Q7187: 'Doctrine', Q9143: 'Doctrine', Q315: 'Doctrine', +}; + +type Rules = readonly (readonly [CardType, RegExp])[]; + +/** P31/P279 label rules (data §1 types.py, with `^human$` and the governing-body fix). Order is load-bearing. */ +export const LABEL_RULES: Rules = [ + ['Doctrine', /aspect of|aspect in|disease|clinical sign|list article|chemical entity/], + ['Event', new RegExp('election|protest|battle|war\\b|storm|nor.easter|cyclone|tornado|earthquake|disaster|event|match|final\\b|' + + 'season|championship|tournament|\\brace\\b|grand prix|scandal|annexation|treaty|incident|festival|referendum|' + + 'conference|ceremony|time period|delegation|spaceflight|siege|riot|massacre|flood|pandemic|epidemic|straw poll')], + ['Institution', /artificial satellite|space station|space telescope|spacecraft|space probe|diocese|ecclesiastical|council\b|governing body|stele/], + ['Location', new RegExp('planet|natural satellite|\\bstar\\b|galaxy|nebula|planetary system|astronomical object|rainforest|reef|' + + 'civili[sz]ation|empire|historical country|archaeological site|' + + 'human settlement|settlement|village|town|city|commune|municipal|parish|county|district|region|province|' + + 'township|hamlet|townland|census area|local government|community of|island|river|lake|mountain|plateau|' + + 'waterfall|valley|bay|peak|geographical feature|historic district|park|state park|square|road|highway|' + + 'building|castle|mosque|church|temple|cathedral|house|home|museum|station|bridge|monument|historic site|' + + 'military base|battery|refinery|shopping|stadium|arch|tower|fort|palace|columbari|freguesia|country\\b|sovereign state')], + ['Figure', /^human$|fictional character|stock character|person|deity|orisha|loa\b|taxon|species|genus|breed|^family$|organism/], + ['Institution', new RegExp('company|business|organi[sz]ation|association|society|party|agency|studio|band|musical group|team|club|' + + 'university|college|school|institute|manufacturer|newspaper|magazine|film|album|' + + 'song|single|musical work|composition|television|series|book|novel|video game|painting|award|position|' + + 'aircraft|ship|steamship|vehicle|automobile|tram|railway line|route|typeface|software|product|brand|artifact|artefact')], + ['Doctrine', new RegExp('concept|theory|theorem|mathematical|programming language|language|gene|protein|chemical|compound|' + + 'ideology|religion|discipline|field|cuisine|food|dish|drink|aspect|' + + 'particle|process|genre|form\\b|game\\b|branch of|class of|type of|tabular|structure')], +]; + +/** Category fallback (stub categories are skipped). */ +export const CATEGORY_RULES: Rules = [ + ['Figure', /\bbirth|\bdeaths\b|living people|people from|\bspecies\b|described in \d|\bgenera\b|deities|characters/], + ['Event', /\belections\b|protests|\bbattles\b|disasters|\braces\b|\bseasons\b|\bevents\b|scandals|annexations|competitions/], + ['Location', new RegExp('villages|communes|parishes|local government|populated places|geography|rivers|islands|buildings and structures|bridges|' + + 'stations|parks|districts|townships|cities and towns|historic places|freguesias')], + ['Institution', new RegExp('companies|organi[sz]ations|\\bfilms\\b|albums|songs|novels|newspapers|television series|musical groups|' + + 'aircraft|ships|typefaces|software|awards|teams|clubs|establishments')], + ['Doctrine', new RegExp('theory|structures$|algebra|terminology|cuisine|drinks|desserts|ecology|languages|diseases|conditions|' + + 'concepts|ranks|etymology|maps|atlases')], +]; + +/** Description fallback (present on ~90% of the sample). */ +export const DESCRIPTION_RULES: Rules = [ + ['Figure', /^(species|genus) of|\b(painter|politician|actor|actress|writer|player|singer|born|species|genus)\b/], + ['Event', /\b(race|election|battle|match|protest|storm|war|competition)\b/], + ['Location', /^(commune|village|town|municipality|river) in|\b(village|town|city|river|island|building|church|columbarium|station|park)\b/], + ['Institution', /\b(company|band|film|album|organi[sz]ation|team|aircraft|ship|newspaper)\b/], + ['Doctrine', /\b(concept|theory|structure|dessert|drink|dish|technique|class of)\b/], +]; + +function firstRule(rules: Rules, texts: readonly string[]): [CardType, string] | null { + for (const [type, rx] of rules) for (const text of texts) if (rx.test(text)) return [type, text]; + return null; +} + +export function classify(profile: Pick): Classification { + const p31 = profile.instanceOf ?? []; + const p279 = profile.subclassOf ?? []; + for (const c of p31) { const t = QID_ANCHORS[c.id]; if (t) return { type: t, source: 'qid', matched: c.id }; } + const p31Labels = p31.map(c => c.label.toLowerCase()); + let hit = firstRule(LABEL_RULES, p31Labels); + if (hit) return { type: hit[0], source: 'p31', matched: hit[1] }; + for (const c of p279) { const t = QID_ANCHORS[c.id]; if (t) return { type: t, source: 'p279-qid', matched: c.id }; } + hit = firstRule(LABEL_RULES, p279.map(c => c.label.toLowerCase())); + if (hit) return { type: hit[0], source: 'p279', matched: hit[1] }; + const cats = (profile.categories ?? []).map(c => c.toLowerCase()).filter(c => !c.includes('stubs')); + hit = firstRule(CATEGORY_RULES, cats); + if (hit) return { type: hit[0], source: 'category', matched: hit[1] }; + const desc = (profile.description ?? '').toLowerCase(); + hit = firstRule(DESCRIPTION_RULES, desc ? [desc] : []); + if (hit) return { type: hit[0], source: 'description', matched: hit[1] }; + return { type: 'Doctrine', source: 'fallback', matched: '' }; +} diff --git a/shared/duel/derive.ts b/shared/duel/derive.ts new file mode 100644 index 0000000..91f1bd2 --- /dev/null +++ b/shared/duel/derive.ts @@ -0,0 +1,317 @@ +/** + * Duel card derivation: an on-chain card plus its frozen off-chain profile becomes a DuelCard + * (BRIEF "Stats", "Keywords", "Factions", "Connected"; data review §2 and §4; designer review §3). + * Pure and deterministic: no fetches, no clocks, no randomness. Every number is data in DERIVE_RULES. + * Owner: duel-cards. + */ +import type { Article } from '../protocol.ts'; +import type { MintStatsSnapshot } from '../enrichment.ts'; +import { rarity as rarityOf } from '../protocol.ts'; +import { CARD_SAMPLE_PERCENTILES } from '../game/card-data.ts'; +import { percentile } from '../game/derive.ts'; +import { classify, type CardProfile, type CardType, type ClassifySource } from './classify.ts'; +import { effectsFor, subtypeFor, type EffectSpec } from './effects.ts'; +import { rulesTextFor } from './text.ts'; + +export type { CardProfile, CardType } from './classify.ts'; +export type { EffectSpec } from './effects.ts'; + +export const DERIVE_VERSION = 'duel-derive-1'; + +export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral'; +export const PORTALS: readonly Portal[] = ['Arts', 'Earth', 'History', 'Science', 'Society', 'Neutral']; +export type Keyword = 'Protected' | 'Featured' | 'Translated' | 'Legacy' | 'Stub' | 'Well-sourced' | 'Multilingual' | 'Local'; +export type Rarity = 'Common' | 'Rare' | 'Epic' | 'Legendary'; + +/** What derive() reads from the chain: a minted block's article and stats snapshot. */ +export interface CardOnChain { + tokenId: string; + article: Pick; + statsSnapshot: Pick; +} + +export interface ConnectKeys { + /** P17/P27 values, or normalised country names from text when Wikidata has none. */ + countries: string[]; + centuries: number[]; + /** Outlink pageIds. */ + links: number[]; + /** P31 Q-ids, excluding human and taxon (the Kin tier). */ + p31: string[]; + /** This card's Wikidata item, and the item Q-ids its claims cite (Linked tier). */ + qid: string | null; + cites: string[]; +} + +export interface DuelCard { + cardId: string; + pageId: number; + revisionId: number; + title: string; + type: CardType; + /** Template family within the type, e.g. 'conflict', 'election', 'organisation', 'pathology'. */ + subtype: string | null; + portal: Portal; + cost: number; + /** Figures: power/toughness. Locations: 0 / Garrison. Others: null. */ + power: number | null; + toughness: number | null; + /** Locations: Citations income ramp (the engine caps the total). */ + territory: number; + keywords: Keyword[]; + effects: EffectSpec[]; + rulesText: string; + flavor: string; + connect: ConnectKeys; + rarity: Rarity; + deriveVersion: string; + /** Why the card got its type (for audit and the card's info panel). */ + typedBy: ClassifySource; + /** The numbers behind cost and body, for the info panel and the simulator. */ + basis: { pctAttention: number | null; pctDepth: number; pctReach: number; fame: number; magnitude: number }; +} + +export interface DeriveRules { + percentiles: Record<'attention' | 'depth' | 'reach', readonly number[]>; + /** fame → cost 1..6: 1 + number of thresholds ≤ fame. */ + costThresholds: readonly number[]; + /** P+T budget by cost (index = cost). MTG vanilla curve. */ + bodyBudget: readonly number[]; + maxKeywords: number; + /** Keywords that cost 1 point of body (from the larger stat, min 1 each). */ + taxedKeywords: readonly Keyword[]; + keywordOrder: readonly Keyword[]; + featuredPct: number; + wellSourcedPct: number; + /** Translated: translatedPct ≤ pct_reach < multilingualPct. Multilingual: pct_reach ≥ multilingualPct. */ + translatedPct: number; + multilingualPct: number; + stubBytes: number; + /** Garrison toughness = 1 + floor(pct_depth / garrisonStep). */ + garrisonStep: number; +} + +export const DERIVE_RULES: DeriveRules = { + percentiles: CARD_SAMPLE_PERCENTILES, + costThresholds: [26, 39, 51, 63, 78], + bodyBudget: [0, 3, 4, 6, 8, 10, 12], + maxKeywords: 2, + taxedKeywords: ['Protected', 'Featured', 'Legacy', 'Multilingual', 'Well-sourced'], + keywordOrder: ['Protected', 'Featured', 'Legacy', 'Multilingual', 'Translated', 'Well-sourced', 'Stub', 'Local'], + featuredPct: 85, + wellSourcedPct: 85, + translatedPct: 75, + multilingualPct: 90, + stubBytes: 3000, + garrisonStep: 25, +}; + +// ---------------------------------------------------------------- Portals (designer §3.2) + +export const PORTAL_RULES: Readonly, RegExp>> = { + Arts: /\b(actor|actress|singer|musician|rapper|band|album|song|single|film|novel|novelist|writer|poet|painter|artist|composer|television|tv series|music|theatre|theater|dance|dancer|video game|studio|animation|anime|fiction|character|literature|book|magazine|typeface|sculpt\w*|architect\w*|comedian|opera|orchestra)\b/g, + Earth: /\b(species|genus|genera|taxon|plant|plants|animal|bird|birds|fish|insect|moth|beetle|grasshopper|orchid|river|rivers|lake|mountain|island|islands|village|villages|commune|communes|geography|forest|park|ecology|breed|weather|storm|nor.easter|cyclone|earthquake|climate|flora|fauna|populated places|municipality|municipalities|county|township|parish|reef|valley|locality|oblast|freguesia|hamlet)\b/g, + History: /(\b\d+(st|nd|rd|th)-century\b|\b\d+ deaths\b|\b(sultan\w*|empire|castle|castles|medieval|ancient|dynasty|war|battle|battles|monarch|monarchs|king|queen|historic|archaeolog\w*|former|disestablish\w*|colonial|kingdom|museum|nobility|pharaoh)\b)/g, + Science: /\b(mathemat\w*|algebra\w*|programming|software|gene|genes|protein|chemi\w*|disease|diseases|scientist|physic\w*|astronom\w*|biolog\w*|medic\w*|engineer\w*|computer|computing|theorem|planet|galaxy|spacecraft|satellite|aircraft|technology|clinical|structure|structures|category theory|syndrome|virus|bacteri\w*)\b/g, + Society: /\b(politic\w*|politician|election|elections|party|government|law|court|sport|sports|football|cricket|basketball|baseball|olympic\w*|team|club|league|church|religio\w*|diocese|mosque|temple|school|university|company|companies|business|corporation|protest|protests|scandal|corruption|people from|living people|police|crime|cuisine|association|council)\b/g, +}; +const PORTAL_TIE_ORDER: readonly Exclude[] = ['History', 'Science', 'Arts', 'Society', 'Earth']; +export const TYPE_DEFAULT_PORTAL: Readonly>> = { + Figure: 'Society', Location: 'Earth', Event: 'History', Institution: 'Arts', Doctrine: 'Science', +}; + +/** Count keyword hits over description + categories + P31 labels; ties go to the type default; no hits → Neutral. */ +export function portalFor(profile: CardProfile, type: CardType): Portal { + const text = [profile.description ?? '', ...profile.categories, ...profile.instanceOf.map(c => c.label)] + .join(' | ').toLowerCase(); + let best = 0; let tied: Exclude[] = []; + for (const portal of PORTAL_TIE_ORDER) { + const hits = text.match(PORTAL_RULES[portal])?.length ?? 0; + if (hits > best) { best = hits; tied = [portal]; } else if (hits === best && hits > 0) tied.push(portal); + } + if (best === 0) return 'Neutral'; + const fallback = TYPE_DEFAULT_PORTAL[type]; + return tied.includes(fallback) ? fallback : tied[0]; +} + +// ---------------------------------------------------------------- Connected keys (data §4) + +const COUNTRY_WORDS: readonly (readonly [RegExp, string])[] = ([ + ['United States|American', 'United States'], ['United Kingdom|British|England|English|Scotland|Scottish|Wales|Welsh', 'United Kingdom'], + ['France|French', 'France'], ['Germany|German', 'Germany'], ['Japan|Japanese', 'Japan'], ['China|Chinese', 'China'], + ['India|Indian', 'India'], ['Brazil|Brazilian', 'Brazil'], ['Poland|Polish', 'Poland'], ['Italy|Italian', 'Italy'], + ['Spain|Spanish', 'Spain'], ['Austria|Austrian', 'Austria'], ['Canada|Canadian', 'Canada'], ['Australia|Australian', 'Australia'], + ['Russia|Russian', 'Russia'], ['Mexico|Mexican', 'Mexico'], ['Iran|Iranian', 'Iran'], ['Pakistan|Pakistani', 'Pakistan'], + ['Bangladesh|Bangladeshi', 'Bangladesh'], ['Sweden|Swedish', 'Sweden'], ['Norway|Norwegian', 'Norway'], ['Estonia|Estonian', 'Estonia'], + ['Ukraine|Ukrainian', 'Ukraine'], ['Croatia|Croatian', 'Croatia'], ['Philippines|Filipino', 'Philippines'], ['Cuba|Cuban', 'Cuba'], + ['Israel|Israeli', 'Israel'], ['Portugal|Portuguese', 'Portugal'], ['Ireland|Irish', 'Ireland'], ['Kazakhstan|Kazakh', 'Kazakhstan'], + ['Malaysia|Malaysian', 'Malaysia'], ['Argentina|Argentine', 'Argentina'], ['Belgium|Belgian', 'Belgium'], ['Iceland|Icelandic', 'Iceland'], + ['Thailand|Thai', 'Thailand'], ['Singapore', 'Singapore'], ['Sri Lanka|Sri Lankan', 'Sri Lanka'], ['Slovenia|Slovene|Slovenian', 'Slovenia'], + ['Moldova', 'Moldova'], ['Cyprus|Cypriot', 'Cyprus'], ['North Macedonia|Macedonian', 'North Macedonia'], ['Mauritania', 'Mauritania'], + ['Congo', 'Congo'], ['New Zealand', 'New Zealand'], ['Korea|Korean', 'Korea'], ['Indonesia|Indonesian|Aceh', 'Indonesia'], + ['Czech', 'Czechia'], ['Netherlands|Dutch', 'Netherlands'], ['Greece|Greek', 'Greece'], ['Turkey|Turkish', 'Turkey'], + ['Egypt|Egyptian', 'Egypt'], ['Nigeria|Nigerian', 'Nigeria'], ['Kenya|Kenyan', 'Kenya'], ['Ghana|Gold Coast', 'Ghana'], + ['Finland|Finnish', 'Finland'], ['Denmark|Danish', 'Denmark'], ['Switzerland|Swiss', 'Switzerland'], ['Hungary|Hungarian', 'Hungary'], + ['Romania|Romanian', 'Romania'], ['Serbia|Serbian', 'Serbia'], ['Bulgaria|Bulgarian', 'Bulgaria'], ['Vietnam|Vietnamese', 'Vietnam'], + ['Sri Lanka', 'Sri Lanka'], ['Chile|Chilean', 'Chile'], ['Colombia|Colombian', 'Colombia'], ['Peru|Peruvian', 'Peru'], +] as const).map(([rx, name]) => [new RegExp(`\\b(${rx})\\b`), name] as const); + +const YEAR = /\b(1[0-9]{3}|20[0-2][0-9])\b/g; +const CENTURY = /\b(\d{1,2})(st|nd|rd|th)[- ]century\b/gi; + +export function connectKeysFor(title: string, profile: CardProfile): ConnectKeys { + const text = [profile.description ?? '', ...profile.categories].join(' | '); + const countries = profile.countries?.length + ? [...new Set(profile.countries)] + : [...new Set(COUNTRY_WORDS.filter(([rx]) => rx.test(text)).map(([, name]) => name))]; + const centuries = new Set(); + if (profile.years?.length) for (const y of profile.years) centuries.add(y > 0 ? Math.floor((y - 1) / 100) + 1 : -(Math.floor(-y / 100) + 1)); + else { + for (const m of `${title} | ${text}`.matchAll(YEAR)) centuries.add(Math.floor((Number(m[1]) - 1) / 100) + 1); + for (const m of text.matchAll(CENTURY)) centuries.add(Number(m[1])); + } + return { + countries: countries.sort(), + centuries: [...centuries].sort((a, b) => a - b), + links: [...new Set(profile.links ?? [])].sort((a, b) => a - b), + p31: [...new Set(profile.instanceOf.map(c => c.id).filter(id => id !== 'Q5' && id !== 'Q16521'))].sort(), + qid: profile.wikidataId, + cites: [...new Set(profile.cites ?? [])].sort(), + }; +} + +// ---------------------------------------------------------------- Flavour + +/** First sentence of the on-chain extract (BRIEF "Flavour text"); the description if there is no extract. */ +export function flavorFor(extract: string, description: string | null): string { + const text = extract.replace(/\s+/g, ' ').trim(); + if (!text) return (description ?? '').trim(); + // A sentence ends at . ! ? followed by a space and an uppercase letter or a quote, skipping + // common abbreviations and initials ("U.S.", "St.", "J. R. R.") so names are not cut. + const re = /[.!?](?=\s+["'“(\[]?[A-Z0-9])/g; + let m: RegExpExecArray | null; + while ((m = re.exec(text))) { + const before = text.slice(0, m.index); + const word = before.split(/\s/).pop() ?? ''; + if (/^([A-Z]|[A-Z][a-z]{0,2}|[A-Z]\.[A-Z]|U\.S|U\.K|c|ca|St|Dr|Mr|Mrs|Ms|Jr|Sr|No|vs|etc|Inc|Ltd|Co|Mt|Ft|Gen|Col|Lt|Sgt|Rev|Prof)$/.test(word.replace(/\.$/, ''))) continue; + return text.slice(0, m.index + 1); + } + return text; +} + +// ---------------------------------------------------------------- Stats and keywords (data §2, designer §3.3–3.4) + +export interface Percentiles { attention: number | null; depth: number; reach: number } + +export function percentilesFor(stats: MintStatsSnapshot['stats'], rules: DeriveRules = DERIVE_RULES): Percentiles { + return { + attention: stats.attention === null ? null : percentile(stats.attention, rules.percentiles.attention), + depth: percentile(stats.depth, rules.percentiles.depth), + reach: percentile(stats.reach, rules.percentiles.reach), + }; +} + +export function fameOf(p: Percentiles): number { + const values = [p.attention, p.depth, p.reach].filter((v): v is number => v !== null); + return Math.floor(values.reduce((a, b) => a + b, 0) / values.length + 0.5); +} + +export function costForFame(fame: number, rules: DeriveRules = DERIVE_RULES): number { + return 1 + rules.costThresholds.filter(t => t <= fame).length; +} + +/** Every keyword the data triggers, in priority order (before the cap). */ +export function triggeredKeywords(chain: CardOnChain, profile: CardProfile, p: Percentiles, rules: DeriveRules = DERIVE_RULES): Keyword[] { + const cats = profile.categories; + const on: Record = { + Protected: cats.includes('Living people'), + Featured: p.attention !== null && p.attention >= rules.featuredPct, + Legacy: profile.died === true || cats.some(c => /^\d+s? (BC )?deaths$/.test(c)), + 'Well-sourced': p.depth >= rules.wellSourcedPct, + // Two bands of the same reach axis: a card never has both (DUEL_DESIGN §4). + Multilingual: p.reach >= rules.multilingualPct, + Translated: p.reach >= rules.translatedPct && p.reach < rules.multilingualPct, + Stub: cats.some(c => c.toLowerCase().includes('stubs')) || chain.statsSnapshot.pageBytes < rules.stubBytes, + Local: chain.statsSnapshot.stats.reach === 0, + }; + return rules.keywordOrder.filter(k => on[k]); +} + +export interface Body { power: number; toughness: number; keywords: Keyword[] } + +/** + * Figure body (DUEL_DESIGN §3): take the first ≤2 triggered keywords in priority order, subtract 1 + * from the cost's P+T budget per taxed keyword, then split by attention vs depth, each stat ≥ 1. + * A taxed keyword that would leave less than 2 points is skipped for the next one. + */ +export function figureBody(cost: number, p: Percentiles, keywords: readonly Keyword[], rules: DeriveRules = DERIVE_RULES): Body { + let budget = rules.bodyBudget[cost]; + if (budget === undefined) throw new RangeError(`bodyBudget has no entry for cost ${cost}`); + const kept: Keyword[] = []; + for (const k of keywords) { + if (kept.length >= rules.maxKeywords) break; + if (rules.taxedKeywords.includes(k)) { + if (budget <= 2) continue; + budget--; + } + kept.push(k); + } + const a = p.attention ?? 50; + const power = Math.min(budget - 1, Math.max(1, Math.round(budget * a / Math.max(1, a + p.depth)))); + return { power, toughness: budget - power, keywords: kept }; +} + +// ---------------------------------------------------------------- derive + +export function derive(chain: CardOnChain, profile: CardProfile, rules: DeriveRules = DERIVE_RULES): DuelCard { + const { type, source } = classify(profile); + const p = percentilesFor(chain.statsSnapshot.stats, rules); + const fame = fameOf(p); + const baseCost = costForFame(fame, rules); + const magnitude = Math.ceil(baseCost / 2); + const portal = portalFor(profile, type); + const subtype = subtypeFor(type, profile); + let cost = baseCost, power: number | null = null, toughness: number | null = null, territory = 0; + let keywords: Keyword[] = []; + if (type === 'Figure') { + const body = figureBody(baseCost, p, triggeredKeywords(chain, profile, p, rules), rules); + ({ power, toughness, keywords } = body); + } else if (type === 'Location') { + cost = magnitude; + power = 0; + toughness = 1 + Math.floor(p.depth / rules.garrisonStep); + territory = 1; + } + const effects = effectsFor(type, subtype, baseCost); + const card: DuelCard = { + cardId: chain.tokenId, pageId: chain.article.pageId, revisionId: chain.article.revisionId, title: chain.article.title, + type, subtype, portal, cost, power, toughness, territory, keywords, effects, rulesText: '', + flavor: flavorFor(chain.article.extract, profile.description), + connect: connectKeysFor(chain.article.title, profile), + rarity: rarityOf(chain.tokenId), deriveVersion: DERIVE_VERSION, typedBy: source, + basis: { pctAttention: p.attention, pctDepth: p.depth, pctReach: p.reach, fame, magnitude }, + }; + card.rulesText = rulesTextFor(card); + return card; +} + +// ---------------------------------------------------------------- Connected (data §4) + +/** DUEL_DESIGN §6: Contemporary counts only between different types. */ +export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin'; + +/** The strongest Connected tier between two cards, or null. Linked gives +2/+2, the others +1/+1 (BRIEF). */ +export function connectedTier(a: DuelCard, b: DuelCard, + tiers: readonly ConnectedTier[] = ['Linked', 'Compatriot', 'Contemporary', 'Kin']): ConnectedTier | null { + if (a.cardId === b.cardId) return null; + const meets = (x: readonly (string | number)[], y: readonly (string | number)[]) => x.some(v => y.includes(v)); + for (const tier of tiers) { + if (tier === 'Linked' && (a.connect.links.includes(b.pageId) || b.connect.links.includes(a.pageId) + || (b.connect.qid !== null && a.connect.cites.includes(b.connect.qid)) + || (a.connect.qid !== null && b.connect.cites.includes(a.connect.qid)))) return tier; + if (tier === 'Compatriot' && meets(a.connect.countries, b.connect.countries)) return tier; + if (tier === 'Contemporary' && a.type !== b.type && meets(a.connect.centuries, b.connect.centuries)) return tier; + if (tier === 'Kin' && meets(a.connect.p31, b.connect.p31)) return tier; + } + return null; +} diff --git a/shared/duel/effects.ts b/shared/duel/effects.ts new file mode 100644 index 0000000..2d7f555 --- /dev/null +++ b/shared/duel/effects.ts @@ -0,0 +1,109 @@ +/** + * Effect templates by type and subtype (designer review §3.5; DUEL_DESIGN.md wins where they differ). + * Effects are plain data for duel-core's interpreter. k = ceil(cost / 2), 1–3, from the derived (fame) cost. + * Owner: duel-cards. + */ +import type { CardProfile, CardType } from './classify.ts'; +import type { Keyword, Portal } from './derive.ts'; + +export type EffectTrigger = 'onPlay' | 'onEnter' | 'startOfTurn' | 'onDestroyed' | 'static' | 'onCombatDamageToPlayer'; +export type EffectOp = 'damage' | 'damageEach' | 'createToken' | 'pump' | 'fight' | 'draw' | 'attach' | 'gainLife'; +export type EffectTarget = 'figure' | 'figureOrLocation' | 'ownFigure' | 'opponentFigure' | 'each' | 'self' | 'attached' | 'ownFigures'; + +export interface EffectSpec { + trigger: EffectTrigger; + op: EffectOp; + target?: EffectTarget; + amount?: number; + power?: number; + toughness?: number; + duration?: 'turn' | 'permanent'; + token?: { name: string; power: number; toughness: number; portal: Portal }; + condition?: { maxPower?: number; samePortal?: boolean; connected?: boolean; maxTokens?: number; whileAttacking?: boolean }; + grant?: Keyword[]; +} + +type Subtypes = readonly (readonly [string, RegExp])[]; + +/** + * Subtype rules per type (DUEL_DESIGN §5), run over P31 labels, P279 labels, the description, then + * categories. First match in list order wins; no match is the type's default template. + * Additions beyond §5 (marked +): bands/associations count as organisations; 'flood' etc. as listed. + */ +export const SUBTYPE_RULES: Readonly> = { + Event: [ + ['conflict', /battle|war\b|siege|annexation|protest|riot|uprising|massacre|coup/], + ['disaster', /storm|nor.easter|cyclone|hurricane|earthquake|flood|tornado|wildfire|eruption|famine|epidemic/], + ['election', /election|referendum|straw poll/], + ['sport', /match|final\b|season|tournament|championship|grand prix|\brace\b/], + ], + Institution: [ + ['organisation', /company|organi[sz]ation|party|agency|studio|military|university|diocese|council|band\b|musical group|association|business|school|college|institute|manufacturer/], + ['work', /film|album|song|\bbook|novel|series|video game|painting|software|typeface|newspaper|magazine/], + ], + Doctrine: [ + ['pathology', /disease|clinical sign|pathogen|syndrome|disorder|toxin|poison/], + ['language', /language|software|programming/], + ['mathematics', /mathemat|theorem|algebra|geometr|polytope|polyhedron|equation|number theory|structure/], + ['ideology', /ideology|religion|belief|doctrine|philosophy|theology/], + ], + Figure: [], + Location: [], +}; + +/** Default template names, for the info panel (null subtype). */ +export const DEFAULT_SUBTYPE: Readonly> = { + Figure: null, Location: null, Event: 'other', Institution: 'other', Doctrine: 'adopt', +}; + +export function subtypeFor(type: CardType, profile: Pick): string | null { + const groups = [ + [...profile.instanceOf.map(c => c.label), ...(profile.subclassOf ?? []).map(c => c.label)], + [profile.description ?? ''], + [...(profile.categories ?? []).filter(c => !/stubs$/i.test(c))], + ].map(g => g.map(t => t.toLowerCase()).filter(Boolean)); + for (const texts of groups) for (const [name, rx] of SUBTYPE_RULES[type]) if (texts.some(t => rx.test(t))) return name; + return DEFAULT_SUBTYPE[type]; +} + +/** The effect list for a card (T1–T12). Figures and Locations have none beyond keywords and stats. */ +export function effectsFor(type: CardType, subtype: string | null, cost: number): EffectSpec[] { + const k = Math.ceil(cost / 2); + switch (type) { + case 'Event': + switch (subtype) { + case 'conflict': return [{ trigger: 'onPlay', op: 'damage', target: 'figureOrLocation', amount: k + 1 }]; + case 'disaster': return [{ trigger: 'onPlay', op: 'damageEach', target: 'each', amount: Math.max(1, k - 1) }]; + case 'election': return [{ trigger: 'onPlay', op: 'createToken', amount: k, + token: { name: 'Elected Member', power: 1, toughness: 1, portal: 'Society' } }]; + case 'sport': return [ + { trigger: 'onPlay', op: 'pump', target: 'ownFigure', power: k, toughness: 0, duration: 'turn' }, + { trigger: 'onPlay', op: 'fight', target: 'opponentFigure' }, + ]; + default: return [{ trigger: 'onPlay', op: 'draw', amount: k }]; + } + case 'Institution': + switch (subtype) { + case 'organisation': { + const token = { name: 'Staff Member', power: 1, toughness: 1, portal: 'Neutral' as const }; + return cost >= 4 + ? [{ trigger: 'startOfTurn', op: 'createToken', amount: 1, token, condition: { maxTokens: 2 } }] + : [{ trigger: 'onEnter', op: 'createToken', amount: 1, token }]; + } + case 'work': return [ + { trigger: 'onEnter', op: 'draw', amount: 1 }, + { trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 1, condition: { connected: true } }, + ]; + default: return [{ trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 0, condition: { maxPower: 2 } }]; + } + case 'Doctrine': { + if (subtype === 'pathology') return [{ trigger: 'onPlay', op: 'attach', target: 'figure', power: -k, toughness: -k, duration: 'permanent' }]; + const attach: EffectSpec = { trigger: 'onPlay', op: 'attach', target: 'ownFigure', power: k, toughness: k, duration: 'permanent' }; + if (subtype === 'mathematics') return [{ ...attach, grant: ['Well-sourced'] }]; + if (subtype === 'language') return [attach, { trigger: 'onCombatDamageToPlayer', op: 'draw', target: 'attached', amount: 1 }]; + if (subtype === 'ideology') return [attach, { trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 0, condition: { samePortal: true } }]; + return [attach]; + } + default: return []; + } +} diff --git a/shared/duel/sample.ts b/shared/duel/sample.ts new file mode 100644 index 0000000..05df0a9 --- /dev/null +++ b/shared/duel/sample.ts @@ -0,0 +1,38 @@ +/** + * Fixture: docs/game/card-sample.json (236 real random cards) → DuelCard[], for sim-balance, the UI + * and tests. The sample has no on-chain extract, so flavour falls back to the description, and its + * tokenIds are synthetic (the pageId as 64 hex digits). Owner: duel-cards. + */ +import type { CardProfile } from './classify.ts'; +import { derive, DERIVE_RULES, type CardOnChain, type DeriveRules, type DuelCard } from './derive.ts'; + +/** The fields of a card-sample.json card that derivation reads. */ +export interface SampleCard { + pageId: number; title: string; description: string | null; wikidataId: string | null; revisionId: number; + pageBytes: number; languageCount: number; categories: string[]; + stats: { attention: number | null; depth: number; reach: number }; + instanceOf: { id: string; label: string }[]; + extract?: string; +} + +export function sampleTokenId(pageId: number): string { + return pageId.toString(16).padStart(64, '0'); +} + +export function sampleInputs(card: SampleCard): { chain: CardOnChain; profile: CardProfile } { + return { + chain: { + tokenId: sampleTokenId(card.pageId), + article: { pageId: card.pageId, title: card.title, extract: card.extract ?? '', revisionId: card.revisionId }, + statsSnapshot: { pageBytes: card.pageBytes, languageCount: card.languageCount, stats: card.stats }, + }, + profile: { + wikidataId: card.wikidataId, description: card.description, categories: card.categories, + instanceOf: card.instanceOf, fetchedRevisionId: card.revisionId, + }, + }; +} + +export function deriveSample(cards: readonly SampleCard[], rules: DeriveRules = DERIVE_RULES): DuelCard[] { + return cards.map(card => { const { chain, profile } = sampleInputs(card); return derive(chain, profile, rules); }); +} diff --git a/shared/duel/text.ts b/shared/duel/text.ts new file mode 100644 index 0000000..e1af298 --- /dev/null +++ b/shared/duel/text.ts @@ -0,0 +1,135 @@ +/** + * Rules text in MTG's terse register (designer review §3.4–3.5, critic S7, BRIEF decision 5). + * Deterministic templates filled only with the card's own derived numbers and keyword names. + * No prose about the subject, no invented facts: flavour text is the article's own first sentence. + * Owner: duel-cards. + */ +import type { DuelCard, Keyword } from './derive.ts'; +import type { EffectSpec } from './effects.ts'; + +/** Reminder text per keyword (DUEL_DESIGN §4). */ +export const KEYWORD_REMINDER: Readonly> = { + Protected: 'Can\'t be the target of Events or Doctrines an opponent controls.', + Featured: 'Can\'t be blocked except by Featured, Translated or Multilingual Figures.', + Legacy: 'When this is destroyed, draw a card.', + Multilingual: 'Can block Featured Figures. Can\'t be blocked by Local Figures.', + Translated: 'Can block Featured Figures.', + 'Well-sourced': 'Prevent the first 1 damage that would be dealt to this each turn.', + Stub: 'At the start of your turn, put a +1/+1 counter on this, to a maximum of 2.', + Local: 'Gets +1/+1 while you control a Compatriot Location.', +}; + +const NUMBER_WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six']; +const word = (n: number) => NUMBER_WORDS[n] ?? String(n); +const signed = (n: number) => (n >= 0 ? `+${n}` : `−${-n}`); +const pt = (p = 0, t = 0) => `${signed(p)}/${signed(t)}`; + +const TARGET_NOUN: Readonly> = { + figure: 'target Figure', figureOrLocation: 'target Figure or Location', ownFigure: 'target Figure you control', + opponentFigure: 'target Figure you don\'t control', each: 'each Figure and each Location', self: 'this', + attached: 'enchanted Figure', ownFigures: 'Figures you control', +}; + +function keywordsAsText(keywords: readonly Keyword[]): string { + return keywords.join(', '); +} + +function staticText(e: EffectSpec): string { + const c = e.condition ?? {}; + let who = 'Figures you control'; + if (c.maxPower !== undefined) who = `Figures you control with power ${c.maxPower} or less`; + if (c.connected) who = 'Figures you control that are Connected to this'; + if (c.samePortal) who = 'Other Figures you control of its Portal'; + if (e.grant?.length && !e.power && !e.toughness) { + return `${who} have ${keywordsAsText(e.grant)}${c.whileAttacking ? ' while attacking' : ''}.`; + } + return `${who} get ${pt(e.power, e.toughness)}.`; +} + +function tokenText(e: EffectSpec): string { + const t = e.token!; + const n = e.amount ?? 1; + const portal = t.portal === 'Neutral' ? '' : `${t.portal} `; + const body = `${t.power}/${t.toughness} ${portal}Figure token${n === 1 ? '' : 's'} named ${t.name}`; + return n === 1 ? `create a ${body}` : `create ${word(n)} ${body}`; +} + +function actionText(e: EffectSpec): string { + switch (e.op) { + case 'damage': return `deal ${e.amount} damage to ${TARGET_NOUN[e.target ?? 'figure']}`; + case 'damageEach': return `deal ${e.amount} damage to each Figure and each Location`; + case 'createToken': return tokenText(e); + case 'pump': return `${TARGET_NOUN[e.target ?? 'figure']} gets ${pt(e.power, e.toughness)}${e.duration === 'turn' ? ' until end of turn' : ''}`; + case 'fight': return `it fights ${TARGET_NOUN[e.target ?? 'opponentFigure']}`; + case 'draw': return e.amount === 1 ? 'draw a card' : `draw ${word(e.amount ?? 1)} cards`; + case 'gainLife': return `you gain ${e.amount} Notability`; + case 'attach': return ''; + } +} + +const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1); + +/** One sentence per effect, in effect order. */ +export function effectText(effects: readonly EffectSpec[]): string[] { + const lines: string[] = []; + for (let i = 0; i < effects.length; i++) { + const e = effects[i]; + if (e.op === 'attach') { + const grant = e.grant?.length ? ` and has ${keywordsAsText(e.grant)}` : ''; + lines.push(`Attach to ${e.target === 'figure' ? 'target Figure' : 'target Figure you control'}. It gets ${pt(e.power, e.toughness)}${grant}.`); + continue; + } + if (e.op === 'fight' && i > 0 && effects[i - 1].op === 'pump') { + lines[lines.length - 1] = lines[lines.length - 1].replace(/\.$/, `, then ${actionText(e)}.`); + continue; + } + switch (e.trigger) { + case 'static': lines.push(staticText(e)); break; + case 'onPlay': lines.push(`${cap(actionText(e))}.`); break; + case 'onEnter': lines.push(`When this enters, ${actionText(e)}.`); break; + case 'onDestroyed': lines.push(`When this is destroyed, ${actionText(e)}.`); break; + case 'startOfTurn': { + const max = e.condition?.maxTokens; + const cond = max !== undefined ? `, if you control fewer than ${max + 1} tokens` : ''; + lines.push(`At the start of your turn${cond}, ${actionText(e)}.`); + break; + } + case 'onCombatDamageToPlayer': + lines.push(`Whenever ${e.target === 'attached' ? 'it' : 'this'} deals combat damage to a player, ${actionText(e)}.`); + break; + } + } + return lines; +} + +/** The type line, e.g. "Figure — Society" or "Event — History". */ +export function typeLine(card: Pick): string { + return card.portal === 'Neutral' ? card.type : `${card.type} — ${card.portal}`; +} + +/** Full rules text: keyword line, Location lines, effect lines. Newline-separated. */ +export function rulesTextFor(card: Pick): string { + const lines: string[] = []; + if (card.keywords.length) lines.push(`${keywordsAsText(card.keywords)}.`); + if (card.type === 'Location') { + if (card.territory) lines.push('Territory.'); + lines.push(`Garrison 0/${card.toughness}.`); + } + lines.push(...effectText(card.effects)); + return lines.join('\n'); +} + +export const RULE_WORD_REMINDER: Readonly> = { + Territory: 'Your Citation maximum is 1 higher while you control this, to at most +2 from Territory.', + Garrison: 'This can block like a Figure with power 0. It can\'t attack.', +}; + +/** Rules text with reminder text for keywords and rule words, for the tap-to-expand view. */ +export function rulesTextWithReminders(card: Pick): string { + const lines = card.keywords.map(k => `${k}. (${KEYWORD_REMINDER[k]})`); + for (const line of rulesTextFor({ ...card, keywords: [] }).split('\n').filter(Boolean)) { + const word = line.match(/^(Territory|Garrison)\b/)?.[1] as keyof typeof RULE_WORD_REMINDER | undefined; + lines.push(word ? `${line} (${RULE_WORD_REMINDER[word]})` : line); + } + return lines.join('\n'); +} diff --git a/tests/duel-cards-derive.test.ts b/tests/duel-cards-derive.test.ts new file mode 100644 index 0000000..5f522ec --- /dev/null +++ b/tests/duel-cards-derive.test.ts @@ -0,0 +1,205 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { classify } from '../shared/duel/classify.ts'; +import { + derive, connectedTier, figureBody, flavorFor, portalFor, DERIVE_RULES, DERIVE_VERSION, + type DuelCard, type CardProfile, +} from '../shared/duel/derive.ts'; +import { deriveSample, sampleInputs, type SampleCard } from '../shared/duel/sample.ts'; +import { rulesTextFor, rulesTextWithReminders, typeLine } from '../shared/duel/text.ts'; + +const root = new URL('../', import.meta.url); +const SAMPLE = (JSON.parse(readFileSync(new URL('docs/game/card-sample.json', root), 'utf8')) as { cards: SampleCard[] }).cards; +const FIXTURE = JSON.parse(readFileSync(new URL('docs/game/duel-card-sample.json', root), 'utf8')) as { deriveVersion: string; cards: DuelCard[] }; +const CARDS = deriveSample(SAMPLE); +const byTitle = (title: string) => { + const card = CARDS.find(c => c.title === title); + assert.ok(card, `missing sample card ${title}`); + return card; +}; +const profile = (overrides: Partial): CardProfile => + ({ wikidataId: null, description: null, categories: [], instanceOf: [], ...overrides }); + +test('every sample card gets a type, and nothing falls through to the Doctrine residual', () => { + assert.equal(CARDS.length, 236); + const fallback = CARDS.filter(c => c.typedBy === 'fallback'); + assert.deepEqual(fallback.map(c => c.title), []); + const share = (t: string) => CARDS.filter(c => c.type === t).length / CARDS.length; + // data §1 distribution, ±4 points + assert.ok(Math.abs(share('Figure') - 0.364) < 0.04); + assert.ok(Math.abs(share('Location') - 0.331) < 0.04); + assert.ok(share('Event') > 0.05 && share('Doctrine') > 0.05 && share('Institution') > 0.1); +}); + +test('"human settlement" villages are Locations, not Figures (the \\bhuman\\b bug)', () => { + for (const title of ['Buky', 'Lunugala', 'Žižki', 'Laukhella']) assert.equal(byTitle(title).type, 'Location', title); + assert.equal(classify(profile({ instanceOf: [{ id: 'Q999', label: 'human settlement' }] })).type, 'Location'); + assert.equal(classify(profile({ instanceOf: [{ id: 'Q999', label: 'human' }] })).type, 'Figure'); +}); + +test('rule order: elections beat "municipal", aspects beat "region", governing bodies are Institutions', () => { + assert.equal(byTitle('2023 Seville municipal election').type, 'Event'); + assert.equal(byTitle('Corruption in Kazakhstan').type, 'Doctrine'); + assert.equal(byTitle('Diocese of Mindelo').type, 'Institution'); + assert.equal(byTitle('Region Östergötland').type, 'Institution'); + assert.equal(byTitle('Lewis and Elizabeth Bolton House').type, 'Location'); +}); + +test('P279 anchors and labels classify items without P31; categories then description are fallbacks', () => { + assert.deepEqual(classify(profile({ subclassOf: [{ id: 'Q1', label: 'algebraic structure' }] })), + { type: 'Doctrine', source: 'p279', matched: 'algebraic structure' }); + assert.equal(classify(profile({ subclassOf: [{ id: 'Q43229', label: 'x' }] })).source, 'p279-qid'); + assert.equal(classify(profile({ categories: ['Villages in Somewhere', 'Somewhere geography stubs'] })).type, 'Location'); + assert.equal(classify(profile({ description: 'Species of beetle' })).type, 'Figure'); + assert.deepEqual(classify(profile({})), { type: 'Doctrine', source: 'fallback', matched: '' }); +}); + +test('derive is deterministic and the committed fixture is current', () => { + assert.deepEqual(deriveSample(SAMPLE), CARDS); + assert.equal(FIXTURE.deriveVersion, DERIVE_VERSION); + assert.deepEqual(FIXTURE.cards, CARDS, 'run: node --experimental-strip-types scripts/duel-card-sample.ts'); + const { chain, profile: p } = sampleInputs(SAMPLE[0]); + const frozen = structuredClone(p); + derive(chain, p); + assert.deepEqual(p, frozen, 'derive must not mutate the profile'); +}); + +test('costs, bodies and keyword caps stay in range', () => { + for (const c of CARDS) { + assert.ok(c.keywords.length <= 2, c.title); + if (c.type === 'Figure') { + assert.ok(c.cost >= 1 && c.cost <= 6, c.title); + const taxed = c.keywords.filter(k => DERIVE_RULES.taxedKeywords.includes(k)).length; + assert.ok(c.connect.qid === null || /^Q\d+$/.test(c.connect.qid)); + assert.equal(c.power! + c.toughness!, DERIVE_RULES.bodyBudget[c.cost] - taxed, c.title); + assert.ok(c.power! >= 1 && c.toughness! >= 1, c.title); + } else if (c.type === 'Location') { + assert.ok(c.cost >= 1 && c.cost <= 3, c.title); + assert.equal(c.power, 0); + assert.ok(c.toughness! >= 1 && c.toughness! <= 4); + assert.deepEqual(c.keywords, []); + } else { + assert.equal(c.power, null); + assert.ok(c.effects.length > 0, c.title); + } + } +}); + +test('no famous Figure is strictly better than another Figure of no lower cost with the same keywords (data §2)', () => { + const figures = CARDS.filter(c => c.type === 'Figure'); + const dominated: string[] = []; + for (const x of figures) for (const y of figures) { + if (x === y || x.keywords.join() !== y.keywords.join()) continue; + if (x.cost <= y.cost && x.power! >= y.power! && x.toughness! >= y.toughness! + && (x.cost < y.cost || x.power! > y.power! || x.toughness! > y.toughness!)) dominated.push(`${x.title} > ${y.title}`); + } + assert.deepEqual(dominated, []); + // Fame buys size, not efficiency: (P+T)/cost does not rise with cost. + const eff = (cost: number) => { const g = figures.filter(c => c.cost === cost); return g.reduce((s, c) => s + (c.power! + c.toughness!) / cost, 0) / g.length; }; + for (let cost = 2; cost <= 6; cost++) assert.ok(eff(cost) < eff(1) && eff(cost) <= 2, `cost ${cost}: ${eff(cost)}`); +}); + +test('figureBody: keyword tax comes off the budget first, then attention vs depth splits it', () => { + assert.deepEqual(figureBody(4, { attention: 90, depth: 10, reach: 0 }, []), { power: 7, toughness: 1, keywords: [] }); + assert.deepEqual(figureBody(4, { attention: 10, depth: 90, reach: 0 }, ['Featured']), { power: 1, toughness: 6, keywords: ['Featured'] }); + assert.deepEqual(figureBody(1, { attention: 50, depth: 50, reach: 0 }, ['Legacy', 'Stub', 'Local']), + { power: 1, toughness: 1, keywords: ['Legacy', 'Stub'] }); + assert.deepEqual(figureBody(1, { attention: 50, depth: 50, reach: 0 }, ['Protected', 'Legacy', 'Stub']), + { power: 1, toughness: 1, keywords: ['Protected', 'Stub'] }); + assert.deepEqual(figureBody(3, { attention: null, depth: 50, reach: 0 }, ['Translated', 'Stub', 'Local']), + { power: 3, toughness: 3, keywords: ['Translated', 'Stub'] }); +}); + +test('keyword bands: Multilingual and Translated never both; Figures only', () => { + for (const c of CARDS) { + assert.ok(!(c.keywords.includes('Multilingual') && c.keywords.includes('Translated')), c.title); + if (c.type !== 'Figure') assert.deepEqual(c.keywords, [], c.title); + } +}); + +test('DUEL_DESIGN §9 worked examples (golden)', () => { + const show = (title: string) => { + const c = byTitle(title); + const body = c.type === 'Figure' || c.type === 'Location' ? ` · ${c.power}/${c.toughness}` : ''; + return `${c.cost} · ${typeLine(c)}${body} · ${c.rulesText.replace(/\n/g, ' ')} · ${c.flavor}`; + }; + const golden: Record = { + 'Marc Fesneau': '5 · Figure — Society · 5/4 · Protected. · French politician (born 1971)', + 'Tom Ewell': '6 · Figure — Arts · 5/5 · Featured, Legacy. · American actor (1909–1994)', + 'Zbyszek Godlewski': '5 · Figure — History · 6/3 · Legacy, Translated. · Polish protester (1952–1970)', + "Pallas's cat": '6 · Figure — Earth · 5/5 · Featured, Multilingual. · Species of small wild cat', + 'Dichromorpha viridis': '2 · Figure — Earth · 3/1 · Stub. · Species of grasshopper', + Monoid: '6 · Doctrine — Science · Attach to target Figure you control. It gets +3/+3 and has Well-sourced. · ' + + 'Algebraic structure with an associative operation and an identity element', + 'Heart rot': '5 · Doctrine — Science · Attach to target Figure. It gets −3/−3. · Fungal disease of trees', + "April 2021 nor'easter": "3 · Event — Earth · Deal 1 damage to each Figure and each Location. · Slow-moving nor'easter in April 2021", + // §9 says History; the Portal score is Society (protest/riot categories outnumber "war"). + '2025 Tehreek-e-Labbaik Pakistan protests': '5 · Event — Society · Deal 4 damage to target Figure or Location. · Gaza war protests in Pakistan', + '1954 Gold Coast general election': '3 · Event — Society · Create two 1/1 Society Figure tokens named Elected Member. · ', + // §9 says History; "mosque" hits (P31, description, 2 categories) outscore 15th-century + Sultanate. + 'Pathrail Mosque': '2 · Location — Society · 0/3 · Territory. Garrison 0/3. · Mosque in Faridpur, Bangladesh', + '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', + 'Agda (programming language)': '6 · Doctrine — Science · Attach to target Figure you control. It gets +3/+3. ' + + 'Whenever it deals combat damage to a player, draw a card. · Functional programming language', + }; + for (const [title, want] of Object.entries(golden)) assert.equal(show(title), want, title); + assert.equal(rulesTextWithReminders(byTitle('Tom Ewell')), + 'Featured. (Can\'t be blocked except by Featured, Translated or Multilingual Figures.)\nLegacy. (When this is destroyed, draw a card.)'); + assert.equal(rulesTextWithReminders(byTitle('Pathrail Mosque')), + 'Territory. (Your Citation maximum is 1 higher while you control this, to at most +2 from Territory.)\n' + + 'Garrison 0/3. (This can block like a Figure with power 0. It can\'t attack.)'); +}); + +test('rules text uses only card numbers and fixed words: no title, description or category text leaks in', () => { + for (const c of CARDS) { + const stripped = c.rulesText.replace(/Protected|Featured|Translated|Legacy|Stub|Well-sourced|Multilingual|Local/g, ''); + assert.ok(!stripped.includes(c.title), c.title); + assert.match(c.rulesText, /^[A-Za-z0-9 ,.;:'()+−/\n—-]*$/, c.title); + assert.equal(rulesTextFor(c), c.rulesText); + } +}); + +test('flavour is the first sentence of the extract, else the description', () => { + assert.equal(flavorFor('Tom Ewell (born Samuel Yewell Tompkins; April 29, 1909 – September 12, 1994) was an American actor. He won a Tony.', null), + 'Tom Ewell (born Samuel Yewell Tompkins; April 29, 1909 – September 12, 1994) was an American actor.'); + assert.equal(flavorFor('J. R. R. Tolkien was an English writer. He wrote.', null), 'J. R. R. Tolkien was an English writer.'); + assert.equal(flavorFor('The U.S. Route 66 is a road in the U.S. state of Arizona. More.', null), 'The U.S. Route 66 is a road in the U.S. state of Arizona.'); + assert.equal(flavorFor('No terminal punctuation', 'desc'), 'No terminal punctuation'); + assert.equal(flavorFor(' ', 'Species of grasshopper'), 'Species of grasshopper'); + assert.equal(byTitle('Dichromorpha viridis').flavor, 'Species of grasshopper'); +}); + +test('Portals: keyword hits decide, ties go to the type default, no hits is Neutral', () => { + assert.equal(portalFor(profile({ description: 'Sultan of Aceh', categories: ['16th-century monarchs in Asia'] }), 'Figure'), 'History'); + assert.equal(portalFor(profile({ description: 'mathematician and politician' }), 'Figure'), 'Society'); + assert.equal(portalFor(profile({ description: 'zzz' }), 'Figure'), 'Neutral'); + const portals = new Set(CARDS.map(c => c.portal)); + for (const p of ['Arts', 'Earth', 'History', 'Science', 'Society']) assert.ok(portals.has(p as DuelCard['portal']), p); +}); + +test('Connected: Linked beats Compatriot beats Contemporary beats Kin; a card is never connected to itself', () => { + const base = (id: string, pageId: number, connect: Partial, type: DuelCard['type'] = 'Event'): DuelCard => + ({ ...byTitle('Tom Ewell'), cardId: id, pageId, type, connect: { countries: [], centuries: [], links: [], p31: [], qid: null, cites: [], ...connect } }); + const a = base('a', 1, { links: [2], countries: ['France'], centuries: [20], p31: ['Q1'], qid: 'Q100' }, 'Figure'); + assert.equal(connectedTier(a, base('g', 7, { cites: ['Q100'] })), 'Linked'); + assert.equal(connectedTier(a, base('h', 8, { centuries: [20] }, 'Figure')), null, 'Contemporary needs different types'); + assert.equal(connectedTier(a, base('b', 2, { countries: ['France'] })), 'Linked'); + assert.equal(connectedTier(base('b', 2, { links: [1] }), a), 'Linked'); + assert.equal(connectedTier(a, base('c', 3, { countries: ['France'], centuries: [20] })), 'Compatriot'); + assert.equal(connectedTier(a, base('d', 4, { centuries: [20] })), 'Contemporary'); + assert.equal(connectedTier(a, base('e', 5, { p31: ['Q1'] })), 'Kin'); + assert.equal(connectedTier(a, base('f', 6, {})), null); + assert.equal(connectedTier(a, a), null); + assert.equal(connectedTier(a, base('c', 3, { centuries: [20] }), ['Linked', 'Compatriot']), null); +}); + +test('Connected fires in a plausible share of sample pairs (BRIEF target 15–30%, tuned in the sim)', () => { + let hits = 0, pairs = 0; + for (let i = 0; i < CARDS.length; i++) for (let j = i + 1; j < CARDS.length; j++) { + pairs++; if (connectedTier(CARDS[i], CARDS[j])) hits++; + } + const rate = hits / pairs; + assert.ok(rate > 0.1 && rate < 0.4, `rate ${rate}`); +}); From a8468dd96c72bce9317c99d6f0365208e2766f2e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:47:00 -0500 Subject: [PATCH 07/25] [duel-cards] profile.ts: build the frozen CardProfile from enrichment + wbgetentities (pure, no fetch) Co-Authored-By: Claude Opus 5.5 --- shared/duel/profile.ts | 114 +++++++++++++++++++++++++++++++ tests/duel-cards-profile.test.ts | 71 +++++++++++++++++++ 2 files changed, 185 insertions(+) create mode 100644 shared/duel/profile.ts create mode 100644 tests/duel-cards-profile.test.ts diff --git a/shared/duel/profile.ts b/shared/duel/profile.ts new file mode 100644 index 0000000..6b24c0f --- /dev/null +++ b/shared/duel/profile.ts @@ -0,0 +1,114 @@ +/** + * Building the frozen CardProfile (data review §3) from data the host already has or fetches once + * through the polite Wikimedia client. Pure: this file never fetches. The host: + * 1. takes the cached PageEnrichment (description, wikidataId, categories), + * 2. fetches the item once with wikidataEntityParams([qid, …]) (≤ 50 ids per request), + * 3. fetches the labels of the P31/P279 classes it doesn't know with wikidataLabelParams(ids), + * 4. optionally adds outlinks (prop=links, ns0) as pageIds, + * 5. calls profileFromSources() and stores the result per tokenId forever. + * Owner: duel-cards. + */ +import type { PageEnrichment } from '../enrichment.ts'; +import type { CardProfile, WikidataClass } from './classify.ts'; + +export const PROFILE_PROPERTIES = { + instanceOf: 'P31', subclassOf: 'P279', country: 'P17', citizenship: 'P27', + birth: 'P569', death: 'P570', inception: 'P571', start: 'P580', pointInTime: 'P585', +} as const; + +/** Properties whose item values count as "cited" for the Linked tier (DUEL_DESIGN §6). */ +export const CITE_PROPERTIES = ['P17', 'P27', 'P131', 'P361', 'P527', 'P463', 'P102', 'P108', 'P69', 'P19', 'P20', 'P710', 'P1344', 'P276'] as const; + +/** Action API parameters for wbgetentities (claims only, so the payload stays small). */ +export function wikidataEntityParams(qids: readonly string[]): Record { + if (qids.length < 1 || qids.length > 50) throw new RangeError('wbgetentities takes 1 to 50 ids'); + return { action: 'wbgetentities', ids: [...qids].sort().join('|'), props: 'claims', format: 'json', formatversion: '2' }; +} + +/** Action API parameters for class labels (English). */ +export function wikidataLabelParams(qids: readonly string[]): Record { + if (qids.length < 1 || qids.length > 50) throw new RangeError('wbgetentities takes 1 to 50 ids'); + return { action: 'wbgetentities', ids: [...qids].sort().join('|'), props: 'labels', languages: 'en', format: 'json', formatversion: '2' }; +} + +/** The slice of a wbgetentities entity this module reads. Unknown shapes are ignored, never thrown on. */ +export interface WikidataEntity { + id?: string; + claims?: Record; +} + +function claimValues(entity: WikidataEntity | null | undefined, property: string): unknown[] { + const statements = entity?.claims?.[property]; + if (!Array.isArray(statements)) return []; + return statements + .filter(s => s?.rank !== 'deprecated' && s?.mainsnak?.snaktype === 'value') + .map(s => s.mainsnak?.datavalue?.value) + .filter(v => v !== undefined); +} + +function itemIds(entity: WikidataEntity | null | undefined, property: string): string[] { + return claimValues(entity, property) + .map(v => (v && typeof v === 'object' && 'id' in v && typeof (v as { id: unknown }).id === 'string') ? (v as { id: string }).id : null) + .filter((id): id is string => id !== null && /^Q\d+$/.test(id)); +} + +/** Years from Wikidata time values ("+1909-04-29T00:00:00Z", "-0044-03-15T…"). */ +function years(entity: WikidataEntity | null | undefined, property: string): number[] { + return claimValues(entity, property) + .map(v => (v && typeof v === 'object' && 'time' in v) ? String((v as { time: unknown }).time) : '') + .map(t => /^([+-])0*(\d{1,6})-/.exec(t)) + .filter((m): m is RegExpExecArray => m !== null) + .map(m => (m[1] === '-' ? -1 : 1) * Number(m[2])) + .filter(y => y !== 0); +} + +/** Q-ids whose labels the host must look up to classify this entity. */ +export function classIdsOf(entity: WikidataEntity | null | undefined): string[] { + return [...new Set([...itemIds(entity, 'P31'), ...itemIds(entity, 'P279')])].sort(); +} + +export interface ProfileSources { + enrichment: Pick; + /** The card's own wbgetentities entity, or null when it has no item or the fetch is pending. */ + entity?: WikidataEntity | null; + /** English labels for class Q-ids; missing labels are kept as the bare Q-id. */ + labels?: Readonly>; + /** Superclass chain for the P31 classes (P279, up to 4 hops), nearest first, if the host resolved it. */ + superclasses?: readonly WikidataClass[]; + /** ns0 outlinks resolved to pageIds. */ + links?: readonly number[]; +} + +export function profileFromSources(src: ProfileSources): CardProfile { + const { enrichment, entity, labels = {} } = src; + const label = (id: string): WikidataClass => ({ id, label: labels[id] ?? id }); + const countries = [...new Set([...itemIds(entity, 'P17'), ...itemIds(entity, 'P27')])].sort(); + const yrs = [...new Set(['P569', 'P570', 'P571', 'P580', 'P585'].flatMap(p => years(entity, p)))].sort((a, b) => a - b); + const cites = [...new Set(CITE_PROPERTIES.flatMap(p => itemIds(entity, p)))].sort(); + const subclassOf = [...itemIds(entity, 'P279').map(label), ...(src.superclasses ?? [])]; + const profile: CardProfile = { + wikidataId: enrichment.wikidataId, + description: enrichment.description, + categories: [...enrichment.categories], + instanceOf: itemIds(entity, 'P31').map(label), + fetchedRevisionId: enrichment.revisionId, + }; + if (subclassOf.length) profile.subclassOf = subclassOf; + if (countries.length) profile.countries = countries; + if (yrs.length) profile.years = yrs; + if (claimValues(entity, 'P570').length) profile.died = true; + if (cites.length) profile.cites = cites; + if (src.links?.length) profile.links = [...new Set(src.links)].sort((a, b) => a - b); + return profile; +} + +/** A canonical JSON string of a profile, for storing, hashing and logging in the match record. */ +export function canonicalProfile(profile: CardProfile): string { + const sortKeys = (v: unknown): unknown => Array.isArray(v) ? v.map(sortKeys) + : v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map(k => [k, sortKeys((v as Record)[k])])) + : v; + return JSON.stringify(sortKeys(profile)); +} diff --git a/tests/duel-cards-profile.test.ts b/tests/duel-cards-profile.test.ts new file mode 100644 index 0000000..9fc274e --- /dev/null +++ b/tests/duel-cards-profile.test.ts @@ -0,0 +1,71 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + canonicalProfile, classIdsOf, profileFromSources, wikidataEntityParams, wikidataLabelParams, type WikidataEntity, +} from '../shared/duel/profile.ts'; +import { classify } from '../shared/duel/classify.ts'; +import { derive } from '../shared/duel/derive.ts'; + +const item = (id: string) => ({ rank: 'normal', mainsnak: { snaktype: 'value', datavalue: { type: 'wikibase-entityid', value: { id } } } }); +const time = (t: string) => ({ rank: 'normal', mainsnak: { snaktype: 'value', datavalue: { type: 'time', value: { time: t } } } }); + +const EWELL: WikidataEntity = { + id: 'Q1351340', + claims: { + P31: [item('Q5')], + P27: [item('Q30')], + P569: [time('+1909-04-29T00:00:00Z')], + P570: [time('+1994-09-12T00:00:00Z')], + P19: [item('Q1018580')], + P106: [item('Q33999')], + P17: [{ rank: 'deprecated', mainsnak: { snaktype: 'value', datavalue: { value: { id: 'Q999' } } } }], + }, +}; +const ENRICH = { description: 'American actor (1909–1994)', wikidataId: 'Q1351340', categories: ['1994 deaths', 'American male actors'], revisionId: 42 }; + +test('profileFromSources reads P31, countries, years, death and cited items; ignores deprecated claims', () => { + const p = profileFromSources({ enrichment: ENRICH, entity: EWELL, labels: { Q5: 'human' }, links: [9, 3, 9] }); + assert.deepEqual(p, { + wikidataId: 'Q1351340', description: 'American actor (1909–1994)', categories: ['1994 deaths', 'American male actors'], + instanceOf: [{ id: 'Q5', label: 'human' }], fetchedRevisionId: 42, + countries: ['Q30'], years: [1909, 1994], died: true, cites: ['Q1018580', 'Q30'], links: [3, 9], + }); + assert.equal(classify(p).type, 'Figure'); +}); + +test('BCE years are negative; malformed and novalue claims are skipped without throwing', () => { + const entity: WikidataEntity = { claims: { + P571: [time('-0753-04-21T00:00:00Z'), { mainsnak: { snaktype: 'novalue' } }, { mainsnak: { snaktype: 'value', datavalue: { value: 'junk' } } }], + P31: [item('not-a-qid'), item('Q515')], + } }; + const p = profileFromSources({ enrichment: { ...ENRICH, categories: [] }, entity }); + assert.deepEqual(p.years, [-753]); + assert.deepEqual(p.instanceOf, [{ id: 'Q515', label: 'Q515' }]); + assert.equal(classify(p).type, 'Location', 'Q-id anchors classify even without labels'); + assert.equal(profileFromSources({ enrichment: ENRICH, entity: null }).instanceOf.length, 0); +}); + +test('without a Wikidata item the profile still classifies from categories and description', () => { + const p = profileFromSources({ enrichment: { description: 'Village in Poland', wikidataId: null, categories: ['Villages in Gmina X'], revisionId: 1 } }); + assert.equal(classify(p).type, 'Location'); +}); + +test('request parameters: claims-only entities, English labels, ≤ 50 sorted ids', () => { + assert.deepEqual(wikidataEntityParams(['Q5', 'Q1']), { action: 'wbgetentities', ids: 'Q1|Q5', props: 'claims', format: 'json', formatversion: '2' }); + assert.equal(wikidataLabelParams(['Q5']).props, 'labels'); + assert.throws(() => wikidataEntityParams([]), RangeError); + assert.throws(() => wikidataLabelParams(Array.from({ length: 51 }, (_, i) => `Q${i + 1}`)), RangeError); + assert.deepEqual(classIdsOf({ claims: { P31: [item('Q5')], P279: [item('Q2'), item('Q5')] } }), ['Q2', 'Q5']); +}); + +test('canonicalProfile is key-order independent, and the frozen profile derives the same card twice', () => { + const p = profileFromSources({ enrichment: ENRICH, entity: EWELL, labels: { Q5: 'human' } }); + const shuffled = Object.fromEntries(Object.entries(p).reverse()) as typeof p; + assert.equal(canonicalProfile(shuffled), canonicalProfile(p)); + const chain = { tokenId: 'ab'.repeat(32), article: { pageId: 1, title: 'Tom Ewell', extract: 'Tom Ewell was an American actor. More.', revisionId: 42 }, + statsSnapshot: { pageBytes: 9000, languageCount: 30, stats: { attention: 60, depth: 70, reach: 50 } } }; + const thawed = JSON.parse(canonicalProfile(p)); + assert.deepEqual(derive(chain, thawed), derive(chain, p)); + assert.equal(derive(chain, p).flavor, 'Tom Ewell was an American actor.'); + assert.ok(derive(chain, p).keywords.includes('Legacy')); +}); From 5d5eaa5488f2dbd0950b67fb915f34e6100716c5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:49:52 -0500 Subject: [PATCH 08/25] 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 --- docs/game/DUEL_API.md | 121 +++++++++-------- shared/duel/ruleset.ts | 15 ++- shared/duel/types.ts | 292 ++++++++++++++++++++++++----------------- 3 files changed, 250 insertions(+), 178 deletions(-) diff --git a/docs/game/DUEL_API.md b/docs/game/DUEL_API.md index a52fd32..79c6d99 100644 --- a/docs/game/DUEL_API.md +++ b/docs/game/DUEL_API.md @@ -1,83 +1,88 @@ # 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 ]`. +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 ]`. ## 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. +- **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 (`shared/duel/derive.ts`) and frozen by the host at match start. +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 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'` | +| `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?` | | -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. +### 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. -- **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. +- **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?, 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). +`{ 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:`); `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 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. +## 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. +- **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`), 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` (null by default): after that many total turns, higher Notability wins, then higher total power in play, then the second player. ## Phases and actions -`phase`: `mulligan` → `main` → `attack` → `block` → (next turn's `main`) … `over`. - -| Phase | Who acts | Actions | +| Phase | Who acts | Listed 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}` (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`. | +| `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 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`. +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, 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. +- `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. +- `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 -`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/`. +`duelEnginePort` (engine.ts) is structurally an `EnginePort` (`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 -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. +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. diff --git a/shared/duel/ruleset.ts b/shared/duel/ruleset.ts index fb33fc0..8c7e2a3 100644 --- a/shared/duel/ruleset.ts +++ b/shared/duel/ruleset.ts @@ -21,12 +21,18 @@ export const DuelRulesetSchema = z.object({ 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(); @@ -43,12 +49,17 @@ export const DEFAULT_DUEL_RULESET: DuelRuleset = Object.freeze({ 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: null, }) as DuelRuleset; @@ -59,7 +70,7 @@ export function parseDuelRuleset(value: unknown): 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 (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({ ...base, ...(overrides as Record) }); + return parseDuelRuleset({ ...structuredClone(base), ...(overrides as Record) }); } diff --git a/shared/duel/types.ts b/shared/duel/types.ts index f1b181c..a2d7e62 100644 --- a/shared/duel/types.ts +++ b/shared/duel/types.ts @@ -1,6 +1,6 @@ /** * WikiDeck Duel: the Magic-style 40-card engine (off-chain). Contract types. - * Spec: docs/game/DUEL_API.md. Owner: duel-core (claude/wikideck#55). + * 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). @@ -18,106 +18,133 @@ export const SEATS: readonly Seat[] = [0, 1]; 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']; +export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral'; +export const PORTALS: readonly Portal[] = ['Arts', 'Earth', 'History', 'Science', 'Society', 'Neutral']; -/** Connected tiers (BRIEF "Connected", data §4). 'Linked' is the direct connection. */ +/** 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[]; +} /** 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) + | '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 -/** The ≤12 effect ops the interpreter knows. duel-cards builds templates from these. */ +/** Effect ops the interpreter knows. duel-cards builds the 12 templates (DUEL_DESIGN §5) 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 + | '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 = - | '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 + // 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; - target: TargetSpec; + /** Default per op: damage → 'anyTarget'; pump → 'self'; draw/gainLife/createToken → 'controller'; drain → 'opponent'. */ + 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). */ + /** 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; } -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. + * 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 card hash (or a sample id in sims). */ + /** 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; - /** Short description line ("American actor (1909–1994)") for log first mentions. */ + /** Wikidata description ("American actor (1909–1994)"), for log first mentions. */ description?: string; type: CardType; - /** Faction ("Portal") id, cosmetic for deckbuilding (no colour restrictions). */ - portal: string; + /** e.g. 'conflict', 'election', 'organisation', 'pathology'. */ + subtype?: string | null; + portal: Portal; cost: number; - /** Figures; 0 for other types. */ - power: number; - toughness: 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: +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 }; + /** Locations: +N max Citations while controlled (all sources together ≤ territoryCap). */ + territory?: 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'; + 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; } // --------------------------------------------------------------------------- @@ -130,22 +157,27 @@ export interface DuelRuleset { engine: 'duel'; version: string; deckSize: number; // 40 - maxCopiesPerPage: number; // 4: copies of one pageId in a deck + maxCopiesPerPage: number; // 4 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 + 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 + maxCitations: number; // 10 + citationsPerTurn: number; // 1 + territoryCap: number; // 2 + locationsPerTurn: number; // 1 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) + 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 - /** Optional: after this many turns in total, more Notability wins (tie: draw). null = none. */ + timeoutsToConcede: number; // 3 consecutive timeouts lose + /** Optional: after this many turns in total, higher Notability wins, then higher power in play, then the second player. */ turnCap: number | null; } @@ -153,10 +185,10 @@ export interface DuelRuleset { // State // --------------------------------------------------------------------------- -/** 'mulligan' → 'main' → 'attack' → ('block' if attackers) → next turn. Refresh, draw, damage and end are automatic steps. */ +/** '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); actions use uids. */ +/** 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; @@ -169,19 +201,25 @@ export interface Permanent extends CardInstance { /** "Pending review": entered this turn, can't attack. */ sick: boolean; damage: number; - /** Permanent +1/+1 counters. */ + /** 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; - /** Stub: counters gained from Stub so far (≤ 2). */ - stubCounters?: number; + shielded: boolean; + /** Entry order (trigger order). */ + entered: number; /** Connected bonus already logged. */ - connectedLogged?: boolean; + connectedLogged: boolean; } export interface PlayerState { @@ -190,17 +228,18 @@ export interface PlayerState { 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 + graveyard: CardInstance[]; // "Deleted", public mulligansTaken: number; - ready: boolean; // kept the opening hand - /** Remaining time bank, in seconds (the host decrements it). */ + ready: boolean; + locationsThisTurn: number; + /** Remaining time bank in seconds (the host decrements it). */ bankSeconds: number; - /** libraryEmpty 'fatigue': damage of the next empty draw minus 1. */ - fatigue?: number; + /** Consecutive timeouts. */ + timeouts: number; + /** libraryEmpty 'fatigue': damage of the last empty draw. */ + fatigue: number; } export interface CombatState { @@ -209,9 +248,11 @@ export interface CombatState { blocks: Record; } +export type EndReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap'; + export interface DuelResult { winner: Seat | null; // null = draw - reason: 'life' | 'library' | 'concede' | 'timeout' | 'turnCap'; + reason: EndReason; } export interface DuelState { @@ -231,6 +272,9 @@ export interface DuelState { 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; } // --------------------------------------------------------------------------- @@ -242,46 +286,57 @@ export type TargetRef = { kind: 'card'; uid: string } | { kind: 'player'; seat: export type DuelAction = | { type: 'keep' } | { type: 'mulligan' } - | { type: 'play'; uid: string; target?: TargetRef } - | { type: 'endPhase' } // main → attack - | { 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), monotonic - | { type: 'confirmBlocks' } // damage, then end of turn - | { type: 'concede' } // any time, either seat - | { type: 'timeout' }; // host-only, for the seat that must act + /** 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, per seat via logFor; full log stays in DuelState.log) +// Log (encyclopedic; clients get logFor(state, seat); state.log is omniscient) // --------------------------------------------------------------------------- -/** Public reference to a card in the log. */ -export interface CardRef { uid: string; cardId: string; title: string; pageId: number | null } +/** 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: 'turn'; seat: Seat; citations: 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 } - | { kind: 'play'; seat: Seat; card: CardRef; cardType: CardType; target?: TargetRef } - | { kind: 'attach'; seat: Seat; card: CardRef; to: 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 } - | { kind: 'effect'; seat: Seat; source: CardRef; op: EffectOp; template?: string; amount?: number; targets: TargetRef[] } + /** 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 }[] } - | { kind: 'damage'; source: CardRef; target: TargetRef; amount: number } - | { kind: 'life'; seat: Seat; delta: number; life: number } + /** 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 } - /** 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'] } + | { kind: 'gameOver'; winner: Seat | null; reason: EndReason; life: [number, number] } ); export type LogKind = LogEvent['kind']; @@ -300,9 +355,10 @@ export interface PermanentView { damage: number; counters: number; attachedTo?: string; - /** Current stats after counters, temp buffs, statics and Connected. */ + /** 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 }; } From f544019bfe99a2dbd4606dd020708a8d7a31eac4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:51:20 -0500 Subject: [PATCH 09/25] Polite Wikimedia client, mint-path fix, disk cache and mining prefetch pool (#62) - server/wikimedia/client.ts: one process-wide client. Per-host token bucket (1 req/s, burst 3), 1 in flight per host, mint > interactive > background lanes with a bounded queue, maxlag=5 on Action API requests, Retry-After and backoff, a circuit breaker after 3 consecutive 429s, a daily cap, and a per-egress-IP budget (WIKIDECK_WIKIMEDIA_NODES_PER_IP). - server/wikimedia/cache.ts: node:sqlite HTTP cache with ETag/If-None-Match, stale-while-revalidate on the background lane. Mint reads never use it. - Mint fix: a 429/5xx/timeout/non-JSON reply on pageviews now fails getFresh() (template 503, miner retries) instead of minting attention: null forever. - server/wikimedia/pool.ts: per-tip article+snapshot prefetch pool for /api/mining/template, about 3 requests per block regardless of miner count. - User-Agent with an operator contact (WIKIDECK_OPERATOR_CONTACT or PUBLIC_ORIGIN) and a start-up warning when it is unset. - Mint request parameters are byte-identical apart from maxlag (golden test). No consensus, block or protocol changes. Tests use fake fetch only. Co-Authored-By: Claude Opus 5.5 --- docs/night2/WIKIMEDIA.md | 68 +++++ server/enrichment.ts | 99 +++++-- server/testnet/http.ts | 12 +- server/wiki.ts | 32 ++- server/wikimedia-user-agent.ts | 47 +++- server/wikimedia/cache.ts | 74 ++++++ server/wikimedia/client.ts | 441 +++++++++++++++++++++++++++++++ server/wikimedia/index.ts | 36 +++ server/wikimedia/pool.ts | 88 ++++++ tests/enrichment.test.ts | 2 +- tests/testnet-user-agent.test.ts | 26 +- tests/wiki.test.ts | 5 +- tests/wikimedia-client.test.ts | 236 +++++++++++++++++ tests/wikimedia-helpers.ts | 52 ++++ tests/wikimedia-mint.test.ts | 104 ++++++++ tests/wikimedia-pool.test.ts | 74 ++++++ 16 files changed, 1336 insertions(+), 60 deletions(-) create mode 100644 docs/night2/WIKIMEDIA.md create mode 100644 server/wikimedia/cache.ts create mode 100644 server/wikimedia/client.ts create mode 100644 server/wikimedia/index.ts create mode 100644 server/wikimedia/pool.ts create mode 100644 tests/wikimedia-client.test.ts create mode 100644 tests/wikimedia-helpers.ts create mode 100644 tests/wikimedia-mint.test.ts create mode 100644 tests/wikimedia-pool.test.ts diff --git a/docs/night2/WIKIMEDIA.md b/docs/night2/WIKIMEDIA.md new file mode 100644 index 0000000..241f24c --- /dev/null +++ b/docs/night2/WIKIMEDIA.md @@ -0,0 +1,68 @@ +# Polite Wikimedia client (Night 2, issue #62) + +Every server-side Wikimedia request goes through one process-wide `WikimediaClient` +(`server/wikimedia/client.ts`). The design comes from engineer review §4 and data review §5. + +## What it does + +| Behaviour | Default | +|---|---| +| Rate per upstream host (`en.wikipedia.org`, `wikimedia.org`, `www.wikidata.org`) | token bucket, 1 req/s, burst 3 | +| Concurrency | 1 request in flight per host | +| Priority lanes | `mint` → `interactive` → `background`; the queue holds 64 waiters, and background work is shed first | +| Longest queue wait | mint 10 s, interactive 5 s, background 120 s | +| `maxlag` | `maxlag=5` on every Action API request; a maxlag reply waits for `Retry-After` and retries up to 2 times | +| 429 / 503 | honour `Retry-After` (seconds or HTTP date), else back off 2ⁿ s with jitter, capped at 10 min, by pausing the whole host | +| Circuit breaker | 3 consecutive 429s stop that host for 10 min. Requests are refused at once without touching Wikimedia | +| Daily cap | 20,000 requests a day per egress IP. Background work stops at 80 %, interactive at 100 %; mint has a 10 % reserve | +| Disk cache | `$WIKIDECK_DATA_DIR/wikimedia-cache.sqlite`: ETag / Last-Modified, `If-None-Match`, stale-while-revalidate on the background lane, stale copy served on refusal | +| User-Agent | `WikiDeck/ (+https://gitea.eom.dev/WikiDeck/wikideck; ) node/` | + +Cache lifetimes: article metadata 24 h, monthly pageviews 7 days (the URL names six closed +months, which do not change). Random articles and all mint reads are never cached. + +## Operator settings + +| Variable | Meaning | +|---|---| +| `WIKIDECK_OPERATOR_CONTACT` | **Set this.** An email address or URL, put in the User-Agent. Without it (and without `PUBLIC_ORIGIN`), the node logs a warning at start-up. Wikimedia policy requires a contact, and contact-less clients are the first to be blocked. | +| `PUBLIC_ORIGIN` | Used as the contact when `WIKIDECK_OPERATOR_CONTACT` is unset. | +| `WIKIDECK_USER_AGENT` | Overrides the whole User-Agent string (sanitized; kept from Night 1). | +| `WIKIDECK_WIKIMEDIA_RPS` | Requests per second per host for the **whole egress IP** (default 1). | +| `WIKIDECK_WIKIMEDIA_BURST` | Token-bucket burst (default 3). | +| `WIKIDECK_WIKIMEDIA_CONCURRENCY` | In-flight requests per host (default 1). | +| `WIKIDECK_WIKIMEDIA_DAILY_CAP` | Requests per UTC day for the whole egress IP (default 20000). | +| `WIKIDECK_WIKIMEDIA_NODES_PER_IP` | How many nodes share this egress IP. The rate and the daily cap are divided by it. **The testnet runs several nodes behind one IP: set it to the node count** (e.g. 3 for `deploy/night/compose.lan.yaml`). | + +The testnet's `WIKIDECK_USER_AGENT` already names the project URL, which satisfies the policy. + +Counters (`lane.*`, `http.429`, `breaker.open`, `cache.hit`, `refused.*`, …), per-host pause state and the +mint pool's state are in the private operations listener's `/status`, under `wikimedia`. + +## Mint path: transport only + +- `random()` (W1) and `getFresh()` (W2 and W3) keep their request parameters byte-identical. The only + addition is `maxlag=5`, which changes only error behaviour. `tests/wikimedia-mint.test.ts` pins the exact URLs. +- Mint reads use the `mint` lane and **never** read or write the disk cache, and never join a display read. +- **Fixed:** a 429, 5xx, timeout, network error or non-JSON reply on the pageviews call used to mint a card with + `attention: null` forever (`enrichment.ts`). Now `getFresh()` rejects, the template returns 503 and the miner + retries. `unavailable` is minted only for a genuine 404 (no data) or missing months. +- No block, transfer, trade or validation code changed. Validation never calls Wikimedia. + +## Mining prefetch pool (`server/wikimedia/pool.ts`) + +Each template used to cost 3+ requests, all in a burst at each new tip, so load scaled with the number of miners. +Now every template on the same tip gets the same fresh article+snapshot pair (miners race for one block anyway), +and a new tip takes the next prefetched pair. Load is about one pair, or 3 requests, per block, whatever the number +of miners. + +- Pairs come from the mint-path reads above, and the snapshot is stamped when the pair is fetched, so `capturedAt` is true. +- Pairs older than 5 minutes are dropped, never served. +- The pool (2 pairs) refills only after use, so an idle node makes no requests. + +## Card faces + +`/api/wikipedia/:id` → `get()`: memory LRU, then the disk cache (fresh, or stale with a background +revalidation), and only then the interactive lane. A grid of cards therefore no longer means a burst +of 2 upstream requests per card per render. `TrendCache` can use `getBackground()` to stay off the +interactive lane. diff --git a/server/enrichment.ts b/server/enrichment.ts index fa7175a..ed55cdf 100644 --- a/server/enrichment.ts +++ b/server/enrichment.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import { ENRICHMENT_USER_AGENT, wikimediaUserAgent } from './wikimedia-user-agent.ts'; +import { WikimediaClient, WikimediaUnavailable, wikimediaClient, type CachePolicy, type Lane } from './wikimedia/client.ts'; import { deriveStats, type PageEnrichment } from '../shared/enrichment.ts'; const MAX_BYTES = 1024 * 1024; @@ -25,7 +25,23 @@ const viewsSchema = z.object({ items: z.array(z.object({ })).max(6) }); type CacheEntry = { expires: number; value: PageEnrichment } | { expires: number; error: Error }; -type Options = { fetch?: typeof globalThis.fetch; now?: () => Date; ttlMs?: number; maxEntries?: number }; +type Options = { fetch?: typeof globalThis.fetch; client?: WikimediaClient; now?: () => Date; ttlMs?: number; maxEntries?: number }; +type Mode = 'mint' | 'display' | 'background'; + +/** Disk-cache lifetimes (engineer review §4). Mint reads never use the cache. */ +const METADATA_CACHE: CachePolicy = { ttlMs: 24 * 3600_000, staleWhileRevalidate: true, maxBytes: MAX_BYTES }; +// The URL names its six completed months, which are immutable; a week bounds late corrections. +const PAGEVIEWS_CACHE: CachePolicy = { ttlMs: 7 * 24 * 3600_000, staleWhileRevalidate: true, maxBytes: MAX_BYTES }; +const NOT_FOUND = Symbol('not found'); + +/** The upstream did not answer properly (throttled, 5xx, timeout, network, non-JSON). Not "no data". */ +export class UpstreamFailure extends Error { + constructor(message: string) { super(message); this.name = 'UpstreamFailure'; } +} +function transportFailure(error: unknown): boolean { + return error instanceof WikimediaUnavailable || error instanceof UpstreamFailure || + (error instanceof DOMException && (error.name === 'TimeoutError' || error.name === 'AbortError')); +} function monthWindow(now: Date): string[] { return Array.from({ length: 6 }, (_, index) => @@ -34,16 +50,17 @@ function monthWindow(now: Date): string[] { /** Fixed-source read-only enrichment; no consensus, persistence, URL or header inputs. */ export class WikipediaEnrichment { - private readonly fetcher: typeof globalThis.fetch; + private readonly client: WikimediaClient; private readonly now: () => Date; private readonly ttlMs: number; private readonly maxEntries: number; private readonly cache = new Map(); - private readonly pending = new Map>(); + private readonly pending = new Map>(); private active = 0; + private mintActive = 0; constructor(options: Options = {}) { - this.fetcher = options.fetch ?? globalThis.fetch; + this.client = options.client ?? (options.fetch ? WikimediaClient.unthrottled(options.fetch) : wikimediaClient); this.now = options.now ?? (() => new Date()); this.ttlMs = options.ttlMs ?? 6 * 60 * 60 * 1000; this.maxEntries = options.maxEntries ?? 128; @@ -53,16 +70,27 @@ export class WikipediaEnrichment { } } + /** Card faces (`/api/wikipedia/:id`): memory, then the disk cache, then the interactive lane. */ async get(pageId: number): Promise { - return this.loadCached(pageId, false); + return this.loadCached(pageId, 'display'); } - /** Bypass cached values when the result is being pinned into a newly minted block. */ + /** Like get(), on the background lane: for trends and other work nobody is waiting on. */ + async getBackground(pageId: number): Promise { + return this.loadCached(pageId, 'background'); + } + + /** + * Mint data: bypasses every cache and uses the mint lane. If pageviews fail in transport + * (429, 5xx, timeout, throttled), this rejects so the template fails and the miner retries; + * `unavailable` is recorded only for a genuine 404 or missing data. + */ async getFresh(pageId: number): Promise { - return this.loadCached(pageId, true); + return this.loadCached(pageId, 'mint'); } - private async loadCached(pageId: number, fresh: boolean): Promise { + private async loadCached(pageId: number, mode: Mode): Promise { + const fresh = mode === 'mint'; if (!Number.isSafeInteger(pageId) || pageId <= 0) throw new RangeError('Invalid Wikipedia page ID'); const now = this.now(); const cached = this.cache.get(pageId); @@ -73,23 +101,29 @@ export class WikipediaEnrichment { if ('error' in cached) throw cached.error; return structuredClone(cached.value); } - this.cache.delete(pageId); - const existing = this.pending.get(pageId); + if (!fresh) this.cache.delete(pageId); + // Mint jobs never join a display job: that one may be served from the disk cache. + const pendingKey = `${fresh ? 'mint' : 'cached'}:${pageId}`; + const existing = this.pending.get(pendingKey); if (existing) return structuredClone(await existing); // Reject immediately: no unbounded waiting queue. Four active jobs also keep // the pending-map ceiling of eight conservative (one upstream request/job). - if (this.pending.size >= 8 || this.active >= 4) throw new Error('Wikipedia enrichment busy'); - this.active++; - const job = this.load(pageId, now).then(value => { + // Mint jobs have their own small allowance so card faces can never starve a template. + if (fresh ? this.mintActive >= 2 : this.pending.size - this.mintActive >= 8 || this.active >= 4) { + throw new Error('Wikipedia enrichment busy'); + } + if (fresh) this.mintActive++; else this.active++; + const job = this.load(pageId, now, mode).then(value => { const ttl = value.pageviews.status === 'available' ? this.ttlMs : Math.min(this.ttlMs, 5 * 60 * 1000); this.remember(pageId, { value, expires: this.now().getTime() + ttl }); return value; }, () => { const error = new Error('Wikipedia page enrichment unavailable'); - this.remember(pageId, { error, expires: this.now().getTime() + 30_000 }); + // A failed mint read says nothing new about display data; keep any cached value. + if (!fresh) this.remember(pageId, { error, expires: this.now().getTime() + 30_000 }); throw error; - }).finally(() => { this.active--; this.pending.delete(pageId); }); - this.pending.set(pageId, job); + }).finally(() => { if (fresh) this.mintActive--; else this.active--; this.pending.delete(pendingKey); }); + this.pending.set(pendingKey, job); return structuredClone(await job); } @@ -99,16 +133,19 @@ export class WikipediaEnrichment { while (this.cache.size > this.maxEntries) this.cache.delete(this.cache.keys().next().value!); } - private async json(url: URL): Promise { - const signal = AbortSignal.timeout(6000); - const response = await this.fetcher(url, { signal, redirect: 'error', - headers: { Accept: 'application/json', 'User-Agent': wikimediaUserAgent(ENRICHMENT_USER_AGENT) } }); + private async json(url: URL, lane: Lane, cache: CachePolicy | undefined, allowNotFound = false): Promise { + const { response, signal } = await this.client.request(url, { lane, timeoutMs: 6000, cache }); + if (allowNotFound && response.status === 404) { await response.body?.cancel(); return NOT_FOUND; } + if (!response.ok || response.redirected) { + await response.body?.cancel(); + throw new UpstreamFailure(`Upstream HTTP ${response.status}`); + } const length = response.headers.get('content-length'); - if (!response.ok || response.redirected || + if ( !/^application\/json(?:\s*;|\s*$)/i.test(response.headers.get('content-type') ?? '') || (length !== null && (!/^\d+$/.test(length) || Number(length) > MAX_BYTES)) || !response.body) { await response.body?.cancel(); - throw new Error('Invalid upstream response'); + throw new UpstreamFailure('Invalid upstream response'); } const reader = response.body.getReader(); const chunks: Uint8Array[] = []; @@ -130,12 +167,14 @@ export class WikipediaEnrichment { } } - private async load(pageId: number, now: Date): Promise { + private async load(pageId: number, now: Date, mode: Mode): Promise { + const lane: Lane = mode === 'mint' ? 'mint' : mode === 'display' ? 'interactive' : 'background'; + const fresh = mode === 'mint'; const url = new URL('https://en.wikipedia.org/w/api.php'); url.search = new URLSearchParams({ action: 'query', format: 'json', formatversion: '2', pageids: String(pageId), prop: 'info|categories|pageprops|description|langlinks', clshow: '!hidden', cllimit: '50', lllimit: '500', ppprop: 'wikibase_item' }).toString(); - const metadata = metadataSchema.parse(await this.json(url)); + const metadata = metadataSchema.parse(await this.json(url, lane, fresh ? undefined : METADATA_CACHE)); const page = metadata.query.pages[0]; if (page.pageid !== pageId) throw new Error('Wikipedia page ID mismatch'); const months = monthWindow(now); @@ -146,7 +185,9 @@ export class WikipediaEnrichment { const title = encodeURIComponent(page.title.replace(/ /g, '_')); const stamp = (month: string) => `${month.replace('-', '')}0100`; const endpoint = new URL(`https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/${title}/monthly/${stamp(months[0])}/${stamp(latestMonth)}`); - const result = viewsSchema.parse(await this.json(endpoint)); + const raw = await this.json(endpoint, lane, fresh ? undefined : PAGEVIEWS_CACHE, true); + if (raw === NOT_FOUND) throw new Error('No pageview data'); + const result = viewsSchema.parse(raw); const byMonth = new Map(); for (const item of result.items) { const month = `${item.timestamp.slice(0, 4)}-${item.timestamp.slice(4, 6)}`; @@ -161,7 +202,11 @@ export class WikipediaEnrichment { const days = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 0)).getUTCDate(); pageviews = { status: 'available', months: ordered, latestMonth, total, dailyAverage: latest / days, trendPercent: prior > 0 ? (latest - prior) / prior * 100 : null }; - } catch { /* Metadata remains useful; unknown views must not become fake zeroes. */ } + } catch (error) { + // Mint: a throttled or failed upstream must not pin `attention: null` into a block forever. + if (fresh && transportFailure(error)) throw error; + /* Metadata remains useful; unknown views must not become fake zeroes. */ + } return { pageId, title: page.title, description: page.description ?? null, wikidataId: page.pageprops?.wikibase_item ?? null, revisionId: page.lastrevid, pageBytes: page.length, languageCount: page.langlinks?.length ?? 0, languagesTruncated: metadata.continue?.llcontinue !== undefined, diff --git a/server/testnet/http.ts b/server/testnet/http.ts index be6d366..681f73f 100644 --- a/server/testnet/http.ts +++ b/server/testnet/http.ts @@ -11,8 +11,7 @@ import { RandomX } from './randomx.ts'; import { Ledger } from './ledger.ts'; import { PeerNetwork } from './peers.ts'; import { wikipediaEnrichment } from '../enrichment.ts'; -import { snapshotStats } from '../../shared/enrichment.ts'; -import { wikipediaArticles } from '../wiki.ts'; +import { configureWikimedia, mintPool, wikimediaStatus } from '../wikimedia/index.ts'; import { IS_MAINNET, PROFILE } from '../../shared/network.ts'; import { assertLaunchAllowed, launchManifest } from '../launch.ts'; import { resourceConfig, RpcBudget, RpcError } from '../resources.ts'; @@ -28,6 +27,7 @@ const apiBudget = new RpcBudget(limits); const peerBudget = new RpcBudget({ ...limits, requestsPerSecond: 40, writesPerSecond: 10, active: 16 }); const dataDir = process.env.WIKIDECK_DATA_DIR ?? resolve(root,'data'); await mkdir(dataDir,{recursive:true}); +configureWikimedia({dataDir}); // Never permit two processes to rewrite the same ledger. A stale lock requires operator review. const lockPath = resolve(dataDir,`${PROFILE}-node.lock`); const lock = await open(lockPath,'wx',0o600).catch(()=>{throw new Error('Data directory locked. Stop its other node; remove stale testnet-node.lock only after verifying no node is running.');}); @@ -119,9 +119,9 @@ const templateLimit=rateLimit({windowMs:60000,limit:20,standardHeaders:'draft-8' app.post('/api/mining/template', templateLimit, async (req,res)=>{ const body=z.object({owner:z.string().regex(/^[a-f0-9]{64}$/),publicKey:z.string().max(256)}).strict().parse(req.body); try { - const article=await wikipediaArticles.random(); - const metrics=await wikipediaEnrichment.getFresh(article.pageId); - res.json(ledger.template(body.owner,body.publicKey,article,snapshotStats(metrics))); + // One fresh article+snapshot per tip, shared by every miner (server/wikimedia/pool.ts). + const {article,statsSnapshot}=await mintPool.take(ledger.summary().tip); + res.json(ledger.template(body.owner,body.publicKey,article,statsSnapshot)); } catch { res.status(503).json({error:'Could not prepare a Wikipedia article and current statistics. Retry shortly.'}); } @@ -170,7 +170,7 @@ const server=app.listen(port,host,()=>{ const operations=startOperations(opsPort,()=>({network:NETWORK, ledger:ledger.diagnostics(),native:engine.diagnostics(), peers:{configured:peers.status().length,connected:peers.status().filter(p=>p.connected).length}, - rpc:{api:apiBudget.status(),p2p:peerBudget.status()}}),resolve(dataDir,PROFILE)); + rpc:{api:apiBudget.status(),p2p:peerBudget.status()},wikimedia:wikimediaStatus()}),resolve(dataDir,PROFILE)); server.maxConnections=256; server.headersTimeout=10000; server.requestTimeout=15000; diff --git a/server/wiki.ts b/server/wiki.ts index 4b5ccaf..d0a7ee5 100644 --- a/server/wiki.ts +++ b/server/wiki.ts @@ -1,6 +1,6 @@ import { z } from 'zod'; import type { Article } from '../shared/protocol.ts'; -import { ARTICLE_USER_AGENT, wikimediaUserAgent } from './wikimedia-user-agent.ts'; +import { WikimediaClient, WikimediaUnavailable, wikimediaClient } from './wikimedia/client.ts'; const pageSchema = z.object({ pageid: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), ns: z.literal(0), @@ -58,11 +58,23 @@ function pictureUrl(value: string | undefined): string | undefined { } catch { return undefined; } } +/** The exact W1 request. Its parameters decide minted article content: keep them byte-identical. */ +export function randomArticlesUrl(): URL { + const url = new URL('https://en.wikipedia.org/w/api.php'); + url.search = new URLSearchParams({ action: 'query', format: 'json', formatversion: '2', + generator: 'random', grnnamespace: '0', grnlimit: '10', prop: 'extracts|pageimages|info|categories', + exintro: '1', explaintext: '1', exchars: '900', piprop: 'thumbnail', pithumbsize: '800', cllimit: '20' }).toString(); + return url; +} + export class WikipediaArticleSource { - private readonly fetcher: typeof globalThis.fetch; + private readonly client: WikimediaClient; private active = 0; - constructor(fetcher: typeof globalThis.fetch = globalThis.fetch) { this.fetcher = fetcher; } + /** A bare fetch (tests) gets an unthrottled pass-through client; production uses the shared client. */ + constructor(source: typeof globalThis.fetch | WikimediaClient = wikimediaClient) { + this.client = source instanceof WikimediaClient ? source : WikimediaClient.unthrottled(source); + } async random(): Promise
{ if (this.active >= 4) throw new Error('Wikipedia article service is busy'); @@ -70,12 +82,8 @@ export class WikipediaArticleSource { try { for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) { try { - const url = new URL('https://en.wikipedia.org/w/api.php'); - url.search = new URLSearchParams({ action: 'query', format: 'json', formatversion: '2', - generator: 'random', grnnamespace: '0', grnlimit: '10', prop: 'extracts|pageimages|info|categories', - exintro: '1', explaintext: '1', exchars: '900', piprop: 'thumbnail', pithumbsize: '800', cllimit: '20' }).toString(); - const response = await this.fetcher(url, { signal: AbortSignal.timeout(3500), redirect: 'error', - headers: { 'User-Agent': wikimediaUserAgent(ARTICLE_USER_AGENT), Accept: 'application/json' } }); + // Mint lane, never cached: random articles become immutable chain data. + const { response } = await this.client.request(randomArticlesUrl(), { lane: 'mint', timeoutMs: 3500 }); const data = responseSchema.parse(await readJson(response)); for (const rawPage of data.query.pages) { const parsedPage = pageSchema.safeParse(rawPage); @@ -88,7 +96,11 @@ export class WikipediaArticleSource { url: `https://en.wikipedia.org/?curid=${page.pageid}`, revisionId: page.lastrevid, source: 'live', category: category(page.title, page.categories?.map(c => c.title) ?? []) }; } - } catch { /* Try another random API response, but keep the number of attempts bounded. */ } + } catch (error) { + // Throttled, paused or failing upstream: stop now rather than hammer it with retries. + if (error instanceof WikimediaUnavailable) throw error; + /* Otherwise try another random API response, but keep the number of attempts bounded. */ + } } throw new Error('Wikipedia did not return an article with a picture after three attempts'); } finally { diff --git a/server/wikimedia-user-agent.ts b/server/wikimedia-user-agent.ts index 39eb229..491a40b 100644 --- a/server/wikimedia-user-agent.ts +++ b/server/wikimedia-user-agent.ts @@ -1,13 +1,48 @@ -// User-Agent for Wikimedia API requests. Wikimedia asks automated clients to identify -// themselves with contact information; operators can opt in with WIKIDECK_USER_AGENT. -// Unset (or blank), each caller keeps its historical default string unchanged. -export const ARTICLE_USER_AGENT = 'Wikideck/0.1 (experimental Wikipedia article cards)'; -export const ENRICHMENT_USER_AGENT = 'Wikideck/0.1 (Wikipedia off-chain page enrichment)'; +// User-Agent for Wikimedia API requests. Wikimedia's User-Agent policy asks automated clients for a +// descriptive agent with contact details: `Tool/version (+https://site; contact) lib/version`. +// Operators set WIKIDECK_OPERATOR_CONTACT (an email address or URL); PUBLIC_ORIGIN is the fallback. +// WIKIDECK_USER_AGENT still overrides the whole string. +import { readFileSync } from 'node:fs'; + +export const PROJECT_URL = 'https://gitea.eom.dev/WikiDeck/wikideck'; const MAX_LENGTH = 256; +const SAFE = /^[\x20-\x7e]+$/; + +function packageVersion(): string { + try { + const raw = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version?: unknown }; + return typeof raw.version === 'string' && /^[\w.+-]{1,32}$/.test(raw.version) ? raw.version : '0'; + } catch { return '0'; } +} +const VERSION = packageVersion(); + +/** The operator contact, or undefined when none (or only an unsafe value) is configured. */ +export function operatorContact(env: Record = process.env): string | undefined { + for (const value of [env.WIKIDECK_OPERATOR_CONTACT, env.PUBLIC_ORIGIN]) { + const trimmed = value?.trim(); + if (trimmed && trimmed.length <= 128 && SAFE.test(trimmed) && !/[();]/.test(trimmed)) return trimmed; + } + return undefined; +} + +/** `WikiDeck/ (+; ) node/`. */ +export function defaultUserAgent(env: Record = process.env): string { + const contact = operatorContact(env); + return `WikiDeck/${VERSION} (+${PROJECT_URL}${contact ? `; ${contact}` : ''}) node/${process.versions.node}`; +} export function wikimediaUserAgent(fallback: string, env: Record = process.env): string { const configured = env.WIKIDECK_USER_AGENT?.trim(); // Reject header-injection/control characters and oversized values; fall back to the default. - if (!configured || configured.length > MAX_LENGTH || !/^[\x20-\x7e]+$/.test(configured)) return fallback; + if (!configured || configured.length > MAX_LENGTH || !SAFE.test(configured)) return fallback; return configured; } + +/** Start-up check: Wikimedia throttles or blocks clients without contact details first. */ +export function warnIfNoContact(env: Record = process.env, + warn: (message: string) => void = console.warn): boolean { + if (wikimediaUserAgent('', env) || operatorContact(env)) return false; + warn('[wikimedia] WARNING: no operator contact in the Wikimedia User-Agent. Set WIKIDECK_OPERATOR_CONTACT ' + + '(an email address or URL) or PUBLIC_ORIGIN; Wikimedia policy requires it and may block this node.'); + return true; +} diff --git a/server/wikimedia/cache.ts b/server/wikimedia/cache.ts new file mode 100644 index 0000000..6ebd42e --- /dev/null +++ b/server/wikimedia/cache.ts @@ -0,0 +1,74 @@ +/** + * On-disk HTTP cache for off-chain Wikimedia reads (`$WIKIDECK_DATA_DIR/wikimedia-cache.sqlite`). + * It stores the raw body with its ETag / Last-Modified so stale entries can be revalidated with + * conditional requests. Mint-path requests never use it (see client.ts). + */ +import { DatabaseSync } from 'node:sqlite'; + +export type StoredEntry = { + status: number; body: Buffer; contentType: string; etag: string | null; lastModified: string | null; + expiresAt: number; storedAt: number; +}; +export type CacheEntry = StoredEntry & { toResponse(): Response }; + +/** Canonical key: origin + path + sorted query, without `maxlag` (it changes only error behaviour). */ +export function cacheKey(url: URL): string { + const params = [...url.searchParams].filter(([name]) => name !== 'maxlag') + .sort(([a, x], [b, y]) => a < b ? -1 : a > b ? 1 : x < y ? -1 : x > y ? 1 : 0); + return `${url.origin}${url.pathname}?${new URLSearchParams(params).toString()}`; +} + +function withResponse(entry: StoredEntry): CacheEntry { + return { ...entry, toResponse: () => new Response(new Uint8Array(entry.body), { status: entry.status, + headers: { 'Content-Type': entry.contentType, 'Content-Length': String(entry.body.byteLength), + ...(entry.etag ? { ETag: entry.etag } : {}) } }) }; +} + +type Row = { status: number; body: Uint8Array; content_type: string; etag: string | null; + last_modified: string | null; expires_at: number; stored_at: number }; + +export class WikimediaCache { + private readonly db: DatabaseSync; + private readonly maxRows: number; + private writes = 0; + + /** `path` may be ':memory:' (tests). */ + constructor(path: string, options: { maxRows?: number } = {}) { + this.maxRows = options.maxRows ?? 100_000; + this.db = new DatabaseSync(path); + this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; + CREATE TABLE IF NOT EXISTS http_cache (key TEXT PRIMARY KEY, status INTEGER NOT NULL, body BLOB NOT NULL, + content_type TEXT NOT NULL, etag TEXT, last_modified TEXT, expires_at INTEGER NOT NULL, stored_at INTEGER NOT NULL); + CREATE INDEX IF NOT EXISTS http_cache_stored ON http_cache(stored_at);`); + } + + get(key: string): CacheEntry | undefined { + const row = this.db.prepare('SELECT * FROM http_cache WHERE key = ?').get(key) as Row | undefined; + if (!row) return undefined; + return withResponse({ status: row.status, body: Buffer.from(row.body), contentType: row.content_type, + etag: row.etag, lastModified: row.last_modified, expiresAt: row.expires_at, storedAt: row.stored_at }); + } + + put(key: string, entry: StoredEntry): CacheEntry { + this.db.prepare(`INSERT OR REPLACE INTO http_cache (key, status, body, content_type, etag, last_modified, expires_at, stored_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(key, entry.status, entry.body, entry.contentType, entry.etag, + entry.lastModified, entry.expiresAt, entry.storedAt); + if (++this.writes % 500 === 0) this.prune(); + return withResponse(entry); + } + + touch(key: string, expiresAt: number): void { + this.db.prepare('UPDATE http_cache SET expires_at = ? WHERE key = ?').run(expiresAt, key); + } + + delete(key: string): void { this.db.prepare('DELETE FROM http_cache WHERE key = ?').run(key); } + + size(): number { return (this.db.prepare('SELECT COUNT(*) AS n FROM http_cache').get() as { n: number }).n; } + + prune(): void { + this.db.prepare(`DELETE FROM http_cache WHERE key IN (SELECT key FROM http_cache ORDER BY stored_at DESC LIMIT -1 OFFSET ?)`) + .run(this.maxRows); + } + + close(): void { this.db.close(); } +} diff --git a/server/wikimedia/client.ts b/server/wikimedia/client.ts new file mode 100644 index 0000000..e63336d --- /dev/null +++ b/server/wikimedia/client.ts @@ -0,0 +1,441 @@ +/** + * One process-wide, polite Wikimedia HTTP client (engineer review §4, data review §5). + * + * Every server-side Wikimedia request goes through `WikimediaClient.request()`: + * - a token bucket per upstream host (default 1 req/s, burst 3) and 1 request in flight per host; + * - priority lanes: `mint` before `interactive` before `background`, with a bounded queue; + * - `maxlag=5` on Action API requests (it changes only error behaviour, never content); + * - `Retry-After` honoured on 429/503/maxlag by pausing the whole host, with exponential backoff; + * - a circuit breaker: 3 consecutive 429s stop all requests to that host for 10 minutes; + * - a daily request cap, and a budget shared by the nodes behind one egress IP; + * - an optional on-disk cache (see cache.ts) with ETag / If-None-Match and stale-while-revalidate. + * + * The client is transport only. It never rewrites request parameters other than adding `maxlag`, + * and requests made with `cache: undefined` (all mint-path requests) never read or write the cache. + * Nothing here is reachable from block validation, so it cannot affect consensus. + */ +import { WikimediaCache, cacheKey } from './cache.ts'; +import { wikimediaUserAgent, defaultUserAgent } from '../wikimedia-user-agent.ts'; + +export type Lane = 'mint' | 'interactive' | 'background'; +const LANES: Lane[] = ['mint', 'interactive', 'background']; + +export type Clock = { + now(): number; + setTimeout(fn: () => void, ms: number): unknown; + clearTimeout(handle: unknown): void; +}; +const realClock: Clock = { + now: () => Date.now(), + setTimeout: (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; }, + clearTimeout: handle => clearTimeout(handle as ReturnType), +}; + +export type ClientConfig = { + /** Sustained requests per second per upstream host, for this whole egress IP. */ + requestsPerSecond: number; + burst: number; + concurrencyPerHost: number; + /** Requests per UTC day for this whole egress IP. */ + dailyCap: number; + /** Nodes sharing one egress IP; the rate and daily cap are divided between them. */ + nodesPerIp: number; + queueLimit: number; + /** Longest wait in the queue before a request fails, per lane. */ + maxWaitMs: Record; + breakerThreshold: number; + breakerMs: number; + maxBackoffMs: number; + maxlag: number; + /** Retries of a single request after a maxlag reply (HTTP 200/503 with MediaWiki-API-Error: maxlag). */ + maxlagRetries: number; +}; + +export const DEFAULT_CONFIG: ClientConfig = { + requestsPerSecond: 1, burst: 3, concurrencyPerHost: 1, dailyCap: 20_000, nodesPerIp: 1, queueLimit: 64, + maxWaitMs: { mint: 10_000, interactive: 5_000, background: 120_000 }, + breakerThreshold: 3, breakerMs: 10 * 60_000, maxBackoffMs: 10 * 60_000, maxlag: 5, maxlagRetries: 2, +}; + +/** Unthrottled settings for tests and tools that inject their own fetch. */ +export const UNTHROTTLED: Partial = { + requestsPerSecond: 1e9, burst: 1e9, concurrencyPerHost: 1e9, dailyCap: Number.MAX_SAFE_INTEGER, queueLimit: 1e9, + breakerThreshold: Number.MAX_SAFE_INTEGER, maxlagRetries: 0, maxBackoffMs: 0, +}; + +function positive(value: string | undefined, fallback: number, integer = false): number { + if (value === undefined || value.trim() === '') return fallback; + const n = Number(value); + if (!Number.isFinite(n) || n <= 0 || (integer && !Number.isSafeInteger(n))) { + console.warn(`[wikimedia] ignoring invalid setting ${JSON.stringify(value)}; using ${fallback}`); + return fallback; + } + return n; +} + +/** Operator settings. Documented in docs/night2/WIKIMEDIA.md. */ +export function configFromEnv(env: Record = process.env): ClientConfig { + return { ...DEFAULT_CONFIG, + requestsPerSecond: positive(env.WIKIDECK_WIKIMEDIA_RPS, DEFAULT_CONFIG.requestsPerSecond), + burst: positive(env.WIKIDECK_WIKIMEDIA_BURST, DEFAULT_CONFIG.burst), + concurrencyPerHost: positive(env.WIKIDECK_WIKIMEDIA_CONCURRENCY, DEFAULT_CONFIG.concurrencyPerHost, true), + dailyCap: positive(env.WIKIDECK_WIKIMEDIA_DAILY_CAP, DEFAULT_CONFIG.dailyCap, true), + nodesPerIp: positive(env.WIKIDECK_WIKIMEDIA_NODES_PER_IP, DEFAULT_CONFIG.nodesPerIp, true), + }; +} + +/** Thrown for every refusal or transport failure: queue full, cap reached, circuit open, timeout, network. */ +export class WikimediaUnavailable extends Error { + readonly reason: string; + readonly status?: number; + constructor(reason: string, status?: number) { + super(`Wikimedia unavailable: ${reason}`); + this.name = 'WikimediaUnavailable'; + this.reason = reason; this.status = status; + } +} + +export type CachePolicy = { + ttlMs: number; + /** Serve a stale entry at once and revalidate it on the background lane. */ + staleWhileRevalidate?: boolean; + /** Largest body stored, in bytes. */ + maxBytes?: number; +}; + +export type RequestOptions = { + lane: Lane; + /** Starts when the request is dispatched, not while it waits in the queue. */ + timeoutMs: number; + headers?: Record; + /** Omit for mint data: the request then bypasses the cache completely. */ + cache?: CachePolicy; +}; + +export type ClientResponse = { response: Response; signal: AbortSignal; fromCache: boolean }; + +type Waiter = { + lane: Lane; host: string; enqueuedAt: number; + run: () => void; fail: (error: Error) => void; timer?: unknown; +}; +type HostState = { + tokens: number; refilledAt: number; inFlight: number; + pausedUntil: number; breakerUntil: number; consecutive429: number; backoffExponent: number; +}; + +export type ClientStatus = { + day: string; requestsToday: number; dailyCap: number; requestsPerSecond: number; queued: number; + counters: Record; + hosts: Record; +}; + +function parseRetryAfter(value: string | null, now: number): number | undefined { + if (!value) return undefined; + if (/^\d+$/.test(value.trim())) return Number(value.trim()) * 1000; + const at = Date.parse(value); + return Number.isNaN(at) ? undefined : Math.max(0, at - now); +} + +function isActionApi(url: URL): boolean { + return url.pathname === '/w/api.php' && /(^|\.)(wikipedia|wikidata|wikimedia)\.org$/.test(url.hostname); +} + +export class WikimediaClient { + readonly config: ClientConfig; + private readonly fetcher: typeof globalThis.fetch; + private readonly clock: Clock; + private readonly userAgent: () => string; + private cache: WikimediaCache | undefined; + private readonly hosts = new Map(); + private readonly queues = new Map(LANES.map(lane => [lane, []])); + private readonly revalidating = new Set(); + private pumpTimer: unknown; + private pumpAt = Infinity; + private day = ''; + private requestsToday = 0; + readonly counters: Record = {}; + + constructor(options: { fetch?: typeof globalThis.fetch; config?: Partial; clock?: Clock; + cache?: WikimediaCache; userAgent?: () => string } = {}) { + this.fetcher = options.fetch ?? ((...args) => globalThis.fetch(...args)); + this.config = { ...DEFAULT_CONFIG, ...options.config, + maxWaitMs: { ...DEFAULT_CONFIG.maxWaitMs, ...options.config?.maxWaitMs } }; + this.clock = options.clock ?? realClock; + this.userAgent = options.userAgent ?? (() => wikimediaUserAgent(defaultUserAgent())); + this.cache = options.cache; + } + + /** A pass-through client for injected fetchers (tests): no rate limit, no breaker, no cache. */ + static unthrottled(fetcher: typeof globalThis.fetch): WikimediaClient { + return new WikimediaClient({ fetch: fetcher, config: UNTHROTTLED }); + } + + attachCache(cache: WikimediaCache | undefined): void { this.cache = cache; } + + private count(name: string): void { this.counters[name] = (this.counters[name] ?? 0) + 1; } + + private get rate(): number { return this.config.requestsPerSecond / this.config.nodesPerIp; } + private get cap(): number { return Math.max(1, Math.floor(this.config.dailyCap / this.config.nodesPerIp)); } + + private host(name: string): HostState { + let state = this.hosts.get(name); + if (!state) { + state = { tokens: this.config.burst, refilledAt: this.clock.now(), inFlight: 0, + pausedUntil: 0, breakerUntil: 0, consecutive429: 0, backoffExponent: 0 }; + this.hosts.set(name, state); + } + return state; + } + + private refill(state: HostState, now: number): void { + state.tokens = Math.min(this.config.burst, state.tokens + (now - state.refilledAt) / 1000 * this.rate); + state.refilledAt = now; + } + + /** Daily budget by lane: background stops at 80 %, interactive at 100 %, mint has a 10 % reserve. */ + private overCap(lane: Lane): boolean { + const today = new Date(this.clock.now()).toISOString().slice(0, 10); + if (today !== this.day) { this.day = today; this.requestsToday = 0; } + const limit = lane === 'background' ? this.cap * 0.8 : lane === 'interactive' ? this.cap : this.cap * 1.1; + return this.requestsToday >= limit; + } + + status(): ClientStatus { + const now = this.clock.now(); + return { day: this.day, requestsToday: this.requestsToday, dailyCap: this.cap, requestsPerSecond: this.rate, + queued: LANES.reduce((n, lane) => n + this.queues.get(lane)!.length, 0), counters: { ...this.counters }, + hosts: Object.fromEntries([...this.hosts].map(([name, s]) => [name, + { inFlight: s.inFlight, pausedForMs: Math.max(0, s.pausedUntil - now), circuitOpen: s.breakerUntil > now, + consecutive429: s.consecutive429 }])) }; + } + + async request(input: URL, options: RequestOptions): Promise { + const url = new URL(input); + if (url.protocol !== 'https:') throw new RangeError('Wikimedia requests must use HTTPS'); + if (isActionApi(url) && !url.searchParams.has('maxlag')) url.searchParams.append('maxlag', String(this.config.maxlag)); + const key = options.cache && this.cache ? cacheKey(url) : undefined; + const entry = key ? this.cache?.get(key) : undefined; + const now = this.clock.now(); + if (entry && entry.expiresAt > now) { + this.count('cache.hit'); + return { response: entry.toResponse(), signal: new AbortController().signal, fromCache: true }; + } + if (entry && options.cache?.staleWhileRevalidate) { + this.count('cache.stale'); + this.revalidate(url, key!, options); + return { response: entry.toResponse(), signal: new AbortController().signal, fromCache: true }; + } + try { + return await this.network(url, options, key); + } catch (error) { + // Prefer a stale copy over an error for anything that is allowed to use the cache. + if (entry && error instanceof WikimediaUnavailable) { + this.count('cache.staleOnError'); + return { response: entry.toResponse(), signal: new AbortController().signal, fromCache: true }; + } + throw error; + } + } + + private revalidate(url: URL, key: string, options: RequestOptions): void { + if (this.revalidating.has(key)) return; + this.revalidating.add(key); + void this.network(url, { ...options, lane: 'background' }, key) + .then(({ response }) => response.body?.cancel(), () => this.count('cache.revalidateFailed')) + .finally(() => this.revalidating.delete(key)); + } + + private async network(url: URL, options: RequestOptions, key: string | undefined): Promise { + for (let attempt = 0; ; attempt++) { + const result = await this.dispatch(url, options, key); + if (result !== 'maxlag') return result; + if (attempt >= this.config.maxlagRetries) throw new WikimediaUnavailable('maxlag'); + } + } + + /** Wait for a slot, send one request, and classify the reply. */ + private async dispatch(url: URL, options: RequestOptions, key: string | undefined): Promise { + const hostName = url.hostname; + const wait = this.acquire(hostName, options.lane); + if (wait) await wait; // No await on the fast path: an idle host dispatches synchronously. + const state = this.host(hostName); + const headers = new Headers({ Accept: 'application/json', 'Accept-Encoding': 'gzip', ...options.headers, + 'User-Agent': this.userAgent() }); + const entry = key ? this.cache?.get(key) : undefined; + if (entry?.etag) headers.set('If-None-Match', entry.etag); + if (entry?.lastModified) headers.set('If-Modified-Since', entry.lastModified); + const signal = AbortSignal.timeout(options.timeoutMs); + this.requestsToday++; + this.count(`lane.${options.lane}`); + let response: Response; + try { + response = await this.fetcher(url, { signal, redirect: 'error', headers }); + } catch (error) { + this.release(state); + this.count('error.network'); + throw new WikimediaUnavailable(signal.aborted ? 'timeout' : `network: ${(error as Error).message}`); + } + const now = this.clock.now(); + const retryAfter = parseRetryAfter(response.headers.get('retry-after'), now); + const apiError = response.headers.get('mediawiki-api-error'); + if (apiError === 'maxlag') { + await response.body?.cancel(); + this.count('maxlag'); + this.pause(state, Math.min(this.config.maxBackoffMs, retryAfter ?? 5000), false); + this.release(state); + return 'maxlag'; + } + if (response.status === 429 || response.status === 503) { + await response.body?.cancel(); + this.count(`http.${response.status}`); + if (response.status === 429) state.consecutive429++; + const backoff = Math.min(this.config.maxBackoffMs, 2 ** state.backoffExponent * 1000 * (1 + Math.random() * 0.25)); + state.backoffExponent = Math.min(state.backoffExponent + 1, 20); + if (state.consecutive429 >= this.config.breakerThreshold) { + this.pause(state, this.config.breakerMs, true); + this.count('breaker.open'); + } else { + this.pause(state, Math.min(this.config.maxBackoffMs, Math.max(retryAfter ?? 0, backoff)), false); + } + this.release(state); + throw new WikimediaUnavailable(`HTTP ${response.status}`, response.status); + } + state.consecutive429 = 0; + state.backoffExponent = 0; + this.release(state); + if (response.status === 304 && entry && key) { + this.count('cache.revalidated'); + this.cache?.touch(key, now + options.cache!.ttlMs); + return { response: entry.toResponse(), signal, fromCache: true }; + } + if (key && this.cache && response.status === 200 && !response.redirected && options.cache && + /^application\/json(?:\s*;|\s*$)/i.test(response.headers.get('content-type') ?? '')) { + // Store the raw body; callers re-validate it exactly as they would a network reply. + const body = await this.readLimited(response, options.cache.maxBytes ?? 1024 * 1024, signal); + const stored = this.cache.put(key, { status: response.status, body, + contentType: response.headers.get('content-type') ?? '', etag: response.headers.get('etag'), + lastModified: response.headers.get('last-modified'), expiresAt: now + options.cache.ttlMs, storedAt: now }); + return { response: stored.toResponse(), signal, fromCache: false }; + } + if (response.status >= 500) this.count(`http.${response.status}`); + return { response, signal, fromCache: false }; + } + + private async readLimited(response: Response, maxBytes: number, signal: AbortSignal): Promise { + const length = response.headers.get('content-length'); + if (length !== null && (!/^\d+$/.test(length) || Number(length) > maxBytes) || !response.body) { + await response.body?.cancel(); + throw new WikimediaUnavailable('oversized or empty response'); + } + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + try { + for (;;) { + if (signal.aborted) throw new WikimediaUnavailable('timeout'); + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > maxBytes) throw new WikimediaUnavailable('oversized response'); + chunks.push(value); + } + return Buffer.concat(chunks); + } catch (error) { + throw error instanceof WikimediaUnavailable ? error : new WikimediaUnavailable('read failed'); + } finally { + await reader.cancel().catch(() => {}); + reader.releaseLock(); + } + } + + private pause(state: HostState, ms: number, breaker: boolean): void { + const until = this.clock.now() + ms; + if (until > state.pausedUntil) { + if (state.pausedUntil <= this.clock.now()) { + console.warn(`[wikimedia] ${breaker ? 'circuit open' : 'pausing'} for ${Math.ceil(ms / 1000)} s`); + } + state.pausedUntil = until; + } + if (breaker) { state.consecutive429 = 0; state.breakerUntil = until; } + } + + private release(state: HostState): void { + state.inFlight--; + this.pump(); + } + + /** Undefined when a slot was taken at once; otherwise a promise for the slot. Throws on refusal. */ + private acquire(hostName: string, lane: Lane): Promise | undefined { + const state = this.host(hostName); + const now = this.clock.now(); + if (this.overCap(lane)) { this.count('refused.cap'); throw new WikimediaUnavailable('daily cap reached'); } + // A paused host refuses at once when the pause outlasts this lane's patience. + if (state.pausedUntil - now > this.config.maxWaitMs[lane]) { + this.count('refused.paused'); + throw new WikimediaUnavailable(state.breakerUntil > now ? 'circuit open' : 'host paused'); + } + this.refill(state, now); + if (state.pausedUntil <= now && state.inFlight < this.config.concurrencyPerHost && state.tokens >= 1 && + !LANES.some(l => this.queues.get(l)!.some(w => w.host === hostName))) { + state.tokens -= 1; + state.inFlight++; + return undefined; + } + const queued = LANES.reduce((n, l) => n + this.queues.get(l)!.length, 0); + if (queued >= this.config.queueLimit) { + // Background work is shed first; a mint request evicts the newest background waiter. + const background = this.queues.get('background')!; + if (lane === 'background' || background.length === 0) { + this.count('refused.queue'); + throw new WikimediaUnavailable('queue full'); + } + const evicted = background.pop()!; + this.clock.clearTimeout(evicted.timer); + evicted.fail(new WikimediaUnavailable('queue full')); + } + return new Promise((resolve, reject) => { + const waiter: Waiter = { lane, host: hostName, enqueuedAt: now, + run: () => { this.clock.clearTimeout(waiter.timer); resolve(); }, + fail: error => reject(error) }; + waiter.timer = this.clock.setTimeout(() => { + const queue = this.queues.get(lane)!; + const index = queue.indexOf(waiter); + if (index >= 0) { queue.splice(index, 1); this.count('refused.wait'); reject(new WikimediaUnavailable('queue wait')); } + }, this.config.maxWaitMs[lane]); + this.queues.get(lane)!.push(waiter); + this.pump(); + }); + } + + /** Start every waiter that may run now, highest lane first; otherwise arm a timer for the next slot. */ + private pump(): void { + const now = this.clock.now(); + let next = Infinity; + for (const lane of LANES) { + const queue = this.queues.get(lane)!; + for (let i = 0; i < queue.length;) { + const waiter = queue[i]; + // A host is served strictly by priority: lower lanes wait while a higher lane waits for the same host. + if (LANES.slice(0, LANES.indexOf(lane)).some(l => this.queues.get(l)!.some(w => w.host === waiter.host))) { i++; continue; } + const state = this.host(waiter.host); + this.refill(state, now); + if (state.pausedUntil > now) { next = Math.min(next, state.pausedUntil); i++; continue; } + if (state.inFlight >= this.config.concurrencyPerHost) { i++; continue; } + if (state.tokens < 1) { next = Math.min(next, now + (1 - state.tokens) / this.rate * 1000); i++; continue; } + state.tokens -= 1; + state.inFlight++; + queue.splice(i, 1); + waiter.run(); + } + } + if (next < Infinity && next < this.pumpAt) { + if (this.pumpTimer !== undefined) this.clock.clearTimeout(this.pumpTimer); + this.pumpAt = next; + this.pumpTimer = this.clock.setTimeout(() => { this.pumpTimer = undefined; this.pumpAt = Infinity; this.pump(); }, + Math.max(1, Math.ceil(next - now))); + } + } +} + +/** The process-wide client. `configureWikimedia()` (server start-up) attaches the disk cache. */ +export const wikimediaClient = new WikimediaClient({ config: configFromEnv() }); diff --git a/server/wikimedia/index.ts b/server/wikimedia/index.ts new file mode 100644 index 0000000..6b7e7d7 --- /dev/null +++ b/server/wikimedia/index.ts @@ -0,0 +1,36 @@ +/** + * Node start-up wiring for the polite Wikimedia client: the disk cache, the User-Agent warning, + * the mining prefetch pool and an ops status snapshot. See docs/night2/WIKIMEDIA.md. + */ +import { resolve } from 'node:path'; +import { WikimediaCache } from './cache.ts'; +import { wikimediaClient } from './client.ts'; +import { MintTemplatePool } from './pool.ts'; +import { warnIfNoContact } from '../wikimedia-user-agent.ts'; +import { wikipediaArticles } from '../wiki.ts'; +import { wikipediaEnrichment } from '../enrichment.ts'; + +export { wikimediaClient } from './client.ts'; + +/** Serves every mining template; shared by all miners of this node. */ +export const mintPool = new MintTemplatePool({ articles: wikipediaArticles, enrichment: wikipediaEnrichment }); + +let cache: WikimediaCache | undefined; + +/** Call once at start-up. Without it the client still works, with in-memory caching only. */ +export function configureWikimedia(options: { dataDir: string }): void { + warnIfNoContact(); + if (cache) return; + try { + cache = new WikimediaCache(resolve(options.dataDir, 'wikimedia-cache.sqlite')); + wikimediaClient.attachCache(cache); + } catch (error) { + console.warn(`[wikimedia] disk cache disabled: ${(error as Error).message}`); + } +} + +export function closeWikimedia(): void { wikimediaClient.attachCache(undefined); cache?.close(); cache = undefined; } + +export function wikimediaStatus() { + return { client: wikimediaClient.status(), cacheEntries: cache?.size() ?? null, mintPool: mintPool.status() }; +} diff --git a/server/wikimedia/pool.ts b/server/wikimedia/pool.ts new file mode 100644 index 0000000..20c23e8 --- /dev/null +++ b/server/wikimedia/pool.ts @@ -0,0 +1,88 @@ +/** + * Mining-template prefetch pool (data review §5, "Mining load"). + * + * Without it every miner costs 3+ Wikimedia requests per template, all in a burst at each new tip. + * The pool keeps a few fresh article + stats snapshots ready, and serves the SAME pair to every + * template built on the same tip (miners race for one block anyway). Wikimedia load is then about + * one pair (3 requests) per block, whatever the number of miners. + * + * Mint data stays transport-only: each pair comes from the mint-path reads (`random()` and + * `getFresh()`, byte-identical parameters, never the disk cache), and the snapshot is stamped when it + * is fetched, so `capturedAt` stays true. Pairs older than `maxAgeMs` are discarded, never served. + * The pool refills only after it is used, so an idle node makes no requests. + */ +import type { Article } from '../../shared/protocol.ts'; +import { snapshotStats, type MintStatsSnapshot, type PageEnrichment } from '../../shared/enrichment.ts'; + +export type MintPair = { article: Article; statsSnapshot: MintStatsSnapshot }; +type Entry = MintPair & { fetchedAt: number }; +type Sources = { + articles: { random(): Promise
}; + enrichment: { getFresh(pageId: number): Promise }; +}; + +export class MintTemplatePool { + private readonly sources: Sources; + private readonly size: number; + private readonly maxAgeMs: number; + private readonly now: () => number; + private readonly ready: Entry[] = []; + private assigned: { tip: string; entry: Entry } | undefined; + private filling: Promise | undefined; + private direct: Promise | undefined; + readonly counters = { served: 0, shared: 0, fetched: 0, expired: 0, failed: 0 }; + + constructor(sources: Sources, options: { size?: number; maxAgeMs?: number; now?: () => number } = {}) { + this.sources = sources; + this.size = options.size ?? 2; + this.maxAgeMs = options.maxAgeMs ?? 5 * 60_000; + this.now = options.now ?? Date.now; + if (!Number.isSafeInteger(this.size) || this.size < 0 || this.size > 16 || + !Number.isFinite(this.maxAgeMs) || this.maxAgeMs <= 0) throw new RangeError('Invalid mint pool options'); + } + + private fresh(entry: Entry): boolean { return this.now() - entry.fetchedAt < this.maxAgeMs; } + + private async fetchOne(): Promise { + const article = await this.sources.articles.random(); + const metrics = await this.sources.enrichment.getFresh(article.pageId); + this.counters.fetched++; + return { article, statsSnapshot: snapshotStats(metrics), fetchedAt: this.now() }; + } + + /** The article and snapshot for a template on `tip`. Rejects when Wikimedia is unavailable. */ + async take(tip: string): Promise { + let entry: Entry | undefined; + if (this.assigned && this.assigned.tip === tip && this.fresh(this.assigned.entry)) { + entry = this.assigned.entry; + this.counters.shared++; + } else { + while (this.ready.length && !this.fresh(this.ready[0])) { this.ready.shift(); this.counters.expired++; } + entry = this.ready.shift(); + if (!entry) { + // Cold: fetch directly, and let concurrent templates share that one fetch. + this.direct ??= this.fetchOne().finally(() => { this.direct = undefined; }); + try { entry = await this.direct; } + catch (error) { this.counters.failed++; throw error; } + if (this.assigned && this.assigned.tip === tip && this.fresh(this.assigned.entry)) entry = this.assigned.entry; + } + this.assigned = { tip, entry }; + } + this.counters.served++; + this.refill(); + return structuredClone({ article: entry.article, statsSnapshot: entry.statsSnapshot }); + } + + /** Top the pool up one pair at a time, in the background. Exposed for tests. */ + refill(): Promise { + this.filling ??= (async () => { + while (this.ready.filter(e => this.fresh(e)).length < this.size) { + try { this.ready.push(await this.fetchOne()); } + catch { this.counters.failed++; break; } // The next take() tries again; no retry loop. + } + })().finally(() => { this.filling = undefined; }); + return this.filling; + } + + status() { return { ready: this.ready.length, size: this.size, maxAgeMs: this.maxAgeMs, ...this.counters }; } +} diff --git a/tests/enrichment.test.ts b/tests/enrichment.test.ts index 72185e3..490ad94 100644 --- a/tests/enrichment.test.ts +++ b/tests/enrichment.test.ts @@ -54,7 +54,7 @@ test('fixed HTTPS sources, encoded title, hidden categories, lower bounds and pl assert.equal(init.redirect, 'error'); assert.ok(init.signal instanceof AbortSignal); assert.equal(new Headers(init.headers).get('accept'), 'application/json'); - assert.match(new Headers(init.headers).get('user-agent')!, /Wikideck/); + assert.match(new Headers(init.headers).get('user-agent')!, /WikiDeck/i); assert.equal(new Headers(init.headers).has('origin'), false); // Server-side requests need no CORS workaround. } assert.equal(result.title, title); diff --git a/tests/testnet-user-agent.test.ts b/tests/testnet-user-agent.test.ts index 818553a..01bf940 100644 --- a/tests/testnet-user-agent.test.ts +++ b/tests/testnet-user-agent.test.ts @@ -2,7 +2,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { WikipediaArticleSource } from '../server/wiki.ts'; import { WikipediaEnrichment } from '../server/enrichment.ts'; -import { ARTICLE_USER_AGENT, ENRICHMENT_USER_AGENT, wikimediaUserAgent } from '../server/wikimedia-user-agent.ts'; +import { PROJECT_URL, defaultUserAgent, wikimediaUserAgent } from '../server/wikimedia-user-agent.ts'; function capture() { const agents: string[] = []; @@ -12,9 +12,10 @@ function capture() { }; return { agents, fetcher }; } -async function agentsFor(env: string | undefined) { - const previous = process.env.WIKIDECK_USER_AGENT; +async function agentsFor(env: string | undefined, contact?: string) { + const previous = process.env.WIKIDECK_USER_AGENT, previousContact = process.env.WIKIDECK_OPERATOR_CONTACT; if (env === undefined) delete process.env.WIKIDECK_USER_AGENT; else process.env.WIKIDECK_USER_AGENT = env; + if (contact === undefined) delete process.env.WIKIDECK_OPERATOR_CONTACT; else process.env.WIKIDECK_OPERATOR_CONTACT = contact; try { const article = capture(), enrichment = capture(); await assert.rejects(new WikipediaArticleSource(article.fetcher).random()); @@ -22,15 +23,22 @@ async function agentsFor(env: string | undefined) { return { article: article.agents, enrichment: enrichment.agents }; } finally { if (previous === undefined) delete process.env.WIKIDECK_USER_AGENT; else process.env.WIKIDECK_USER_AGENT = previous; + if (previousContact === undefined) delete process.env.WIKIDECK_OPERATOR_CONTACT; + else process.env.WIKIDECK_OPERATOR_CONTACT = previousContact; } } -test('default Wikimedia user agents are unchanged when WIKIDECK_USER_AGENT is unset', async () => { - assert.equal(ARTICLE_USER_AGENT, 'Wikideck/0.1 (experimental Wikipedia article cards)'); - assert.equal(ENRICHMENT_USER_AGENT, 'Wikideck/0.1 (Wikipedia off-chain page enrichment)'); - const { article, enrichment } = await agentsFor(undefined); - assert.ok(article.length > 0 && article.every(a => a === ARTICLE_USER_AGENT)); - assert.ok(enrichment.length > 0 && enrichment.every(a => a === ENRICHMENT_USER_AGENT)); +test('default Wikimedia user agent names the project, the operator contact and node', async () => { + const { article, enrichment } = await agentsFor(undefined, 'ops@example.org'); + const expected = `WikiDeck/0.1.0 (+${PROJECT_URL}; ops@example.org) node/${process.versions.node}`; + assert.equal(defaultUserAgent({ WIKIDECK_OPERATOR_CONTACT: 'ops@example.org' }), expected); + assert.ok(article.length > 0 && article.every(a => a === expected)); + assert.ok(enrichment.length > 0 && enrichment.every(a => a === expected)); + assert.equal(defaultUserAgent({ PUBLIC_ORIGIN: 'https://node.example' }), + `WikiDeck/0.1.0 (+${PROJECT_URL}; https://node.example) node/${process.versions.node}`); + assert.equal(defaultUserAgent({}), `WikiDeck/0.1.0 (+${PROJECT_URL}) node/${process.versions.node}`); + // Unsafe contacts are dropped rather than breaking the header's comment syntax. + assert.equal(defaultUserAgent({ WIKIDECK_OPERATOR_CONTACT: 'a); evil(' }), defaultUserAgent({})); }); test('WIKIDECK_USER_AGENT overrides both Wikimedia clients', async () => { diff --git a/tests/wiki.test.ts b/tests/wiki.test.ts index 06e45e2..e1415fc 100755 --- a/tests/wiki.test.ts +++ b/tests/wiki.test.ts @@ -56,13 +56,16 @@ test('random article fetch rejects unsafe response types, redirects, and oversiz () => new Response('{}', { headers: { 'Content-Type': 'text/html' } }), () => new Response(null, { status: 302, headers: { Location: 'https://evil.example' } }), () => new Response(' '.repeat(512 * 1024 + 1), { headers: { 'Content-Type': 'application/json' } }), - () => { throw new Error('offline'); }, ]; for (const fail of failures) { const { fetcher, calls } = mockFetch(() => fail()); await assert.rejects(new WikipediaArticleSource(fetcher).random()); assert.equal(calls.length, 3); } + // A network failure (or throttling) stops at once instead of retrying against an unreachable upstream. + const { fetcher, calls } = mockFetch(() => { throw new Error('offline'); }); + await assert.rejects(new WikipediaArticleSource(fetcher).random(), /Wikimedia unavailable/); + assert.equal(calls.length, 1); }); test('bad page records are skipped while later valid candidates are considered', async () => { diff --git a/tests/wikimedia-client.test.ts b/tests/wikimedia-client.test.ts new file mode 100644 index 0000000..a90520e --- /dev/null +++ b/tests/wikimedia-client.test.ts @@ -0,0 +1,236 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { WikimediaClient, WikimediaUnavailable, configFromEnv, type ClientConfig } from '../server/wikimedia/client.ts'; +import { WikimediaCache, cacheKey } from '../server/wikimedia/cache.ts'; +import { warnIfNoContact } from '../server/wikimedia-user-agent.ts'; +import { FakeClock, flush, json, recorder } from './wikimedia-helpers.ts'; + +const API = 'https://en.wikipedia.org/w/api.php?action=query&format=json&pageids=1'; +const REST = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/x'; + +function setup(handler: Parameters[1] = () => json({ ok: true }), config: Partial = {}, + cache?: WikimediaCache) { + const clock = new FakeClock(); + const rec = recorder(clock, handler); + const client = new WikimediaClient({ fetch: rec.fetcher, clock, config, cache, userAgent: () => 'Test/1 (+x; y)' }); + return { clock, client, ...rec }; +} + +test('token bucket: burst of 3, then 1 request per second, one in flight per host', async () => { + const { clock, client, calls } = setup(); + const jobs = Array.from({ length: 6 }, () => client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 }) + .then(r => r.response.body?.cancel())); + await clock.advance(0); + assert.equal(calls.length, 3); + await clock.advance(999); + assert.equal(calls.length, 3); + await clock.advance(1); + assert.equal(calls.length, 4); + await clock.advance(2000); + await Promise.all(jobs); + assert.deepEqual(calls.map(c => c.at - calls[0].at), [0, 0, 0, 1000, 2000, 3000]); + // Different hosts have separate buckets. + await client.request(new URL(REST), { lane: 'interactive', timeoutMs: 1000 }); + assert.equal(calls.at(-1)!.url.hostname, 'wikimedia.org'); +}); + +test('only one request is in flight per host, even with tokens to spare', async () => { + const releases: (() => void)[] = []; + const { clock, client, calls } = setup(() => new Promise(resolve => releases.push(() => resolve(json({}))))); + const a = client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 }); + const b = client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 }); + await clock.advance(0); + assert.equal(calls.length, 1); + releases.shift()!(); + await a; + await clock.advance(0); + assert.equal(calls.length, 2); + releases.shift()!(); + await b; +}); + +test('priority lanes: mint, then interactive, then background', async () => { + const { clock, client, calls } = setup(url => json({ lane: url.searchParams.get('n') }), { burst: 1 }); + await client.request(new URL(`${API}&n=warm`), { lane: 'background', timeoutMs: 1000 }); // Uses the only token. + const order: string[] = []; + const go = (lane: 'mint' | 'interactive' | 'background', n: string) => + client.request(new URL(`${API}&n=${n}`), { lane, timeoutMs: 1000 }).then(() => order.push(n)); + const jobs = [go('background', 'b1'), go('interactive', 'i1'), go('background', 'b2'), go('mint', 'm1'), go('interactive', 'i2')]; + await clock.advance(5000); + await Promise.all(jobs); + assert.deepEqual(order, ['m1', 'i1', 'i2', 'b1', 'b2']); + assert.equal(calls.length, 6); +}); + +test('maxlag=5 is added to Action API requests only, and a maxlag reply waits for Retry-After', async () => { + let lagged = 1; + const { clock, client, calls } = setup(url => url.pathname === '/w/api.php' && lagged-- > 0 + ? json({ error: { code: 'maxlag' } }, { 'MediaWiki-API-Error': 'maxlag', 'Retry-After': '5' }) + : json({ ok: true })); + const job = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }); + await clock.advance(0); + assert.equal(calls.length, 1); + assert.equal(calls[0].url.searchParams.get('maxlag'), '5'); + await clock.advance(4999); + assert.equal(calls.length, 1); + await clock.advance(1); + const { response } = await job; + assert.deepEqual(await response.json(), { ok: true }); + assert.equal(calls.length, 2); + await client.request(new URL(REST), { lane: 'background', timeoutMs: 1000 }); + assert.equal(calls[2].url.searchParams.has('maxlag'), false); + assert.equal(calls[0].headers.get('user-agent'), 'Test/1 (+x; y)'); +}); + +test('429 honours Retry-After by pausing the host; three in a row open the circuit for 10 minutes', async () => { + let status = 429; + const { clock, client, calls } = setup(() => status === 200 ? json({}) : new Response('slow down', + { status, headers: { 'Retry-After': '2' } })); + const req = (lane: 'mint' | 'background' = 'background') => client.request(new URL(API), { lane, timeoutMs: 1000 }); + await assert.rejects(req(), (e: unknown) => e instanceof WikimediaUnavailable && e.status === 429); + // The next request waits out Retry-After (2 s) instead of going straight back. + const second = req().catch(e => e); + await clock.advance(1999); + assert.equal(calls.length, 1); + await clock.advance(1); + assert.equal(((await second) as WikimediaUnavailable).status, 429); + const third = req().catch(e => e); + await clock.advance(10_000); + assert.equal(((await third) as WikimediaUnavailable).status, 429); + assert.equal(calls.length, 3); + assert.equal(client.status().hosts['en.wikipedia.org'].circuitOpen, true); + // Open circuit: refused at once without touching Wikimedia, even on the mint lane. + status = 200; + await assert.rejects(req('mint'), /circuit open/); + assert.equal(calls.length, 3); + await clock.advance(10 * 60_000); + await req('mint'); + assert.equal(calls.length, 4); + assert.equal(client.status().counters['breaker.open'], 1); +}); + +test('a success resets the consecutive-429 count', async () => { + const replies = [429, 200, 429, 200, 429]; + const { clock, client } = setup(() => { + const status = replies.shift()!; + return status === 200 ? json({}) : new Response('', { status }); + }); + for (let i = 0; i < 5; i++) { + const job = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }).catch(() => {}); + await clock.advance(60_000); + await job; + } + assert.equal(client.status().hosts['en.wikipedia.org'].circuitOpen, false); +}); + +test('daily cap: background stops at 80 %, interactive at 100 %, mint keeps a 10 % reserve; resets at UTC midnight', async () => { + const { clock, client } = setup(() => json({}), { dailyCap: 10, requestsPerSecond: 1000, burst: 1000 }); + const req = (lane: 'mint' | 'interactive' | 'background') => client.request(new URL(API), { lane, timeoutMs: 1000 }); + for (let i = 0; i < 8; i++) await req('background'); + await assert.rejects(req('background'), /daily cap/); + await req('interactive'); await req('interactive'); + await assert.rejects(req('interactive'), /daily cap/); + await req('mint'); + await assert.rejects(req('mint'), /daily cap/); + await clock.advance(24 * 3600_000); + await req('background'); +}); + +test('nodes sharing one egress IP split the rate and the daily cap', () => { + const config = configFromEnv({ WIKIDECK_WIKIMEDIA_RPS: '0.9', WIKIDECK_WIKIMEDIA_NODES_PER_IP: '3', + WIKIDECK_WIKIMEDIA_DAILY_CAP: '3000' }); + const client = new WikimediaClient({ fetch: async () => json({}), config }); + assert.ok(Math.abs(client.status().requestsPerSecond - 0.3) < 1e-9); + assert.equal(client.status().dailyCap, 1000); + assert.equal(configFromEnv({ WIKIDECK_WIKIMEDIA_RPS: 'abc' }).requestsPerSecond, 1); +}); + +test('a full queue sheds background work first and a mint request evicts a background waiter', async () => { + const { clock, client } = setup(() => json({}), { queueLimit: 2, burst: 1 }); + await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 }); + const b1 = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }).then(() => 'ok', e => e.message); + const b2 = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }).then(() => 'ok', e => e.message); + await assert.rejects(client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }), /queue full/); + const mint = client.request(new URL(API), { lane: 'mint', timeoutMs: 1000 }); + await clock.advance(5000); + await mint; + assert.deepEqual([await b1, await b2], ['ok', 'Wikimedia unavailable: queue full']); +}); + +test('waiting longer than the lane allows fails instead of queueing forever', async () => { + const { clock, client } = setup(() => json({}), { burst: 1, requestsPerSecond: 0.01, maxWaitMs: { interactive: 3000 } as ClientConfig['maxWaitMs'] }); + await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 }); + const late = client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 }).catch(e => e); + await clock.advance(3000); + assert.match(String(await late), /queue wait/); +}); + +test('disk cache: ETag revalidation with If-None-Match, 304 refresh, stale-while-revalidate on the background lane', async () => { + const cache = new WikimediaCache(':memory:'); + let body = { v: 1 }; + const { clock, client, calls } = setup((_url, headers) => headers.get('if-none-match') === '"v1"' && body.v === 1 + ? new Response(null, { status: 304 }) : json(body, { ETag: `"v${body.v}"` }), {}, cache); + const policy = { ttlMs: 1000, staleWhileRevalidate: false }; + const read = async (lane: 'interactive' | 'background' = 'interactive', cachePolicy = policy) => + (await (await client.request(new URL(API), { lane, timeoutMs: 1000, cache: cachePolicy })).response.json()); + assert.deepEqual(await read(), { v: 1 }); + assert.deepEqual(await read(), { v: 1 }); + assert.equal(calls.length, 1); // Fresh hit. + await clock.advance(1000); + assert.deepEqual(await read(), { v: 1 }); + assert.equal(calls.length, 2); + assert.equal(calls[1].headers.get('if-none-match'), '"v1"'); // Conditional request, answered 304. + assert.equal(client.status().counters['cache.revalidated'], 1); + // Stale-while-revalidate: the stale copy is served at once; the refresh happens on the background lane. + await clock.advance(1000); + body = { v: 2 }; + assert.deepEqual(await read('interactive', { ttlMs: 1000, staleWhileRevalidate: true }), { v: 1 }); + await clock.advance(0); await flush(); + assert.equal(calls.length, 3); + assert.equal(client.status().counters['lane.background'], 1); + assert.deepEqual(await read(), { v: 2 }); + assert.equal(calls.length, 3); + // The key ignores maxlag and parameter order. + assert.equal(cacheKey(new URL('https://h.org/p?b=2&a=1&maxlag=5')), cacheKey(new URL('https://h.org/p?a=1&b=2'))); +}); + +test('requests without a cache policy (mint) neither read nor write the cache', async () => { + const cache = new WikimediaCache(':memory:'); + const { client, calls } = setup(() => json({ n: calls.length }), {}, cache); + await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000, cache: { ttlMs: 60_000 } }); + const minted = await client.request(new URL(API), { lane: 'mint', timeoutMs: 1000 }); + assert.equal(minted.fromCache, false); + assert.equal(calls.length, 2); + assert.equal(cache.size(), 1); +}); + +test('a stale copy is served when the upstream refuses, and non-JSON replies are never cached', async () => { + const cache = new WikimediaCache(':memory:'); + let fail = false, html = false; + const { clock, client } = setup(() => fail ? new Response('', { status: 429 }) + : html ? new Response('', { headers: { 'Content-Type': 'text/html' } }) : json({ v: 1 }), {}, cache); + const policy = { ttlMs: 1000 }; + await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000, cache: policy }); + await clock.advance(2000); + fail = true; + const stale = await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000, cache: policy }); + assert.equal(stale.fromCache, true); + fail = false; html = true; + await clock.advance(60_000); + await client.request(new URL(`${API}&other=1`), { lane: 'interactive', timeoutMs: 1000, cache: policy }); + assert.equal(cache.size(), 1); +}); + +test('start-up warns when there is no operator contact', () => { + const messages: string[] = []; + assert.equal(warnIfNoContact({}, m => messages.push(m)), true); + assert.match(messages[0], /WIKIDECK_OPERATOR_CONTACT/); + assert.equal(warnIfNoContact({ WIKIDECK_OPERATOR_CONTACT: 'ops@example.org' }, m => messages.push(m)), false); + assert.equal(warnIfNoContact({ WIKIDECK_USER_AGENT: 'X/1 (+https://x; y)' }, m => messages.push(m)), false); + assert.equal(messages.length, 1); +}); + +test('only HTTPS is allowed', async () => { + const { client } = setup(); + await assert.rejects(client.request(new URL('http://en.wikipedia.org/w/api.php'), { lane: 'mint', timeoutMs: 1 }), RangeError); +}); diff --git a/tests/wikimedia-helpers.ts b/tests/wikimedia-helpers.ts new file mode 100644 index 0000000..cec839e --- /dev/null +++ b/tests/wikimedia-helpers.ts @@ -0,0 +1,52 @@ +// Shared fakes for tests/wikimedia-*.test.ts: a manual clock and a recording fetch. Zero network. +import type { Clock } from '../server/wikimedia/client.ts'; + +export class FakeClock implements Clock { + time: number; + private timers: { at: number; fn: () => void; id: number }[] = []; + private nextId = 1; + constructor(start = Date.parse('2026-11-17T12:00:00Z')) { this.time = start; } + now(): number { return this.time; } + setTimeout(fn: () => void, ms: number): unknown { + const id = this.nextId++; + this.timers.push({ at: this.time + Math.max(0, ms), fn, id }); + return id; + } + clearTimeout(handle: unknown): void { this.timers = this.timers.filter(t => t.id !== handle); } + /** Advance time, firing due timers in order and letting promise chains settle between them. */ + async advance(ms: number): Promise { + const target = this.time + ms; + await flush(); + for (;;) { + this.timers.sort((a, b) => a.at - b.at || a.id - b.id); + const next = this.timers[0]; + if (!next || next.at > target) break; + this.timers.shift(); + this.time = Math.max(this.time, next.at); + next.fn(); + await flush(); + } + this.time = target; + await flush(); + } +} + +export async function flush(): Promise { + for (let i = 0; i < 10; i++) await new Promise(resolve => setImmediate(resolve)); +} + +export function json(value: unknown, headers: Record = {}, status = 200): Response { + return new Response(JSON.stringify(value), { status, headers: { 'Content-Type': 'application/json; charset=utf-8', ...headers } }); +} + +export type Call = { url: URL; headers: Headers; at: number }; +export function recorder(clock: { now(): number }, handler: (url: URL, headers: Headers) => Response | Promise) { + const calls: Call[] = []; + const fetcher: typeof fetch = async (input, init) => { + const url = new URL(String(input)); + const headers = new Headers(init?.headers); + calls.push({ url, headers, at: clock.now() }); + return handler(url, headers); + }; + return { calls, fetcher }; +} diff --git a/tests/wikimedia-mint.test.ts b/tests/wikimedia-mint.test.ts new file mode 100644 index 0000000..30444b3 --- /dev/null +++ b/tests/wikimedia-mint.test.ts @@ -0,0 +1,104 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { WikipediaEnrichment } from '../server/enrichment.ts'; +import { WikipediaArticleSource, randomArticlesUrl } from '../server/wiki.ts'; +import { WikimediaClient } from '../server/wikimedia/client.ts'; +import { WikimediaCache } from '../server/wikimedia/cache.ts'; +import { UNTHROTTLED } from '../server/wikimedia/client.ts'; +import { json } from './wikimedia-helpers.ts'; + +const JANUARY = new Date('2025-01-15T23:59:59Z'); +const MONTHS = ['2024-07', '2024-08', '2024-09', '2024-10', '2024-11', '2024-12']; +const metadata = (pageId = 736) => ({ query: { pages: [{ pageid: pageId, ns: 0, title: 'Albert Einstein', lastrevid: 1234, + length: 100_000, pageprops: { wikibase_item: 'Q937' }, categories: [], langlinks: [{ lang: 'de' }] }] } }); +const views = (counts = [10, 20, 30, 40, 50, 100]) => ({ items: MONTHS.map((month, i) => ({ timestamp: `${month.replace('-', '')}0100`, + views: counts[i], project: 'en.wikipedia', access: 'all-access', agent: 'user', granularity: 'monthly' })) }); + +function service(viewsReply: () => Response | Promise, cache?: WikimediaCache) { + const urls: URL[] = []; + const fetcher: typeof fetch = async input => { + const url = new URL(String(input)); + urls.push(url); + return url.hostname === 'en.wikipedia.org' ? json(metadata(Number(url.searchParams.get('pageids')))) : viewsReply(); + }; + const client = new WikimediaClient({ fetch: fetcher, config: UNTHROTTLED, cache }); + return { urls, client, enrichment: new WikipediaEnrichment({ client, now: () => JANUARY }) }; +} + +test('mint fix: a 429, 5xx, timeout or network failure on pageviews fails the mint read instead of pinning attention: null', async () => { + const failures: (() => Response | Promise)[] = [ + () => new Response('', { status: 429, headers: { 'Retry-After': '0' } }), + () => new Response('', { status: 503 }), + () => new Response('', { status: 500 }), + () => new Response('busy', { headers: { 'Content-Type': 'text/html' } }), + () => { throw new TypeError('fetch failed'); }, + () => Promise.reject(new DOMException('The operation timed out.', 'TimeoutError')), + ]; + for (const failure of failures) { + const { enrichment } = service(failure); + await assert.rejects(enrichment.getFresh(736), /unavailable/); + // Display reads keep their old behaviour: metadata with unavailable views. + const shown = await enrichment.get(736); + assert.equal(shown.pageviews.status, 'unavailable'); + assert.equal(shown.stats.attention, null); + } +}); + +test('mint records unavailable views only for a genuine 404 or missing data', async () => { + for (const reply of [() => json({ type: 'not found' }, {}, 404), () => json({ items: [] }), () => json({ items: views().items.slice(1) })]) { + const { enrichment } = service(reply); + const minted = await enrichment.getFresh(736); + assert.equal(minted.pageviews.status, 'unavailable'); + assert.equal(minted.stats.attention, null); + } + const { enrichment } = service(() => json(views())); + assert.equal((await enrichment.getFresh(736)).stats.attention, 33); +}); + +test('mint reads never use the disk cache or join a display read', async () => { + const cache = new WikimediaCache(':memory:'); + let count = 100; + const { enrichment, urls } = service(() => json(views([1, 1, 1, 1, 1, count++])), cache); + const shown = await enrichment.get(736); + assert.equal(cache.size(), 2); + const [display, minted] = await Promise.all([enrichment.get(736), enrichment.getFresh(736)]); + assert.equal(display.pageviews.months[5].views, shown.pageviews.months[5].views); + assert.equal(minted.pageviews.months[5].views, 101); // Fetched again, not the cached 100. + assert.equal(urls.length, 4); + // A later display read (memory cache cleared by a new service) is served from disk: no upstream call. + const second = new WikipediaEnrichment({ client: new WikimediaClient({ fetch: async () => { throw new Error('no network'); }, + config: UNTHROTTLED, cache }), now: () => JANUARY }); + assert.equal((await second.get(736)).pageviews.months[5].views, 100); +}); + +test('golden mint URLs: request parameters are byte-identical apart from the added maxlag', async () => { + assert.equal(randomArticlesUrl().toString(), 'https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2' + + '&generator=random&grnnamespace=0&grnlimit=10&prop=extracts%7Cpageimages%7Cinfo%7Ccategories&exintro=1&explaintext=1' + + '&exchars=900&piprop=thumbnail&pithumbsize=800&cllimit=20'); + const urls: string[] = []; + const fetcher: typeof fetch = async input => { + const url = new URL(String(input)); + urls.push(url.toString()); + if (url.searchParams.get('generator') === 'random') return json({ query: { pages: [{ pageid: 9, ns: 0, title: 'T', + extract: 'An extract that is comfortably longer than forty characters.', lastrevid: 2, + thumbnail: { source: 'https://upload.wikimedia.org/a.jpg' } }] } }); + return url.hostname === 'en.wikipedia.org' ? json(metadata(9)) : json(views()); + }; + const client = new WikimediaClient({ fetch: fetcher, config: UNTHROTTLED }); + const article = await new WikipediaArticleSource(client).random(); + await new WikipediaEnrichment({ client, now: () => JANUARY }).getFresh(article.pageId); + assert.deepEqual(urls, [ + `${randomArticlesUrl()}&maxlag=5`, + 'https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&pageids=9' + + '&prop=info%7Ccategories%7Cpageprops%7Cdescription%7Clanglinks&clshow=%21hidden&cllimit=50&lllimit=500' + + '&ppprop=wikibase_item&maxlag=5', + 'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/Albert_Einstein/monthly/2024070100/2024120100', + ]); +}); + +test('a throttled upstream stops random() at once instead of retrying three times', async () => { + let calls = 0; + const source = new WikipediaArticleSource(async () => { calls++; return new Response('', { status: 429 }); }); + await assert.rejects(source.random(), /HTTP 429/); + assert.equal(calls, 1); +}); diff --git a/tests/wikimedia-pool.test.ts b/tests/wikimedia-pool.test.ts new file mode 100644 index 0000000..41b3be8 --- /dev/null +++ b/tests/wikimedia-pool.test.ts @@ -0,0 +1,74 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { MintTemplatePool } from '../server/wikimedia/pool.ts'; +import type { Article } from '../shared/protocol.ts'; +import type { PageEnrichment } from '../shared/enrichment.ts'; + +function article(pageId: number): Article { + return { pageId, title: `Page ${pageId}`, extract: 'An extract that is comfortably longer than forty characters.', + image: 'https://upload.wikimedia.org/a.jpg', url: `https://en.wikipedia.org/?curid=${pageId}`, revisionId: pageId + 1, + source: 'live', category: 'Culture' }; +} +function enrichment(pageId: number): PageEnrichment { + return { pageId, title: `Page ${pageId}`, description: null, wikidataId: null, revisionId: pageId + 1, pageBytes: 10, + languageCount: 1, languagesTruncated: false, categories: [], categoriesTruncated: false, fetchedAt: '2026-11-17T00:00:00Z', + pageviews: { status: 'available', months: [], latestMonth: '2026-10', total: 1, dailyAverage: 1, trendPercent: null }, + stats: { attention: 1, depth: 1, reach: 1 } }; +} + +function fixture(options: { size?: number; maxAgeMs?: number } = {}) { + let next = 1, now = 0, fail = false; + const log: string[] = []; + const sources = { + articles: { random: async () => { log.push('random'); if (fail) throw new Error('Wikimedia unavailable: HTTP 429'); return article(next++); } }, + enrichment: { getFresh: async (id: number) => { log.push(`fresh:${id}`); return enrichment(id); } }, + }; + const pool = new MintTemplatePool(sources, { now: () => now, ...options }); + return { pool, log, advance: (ms: number) => { now += ms; }, setFail: (value: boolean) => { fail = value; } }; +} + +test('every template on one tip shares one article; a new tip gets a different one', async () => { + const { pool, log } = fixture({ size: 1 }); + const first = await Promise.all(Array.from({ length: 20 }, () => pool.take('tip-a'))); + assert.ok(first.every(pair => pair.article.pageId === first[0].article.pageId)); + await pool.refill(); + const requestsForTwentyMiners = log.length; + assert.equal(requestsForTwentyMiners, 4); // One direct pair, one prefetched pair: 2 calls each. + const second = await pool.take('tip-b'); + assert.notEqual(second.article.pageId, first[0].article.pageId); + assert.equal(second.article.pageId, 2); // Served from the prefetched pair, no wait. + await pool.refill(); + assert.equal(log.length, 6); // ...and that use alone triggers the next prefetch. + // The stats snapshot comes from a mint-path read of the same page. + assert.equal(second.statsSnapshot.revisionId, second.article.pageId + 1); +}); + +test('pairs older than maxAge are dropped, never served', async () => { + const { pool, advance } = fixture({ size: 1, maxAgeMs: 1000 }); + const a = await pool.take('t1'); + await pool.refill(); + advance(1000); + const b = await pool.take('t1'); // Same tip, but its pair expired; the ready pair expired too. + assert.notEqual(b.article.pageId, a.article.pageId); + assert.equal(pool.status().expired, 1); +}); + +test('an idle pool makes no requests, and a failure rejects the template without a retry loop', async () => { + const { pool, log, setFail } = fixture({ size: 2 }); + assert.equal(log.length, 0); + setFail(true); + await assert.rejects(pool.take('t1'), /429/); + await pool.refill(); + assert.equal(log.filter(entry => entry === 'random').length, 2); // The direct attempt and one refill attempt. + setFail(false); + assert.ok((await pool.take('t1')).article.pageId > 0); +}); + +test('callers get copies they cannot mutate', async () => { + const { pool } = fixture(); + const a = await pool.take('t'); + a.article.title = 'changed'; + assert.equal((await pool.take('t')).article.title.startsWith('Page'), true); + assert.throws(() => new MintTemplatePool({ articles: { random: async () => article(1) }, + enrichment: { getFresh: async () => enrichment(1) } }, { size: 99 }), RangeError); +}); From 6182dff1cd06b347121c13f857577e6155d79e79 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:54:35 -0500 Subject: [PATCH 10/25] DUEL_DESIGN v1.1: night-review nits (public Deleted, Garrison vs Featured, clock, rivalry wording), align with duel-cards #70 Co-Authored-By: Claude Opus 5.5 --- docs/game/DUEL_DESIGN.md | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/docs/game/DUEL_DESIGN.md b/docs/game/DUEL_DESIGN.md index 330fffc..ad528d5 100644 --- a/docs/game/DUEL_DESIGN.md +++ b/docs/game/DUEL_DESIGN.md @@ -1,6 +1,6 @@ # WikiDeck Duel: design v1 -**Status:** v1, Night 2 (2026-11-17). Owner: duel-design (issue #60). +**Status:** v1.1, Night 2 (2026-11-17): v1 plus night-review's nits on PR #66 and duel-cards' implementation choices from PR #70. 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). @@ -38,11 +38,13 @@ Testnet end-to-end mode files may lower `deckSize`. Production stays at 40. 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). +**Zones.** Library and hand are hidden (a hand's size is public). The battlefield and **Deleted** (the graveyard) are **public**: a discarded card is revealed and named once it reaches Deleted. + 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. +- **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: **a Garrison Location can't block a Featured attacker** (only Featured, Translated or Multilingual Figures can). - **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. @@ -59,7 +61,7 @@ There is **no second main phase, no stack, no priority and nothing at instant sp 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. +- `turnSeconds` **60** per turn plus `bankSeconds` **300** per player. The turn timer runs first; when it expires, the player's bank drains; when the bank is also empty, the turn passes (`timeout` action). The bank does not refill. 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. @@ -71,7 +73,7 @@ All randomness (shuffles, coin flip, template variants) comes from the match see ## 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. +- **Figure body budget** P+T = [3, 4, 6, 8, 10, 12] for cost 1–6 (MTG vanilla curve). Subtract **1 per taxed keyword** (§4). At cost 1, a second taxed keyword is skipped, so a body never drops below 1/1. 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. @@ -115,13 +117,13 @@ Subtype regexes run over the frozen P31/P279 labels, then the description, then | 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." | +| T8 | Institution: organisation | `company\|organi[sz]ation\|party\|agency\|studio\|military\|university\|diocese\|council\|band\|musical group\|association\|business\|school\|college\|institute\|manufacturer` | 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. | +| T11 | Doctrine: Adopt | (all non-Pathology Doctrines) | Attach to target Figure you control. It gets +k/+k. Rider by subtype, checked in the order pathology (→ T12) > language/software > mathematics, so "functional programming language" is not maths: 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. +Elected Member tokens are Society; Staff Member tokens have no Portal ("1/1 Figure token"). 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." @@ -181,7 +183,7 @@ Computed by the host at match start from frozen card profiles. No network calls - 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. +- `logFor(seat)` hides the opponent's hand: their draws read "bob drew a card." and mulligans are not named. Discards are named, because Deleted is public (§2.3). | Event | Variants (`{card}` italic, `{player}` the seat name) | |---|---| @@ -197,7 +199,8 @@ Computed by the host at match start from frozen card profiles. No network calls | 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}." | +| discard | "{player} discarded {card}." · "{card} was discarded by {player}." · "{player} moved {card} from hand to Deleted." | +| rivalry (opposing Connected pair, once) | "{a} and {b} are both listed under {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." | @@ -222,7 +225,7 @@ A deterministic function `recap(matchRecord) → RecapDoc` (structured data; ui- **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. +2. **Background:** each side's Portal mix ("History was the largest Portal in the force of alice (eleven of twenty cards played)"). 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. @@ -233,7 +236,7 @@ A deterministic function `recap(matchRecord) → RecapDoc` (structured data; ui- --- ## 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. +Computed with the rules above (data §2 budget, §4 keyword priority, §5 templates) by a script over the sample, and checked by hand. duel-cards' implementation (PR #70) agrees on all 12, with the two Portal corrections now applied (#9, #11). 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 | |---|---|---|---| @@ -242,12 +245,12 @@ Computed with the rules above (data §2 budget, §4 keyword priority, §5 templa | 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." | +| 6 | **Monoid** (maths) | no P31; category "Algebraic structures" → Doctrine, Science. fame 96 → cost 6, k = 3. Maths rider. | **Monoid** · 6 · Doctrine — Science · 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." | +| 9 | **2025 Tehreek-e-Labbaik Pakistan protests** (conflict) | P31 protest → Event, conflict (T3). Society (protest/riot hits outnumber "war"). fame 64 → cost 5, k = 3. | **2025 Tehreek-e-Labbaik Pakistan protests** · 5 · Event — Society · 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." | +| 11 | **Pathrail Mosque** | P31 mosque → Location, Society ("mosque" hits in P31, the description and two categories outnumber 15th-century + Sultanate). fame 49 → cost 3 → Location cost 2. pct_d 54 → Garrison 0/3. | **Pathrail Mosque** · 2 · Location — Society · 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: From 0ca7704767b0a786d5e74815b090f5e6e549b7cf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:55:25 -0500 Subject: [PATCH 11/25] story: public discards, factual rivalry wording, Portal ties, fixture Portals per duel-cards #70 Co-Authored-By: Claude Opus 5.5 --- shared/duel/story/log.ts | 2 ++ shared/duel/story/recap.ts | 13 +++++++++++-- shared/duel/story/templates.ts | 7 ++++++- shared/duel/story/types.ts | 2 ++ tests/duel-design-story.golden.json | 24 ++++++++++++------------ tests/duel-design-story.test.ts | 14 ++++++++++---- 6 files changed, 43 insertions(+), 19 deletions(-) diff --git a/shared/duel/story/log.ts b/shared/duel/story/log.ts index ca91392..45d5c52 100644 --- a/shared/duel/story/log.ts +++ b/shared/duel/story/log.ts @@ -150,6 +150,8 @@ export function renderEvent(nar: Narrator, ev: StoryEvent, index: number, viewer if (count > 1) return nar.sentence('drawHiddenMany', index, { player: P(ev.seat), count: () => numberWord(count) }); return nar.sentence('drawHidden', index, { player: P(ev.seat) }); } + case 'discard': + return nar.sentence('discard', index, { player: P(ev.seat), card: M(ev.card) }); case 'connected': return nar.sentence('connected', index, { a: M(ev.a), b: M(ev.b), reason: () => ev.reason }); case 'rivalry': diff --git a/shared/duel/story/recap.ts b/shared/duel/story/recap.ts index aa6cf82..2a0b6f0 100644 --- a/shared/duel/story/recap.ts +++ b/shared/duel/story/recap.ts @@ -181,8 +181,13 @@ export function recap(record: MatchRecord): RecapDoc { if (!mine.length) { background.push(`${record.players[seat].name} played no cards.`); continue; } const counts = new Map(); for (const p of mine) { const k = C[p.id].portal ?? 'Neutral'; counts.set(k, (counts.get(k) ?? 0) + 1); } - const [portal, n] = [...counts.entries()].sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0]))[0]; - background.push(`${portal} was the largest Portal in the force of ${record.players[seat].name} (${numberWord(n)} of ${numberWord(mine.length)} ${mine.length === 1 ? 'card' : 'cards'} played).`); + const sorted = [...counts.entries()].sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0])); + const max = sorted[0][1]; + const tops = sorted.filter(([, n]) => n === max).map(([k]) => k); + const name = record.players[seat].name; + const played = `${numberWord(mine.length)} ${mine.length === 1 ? 'card' : 'cards'} played`; + if (tops.length === 1) background.push(`${tops[0]} was the largest Portal in the force of ${name} (${numberWord(max)} of ${played}).`); + else background.push(`${listJoin(tops)} were equally represented in the force of ${name} (${numberWord(max)} ${max === 1 ? 'card' : 'cards'} each, of ${played}).`); } // Course of the battle: the largest Notability swings and destroyed cards of cost ≥ 4. @@ -266,6 +271,10 @@ export function recap(record: MatchRecord): RecapDoc { }; } +function listJoin(xs: string[]): string { + return xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`; +} + function cards(n: number): string { return `${n} ${n === 1 ? 'card' : 'cards'}`; } function turnAt(events: StoryEvent[], index: number): number { diff --git a/shared/duel/story/templates.ts b/shared/duel/story/templates.ts index f2de0cc..312ecca 100644 --- a/shared/duel/story/templates.ts +++ b/shared/duel/story/templates.ts @@ -71,13 +71,18 @@ export const LOG_TEMPLATES = { '{player} added {count} cards to their hand.', '{player} took {count} cards into hand.', ], + discard: [ + '{player} discarded {card}.', + '{card} was discarded by {player}.', + '{player} moved {card} from hand to Deleted.', + ], connected: [ '{a} and {b} were Connected ({reason}).', '{a} was Connected to {b} through {reason}.', 'Records link {a} and {b} ({reason}).', ], rivalry: [ - '{a} and {b} had previously been associated through {reason}.', + '{a} and {b} are both listed under {reason}.', '{a} and {b} share {reason}.', 'The two sides were linked through {reason}.', ], diff --git a/shared/duel/story/types.ts b/shared/duel/story/types.ts index 49bbf6c..7e5625c 100644 --- a/shared/duel/story/types.ts +++ b/shared/duel/story/types.ts @@ -43,6 +43,8 @@ export type StoryEvent = | { kind: 'tokenCreated'; seat: Seat; source: string; token: string; count: number } /** `card` set when the drawn card is known to the viewer's record; hidden draws omit it. */ | { kind: 'draw'; seat: Seat; card?: string; count?: number } + /** Deleted is public (DUEL_DESIGN §2.3): discards are always named. */ + | { kind: 'discard'; seat: Seat; card: string } | { kind: 'connected'; seat: Seat; a: string; b: string; reason: string } | { kind: 'rivalry'; a: string; b: string; reason: string } | { kind: 'gameOver'; winner: Seat; reason: GameOverReason; turn: number }; diff --git a/tests/duel-design-story.golden.json b/tests/duel-design-story.golden.json index 1fbc5aa..1df7fa1 100644 --- a/tests/duel-design-story.golden.json +++ b/tests/duel-design-story.golden.json @@ -9,23 +9,23 @@ "Turn 7. alice added a card to their hand. *Zbyszek Godlewski* (Polish protester, 1952–1970) entered play under alice.[5]", "Turn 8. bob added a card to their hand. *Marc Fesneau* (French politician, born 1971) entered play under bob.[6]", "Turn 9. alice drew one card. *Zbyszek Godlewski* (6/3) attacked. *Zbyszek Godlewski* was blocked by *Marc Fesneau* (5/4). *Zbyszek Godlewski* was removed from play. *Marc Fesneau* was removed from play. alice drew one card.", - "Turn 10. bob added a card to their hand. bob brought *Pallas's cat* (Species of small wild cat) into play.[7]", - "Turn 11. alice drew a card. *Tom Ewell* (American actor, 1909–1994) was deployed by alice.[8]", - "Turn 12. bob drew a card. *Tom Ewell* adopted *Heart rot* (Fungal disease of trees) and became a 2/2.[9] *Pallas's cat* (5/5) attacked. *Pallas's cat* dealt 5 damage to alice, leaving 15 Notability.", - "Turn 13. alice drew one card. *Tom Ewell* adopted *Monoid* (Algebraic structure with an associative operation and an identity element) and became a 5/5.[10] *Tom Ewell* (5/5) advanced on bob. bob lost 5 Notability (11 remaining).", - "Turn 14. bob drew one card. bob cited *2025 Tehreek-e-Labbaik Pakistan protests* (Gaza war protests in Pakistan).[11] *Tom Ewell* took 3 damage from *2025 Tehreek-e-Labbaik Pakistan protests*. *Tatsunoko Production* (Japanese animation studio) was deployed by bob.[12] *Pallas's cat* (5/5) attacked. alice's Notability fell to 10.", - "Turn 15. alice drew one card. *Tom Ewell* (5/5) advanced on bob. *Tom Ewell* dealt 5 damage to bob, leaving 6 Notability.", - "Turn 16. bob added a card to their hand. bob sent *Pallas's cat* (5/5) into combat. *Pallas's cat* dealt 5 damage to alice, leaving 5 Notability.", - "Turn 17. alice added a card to their hand. *Tom Ewell* (5/5) advanced on bob. *Tom Ewell* dealt 5 damage to bob, leaving 1 Notability.", - "Turn 18. bob drew one card. *Pallas's cat* (5/5) advanced on alice. alice lost 5 Notability (0 remaining). alice was nominated for deletion. The result was **delete**." + "Turn 10. bob added a card to their hand. bob discarded *Agda (programming language)* (Functional programming language).[7] bob deployed *Pallas's cat* (Species of small wild cat).[8]", + "Turn 11. alice drew one card. alice deployed *Tom Ewell* (American actor, 1909–1994).[9]", + "Turn 12. bob added a card to their hand. bob attached *Heart rot* (Fungal disease of trees) to *Tom Ewell* (2/2).[10] *Pallas's cat* (5/5) advanced on alice. *Pallas's cat* dealt 5 damage to alice, leaving 15 Notability.", + "Turn 13. alice added a card to their hand. *Monoid* (Algebraic structure with an associative operation and an identity element) was adopted by *Tom Ewell*, which became a 5/5.[11] alice sent *Tom Ewell* (5/5) into combat. bob lost 5 Notability (11 remaining).", + "Turn 14. bob drew one card. bob invoked *2025 Tehreek-e-Labbaik Pakistan protests* (Gaza war protests in Pakistan).[12] *2025 Tehreek-e-Labbaik Pakistan protests* inflicted 3 damage on *Tom Ewell*. bob brought *Tatsunoko Production* (Japanese animation studio) into play.[13] bob sent *Pallas's cat* (5/5) into combat. alice's Notability fell to 10.", + "Turn 15. alice drew a card. *Tom Ewell* (5/5) advanced on bob. bob lost 5 Notability (6 remaining).", + "Turn 16. bob drew a card. bob sent *Pallas's cat* (5/5) into combat. alice lost 5 Notability (5 remaining).", + "Turn 17. alice drew one card. *Tom Ewell* (5/5) advanced on bob. bob's Notability fell to 1.", + "Turn 18. bob drew one card. bob sent *Pallas's cat* (5/5) into combat. alice lost 5 Notability (0 remaining). alice was reduced to 0 Notability. bob won." ], "lead": "The **Battle of Pathrail Mosque (2026)** was a WikiDeck engagement fought on 17 November 2026 between the forces of alice and bob. It lasted eighteen turns and ended in a Pyrrhic victory for bob.[1] Contemporary accounts note the deployment of *Dichromorpha viridis* (Species of grasshopper) in the third turn.[2]", "sections": [ { "heading": "Background", "paragraphs": [ - "History was the largest Portal in the force of alice (two of five cards played).", - "Earth was the largest Portal in the force of bob (two of seven cards played)." + "Arts, Earth, History, Science and Society were equally represented in the force of alice (one card each, of five cards played).", + "Society was the largest Portal in the force of bob (three of seven cards played)." ] }, { @@ -37,7 +37,7 @@ "In the fourteenth turn, *Pallas's cat* dealt 5 damage to alice, leaving 10 Notability.", "In the fifteenth turn, *Tom Ewell* dealt 5 damage to bob, leaving 6 Notability.", "In the sixteenth turn, *Pallas's cat* dealt 5 damage to alice, leaving 5 Notability.", - "alice was reduced to 0 Notability. bob won." + "alice was nominated for deletion. The result was **delete**." ] }, { diff --git a/tests/duel-design-story.test.ts b/tests/duel-design-story.test.ts index 6187319..21dea81 100644 --- a/tests/duel-design-story.test.ts +++ b/tests/duel-design-story.test.ts @@ -19,7 +19,7 @@ function card(id: string, title: string, type: CardType, cost: number, portal: s } const cards: Record = Object.fromEntries([ card('a1', 'Dichromorpha viridis', 'Figure', 2, 'Earth', 0), - card('a2', 'Pathrail Mosque', 'Location', 2, 'History', 0), + card('a2', 'Pathrail Mosque', 'Location', 2, 'Society', 0), card('a3', 'Zbyszek Godlewski', 'Figure', 5, 'History', 0), card('a4', 'Monoid', 'Doctrine', 6, 'Science', 0), card('a5', 'Tom Ewell', 'Figure', 6, 'Arts', 0), @@ -28,8 +28,9 @@ const cards: Record = Object.fromEntries([ card('b3', 'Marc Fesneau', 'Figure', 5, 'Society', 1), card('b4', "Pallas's cat", 'Figure', 6, 'Earth', 1), card('b5', 'Heart rot', 'Doctrine', 5, 'Science', 1), - card('b6', '2025 Tehreek-e-Labbaik Pakistan protests', 'Event', 5, 'History', 1), + card('b6', '2025 Tehreek-e-Labbaik Pakistan protests', 'Event', 5, 'Society', 1), card('b7', 'Tatsunoko Production', 'Institution', 6, 'Arts', 1), + card('b8', 'Agda (programming language)', 'Doctrine', 6, 'Science', 1), ].map(c => [c.id, c])); const T = (turn: number): StoryEvent => ({ kind: 'turnStart', turn, seat: turn % 2 === 1 ? 0 : 1 }); @@ -49,7 +50,7 @@ const events: StoryEvent[] = [ T(9), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a3', power: 6, toughness: 3 }, { kind: 'block', seat: 1, blocker: 'b3', attacker: 'a3', power: 5, toughness: 4 }, { kind: 'destroyed', card: 'a3' }, { kind: 'destroyed', card: 'b3' }, { kind: 'draw', seat: 0 }, - T(10), { kind: 'draw', seat: 1 }, { kind: 'deploy', seat: 1, card: 'b4' }, + T(10), { kind: 'draw', seat: 1 }, { kind: 'discard', seat: 1, card: 'b8' }, { kind: 'deploy', seat: 1, card: 'b4' }, T(11), { kind: 'draw', seat: 0 }, { kind: 'deploy', seat: 0, card: 'a5' }, T(12), { kind: 'draw', seat: 1 }, { kind: 'adopt', seat: 1, doctrine: 'b5', figure: 'a5', power: 2, toughness: 2 }, { kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 }, { kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 15 }, @@ -124,7 +125,7 @@ test('log: golden lines for the omniscient view', () => { const later = lines.filter(l => l.text.includes('*Tom Ewell*')); assert.ok(later.length >= 3); assert.equal(later.filter(l => l.text.includes('American actor')).length, 1); - assert.equal(references.length, 12); + assert.equal(references.length, 13); // 12 played + the discarded Agda // snapshot of the whole log text (golden): regenerate deliberately if templates change assert.equal(paras.join('\n').length > 1500, true); assert.deepEqual(renderLog(record, null), { lines, references }); @@ -142,6 +143,11 @@ test('log: logFor hides the opponent\'s draws', () => { assert.ok(forAlice.some(t => /alice.*Dichromorpha viridis|Dichromorpha viridis.*alice/.test(t) && /drew|drawn|hand/.test(t))); }); +test('log: discards are public (Deleted is a public zone)', () => { + const forAlice = renderLog(record, 0).lines.map(l => l.text); + assert.ok(forAlice.some(t => /Agda \(programming language\)/.test(t) && /discard|Deleted/.test(t))); +}); + test('determinism: same seed gives the same text; another seed varies it', () => { assert.deepEqual(recap(record), recap(structuredClone(record))); const other = recap({ ...record, seed: 'another-seed' }); From 57d2fc2fc7a473b85ddec073a47d9f2459b987ea Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:58:37 -0500 Subject: [PATCH 12/25] [duel-cards] Match duel-core's contract (#72): template ids, description, maxTokens = fewer than N Co-Authored-By: Claude Opus 5.5 --- docs/game/duel-card-sample.json | 934 +++++++++++++++++++++----------- shared/duel/derive.ts | 3 + shared/duel/effects.ts | 23 +- shared/duel/text.ts | 4 +- 4 files changed, 645 insertions(+), 319 deletions(-) diff --git a/docs/game/duel-card-sample.json b/docs/game/duel-card-sample.json index 480513b..ef983ed 100644 --- a/docs/game/duel-card-sample.json +++ b/docs/game/duel-card-sample.json @@ -42,7 +42,8 @@ "pctReach": 63, "fame": 58, "magnitude": 2 - } + }, + "description": "Sultan of Aceh (1530–1537/9)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000a4cc4d", @@ -82,7 +83,8 @@ "pctReach": 93, "fame": 57, "magnitude": 2 - } + }, + "description": "Municipality in Carinthia, Austria" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001849df5", @@ -121,7 +123,8 @@ "pctReach": 91, "fame": 59, "magnitude": 2 - } + }, + "description": "Municipality of Bahia, Brazil" }, { "cardId": "00000000000000000000000000000000000000000000000000000000018a8b89", @@ -160,7 +163,8 @@ "pctReach": 53, "fame": 38, "magnitude": 1 - } + }, + "description": "Species of grasshopper" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002309e43", @@ -179,7 +183,8 @@ { "trigger": "onEnter", "op": "draw", - "amount": 1 + "amount": 1, + "template": "T9" }, { "trigger": "static", @@ -189,7 +194,8 @@ "toughness": 1, "condition": { "connected": true - } + }, + "template": "T9" } ], "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", @@ -217,7 +223,8 @@ "pctReach": 53, "fame": 60, "magnitude": 2 - } + }, + "description": "2012 British television film" }, { "cardId": "000000000000000000000000000000000000000000000000000000000279b34c", @@ -300,7 +307,8 @@ "pctReach": 47, "fame": 32, "magnitude": 1 - } + }, + "description": "American botanist (c.1872–1919)" }, { "cardId": "00000000000000000000000000000000000000000000000000000000039663ae", @@ -337,7 +345,8 @@ "pctReach": 63, "fame": 39, "magnitude": 2 - } + }, + "description": "Genus of crustaceans" }, { "cardId": "000000000000000000000000000000000000000000000000000000000404da56", @@ -357,7 +366,8 @@ "trigger": "onPlay", "op": "damageEach", "target": "each", - "amount": 1 + "amount": 1, + "template": "T4" } ], "rulesText": "Deal 1 damage to each Figure and each Location.", @@ -385,7 +395,8 @@ "pctReach": 8, "fame": 50, "magnitude": 2 - } + }, + "description": "Slow-moving nor'easter in April 2021" }, { "cardId": "00000000000000000000000000000000000000000000000000000000007f1bfc", @@ -412,8 +423,9 @@ "portal": "Neutral" }, "condition": { - "maxTokens": 2 - } + "maxTokens": 3 + }, + "template": "T8" } ], "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", @@ -441,7 +453,8 @@ "pctReach": 82, "fame": 77, "magnitude": 3 - } + }, + "description": "Japanese transportation company" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000f14093", @@ -480,7 +493,8 @@ "pctReach": 94, "fame": 39, "magnitude": 2 - } + }, + "description": "Commune in Centre-Val de Loire, France" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000f2623f", @@ -519,7 +533,8 @@ "pctReach": 58, "fame": 38, "magnitude": 1 - } + }, + "description": "River on Stewart Island / Rakiura, New Zealand" }, { "cardId": "00000000000000000000000000000000000000000000000000000000011e7dea", @@ -558,7 +573,8 @@ "pctReach": 67, "fame": 24, "magnitude": 1 - } + }, + "description": "Village in Łódź Voivodeship, Poland" }, { "cardId": "000000000000000000000000000000000000000000000000000000000175fc6f", @@ -632,7 +648,8 @@ "pctReach": 67, "fame": 39, "magnitude": 2 - } + }, + "description": "Municipality in Quebec, Canada" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001c845f2", @@ -672,7 +689,8 @@ "pctReach": 67, "fame": 44, "magnitude": 2 - } + }, + "description": "Village in Herefordshire, England" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003f6d6d1", @@ -711,7 +729,8 @@ "pctReach": 71, "fame": 38, "magnitude": 1 - } + }, + "description": "Species of fungus" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004cd4092", @@ -733,12 +752,14 @@ "target": "ownFigure", "power": 1, "toughness": 0, - "duration": "turn" + "duration": "turn", + "template": "T6" }, { "trigger": "onPlay", "op": "fight", - "target": "opponentFigure" + "target": "opponentFigure", + "template": "T6" } ], "rulesText": "Target Figure you control gets +1/+0 until end of turn, then it fights target Figure you don't control.", @@ -767,7 +788,8 @@ "pctReach": 8, "fame": 32, "magnitude": 1 - } + }, + "description": "Football match" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000071fcb", @@ -808,7 +830,8 @@ "pctReach": 74, "fame": 79, "magnitude": 3 - } + }, + "description": "Local government area in Victoria, Australia" }, { "cardId": "000000000000000000000000000000000000000000000000000000000025711c", @@ -830,7 +853,8 @@ "target": "figure", "power": -3, "toughness": -3, - "duration": "permanent" + "duration": "permanent", + "template": "T12" } ], "rulesText": "Attach to target Figure. It gets −3/−3.", @@ -854,7 +878,8 @@ "pctReach": 53, "fame": 68, "magnitude": 3 - } + }, + "description": "Fungal disease of trees" }, { "cardId": "00000000000000000000000000000000000000000000000000000000002ad3e8", @@ -897,7 +922,8 @@ "pctReach": 89, "fame": 95, "magnitude": 3 - } + }, + "description": "American voice actor and singer (born 1963)" }, { "cardId": "000000000000000000000000000000000000000000000000000000000089b9d0", @@ -919,13 +945,15 @@ "target": "ownFigure", "power": 3, "toughness": 3, - "duration": "permanent" + "duration": "permanent", + "template": "T11" }, { "trigger": "onCombatDamageToPlayer", "op": "draw", "target": "attached", - "amount": 1 + "amount": 1, + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +3/+3.\nWhenever it deals combat damage to a player, draw a card.", @@ -988,7 +1016,8 @@ "pctReach": 96, "fame": 55, "magnitude": 2 - } + }, + "description": "Commune in Grand Est, France" }, { "cardId": "000000000000000000000000000000000000000000000000000000000246d152", @@ -1013,7 +1042,8 @@ "power": 1, "toughness": 1, "portal": "Neutral" - } + }, + "template": "T8" } ], "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", @@ -1039,7 +1069,8 @@ "pctReach": 23, "fame": 31, "magnitude": 1 - } + }, + "description": "English blues/indie rock band" }, { "cardId": "00000000000000000000000000000000000000000000000000000000025ed7ee", @@ -1061,12 +1092,14 @@ "target": "ownFigure", "power": 2, "toughness": 0, - "duration": "turn" + "duration": "turn", + "template": "T6" }, { "trigger": "onPlay", "op": "fight", - "target": "opponentFigure" + "target": "opponentFigure", + "template": "T6" } ], "rulesText": "Target Figure you control gets +2/+0 until end of turn, then it fights target Figure you don't control.", @@ -1094,7 +1127,8 @@ "pctReach": 8, "fame": 41, "magnitude": 2 - } + }, + "description": "American college basketball season" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002f85b42", @@ -1132,7 +1166,8 @@ "pctReach": 8, "fame": 20, "magnitude": 1 - } + }, + "description": "Species of ancient plant" }, { "cardId": "00000000000000000000000000000000000000000000000000000000031e1299", @@ -1173,7 +1208,8 @@ "pctReach": 47, "fame": 49, "magnitude": 2 - } + }, + "description": "Mosque in Faridpur, Bangladesh" }, { "cardId": "00000000000000000000000000000000000000000000000000000000001e346c", @@ -1215,7 +1251,8 @@ "pctReach": 78, "fame": 68, "magnitude": 3 - } + }, + "description": "Polish protester (1952–1970)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000438c15", @@ -1237,13 +1274,15 @@ "target": "ownFigure", "power": 3, "toughness": 3, - "duration": "permanent" + "duration": "permanent", + "template": "T11" }, { "trigger": "onCombatDamageToPlayer", "op": "draw", "target": "attached", - "amount": 1 + "amount": 1, + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +3/+3.\nWhenever it deals combat damage to a player, draw a card.", @@ -1274,7 +1313,8 @@ "pctReach": 78, "fame": 82, "magnitude": 3 - } + }, + "description": "Functional programming language" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000475385", @@ -1313,7 +1353,8 @@ "pctReach": 90, "fame": 80, "magnitude": 3 - } + }, + "description": "Commune in Sisak-Moslavina County, Croatia" }, { "cardId": "00000000000000000000000000000000000000000000000000000000004dc3c7", @@ -1359,7 +1400,8 @@ "pctReach": 97, "fame": 90, "magnitude": 3 - } + }, + "description": "Queen of Portugal from 1497 to 1498" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000f2d966", @@ -1398,7 +1440,8 @@ "pctReach": 95, "fame": 34, "magnitude": 1 - } + }, + "description": "Commune in Hauts-de-France, France" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000f39622", @@ -1447,7 +1490,8 @@ "pctReach": 81, "fame": 70, "magnitude": 3 - } + }, + "description": "Bulgarian footballer" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001aba163", @@ -1486,7 +1530,8 @@ "pctReach": 78, "fame": 33, "magnitude": 1 - } + }, + "description": "Village in Estonia" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002ed73e4", @@ -1526,7 +1571,8 @@ "pctReach": 47, "fame": 37, "magnitude": 1 - } + }, + "description": "Town in Dhaka Division, Bangladesh" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002f27561", @@ -1569,7 +1615,8 @@ "pctReach": 78, "fame": 75, "magnitude": 3 - } + }, + "description": "Serbian archaeologist (1869–1956)" }, { "cardId": "000000000000000000000000000000000000000000000000000000000001adbf", @@ -1609,7 +1656,8 @@ "pctReach": 91, "fame": 72, "magnitude": 3 - } + }, + "description": "Town in Georgia, United States" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000ab844d", @@ -1653,7 +1701,8 @@ "pctReach": 82, "fame": 58, "magnitude": 2 - } + }, + "description": "French-Hungarian footballer (1929-2006)" }, { "cardId": "000000000000000000000000000000000000000000000000000000000162de74", @@ -1692,7 +1741,8 @@ "pctReach": 67, "fame": 29, "magnitude": 1 - } + }, + "description": "Species of orchid" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001d74bfb", @@ -1731,7 +1781,8 @@ "pctReach": 23, "fame": 38, "magnitude": 1 - } + }, + "description": "River in Michigan, United States" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003b4f3b0", @@ -1774,7 +1825,8 @@ "pctReach": 47, "fame": 41, "magnitude": 2 - } + }, + "description": "Vietnamese chess grandmaster (born 1985)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003d6c241", @@ -1851,7 +1903,8 @@ "pctReach": 36, "fame": 60, "magnitude": 2 - } + }, + "description": "Indian film director" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004d8a703", @@ -1871,7 +1924,8 @@ "trigger": "onPlay", "op": "damage", "target": "figureOrLocation", - "amount": 4 + "amount": 4, + "template": "T3" } ], "rulesText": "Deal 4 damage to target Figure or Location.", @@ -1900,7 +1954,8 @@ "pctReach": 23, "fame": 64, "magnitude": 3 - } + }, + "description": "Gaza war protests in Pakistan" }, { "cardId": "00000000000000000000000000000000000000000000000000000000000dc52e", @@ -1939,7 +1994,8 @@ "pctReach": 94, "fame": 76, "magnitude": 3 - } + }, + "description": "Region of Mauritania" }, { "cardId": "000000000000000000000000000000000000000000000000000000000014fa5c", @@ -1981,7 +2037,8 @@ "pctReach": 93, "fame": 90, "magnitude": 3 - } + }, + "description": "American actor (1909–1994)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000ea6920", @@ -2006,7 +2063,8 @@ "power": 1, "toughness": 1, "portal": "Society" - } + }, + "template": "T5" } ], "rulesText": "Create two 1/1 Society Figure tokens named Elected Member.", @@ -2076,7 +2134,8 @@ "pctReach": 36, "fame": 58, "magnitude": 2 - } + }, + "description": "American entrepreneur" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002f59319", @@ -2095,7 +2154,8 @@ { "trigger": "onEnter", "op": "draw", - "amount": 1 + "amount": 1, + "template": "T9" }, { "trigger": "static", @@ -2105,7 +2165,8 @@ "toughness": 1, "condition": { "connected": true - } + }, + "template": "T9" } ], "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", @@ -2133,7 +2194,8 @@ "pctReach": 23, "fame": 44, "magnitude": 2 - } + }, + "description": "Song by the 18th century Swedish bard Carl Michael Bellman" }, { "cardId": "000000000000000000000000000000000000000000000000000000000506ce99", @@ -2175,7 +2237,8 @@ "pctReach": 23, "fame": 39, "magnitude": 2 - } + }, + "description": "Argentine journalist and radio host (1951–2026)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000246570", @@ -2214,7 +2277,8 @@ "pctReach": 91, "fame": 68, "magnitude": 3 - } + }, + "description": "River in Italy" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000751b4c", @@ -2254,7 +2318,8 @@ "pctReach": 23, "fame": 16, "magnitude": 1 - } + }, + "description": "Place in the Blue Mountains, Australia" }, { "cardId": "000000000000000000000000000000000000000000000000000000000140afac", @@ -2338,7 +2403,8 @@ "pctReach": 8, "fame": 43, "magnitude": 2 - } + }, + "description": "Cuban-American criminologist (born 1970)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000183a95", @@ -2377,7 +2443,8 @@ "pctReach": 98, "fame": 92, "magnitude": 3 - } + }, + "description": "Place in Málaga, Spain" }, { "cardId": "000000000000000000000000000000000000000000000000000000000041756b", @@ -2418,7 +2485,8 @@ "pctReach": 80, "fame": 71, "magnitude": 3 - } + }, + "description": "Extinct genus of reptiles" }, { "cardId": "00000000000000000000000000000000000000000000000000000000010b1fc1", @@ -2461,7 +2529,8 @@ "pctReach": 78, "fame": 46, "magnitude": 2 - } + }, + "description": "German skeleton racer" }, { "cardId": "00000000000000000000000000000000000000000000000000000000013be088", @@ -2488,8 +2557,9 @@ "portal": "Neutral" }, "condition": { - "maxTokens": 2 - } + "maxTokens": 3 + }, + "template": "T8" } ], "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", @@ -2517,7 +2587,8 @@ "pctReach": 36, "fame": 54, "magnitude": 2 - } + }, + "description": "American indie folk band" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002d92236", @@ -2558,7 +2629,8 @@ "pctReach": 58, "fame": 55, "magnitude": 2 - } + }, + "description": "German film director and screenwriter (born 1973)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003d70634", @@ -2583,7 +2655,8 @@ "power": 1, "toughness": 1, "portal": "Society" - } + }, + "template": "T5" } ], "rulesText": "Create two 1/1 Society Figure tokens named Elected Member.", @@ -2611,7 +2684,8 @@ "pctReach": 36, "fame": 62, "magnitude": 2 - } + }, + "description": "Election in the Spanish municipality of Seville" }, { "cardId": "00000000000000000000000000000000000000000000000000000000049c9880", @@ -2636,7 +2710,8 @@ "power": 1, "toughness": 1, "portal": "Neutral" - } + }, + "template": "T8" } ], "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", @@ -2660,7 +2735,8 @@ "pctReach": 23, "fame": 45, "magnitude": 2 - } + }, + "description": "Political party in Panama" }, { "cardId": "000000000000000000000000000000000000000000000000000000000001c2f8", @@ -2699,7 +2775,8 @@ "pctReach": 94, "fame": 66, "magnitude": 3 - } + }, + "description": "City in Kentucky, United States" }, { "cardId": "000000000000000000000000000000000000000000000000000000000041fc69", @@ -2740,7 +2817,8 @@ "pctReach": 47, "fame": 50, "magnitude": 2 - } + }, + "description": "Finnish social scientist" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000908a9f", @@ -2759,7 +2837,8 @@ { "trigger": "onEnter", "op": "draw", - "amount": 1 + "amount": 1, + "template": "T9" }, { "trigger": "static", @@ -2769,7 +2848,8 @@ "toughness": 1, "condition": { "connected": true - } + }, + "template": "T9" } ], "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", @@ -2793,7 +2873,8 @@ "pctReach": 23, "fame": 26, "magnitude": 1 - } + }, + "description": "Serif typeface" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000befc0f", @@ -2832,7 +2913,8 @@ "pctReach": 47, "fame": 24, "magnitude": 1 - } + }, + "description": "Hamlet in Kent, England" }, { "cardId": "000000000000000000000000000000000000000000000000000000000181aa81", @@ -2852,7 +2934,8 @@ "trigger": "onPlay", "op": "damage", "target": "figureOrLocation", - "amount": 4 + "amount": 4, + "template": "T3" } ], "rulesText": "Deal 4 damage to target Figure or Location.", @@ -2881,7 +2964,8 @@ "pctReach": 74, "fame": 83, "magnitude": 3 - } + }, + "description": "Russian annexation of Outer Manchuria" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001fbc437", @@ -2921,7 +3005,8 @@ "pctReach": 83, "fame": 51, "magnitude": 2 - } + }, + "description": "Rural locality in Cherkasy Oblast, Ukraine" }, { "cardId": "000000000000000000000000000000000000000000000000000000000256bae2", @@ -2943,12 +3028,14 @@ "target": "ownFigure", "power": 2, "toughness": 0, - "duration": "turn" + "duration": "turn", + "template": "T6" }, { "trigger": "onPlay", "op": "fight", - "target": "opponentFigure" + "target": "opponentFigure", + "template": "T6" } ], "rulesText": "Target Figure you control gets +2/+0 until end of turn, then it fights target Figure you don't control.", @@ -2976,7 +3063,8 @@ "pctReach": 8, "fame": 51, "magnitude": 2 - } + }, + "description": "American college football season" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002c1eb97", @@ -3018,7 +3106,8 @@ "pctReach": 36, "fame": 46, "magnitude": 2 - } + }, + "description": "Haitian footballer (born 1990)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002fdc661", @@ -3058,7 +3147,8 @@ "pctReach": 63, "fame": 53, "magnitude": 2 - } + }, + "description": "Uzbek literary scholar and educator (1886–1938)" }, { "cardId": "000000000000000000000000000000000000000000000000000000000321b424", @@ -3104,7 +3194,8 @@ "pctReach": 78, "fame": 36, "magnitude": 1 - } + }, + "description": "Russian handball player" }, { "cardId": "00000000000000000000000000000000000000000000000000000000043bf4f0", @@ -3126,12 +3217,14 @@ "target": "ownFigure", "power": 1, "toughness": 0, - "duration": "turn" + "duration": "turn", + "template": "T6" }, { "trigger": "onPlay", "op": "fight", - "target": "opponentFigure" + "target": "opponentFigure", + "template": "T6" } ], "rulesText": "Target Figure you control gets +1/+0 until end of turn, then it fights target Figure you don't control.", @@ -3157,7 +3250,8 @@ "pctReach": 8, "fame": 23, "magnitude": 1 - } + }, + "description": "Motor car race" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004d8d1a8", @@ -3199,7 +3293,8 @@ "pctReach": 23, "fame": 54, "magnitude": 2 - } + }, + "description": "Argentine tennis player (born 1997)" }, { "cardId": "000000000000000000000000000000000000000000000000000000000021dbee", @@ -3223,7 +3318,8 @@ "toughness": 0, "condition": { "maxPower": 2 - } + }, + "template": "T10" } ], "rulesText": "Figures you control with power 2 or less get +1/+0.", @@ -3249,7 +3345,8 @@ "pctReach": 76, "fame": 84, "magnitude": 3 - } + }, + "description": "Political office in Malaysia" }, { "cardId": "00000000000000000000000000000000000000000000000000000000007e454c", @@ -3290,7 +3387,8 @@ "pctReach": 36, "fame": 63, "magnitude": 3 - } + }, + "description": "American politician (1735–1778)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001462f3f", @@ -3329,7 +3427,8 @@ "pctReach": 36, "fame": 20, "magnitude": 1 - } + }, + "description": "River in France" }, { "cardId": "000000000000000000000000000000000000000000000000000000000155d87e", @@ -3369,7 +3468,8 @@ "pctReach": 80, "fame": 48, "magnitude": 2 - } + }, + "description": "Commune in Gagauzia, Moldova" }, { "cardId": "00000000000000000000000000000000000000000000000000000000015797a4", @@ -3406,7 +3506,8 @@ "pctReach": 23, "fame": 50, "magnitude": 2 - } + }, + "description": "Columbarium in Singapore" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002d51886", @@ -3448,7 +3549,8 @@ "pctReach": 53, "fame": 27, "magnitude": 1 - } + }, + "description": "American singer and actress (1917–1989)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002e752d2", @@ -3488,7 +3590,8 @@ "pctReach": 36, "fame": 56, "magnitude": 2 - } + }, + "description": "Iranian-American Professor" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004b36e3e", @@ -3527,7 +3630,8 @@ "pctReach": 36, "fame": 18, "magnitude": 1 - } + }, + "description": "Building in Mercenasco, Italy" }, { "cardId": "00000000000000000000000000000000000000000000000000000000050afd22", @@ -3570,7 +3674,8 @@ "pctReach": 8, "fame": 39, "magnitude": 2 - } + }, + "description": "American physician (1864–1942)" }, { "cardId": "00000000000000000000000000000000000000000000000000000000000ef95c", @@ -3597,8 +3702,9 @@ "portal": "Neutral" }, "condition": { - "maxTokens": 2 - } + "maxTokens": 3 + }, + "template": "T8" } ], "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", @@ -3626,7 +3732,8 @@ "pctReach": 86, "fame": 93, "magnitude": 3 - } + }, + "description": "Japanese animation studio" }, { "cardId": "00000000000000000000000000000000000000000000000000000000001ed529", @@ -3648,7 +3755,8 @@ "target": "ownFigure", "power": 3, "toughness": 3, - "duration": "permanent" + "duration": "permanent", + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +3/+3.", @@ -3670,7 +3778,8 @@ "pctReach": 63, "fame": 78, "magnitude": 3 - } + }, + "description": "Class of seating in arena or stadium" }, { "cardId": "00000000000000000000000000000000000000000000000000000000002d7151", @@ -3707,7 +3816,8 @@ "pctReach": 86, "fame": 59, "magnitude": 2 - } + }, + "description": "Genus of legumes" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000d65bfa", @@ -3746,7 +3856,8 @@ "pctReach": 47, "fame": 63, "magnitude": 3 - } + }, + "description": "Village in Saskatchewan, Canada" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001d1c4f7", @@ -3771,7 +3882,8 @@ "power": 1, "toughness": 1, "portal": "Neutral" - } + }, + "template": "T8" } ], "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", @@ -3799,7 +3911,8 @@ "pctReach": 47, "fame": 46, "magnitude": 2 - } + }, + "description": "Prototype reconnaissance floatplane" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001d6c6e5", @@ -3839,7 +3952,8 @@ "pctReach": 89, "fame": 61, "magnitude": 2 - } + }, + "description": "Genus of fishes" }, { "cardId": "00000000000000000000000000000000000000000000000000000000028ca141", @@ -3878,7 +3992,8 @@ "pctReach": 23, "fame": 13, "magnitude": 1 - } + }, + "description": "Manor house in Charente-Maritime, France" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002e6632d", @@ -3898,7 +4013,8 @@ "trigger": "onPlay", "op": "damageEach", "target": "each", - "amount": 1 + "amount": 1, + "template": "T4" } ], "rulesText": "Deal 1 damage to each Figure and each Location.", @@ -3965,7 +4081,8 @@ "pctReach": 23, "fame": 33, "magnitude": 1 - } + }, + "description": "Building on Oxford Street, London, England" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000337786", @@ -4009,7 +4126,8 @@ "pctReach": 81, "fame": 61, "magnitude": 2 - } + }, + "description": "Cuban sprinter (1948–2024)" }, { "cardId": "00000000000000000000000000000000000000000000000000000000007f4694", @@ -4050,7 +4168,8 @@ "pctReach": 47, "fame": 66, "magnitude": 3 - } + }, + "description": "Family of Nicolae Ceaușescu" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000d29182", @@ -4072,7 +4191,8 @@ "target": "ownFigure", "power": 2, "toughness": 2, - "duration": "permanent" + "duration": "permanent", + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +2/+2.", @@ -4096,7 +4216,8 @@ "pctReach": 36, "fame": 46, "magnitude": 2 - } + }, + "description": "Stimulant drug" }, { "cardId": "00000000000000000000000000000000000000000000000000000000010eef0c", @@ -4139,7 +4260,8 @@ "pctReach": 58, "fame": 75, "magnitude": 3 - } + }, + "description": "Chinese-American biochemist" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001225032", @@ -4182,7 +4304,8 @@ "pctReach": 86, "fame": 39, "magnitude": 2 - } + }, + "description": "Russian basketball player" }, { "cardId": "00000000000000000000000000000000000000000000000000000000016ff42e", @@ -4204,7 +4327,8 @@ "target": "ownFigure", "power": 3, "toughness": 3, - "duration": "permanent" + "duration": "permanent", + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +3/+3.", @@ -4226,7 +4350,8 @@ "pctReach": 71, "fame": 66, "magnitude": 3 - } + }, + "description": "Type of dessert" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001e1e5e4", @@ -4267,7 +4392,8 @@ "pctReach": 36, "fame": 55, "magnitude": 2 - } + }, + "description": "Art museum in Parkville, Victoria" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001ff532a", @@ -4309,7 +4435,8 @@ "pctReach": 53, "fame": 31, "magnitude": 1 - } + }, + "description": "Dutch actor and comedian (1872–1936)" }, { "cardId": "000000000000000000000000000000000000000000000000000000000212369d", @@ -4346,7 +4473,8 @@ "pctReach": 71, "fame": 30, "magnitude": 1 - } + }, + "description": "Genus of crabs" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002d706ce", @@ -4387,7 +4515,8 @@ "pctReach": 8, "fame": 37, "magnitude": 1 - } + }, + "description": "American athletics facility at Indiana University Bloomington" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003853be9", @@ -4430,7 +4559,8 @@ "pctReach": 23, "fame": 70, "magnitude": 3 - } + }, + "description": "American politician and composer (born 1968)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003a79927", @@ -4474,7 +4604,8 @@ "pctReach": 8, "fame": 19, "magnitude": 1 - } + }, + "description": "American Japanologist (1879–1972)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000179138", @@ -4518,7 +4649,8 @@ "pctReach": 86, "fame": 88, "magnitude": 3 - } + }, + "description": "American theologian and Baptist pastor (1861-1918)" }, { "cardId": "00000000000000000000000000000000000000000000000000000000002518b4", @@ -4545,8 +4677,9 @@ "portal": "Neutral" }, "condition": { - "maxTokens": 2 - } + "maxTokens": 3 + }, + "template": "T8" } ], "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", @@ -4574,7 +4707,8 @@ "pctReach": 67, "fame": 85, "magnitude": 3 - } + }, + "description": "Structure of German air force" }, { "cardId": "00000000000000000000000000000000000000000000000000000000006af267", @@ -4601,8 +4735,9 @@ "portal": "Neutral" }, "condition": { - "maxTokens": 2 - } + "maxTokens": 3 + }, + "template": "T8" } ], "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", @@ -4631,7 +4766,8 @@ "pctReach": 36, "fame": 77, "magnitude": 3 - } + }, + "description": "Football team of Duke University" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000a9306d", @@ -4653,7 +4789,8 @@ "target": "ownFigure", "power": 2, "toughness": 2, - "duration": "permanent" + "duration": "permanent", + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +2/+2.", @@ -4677,7 +4814,8 @@ "pctReach": 36, "fame": 49, "magnitude": 2 - } + }, + "description": "Protein-coding gene in the species Homo sapiens" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000e463d7", @@ -4717,7 +4855,8 @@ "pctReach": 63, "fame": 56, "magnitude": 2 - } + }, + "description": "Village and civil parish in Nottinghamshire, England" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001625b83", @@ -4756,7 +4895,8 @@ "pctReach": 67, "fame": 51, "magnitude": 2 - } + }, + "description": "Genus of fungi" }, { "cardId": "000000000000000000000000000000000000000000000000000000000229b4e9", @@ -4795,7 +4935,8 @@ "pctReach": 8, "fame": 31, "magnitude": 1 - } + }, + "description": "Townland in County Fermanagh, Northern Ireland" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003256025", @@ -4819,7 +4960,8 @@ "toughness": 0, "condition": { "maxPower": 2 - } + }, + "template": "T10" } ], "rulesText": "Figures you control with power 2 or less get +1/+0.", @@ -4847,7 +4989,8 @@ "pctReach": 8, "fame": 17, "magnitude": 1 - } + }, + "description": "Steamship by John Elder" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000004cc4", @@ -4872,7 +5015,8 @@ "duration": "permanent", "grant": [ "Well-sourced" - ] + ], + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +3/+3 and has Well-sourced.", @@ -4894,7 +5038,8 @@ "pctReach": 98, "fame": 96, "magnitude": 3 - } + }, + "description": "Algebraic structure with an associative operation and an identity element" }, { "cardId": "00000000000000000000000000000000000000000000000000000000004bb672", @@ -4916,7 +5061,8 @@ "target": "ownFigure", "power": 3, "toughness": 3, - "duration": "permanent" + "duration": "permanent", + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +3/+3.", @@ -4940,7 +5086,8 @@ "pctReach": 36, "fame": 68, "magnitude": 3 - } + }, + "description": "Depictions of the positions of stars on the celestial sphere" }, { "cardId": "00000000000000000000000000000000000000000000000000000000008b571b", @@ -4959,7 +5106,8 @@ { "trigger": "onPlay", "op": "draw", - "amount": 2 + "amount": 2, + "template": "T7" } ], "rulesText": "Draw two cards.", @@ -4985,7 +5133,8 @@ "pctReach": 58, "fame": 52, "magnitude": 2 - } + }, + "description": "Olympic shooting event" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000b8fc3c", @@ -5026,7 +5175,8 @@ "pctReach": 36, "fame": 27, "magnitude": 1 - } + }, + "description": "Forest park in Ban Phue District, Thailand" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000e67fba", @@ -5051,7 +5201,8 @@ "duration": "permanent", "grant": [ "Well-sourced" - ] + ], + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +3/+3 and has Well-sourced.", @@ -5073,7 +5224,8 @@ "pctReach": 99, "fame": 97, "magnitude": 3 - } + }, + "description": "Excavation or structure to provide access to groundwater" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002e39459", @@ -5114,7 +5266,8 @@ "pctReach": 8, "fame": 8, "magnitude": 1 - } + }, + "description": "Historic house in Arkansas, United States" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003f34d76", @@ -5157,7 +5310,8 @@ "pctReach": 23, "fame": 20, "magnitude": 1 - } + }, + "description": "Genus of reptiles" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004dba1f0", @@ -5215,7 +5369,8 @@ { "trigger": "onEnter", "op": "draw", - "amount": 1 + "amount": 1, + "template": "T9" }, { "trigger": "static", @@ -5225,7 +5380,8 @@ "toughness": 1, "condition": { "connected": true - } + }, + "template": "T9" } ], "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", @@ -5253,7 +5409,8 @@ "pctReach": 90, "fame": 77, "magnitude": 3 - } + }, + "description": "1994 studio album by Burzum" }, { "cardId": "00000000000000000000000000000000000000000000000000000000003efcc4", @@ -5292,7 +5449,8 @@ "pctReach": 36, "fame": 44, "magnitude": 2 - } + }, + "description": "Town in Uva Province, Sri Lanka" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000ec5681", @@ -5334,7 +5492,8 @@ "pctReach": 58, "fame": 83, "magnitude": 3 - } + }, + "description": "American football player (born 1986)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001774450", @@ -5373,7 +5532,8 @@ "pctReach": 84, "fame": 48, "magnitude": 2 - } + }, + "description": "Place in Prekmurje, Slovenia" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003115e59", @@ -5412,7 +5572,8 @@ "pctReach": 8, "fame": 30, "magnitude": 1 - } + }, + "description": "Historic site in Queensland, Australia" }, { "cardId": "00000000000000000000000000000000000000000000000000000000032f1880", @@ -5437,7 +5598,8 @@ "power": 1, "toughness": 1, "portal": "Society" - } + }, + "template": "T5" } ], "rulesText": "Create two 1/1 Society Figure tokens named Elected Member.", @@ -5522,7 +5684,8 @@ { "trigger": "onEnter", "op": "draw", - "amount": 1 + "amount": 1, + "template": "T9" }, { "trigger": "static", @@ -5532,7 +5695,8 @@ "toughness": 1, "condition": { "connected": true - } + }, + "template": "T9" } ], "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", @@ -5560,7 +5724,8 @@ "pctReach": 8, "fame": 31, "magnitude": 1 - } + }, + "description": "Semi-weekly newspaper published in Waldorf, Maryland, US" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004a88b48", @@ -5601,7 +5766,8 @@ "pctReach": 23, "fame": 12, "magnitude": 1 - } + }, + "description": "Species of king crab" }, { "cardId": "000000000000000000000000000000000000000000000000000000000002061e", @@ -5638,7 +5804,8 @@ "pctReach": 63, "fame": 55, "magnitude": 2 - } + }, + "description": "Township in Pennsylvania, US" }, { "cardId": "00000000000000000000000000000000000000000000000000000000000d1815", @@ -5665,8 +5832,9 @@ "portal": "Neutral" }, "condition": { - "maxTokens": 2 - } + "maxTokens": 3 + }, + "template": "T8" } ], "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", @@ -5694,7 +5862,8 @@ "pctReach": 36, "fame": 52, "magnitude": 2 - } + }, + "description": "British manufacturers of car body shells & chassis for specials (1955-1962)" }, { "cardId": "00000000000000000000000000000000000000000000000000000000010c9c6d", @@ -5713,7 +5882,8 @@ { "trigger": "onEnter", "op": "draw", - "amount": 1 + "amount": 1, + "template": "T9" }, { "trigger": "static", @@ -5723,7 +5893,8 @@ "toughness": 1, "condition": { "connected": true - } + }, + "template": "T9" } ], "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", @@ -5752,7 +5923,8 @@ "pctReach": 36, "fame": 42, "magnitude": 2 - } + }, + "description": "1939 film by Wilhelm Thiele" }, { "cardId": "00000000000000000000000000000000000000000000000000000000015e910f", @@ -5771,7 +5943,8 @@ { "trigger": "onPlay", "op": "draw", - "amount": 3 + "amount": 3, + "template": "T7" } ], "rulesText": "Draw three cards.", @@ -5836,7 +6009,8 @@ "pctReach": 47, "fame": 20, "magnitude": 1 - } + }, + "description": "Species of plant" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002217317", @@ -5858,7 +6032,8 @@ "target": "ownFigure", "power": 2, "toughness": 2, - "duration": "permanent" + "duration": "permanent", + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +2/+2.", @@ -5882,7 +6057,8 @@ "pctReach": 58, "fame": 50, "magnitude": 2 - } + }, + "description": "Italian chocolate coffee drink" }, { "cardId": "00000000000000000000000000000000000000000000000000000000023d5c96", @@ -5925,7 +6101,8 @@ "pctReach": 74, "fame": 51, "magnitude": 2 - } + }, + "description": "German footballer" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003d66226", @@ -5968,7 +6145,8 @@ "pctReach": 36, "fame": 24, "magnitude": 1 - } + }, + "description": "Russian handball player" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003eadb6d", @@ -6007,7 +6185,8 @@ "pctReach": 23, "fame": 50, "magnitude": 2 - } + }, + "description": "U.S. Marine major general" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004e3418c", @@ -6032,7 +6211,8 @@ "power": 1, "toughness": 1, "portal": "Neutral" - } + }, + "template": "T8" } ], "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", @@ -6058,7 +6238,8 @@ "pctReach": 8, "fame": 47, "magnitude": 2 - } + }, + "description": "New Zealand timber and building supplies company" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000129da3", @@ -6102,7 +6283,8 @@ "pctReach": 8, "fame": 54, "magnitude": 2 - } + }, + "description": "Recipient of the Victoria Cross" }, { "cardId": "000000000000000000000000000000000000000000000000000000000134dd65", @@ -6145,7 +6327,8 @@ "pctReach": 82, "fame": 42, "magnitude": 2 - } + }, + "description": "Hungarian canoeist (1941–2022)" }, { "cardId": "000000000000000000000000000000000000000000000000000000000182777d", @@ -6186,7 +6369,8 @@ "pctReach": 63, "fame": 69, "magnitude": 3 - } + }, + "description": "French politician (born 1971)" }, { "cardId": "000000000000000000000000000000000000000000000000000000000279e59b", @@ -6205,7 +6389,8 @@ { "trigger": "onEnter", "op": "draw", - "amount": 1 + "amount": 1, + "template": "T9" }, { "trigger": "static", @@ -6215,7 +6400,8 @@ "toughness": 1, "condition": { "connected": true - } + }, + "template": "T9" } ], "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", @@ -6245,7 +6431,8 @@ "pctReach": 53, "fame": 48, "magnitude": 2 - } + }, + "description": "1917 American silent film" }, { "cardId": "00000000000000000000000000000000000000000000000000000000027f963c", @@ -6270,7 +6457,8 @@ "power": 1, "toughness": 1, "portal": "Neutral" - } + }, + "template": "T8" } ], "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", @@ -6296,7 +6484,8 @@ "pctReach": 8, "fame": 15, "magnitude": 1 - } + }, + "description": "Non-profit organization in Florida, US" }, { "cardId": "00000000000000000000000000000000000000000000000000000000028399d2", @@ -6336,7 +6525,8 @@ "pctReach": 80, "fame": 62, "magnitude": 2 - } + }, + "description": "Extremely clumsy female character in anime and manga" }, { "cardId": "00000000000000000000000000000000000000000000000000000000033104b5", @@ -6377,7 +6567,8 @@ "pctReach": 23, "fame": 39, "magnitude": 2 - } + }, + "description": "Railway station in Jünkerath, Germany" }, { "cardId": "000000000000000000000000000000000000000000000000000000000391b393", @@ -6404,8 +6595,9 @@ "portal": "Neutral" }, "condition": { - "maxTokens": 2 - } + "maxTokens": 3 + }, + "template": "T8" } ], "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", @@ -6433,7 +6625,8 @@ "pctReach": 47, "fame": 77, "magnitude": 3 - } + }, + "description": "Film distribution successor to United Artists" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004a1ebca", @@ -6513,7 +6706,8 @@ "pctReach": 67, "fame": 63, "magnitude": 3 - } + }, + "description": "British track cyclist" }, { "cardId": "0000000000000000000000000000000000000000000000000000000005057304", @@ -6552,7 +6746,8 @@ "pctReach": 78, "fame": 37, "magnitude": 1 - } + }, + "description": "Extinct parish in Guimarães, Portugal" }, { "cardId": "00000000000000000000000000000000000000000000000000000000000155c7", @@ -6591,7 +6786,8 @@ "pctReach": 93, "fame": 88, "magnitude": 3 - } + }, + "description": "Census area in Alaska, United States" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000365525", @@ -6633,7 +6829,8 @@ "pctReach": 47, "fame": 56, "magnitude": 2 - } + }, + "description": "British businessman (born 1952)" }, { "cardId": "000000000000000000000000000000000000000000000000000000000051e94e", @@ -6674,7 +6871,8 @@ "pctReach": 8, "fame": 48, "magnitude": 2 - } + }, + "description": "Shopping mall in Connecticut, United States" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001e1c7a2", @@ -6716,7 +6914,8 @@ "pctReach": 58, "fame": 51, "magnitude": 2 - } + }, + "description": "Italian long-distance runner (born 1979)" }, { "cardId": "000000000000000000000000000000000000000000000000000000000211993c", @@ -6801,7 +7000,8 @@ "pctReach": 8, "fame": 14, "magnitude": 1 - } + }, + "description": "Historic house in Missouri, United States" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000347e0d", @@ -6820,7 +7020,8 @@ { "trigger": "onPlay", "op": "draw", - "amount": 2 + "amount": 2, + "template": "T7" } ], "rulesText": "Draw two cards.", @@ -6848,7 +7049,8 @@ "pctReach": 85, "fame": 58, "magnitude": 2 - } + }, + "description": "Sporting event delegation" }, { "cardId": "000000000000000000000000000000000000000000000000000000000042c0a6", @@ -6873,7 +7075,8 @@ "duration": "permanent", "grant": [ "Well-sourced" - ] + ], + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +2/+2 and has Well-sourced.", @@ -6919,7 +7122,8 @@ "target": "figure", "power": -2, "toughness": -2, - "duration": "permanent" + "duration": "permanent", + "template": "T12" } ], "rulesText": "Attach to target Figure. It gets −2/−2.", @@ -6943,7 +7147,8 @@ "pctReach": 36, "fame": 48, "magnitude": 2 - } + }, + "description": "Crystallized urea deposits on skin" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000f4bc30", @@ -6982,7 +7187,8 @@ "pctReach": 95, "fame": 34, "magnitude": 1 - } + }, + "description": "Commune in Pays de la Loire, France" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001334c0c", @@ -7025,7 +7231,8 @@ "pctReach": 23, "fame": 13, "magnitude": 1 - } + }, + "description": "American baseball player (1839–1901)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001b5f940", @@ -7064,7 +7271,8 @@ "pctReach": 67, "fame": 36, "magnitude": 1 - } + }, + "description": "Island in Iceland" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002aa485f", @@ -7088,7 +7296,8 @@ "toughness": 0, "condition": { "maxPower": 2 - } + }, + "template": "T10" } ], "rulesText": "Figures you control with power 2 or less get +1/+0.", @@ -7117,7 +7326,8 @@ "pctReach": 74, "fame": 57, "magnitude": 2 - } + }, + "description": "Suburban tram line in Hauts-de-Seine and Yvelines, southwest of Paris" }, { "cardId": "00000000000000000000000000000000000000000000000000000000004d774c", @@ -7144,8 +7354,9 @@ "portal": "Neutral" }, "condition": { - "maxTokens": 2 - } + "maxTokens": 3 + }, + "template": "T8" } ], "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", @@ -7171,7 +7382,8 @@ "pctReach": 23, "fame": 51, "magnitude": 2 - } + }, + "description": "Anti-Slavery organization" }, { "cardId": "00000000000000000000000000000000000000000000000000000000008223bb", @@ -7213,7 +7425,8 @@ "pctReach": 8, "fame": 52, "magnitude": 2 - } + }, + "description": "Former oil refinery in Neath Port Talbot, Wales" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000ea3205", @@ -7238,7 +7451,8 @@ "power": 1, "toughness": 1, "portal": "Neutral" - } + }, + "template": "T8" } ], "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", @@ -7265,7 +7479,8 @@ "pctReach": 81, "fame": 38, "magnitude": 1 - } + }, + "description": "Roman Catholic diocese in Cape Verde" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000edde01", @@ -7305,7 +7520,8 @@ "pctReach": 91, "fame": 34, "magnitude": 1 - } + }, + "description": "Part of Ornans in Bourgogne-Franche-Comté, France" }, { "cardId": "00000000000000000000000000000000000000000000000000000000010609ef", @@ -7344,7 +7560,8 @@ "pctReach": 84, "fame": 67, "magnitude": 3 - } + }, + "description": "Place in Haut-Lomami, Democratic Republic of the Congo" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001639bbc", @@ -7383,7 +7600,8 @@ "pctReach": 74, "fame": 38, "magnitude": 1 - } + }, + "description": "Place in Paphos District, Cyprus" }, { "cardId": "00000000000000000000000000000000000000000000000000000000025124c9", @@ -7425,7 +7643,8 @@ "pctReach": 8, "fame": 26, "magnitude": 1 - } + }, + "description": "American Spiritualist medium (died 1960)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003c6d80f", @@ -7468,7 +7687,8 @@ "pctReach": 63, "fame": 80, "magnitude": 3 - } + }, + "description": "American basketball player (born 2000)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004606820", @@ -7507,7 +7727,8 @@ "pctReach": 53, "fame": 34, "magnitude": 1 - } + }, + "description": "Village in Skopje, North Macedonia" }, { "cardId": "00000000000000000000000000000000000000000000000000000000000e1834", @@ -7546,7 +7767,8 @@ "pctReach": 97, "fame": 69, "magnitude": 3 - } + }, + "description": "Commune in Auvergne-Rhône-Alpes, France" }, { "cardId": "00000000000000000000000000000000000000000000000000000000003487d1", @@ -7587,7 +7809,8 @@ "pctReach": 36, "fame": 34, "magnitude": 1 - } + }, + "description": "Provincial park in Ontario, Canada" }, { "cardId": "00000000000000000000000000000000000000000000000000000000004563e8", @@ -7609,7 +7832,8 @@ "target": "figure", "power": -2, "toughness": -2, - "duration": "permanent" + "duration": "permanent", + "template": "T12" } ], "rulesText": "Attach to target Figure. It gets −2/−2.", @@ -7633,7 +7857,8 @@ "pctReach": 53, "fame": 57, "magnitude": 2 - } + }, + "description": "Flattening of the trachea in animals" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000d2549d", @@ -7673,7 +7898,8 @@ "pctReach": 63, "fame": 48, "magnitude": 2 - } + }, + "description": "Waterfall on the Ellenborough River in New South Wales, Australia" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001fe7b62", @@ -7714,7 +7940,8 @@ "pctReach": 47, "fame": 23, "magnitude": 1 - } + }, + "description": "Ancient Greek vase painter" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002b548f0", @@ -7758,7 +7985,8 @@ "pctReach": 89, "fame": 90, "magnitude": 3 - } + }, + "description": "Major water Orisha in the Yoruba religion" }, { "cardId": "00000000000000000000000000000000000000000000000000000000047e7091", @@ -7801,7 +8029,8 @@ "pctReach": 36, "fame": 53, "magnitude": 2 - } + }, + "description": "Indonesian activist and politician" }, { "cardId": "00000000000000000000000000000000000000000000000000000000002f764e", @@ -7840,7 +8069,8 @@ "pctReach": 53, "fame": 29, "magnitude": 1 - } + }, + "description": "Village in Senja Municipality, Norway" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000768587", @@ -7881,7 +8111,8 @@ "pctReach": 74, "fame": 25, "magnitude": 1 - } + }, + "description": "Species of amphibian" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000e314ca", @@ -7903,7 +8134,8 @@ "target": "ownFigure", "power": 1, "toughness": 1, - "duration": "permanent" + "duration": "permanent", + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +1/+1.", @@ -7927,7 +8159,8 @@ "pctReach": 58, "fame": 25, "magnitude": 1 - } + }, + "description": "Protein-coding gene in the species Homo sapiens" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001e25f63", @@ -7968,7 +8201,8 @@ "pctReach": 36, "fame": 62, "magnitude": 2 - } + }, + "description": "Irish politician (born 1974)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002004071", @@ -8007,7 +8241,8 @@ "pctReach": 47, "fame": 17, "magnitude": 1 - } + }, + "description": "River in Thuringia, Germany" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002469bab", @@ -8049,7 +8284,8 @@ "pctReach": 47, "fame": 42, "magnitude": 2 - } + }, + "description": "Hungarian economist and politician" }, { "cardId": "00000000000000000000000000000000000000000000000000000000030834b6", @@ -8074,7 +8310,8 @@ "power": 1, "toughness": 1, "portal": "Neutral" - } + }, + "template": "T8" } ], "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", @@ -8141,7 +8378,8 @@ "pctReach": 47, "fame": 18, "magnitude": 1 - } + }, + "description": "Species of true bug" }, { "cardId": "00000000000000000000000000000000000000000000000000000000000c07c1", @@ -8168,8 +8406,9 @@ "portal": "Neutral" }, "condition": { - "maxTokens": 2 - } + "maxTokens": 3 + }, + "template": "T8" } ], "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", @@ -8199,7 +8438,8 @@ "pctReach": 86, "fame": 87, "magnitude": 3 - } + }, + "description": "Israeli settlement in the West Bank" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000314a5b", @@ -8236,7 +8476,8 @@ "pctReach": 74, "fame": 64, "magnitude": 3 - } + }, + "description": "One of the principal islands of Bermuda" }, { "cardId": "00000000000000000000000000000000000000000000000000000000006ec6df", @@ -8261,7 +8502,8 @@ "power": 1, "toughness": 1, "portal": "Neutral" - } + }, + "template": "T8" } ], "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", @@ -8315,7 +8557,8 @@ "duration": "permanent", "grant": [ "Well-sourced" - ] + ], + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +2/+2 and has Well-sourced.", @@ -8339,7 +8582,8 @@ "pctReach": 36, "fame": 49, "magnitude": 2 - } + }, + "description": "Arrangement of 30 points and 12 lines" }, { "cardId": "000000000000000000000000000000000000000000000000000000000234c209", @@ -8380,7 +8624,8 @@ "pctReach": 67, "fame": 29, "magnitude": 1 - } + }, + "description": "Church in Naples, Italy" }, { "cardId": "000000000000000000000000000000000000000000000000000000000249a814", @@ -8425,7 +8670,8 @@ "pctReach": 8, "fame": 30, "magnitude": 1 - } + }, + "description": "Indian surgeon and artist" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002c76795", @@ -8467,7 +8713,8 @@ "pctReach": 36, "fame": 63, "magnitude": 3 - } + }, + "description": "Canadian politician (born 1980)" }, { "cardId": "00000000000000000000000000000000000000000000000000000000048da231", @@ -8487,7 +8734,8 @@ "trigger": "onPlay", "op": "damage", "target": "figureOrLocation", - "amount": 4 + "amount": 4, + "template": "T3" } ], "rulesText": "Deal 4 damage to target Figure or Location.", @@ -8515,7 +8763,8 @@ "pctReach": 58, "fame": 76, "magnitude": 3 - } + }, + "description": "Protests against the Cuban government" }, { "cardId": "000000000000000000000000000000000000000000000000000000000070b485", @@ -8534,7 +8783,8 @@ { "trigger": "onEnter", "op": "draw", - "amount": 1 + "amount": 1, + "template": "T9" }, { "trigger": "static", @@ -8544,7 +8794,8 @@ "toughness": 1, "condition": { "connected": true - } + }, + "template": "T9" } ], "rulesText": "When this enters, draw a card.\nFigures you control that are Connected to this get +1/+1.", @@ -8573,7 +8824,8 @@ "pctReach": 8, "fame": 45, "magnitude": 2 - } + }, + "description": "1969 American TV series or program" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000be57a1", @@ -8615,7 +8867,8 @@ "pctReach": 87, "fame": 50, "magnitude": 2 - } + }, + "description": "Species of bird" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001289a8f", @@ -8658,7 +8911,8 @@ "pctReach": 89, "fame": 44, "magnitude": 2 - } + }, + "description": "German physician and botanist" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002636619", @@ -8695,7 +8949,8 @@ "pctReach": 23, "fame": 26, "magnitude": 1 - } + }, + "description": "Massachusetts state park" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004db234b", @@ -8722,8 +8977,9 @@ "portal": "Neutral" }, "condition": { - "maxTokens": 2 - } + "maxTokens": 3 + }, + "template": "T8" } ], "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", @@ -8751,7 +9007,8 @@ "pctReach": 8, "fame": 57, "magnitude": 2 - } + }, + "description": "Government agency in the Philippines" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004f1c0b9", @@ -8773,7 +9030,8 @@ "target": "ownFigure", "power": 2, "toughness": 2, - "duration": "permanent" + "duration": "permanent", + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +2/+2.", @@ -8795,7 +9053,8 @@ "pctReach": 8, "fame": 46, "magnitude": 2 - } + }, + "description": "Recurring assemblage of lichen species and its classification in vegetation science" }, { "cardId": "000000000000000000000000000000000000000000000000000000000017f942", @@ -8817,7 +9076,8 @@ "target": "ownFigure", "power": 3, "toughness": 3, - "duration": "permanent" + "duration": "permanent", + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +3/+3.", @@ -8878,7 +9138,8 @@ "pctReach": 71, "fame": 25, "magnitude": 1 - } + }, + "description": "Village in Silesian Voivodeship, Poland" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001b2dc67", @@ -8948,8 +9209,9 @@ "portal": "Neutral" }, "condition": { - "maxTokens": 2 - } + "maxTokens": 3 + }, + "template": "T8" } ], "rulesText": "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.", @@ -8977,7 +9239,8 @@ "pctReach": 23, "fame": 64, "magnitude": 3 - } + }, + "description": "Philippine department store chain" }, { "cardId": "00000000000000000000000000000000000000000000000000000000025e3602", @@ -9018,7 +9281,8 @@ "pctReach": 8, "fame": 15, "magnitude": 1 - } + }, + "description": "United States historic place" }, { "cardId": "0000000000000000000000000000000000000000000000000000000002b69213", @@ -9055,7 +9319,8 @@ "pctReach": 23, "fame": 28, "magnitude": 1 - } + }, + "description": "State highway in Lincoln County, Maine, US" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003105e51", @@ -9121,7 +9386,8 @@ "target": "ownFigure", "power": 3, "toughness": 3, - "duration": "permanent" + "duration": "permanent", + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +3/+3.", @@ -9190,7 +9456,8 @@ "pctReach": 8, "fame": 27, "magnitude": 1 - } + }, + "description": "American politician" }, { "cardId": "000000000000000000000000000000000000000000000000000000000508b134", @@ -9227,7 +9494,8 @@ "pctReach": 53, "fame": 42, "magnitude": 2 - } + }, + "description": "Species of marine amphipod" }, { "cardId": "000000000000000000000000000000000000000000000000000000000000c16a", @@ -9270,7 +9538,8 @@ "pctReach": 97, "fame": 91, "magnitude": 3 - } + }, + "description": "French mathematician (1875–1941)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000e13cb0", @@ -9292,7 +9561,8 @@ "target": "ownFigure", "power": 1, "toughness": 1, - "duration": "permanent" + "duration": "permanent", + "template": "T11" } ], "rulesText": "Attach to target Figure you control. It gets +1/+1.", @@ -9316,7 +9586,8 @@ "pctReach": 23, "fame": 38, "magnitude": 1 - } + }, + "description": "Protein-coding gene in humans" }, { "cardId": "00000000000000000000000000000000000000000000000000000000044ec330", @@ -9357,7 +9628,8 @@ "pctReach": 58, "fame": 53, "magnitude": 2 - } + }, + "description": "County in Alborz province, Iran" }, { "cardId": "00000000000000000000000000000000000000000000000000000000047b26e9", @@ -9382,7 +9654,8 @@ "power": 1, "toughness": 1, "portal": "Society" - } + }, + "template": "T5" } ], "rulesText": "Create a 1/1 Society Figure token named Elected Member.", @@ -9435,7 +9708,8 @@ "power": 1, "toughness": 1, "portal": "Neutral" - } + }, + "template": "T8" } ], "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", @@ -9463,7 +9737,8 @@ "pctReach": 47, "fame": 48, "magnitude": 2 - } + }, + "description": "Regional council of Östergötland County, Sweden" }, { "cardId": "0000000000000000000000000000000000000000000000000000000004fb7786", @@ -9506,7 +9781,8 @@ "pctReach": 23, "fame": 53, "magnitude": 2 - } + }, + "description": "Polish mixed martial artist (born 1996)" }, { "cardId": "000000000000000000000000000000000000000000000000000000000001f064", @@ -9546,7 +9822,8 @@ "pctReach": 87, "fame": 75, "magnitude": 3 - } + }, + "description": "Village in New York, United States" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000042d2a", @@ -9586,7 +9863,8 @@ "pctReach": 99, "fame": 98, "magnitude": 3 - } + }, + "description": "Species of small wild cat" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001a702c7", @@ -9611,7 +9889,8 @@ "power": 1, "toughness": 1, "portal": "Neutral" - } + }, + "template": "T8" } ], "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", @@ -9640,7 +9919,8 @@ "pctReach": 8, "fame": 36, "magnitude": 1 - } + }, + "description": "Scottish post-rock band" }, { "cardId": "000000000000000000000000000000000000000000000000000000000003c754", @@ -9662,12 +9942,14 @@ "target": "ownFigure", "power": 3, "toughness": 0, - "duration": "turn" + "duration": "turn", + "template": "T6" }, { "trigger": "onPlay", "op": "fight", - "target": "opponentFigure" + "target": "opponentFigure", + "template": "T6" } ], "rulesText": "Target Figure you control gets +3/+0 until end of turn, then it fights target Figure you don't control.", @@ -9696,7 +9978,8 @@ "pctReach": 97, "fame": 96, "magnitude": 3 - } + }, + "description": "Formula One Grand Prix" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000577b42", @@ -9718,12 +10001,14 @@ "target": "ownFigure", "power": 3, "toughness": 0, - "duration": "turn" + "duration": "turn", + "template": "T6" }, { "trigger": "onPlay", "op": "fight", - "target": "opponentFigure" + "target": "opponentFigure", + "template": "T6" } ], "rulesText": "Target Figure you control gets +3/+0 until end of turn, then it fights target Figure you don't control.", @@ -9773,12 +10058,14 @@ "target": "ownFigure", "power": 2, "toughness": 0, - "duration": "turn" + "duration": "turn", + "template": "T6" }, { "trigger": "onPlay", "op": "fight", - "target": "opponentFigure" + "target": "opponentFigure", + "template": "T6" } ], "rulesText": "Target Figure you control gets +2/+0 until end of turn, then it fights target Figure you don't control.", @@ -9806,7 +10093,8 @@ "pctReach": 71, "fame": 51, "magnitude": 2 - } + }, + "description": "International speed skating competition" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001b85b73", @@ -9845,7 +10133,8 @@ "pctReach": 71, "fame": 33, "magnitude": 1 - } + }, + "description": "Village in Estonia" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001e7779d", @@ -9869,7 +10158,8 @@ "toughness": 0, "condition": { "maxPower": 2 - } + }, + "template": "T10" } ], "rulesText": "Figures you control with power 2 or less get +1/+0.", @@ -9938,7 +10228,8 @@ "pctReach": 8, "fame": 39, "magnitude": 2 - } + }, + "description": "United States Coast Guardsman" }, { "cardId": "00000000000000000000000000000000000000000000000000000000026196e4", @@ -9963,7 +10254,8 @@ "power": 1, "toughness": 1, "portal": "Neutral" - } + }, + "template": "T8" } ], "rulesText": "When this enters, create a 1/1 Figure token named Staff Member.", @@ -9987,7 +10279,8 @@ "pctReach": 8, "fame": 17, "magnitude": 1 - } + }, + "description": "Military decoration" }, { "cardId": "000000000000000000000000000000000000000000000000000000000292a898", @@ -10027,7 +10320,8 @@ "pctReach": 8, "fame": 17, "magnitude": 1 - } + }, + "description": "Union Army soldier" }, { "cardId": "00000000000000000000000000000000000000000000000000000000046d99b5", @@ -10046,7 +10340,8 @@ { "trigger": "onPlay", "op": "draw", - "amount": 2 + "amount": 2, + "template": "T7" } ], "rulesText": "Draw two cards.", @@ -10074,7 +10369,8 @@ "pctReach": 8, "fame": 50, "magnitude": 2 - } + }, + "description": "LGBT sex scandal in September 1940" }, { "cardId": "0000000000000000000000000000000000000000000000000000000000ca0a2e", @@ -10116,7 +10412,8 @@ "pctReach": 8, "fame": 14, "magnitude": 1 - } + }, + "description": "United States historic place" }, { "cardId": "0000000000000000000000000000000000000000000000000000000001283431", @@ -10157,7 +10454,8 @@ "pctReach": 71, "fame": 62, "magnitude": 2 - } + }, + "description": "French jurist, bishop and Cardinal" }, { "cardId": "00000000000000000000000000000000000000000000000000000000017a1788", @@ -10199,7 +10497,8 @@ "pctReach": 8, "fame": 52, "magnitude": 2 - } + }, + "description": "US Army facility in Illesheim, Germany" }, { "cardId": "000000000000000000000000000000000000000000000000000000000252776f", @@ -10236,7 +10535,8 @@ "pctReach": 8, "fame": 15, "magnitude": 1 - } + }, + "description": "Artillery batteries in Gibraltar" }, { "cardId": "00000000000000000000000000000000000000000000000000000000028e29f5", @@ -10280,7 +10580,8 @@ "pctReach": 23, "fame": 51, "magnitude": 2 - } + }, + "description": "Russian-born American Yiddish-language writer (1877–1962)" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003bf2818", @@ -10319,7 +10620,8 @@ "pctReach": 8, "fame": 26, "magnitude": 1 - } + }, + "description": "Historic district in Missouri, United States" }, { "cardId": "0000000000000000000000000000000000000000000000000000000003f5c331", @@ -10344,7 +10646,8 @@ "power": 1, "toughness": 1, "portal": "Society" - } + }, + "template": "T5" } ], "rulesText": "Create three 1/1 Society Figure tokens named Elected Member.", @@ -10413,7 +10716,8 @@ "pctReach": 67, "fame": 55, "magnitude": 2 - } + }, + "description": "Township in Pennsylvania, US" } ] } diff --git a/shared/duel/derive.ts b/shared/duel/derive.ts index 91f1bd2..f6b180a 100644 --- a/shared/duel/derive.ts +++ b/shared/duel/derive.ts @@ -48,6 +48,8 @@ export interface DuelCard { pageId: number; revisionId: number; title: string; + /** Wikidata short description, for log first mentions (omitted when absent). */ + description?: string; type: CardType; /** Template family within the type, e.g. 'conflict', 'election', 'organisation', 'pathology'. */ subtype: string | null; @@ -291,6 +293,7 @@ export function derive(chain: CardOnChain, profile: CardProfile, rules: DeriveRu rarity: rarityOf(chain.tokenId), deriveVersion: DERIVE_VERSION, typedBy: source, basis: { pctAttention: p.attention, pctDepth: p.depth, pctReach: p.reach, fame, magnitude }, }; + if (profile.description) card.description = profile.description; card.rulesText = rulesTextFor(card); return card; } diff --git a/shared/duel/effects.ts b/shared/duel/effects.ts index 2d7f555..c433f6d 100644 --- a/shared/duel/effects.ts +++ b/shared/duel/effects.ts @@ -19,8 +19,11 @@ export interface EffectSpec { toughness?: number; duration?: 'turn' | 'permanent'; token?: { name: string; power: number; toughness: number; portal: Portal }; - condition?: { maxPower?: number; samePortal?: boolean; connected?: boolean; maxTokens?: number; whileAttacking?: boolean }; + /** maxTokens: createToken only if the controller controls fewer than this many tokens (duel-core types.ts). */ + condition?: { maxPower?: number; samePortal?: boolean; connected?: boolean; maxTokens?: number }; grant?: Keyword[]; + /** Template id (DUEL_DESIGN §5, T3–T12) for rules text and log wording. */ + template?: string; } type Subtypes = readonly (readonly [string, RegExp])[]; @@ -67,7 +70,23 @@ export function subtypeFor(type: CardType, profile: Pick)[subtype ?? ''] ?? 'T7'; + case 'Institution': return subtype === 'organisation' ? 'T8' : subtype === 'work' ? 'T9' : 'T10'; + case 'Doctrine': return subtype === 'pathology' ? 'T12' : 'T11'; + } +} + export function effectsFor(type: CardType, subtype: string | null, cost: number): EffectSpec[] { + const template = templateFor(type, subtype); + return baseEffects(type, subtype, cost).map(e => (template ? { ...e, template } : e)); +} + +function baseEffects(type: CardType, subtype: string | null, cost: number): EffectSpec[] { const k = Math.ceil(cost / 2); switch (type) { case 'Event': @@ -87,7 +106,7 @@ export function effectsFor(type: CardType, subtype: string | null, cost: number) case 'organisation': { const token = { name: 'Staff Member', power: 1, toughness: 1, portal: 'Neutral' as const }; return cost >= 4 - ? [{ trigger: 'startOfTurn', op: 'createToken', amount: 1, token, condition: { maxTokens: 2 } }] + ? [{ trigger: 'startOfTurn', op: 'createToken', amount: 1, token, condition: { maxTokens: 3 } }] : [{ trigger: 'onEnter', op: 'createToken', amount: 1, token }]; } case 'work': return [ diff --git a/shared/duel/text.ts b/shared/duel/text.ts index e1af298..49bc556 100644 --- a/shared/duel/text.ts +++ b/shared/duel/text.ts @@ -41,7 +41,7 @@ function staticText(e: EffectSpec): string { if (c.connected) who = 'Figures you control that are Connected to this'; if (c.samePortal) who = 'Other Figures you control of its Portal'; if (e.grant?.length && !e.power && !e.toughness) { - return `${who} have ${keywordsAsText(e.grant)}${c.whileAttacking ? ' while attacking' : ''}.`; + return `${who} have ${keywordsAsText(e.grant)}.`; } return `${who} get ${pt(e.power, e.toughness)}.`; } @@ -90,7 +90,7 @@ export function effectText(effects: readonly EffectSpec[]): string[] { case 'onDestroyed': lines.push(`When this is destroyed, ${actionText(e)}.`); break; case 'startOfTurn': { const max = e.condition?.maxTokens; - const cond = max !== undefined ? `, if you control fewer than ${max + 1} tokens` : ''; + const cond = max !== undefined ? `, if you control fewer than ${max} tokens` : ''; lines.push(`At the start of your turn${cond}, ${actionText(e)}.`); break; } From 9943de3b538705f3a469f6fb37b699e911800697 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:02:50 -0500 Subject: [PATCH 13/25] [ownership] collectionRouter: optional injected duelCard hook (#57) Attaches duel: DuelCard to collection cards when the server has a frozen profile (requested by ui-duel); omitted while pending, never fetches. Co-Authored-By: Claude Opus 5.5 --- server/game/collection.ts | 25 ++++++++++++++++++++++--- tests/ownership-deck.test.ts | 16 ++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/server/game/collection.ts b/server/game/collection.ts index 74044b2..e000c91 100644 --- a/server/game/collection.ts +++ b/server/game/collection.ts @@ -24,7 +24,8 @@ export type CollectionResponse = { needed: number; /** playable >= deckSize. */ eligible: boolean; - cards: ChainCard[]; + /** `duel` is present when the server has a frozen profile for the card (see collectionRouter's `duelCard`). */ + cards: (ChainCard & { duel?: unknown })[]; }; export function collectionResponse(deps: Pick, sub: string, @@ -37,7 +38,16 @@ export function collectionResponse(deps: Pick= r.deckSize, cards }; } -export function collectionRouter(deps: OwnershipDeps & { rules?: Partial }): Router { +export type CollectionRouterDeps = OwnershipDeps & { + rules?: Partial; + /** + * Optional: the same chain card → duel card function the PvP host uses, so the browser shows and + * plays exactly what PvP would. Return undefined while a card's profile is pending; it must not fetch. + */ + duelCard?: (card: ChainCard) => unknown; +}; + +export function collectionRouter(deps: CollectionRouterDeps): Router { const router = Router(); router.get('/', async (req: Request, res: Response) => { res.setHeader('Cache-Control', 'no-store'); @@ -46,7 +56,16 @@ export function collectionRouter(deps: OwnershipDeps & { rules?: Partial { + let duel: unknown; + try { duel = toDuel(c); } catch { duel = undefined; } + return duel === undefined ? c : { ...c, duel }; + }); + } + res.json(body); } catch (e) { const err = e as Error & { status?: number }; const status = e instanceof DeckError ? err.status! : err.status === 503 ? 503 : 500; diff --git a/tests/ownership-deck.test.ts b/tests/ownership-deck.test.ts index 309801c..073525e 100644 --- a/tests/ownership-deck.test.ts +++ b/tests/ownership-deck.test.ts @@ -273,3 +273,19 @@ test('GET /api/game/collection requires a verified eom.dev token (local loopback assert.equal((await res.json()).owned, 0); } finally { await close(); } }); + +test('GET /api/game/collection attaches the injected duel card when one is ready, and omits it otherwise', async () => { + const { ledger, deps } = fixture(); + mintMany(ledger, ALICE, 3); + const duelCard = (c: { pageId: number }) => { + if (c.pageId === 2) return undefined; // profile pending + if (c.pageId === 3) throw new Error('boom'); // never breaks the collection + return { kind: 'Figure', pageId: c.pageId }; + }; + const { base, close } = await serve(collectionRouter({ ...deps, duelCard })); + try { + const body = await (await fetch(base, { headers: { authorization: 'Bearer good.token.alice' } })).json(); + assert.deepEqual(body.cards.map((c: { duel?: unknown }) => c.duel), [{ kind: 'Figure', pageId: 1 }, undefined, undefined]); + assert.ok(!('duel' in body.cards[1])); + } finally { await close(); } +}); From 83a3afef1b027f65e98d635b21eef3634fa5621f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:04:39 -0500 Subject: [PATCH 14/25] story: tokens (never cited) and drawn matches, for duel-core's LogEvent shape Co-Authored-By: Claude Opus 5.5 --- shared/duel/story/log.ts | 5 ++++- shared/duel/story/recap.ts | 12 +++++++++--- shared/duel/story/templates.ts | 5 +++++ shared/duel/story/types.ts | 9 ++++++--- tests/duel-design-story.test.ts | 23 +++++++++++++++++++++++ 5 files changed, 47 insertions(+), 7 deletions(-) diff --git a/shared/duel/story/log.ts b/shared/duel/story/log.ts index 45d5c52..07e65f8 100644 --- a/shared/duel/story/log.ts +++ b/shared/duel/story/log.ts @@ -47,11 +47,12 @@ export class Narrator { player(seat: Seat): string { return this.record.players[seat].name; } - /** Assigns a reference number without mentioning the card (e.g. for the References list). */ + /** Assigns a reference number without mentioning the card (e.g. for the References list). Tokens get none (0). */ cite(id: string): number { let n = this.refByCard.get(id); if (n === undefined) { const c = this.card(id); + if (c.token || c.revisionId === undefined) return 0; n = this.references.length + 1; this.refByCard.set(id, n); this.references.push({ @@ -66,6 +67,7 @@ export class Narrator { /** A card's name for a sentence: italic, with its description on first mention. */ mention(id: string): string { const c = this.card(id); + if (c.token || c.revisionId === undefined) return c.title; const first = !this.refByCard.has(id); const n = this.cite(id); if (!first) return `*${c.title}*`; @@ -157,6 +159,7 @@ export function renderEvent(nar: Narrator, ev: StoryEvent, index: number, viewer case 'rivalry': return nar.sentence('rivalry', index, { a: M(ev.a), b: M(ev.b), reason: () => ev.reason }); case 'gameOver': { + if (ev.winner === null) return nar.sentence('gameOverDraw', index, { turn: N(ev.turn) }); const key = ({ life: 'gameOverLife', library: 'gameOverLibrary', concede: 'gameOverConcede', timeout: 'gameOverTimeout', turnCap: 'gameOverTurnCap' } as const)[ev.reason]; return nar.sentence(key, index, { winner: P(ev.winner), loser: P(other(ev.winner)), turn: N(ev.turn) }); } diff --git a/shared/duel/story/recap.ts b/shared/duel/story/recap.ts index 2a0b6f0..21ec228 100644 --- a/shared/duel/story/recap.ts +++ b/shared/duel/story/recap.ts @@ -50,7 +50,9 @@ export function longDate(iso: string): string { interface Played { id: string; seat: Seat; order: number } interface Facts { + /** For a draw: seat 0, with `draw` set. */ winner: Seat; + draw: boolean; loser: Seat; reason: GameOverReason; turns: number; @@ -72,7 +74,8 @@ function facts(record: MatchRecord): Facts { if (e.kind === 'adopt') played.push({ id: e.doctrine, seat: e.seat, order: i }); if (e.kind === 'destroyed') destroyed.push(e.card); }); - return { winner: over.winner, loser: over.winner === 0 ? 1 : 0, reason: over.reason, turns: over.turn, life, played, destroyed }; + const winner: Seat = over.winner ?? 0; + return { winner, draw: over.winner === null, loser: winner === 0 ? 1 : 0, reason: over.reason, turns: over.turn, life, played, destroyed }; } /** Highest cost wins; ties go to the card played first. */ @@ -104,6 +107,7 @@ export function battleTitle(record: MatchRecord, f: Facts = facts(record)): stri function resultText(record: MatchRecord, f: Facts): string { const w = record.players[f.winner].name; + if (f.draw) return 'Inconclusive'; switch (f.reason) { case 'concede': case 'timeout': return `${w} victory by withdrawal`; case 'library': return `${w} victory by attrition`; @@ -138,6 +142,7 @@ function sub(t: string, v: Record): string { /** The result as a phrase for the lead: "a Pyrrhic victory for bob". */ function resultPhrase(record: MatchRecord, f: Facts): string { const w = record.players[f.winner].name; + if (f.draw) return 'a draw'; switch (f.reason) { case 'concede': case 'timeout': return `a victory for ${w} by withdrawal`; case 'library': return `a victory for ${w} by attrition`; @@ -216,8 +221,9 @@ export function recap(record: MatchRecord): RecapDoc { if (end) course.push(end.text); // Aftermath. - const aftermath = [ - `${record.players[f.winner].name} ended the engagement with ${f.life[f.winner]} Notability; ${record.players[f.loser].name} ended with ${f.life[f.loser]}.`, + const aftermath = [f.draw + ? `Both ${a} and ${b} ended the engagement with ${f.life[0]} Notability.` + : `${record.players[f.winner].name} ended the engagement with ${f.life[f.winner]} Notability; ${record.players[f.loser].name} ended with ${f.life[f.loser]}.`, ]; if (record.ratingChange) { const fmt = (n: number) => (n >= 0 ? `+${n}` : `${n}`); diff --git a/shared/duel/story/templates.ts b/shared/duel/story/templates.ts index 312ecca..657d29a 100644 --- a/shared/duel/story/templates.ts +++ b/shared/duel/story/templates.ts @@ -91,6 +91,11 @@ export const LOG_TEMPLATES = { '{loser} was reduced to 0 Notability. {winner} won.', '{winner} won on turn {turn}.', ], + gameOverDraw: [ + 'Both sides were reduced to 0 Notability. The engagement ended in a draw.', + 'The engagement ended in a draw on turn {turn}.', + 'Neither side retained any Notability. No winner was recorded.', + ], gameOverLibrary: [ '{loser} could not draw a card and lost.', '{loser} ran out of cards. {winner} won.', diff --git a/shared/duel/story/types.ts b/shared/duel/story/types.ts index 7e5625c..df8bab4 100644 --- a/shared/duel/story/types.ts +++ b/shared/duel/story/types.ts @@ -19,8 +19,10 @@ export interface StoryCard { cost: number; /** Portal (faction): Arts, Earth, History, Science, Society or Neutral. */ portal?: string; - /** The article revision the card was minted from (on-chain). */ - revisionId: number; + /** The article revision the card was minted from (on-chain). Absent for tokens: they are never cited. */ + revisionId?: number; + /** Tokens (Elected Member, Staff Member): generic, not articles, never cited or glossed. */ + token?: boolean; /** On-chain token id of the mint, if known. */ tokenId?: string; /** Seat that owns the card in this match. */ @@ -47,7 +49,8 @@ export type StoryEvent = | { kind: 'discard'; seat: Seat; card: string } | { kind: 'connected'; seat: Seat; a: string; b: string; reason: string } | { kind: 'rivalry'; a: string; b: string; reason: string } - | { kind: 'gameOver'; winner: Seat; reason: GameOverReason; turn: number }; + /** winner null = draw (both players reached 0 at once). */ + | { kind: 'gameOver'; winner: Seat | null; reason: GameOverReason; turn: number }; export interface StoryPlayer { /** Display name of the seat (account display name or "Bot (Normal)"). */ diff --git a/tests/duel-design-story.test.ts b/tests/duel-design-story.test.ts index 21dea81..779683a 100644 --- a/tests/duel-design-story.test.ts +++ b/tests/duel-design-story.test.ts @@ -216,3 +216,26 @@ test('golden: full log and recap prose match tests/duel-design-story.golden.json const r = recap(record); assert.deepEqual({ log: logParagraphs(renderLog(record).lines), lead: r.lead, sections: r.sections }, golden); }); + +test('tokens are named plainly and never cited; draws are recorded as inconclusive', () => { + const withToken: MatchRecord = { + ...record, + cards: { ...cards, 't:1': { id: 't:1', title: 'Elected Member', type: 'Figure', cost: 0, portal: 'Society', owner: 1, token: true } }, + events: [ + T(1), { kind: 'cast', seat: 1, card: 'b1' }, + { kind: 'tokenCreated', seat: 1, source: 'b1', token: 'Elected Member', count: 1 }, + T(2), { kind: 'attack', seat: 1, card: 't:1', power: 1, toughness: 1 }, + { kind: 'playerDamage', seat: 0, source: 't:1', amount: 20, life: 0 }, + { kind: 'playerDamage', seat: 1, amount: 20, life: 0 }, + { kind: 'gameOver', winner: null, reason: 'life', turn: 2 }, + ], + }; + const { lines, references } = renderLog(withToken); + assert.ok(lines.some(l => /Elected Member \(1\/1\)/.test(l.text) && !/\*Elected Member\*/.test(l.text))); + assert.deepEqual(references.map(r => r.title), ['1954 Gold Coast general election']); + assert.match(lines[lines.length - 1].text, /draw|No winner/); + const r = recap(withToken); + assert.equal(r.infobox.result, 'Inconclusive'); + assert.match(r.lead, /ended in a draw\./); + assert.ok(r.references.every(x => x.revisionId !== undefined)); +}); From 79041990edbd58d80e59961c3f41851f4fd8dc95 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:10:16 -0500 Subject: [PATCH 15/25] duel-core: ConnectKeys qid/cites for claim-based Linked; seed secrecy rule Co-Authored-By: Claude Opus 5.5 --- docs/game/DUEL_API.md | 3 ++- shared/duel/types.ts | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/game/DUEL_API.md b/docs/game/DUEL_API.md index 79c6d99..511c5eb 100644 --- a/docs/game/DUEL_API.md +++ b/docs/game/DUEL_API.md @@ -59,7 +59,7 @@ Built by duel-cards (`derive()`), frozen by the host at match start. Shape agree - **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`), 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`. +- **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` (null by default): after that many total turns, higher Notability wins, then higher total power in play, then the second player. @@ -77,6 +77,7 @@ Declarations are **monotonic** (no un-declare), so every turn has a bounded numb ## 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. diff --git a/shared/duel/types.ts b/shared/duel/types.ts index a2d7e62..96e4742 100644 --- a/shared/duel/types.ts +++ b/shared/duel/types.ts @@ -39,6 +39,9 @@ export interface ConnectKeys { 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. */ From 39ffe409cbb031c05333c0ea7ccb653264cb557b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:16:56 -0500 Subject: [PATCH 16/25] story: lifeGain event, authoritative gameOver.life, document story seed (night-review #69 notes) Co-Authored-By: Claude Opus 5.5 --- shared/duel/story/log.ts | 2 ++ shared/duel/story/recap.ts | 3 ++- shared/duel/story/templates.ts | 5 +++++ shared/duel/story/types.ts | 11 +++++++++-- tests/duel-design-story.test.ts | 15 +++++++++++++++ 5 files changed, 33 insertions(+), 3 deletions(-) diff --git a/shared/duel/story/log.ts b/shared/duel/story/log.ts index 07e65f8..6b18022 100644 --- a/shared/duel/story/log.ts +++ b/shared/duel/story/log.ts @@ -137,6 +137,8 @@ export function renderEvent(nar: Narrator, ev: StoryEvent, index: number, viewer if (ev.source) v.source = M(ev.source); return nar.sentence('playerDamage', index, v, opts.preferSource && ev.source ? ['source'] : []); } + case 'lifeGain': + return nar.sentence('lifeGain', index, { player: P(ev.seat), source: M(ev.source), n: N(ev.amount), life: N(ev.life) }); case 'effectDamage': return nar.sentence('effectDamage', index, { source: M(ev.source), target: M(ev.target), n: N(ev.amount) }); case 'destroyed': diff --git a/shared/duel/story/recap.ts b/shared/duel/story/recap.ts index 21ec228..721db36 100644 --- a/shared/duel/story/recap.ts +++ b/shared/duel/story/recap.ts @@ -69,11 +69,12 @@ function facts(record: MatchRecord): Facts { const played: Played[] = []; const destroyed: string[] = []; record.events.forEach((e, i) => { - if (e.kind === 'playerDamage') life[e.seat] = Math.max(0, e.life); + if (e.kind === 'playerDamage' || e.kind === 'lifeGain') life[e.seat] = Math.max(0, e.life); if (e.kind === 'deploy' || e.kind === 'cast') played.push({ id: e.card, seat: e.seat, order: i }); if (e.kind === 'adopt') played.push({ id: e.doctrine, seat: e.seat, order: i }); if (e.kind === 'destroyed') destroyed.push(e.card); }); + if (over.life) { life[0] = Math.max(0, over.life[0]); life[1] = Math.max(0, over.life[1]); } const winner: Seat = over.winner ?? 0; return { winner, draw: over.winner === null, loser: winner === 0 ? 1 : 0, reason: over.reason, turns: over.turn, life, played, destroyed }; } diff --git a/shared/duel/story/templates.ts b/shared/duel/story/templates.ts index 657d29a..b63b98c 100644 --- a/shared/duel/story/templates.ts +++ b/shared/duel/story/templates.ts @@ -40,6 +40,11 @@ export const LOG_TEMPLATES = { '{source} dealt {n} damage to {player}, leaving {life} Notability.', "{player}'s Notability fell to {life}.", ], + lifeGain: [ + '{player} gained {n} Notability from {source} ({life} total).', + '{source} restored {n} Notability to {player}.', + "{player}'s Notability rose to {life} ({source}).", + ], effectDamage: [ '{source} dealt {n} damage to {target}.', '{target} took {n} damage from {source}.', diff --git a/shared/duel/story/types.ts b/shared/duel/story/types.ts index df8bab4..a740207 100644 --- a/shared/duel/story/types.ts +++ b/shared/duel/story/types.ts @@ -40,6 +40,8 @@ export type StoryEvent = | { kind: 'block'; seat: Seat; blocker: string; attacker: string; power: number; toughness: number } /** `seat` is the player who lost Notability; `life` is what remains. */ | { kind: 'playerDamage'; seat: Seat; source?: string; amount: number; life: number } + /** `life` is the new total. */ + | { kind: 'lifeGain'; seat: Seat; source: string; amount: number; life: number } | { kind: 'effectDamage'; source: string; target: string; amount: number } | { kind: 'destroyed'; card: string } | { kind: 'tokenCreated'; seat: Seat; source: string; token: string; count: number } @@ -50,7 +52,8 @@ export type StoryEvent = | { kind: 'connected'; seat: Seat; a: string; b: string; reason: string } | { kind: 'rivalry'; a: string; b: string; reason: string } /** winner null = draw (both players reached 0 at once). */ - | { kind: 'gameOver'; winner: Seat | null; reason: GameOverReason; turn: number }; + /** `life`: final Notability per seat, authoritative when present (duel-core carries it). */ + | { kind: 'gameOver'; winner: Seat | null; reason: GameOverReason; turn: number; life?: [number, number] }; export interface StoryPlayer { /** Display name of the seat (account display name or "Bot (Normal)"). */ @@ -59,7 +62,11 @@ export interface StoryPlayer { export interface MatchRecord { matchId: string; - /** Match seed (the same one the engine used). Drives template variants. */ + /** + * Story seed: drives template variants only. NOT the engine seed: a client rendering + * logFor text must never learn the engine seed (it would reveal library order). The host + * derives it, e.g. sha256(engineSeed + ':story'). Recaps after the match may use either. + */ seed: number | string; /** Match date, ISO `YYYY-MM-DD`. No clock is read by the story code. */ date: string; diff --git a/tests/duel-design-story.test.ts b/tests/duel-design-story.test.ts index 779683a..6d7cdb6 100644 --- a/tests/duel-design-story.test.ts +++ b/tests/duel-design-story.test.ts @@ -239,3 +239,18 @@ test('tokens are named plainly and never cited; draws are recorded as inconclusi assert.match(r.lead, /ended in a draw\./); assert.ok(r.references.every(x => x.revisionId !== undefined)); }); + +test('final Notability: lifeGain is tracked, and gameOver.life wins when present', () => { + const ev: StoryEvent[] = [ + T(1), { kind: 'deploy', seat: 0, card: 'a2' }, + { kind: 'playerDamage', seat: 0, amount: 18, life: 2 }, + { kind: 'lifeGain', seat: 0, source: 'a2', amount: 10, life: 12 }, + { kind: 'playerDamage', seat: 1, amount: 20, life: 0 }, + { kind: 'gameOver', winner: 0, reason: 'life', turn: 1 }, + ]; + const r = recap({ ...record, events: ev }); + assert.equal(r.infobox.result, 'Decisive alice victory'); // 12 vs 0, not Pyrrhic at 2 + assert.ok(renderLog({ ...record, events: ev }).lines.some(l => /Notability/.test(l.text) && /12/.test(l.text))); + const withFinal = recap({ ...record, events: [...ev.slice(0, -1), { kind: 'gameOver', winner: 0, reason: 'life', turn: 1, life: [3, 0] }] }); + assert.equal(withFinal.infobox.result, 'Pyrrhic alice victory'); +}); From 2ad4d022aa83a069b49a421e6a35f5358af0331f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:20:21 -0500 Subject: [PATCH 17/25] docs: note the deliberate 1 req/s REST rate (review on #73) Co-Authored-By: Claude Opus 5.5 --- docs/night2/WIKIMEDIA.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/night2/WIKIMEDIA.md b/docs/night2/WIKIMEDIA.md index 241f24c..3979092 100644 --- a/docs/night2/WIKIMEDIA.md +++ b/docs/night2/WIKIMEDIA.md @@ -18,6 +18,10 @@ Every server-side Wikimedia request goes through one process-wide `WikimediaClie | Disk cache | `$WIKIDECK_DATA_DIR/wikimedia-cache.sqlite`: ETag / Last-Modified, `If-None-Match`, stale-while-revalidate on the background lane, stale copy served on refusal | | User-Agent | `WikiDeck/ (+https://gitea.eom.dev/WikiDeck/wikideck; ) node/` | +The rate is deliberately 1 req/s for **every** host, including the `wikimedia.org` REST (pageviews) host. +The engineer review suggested 5 req/s there; we are stricter on purpose after the Night 1 rate limiting, because the +budget is per egress IP. Raise it only with a reason and a per-host setting. + Cache lifetimes: article metadata 24 h, monthly pageviews 7 days (the URL names six closed months, which do not change). Random articles and all mint reads are never cached. From adc78409fea011f2319979a81a77a9660b2cf808 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:06:38 -0500 Subject: [PATCH 18/25] host-pvp: multi-engine host, owned-deck seats, invites, quick match, Elo, ?v= polling (#56) - Mode schema wikideck.mode/2: required `engine` (editwar | duel); Night 1 wikideck.mode/1 documents are rejected with a clear message. Deck policies: constructed (owned NFT token ids, minConfirmations), starter (Edit War only), draft with source preview (Edit War only) or collections. limits.rated and limits.accountsOnly. - ModeHost runs every engine it is given, chosen per mode. Duel modes refuse loaner policies at startup (BRIEF decision 1). - Seats: eom.dev account via Dex ID token (body or JWT bearer on seat-creating routes), player id sha256('acct:'+iss+'\n'+sub); guests only in Edit War. - Constructed decks resolved through an injected OwnershipPort (#57), cards built by the engine's fromChain; creator's deck re-resolved at join. - Private lobbies + invite codes (GET /invites/:code, POST /invites/:code/join), quick match (POST /modes/:id/quick), lobby state version with 204 on ?v=. - Elo (1200, K 24) per mode for rated account-vs-account matches, recomputed from matches.jsonl; records carry engine, rated, tokens. /modes/:id/ladder. Co-Authored-By: Claude Opus 5.5 --- docs/game/HOSTING.md | 25 ++- server/game/engine-port.ts | 28 +++ server/game/host.ts | 334 +++++++++++++++++++++++++------- server/game/index.ts | 14 +- server/game/modes/classic.json | 22 ++- server/game/modes/draft.json | 4 +- server/game/modes/trending.json | 3 +- server/game/router.ts | 33 +++- server/game/store.ts | 42 +++- shared/game/modes.ts | 53 ++++- tests/host-pvp-host.test.ts | 328 +++++++++++++++++++++++++++++++ tests/modes-api.test.ts | 20 +- tests/modes-host.test.ts | 28 +-- tests/modes-schema.test.ts | 2 +- 14 files changed, 805 insertions(+), 131 deletions(-) create mode 100644 tests/host-pvp-host.test.ts diff --git a/docs/game/HOSTING.md b/docs/game/HOSTING.md index d736c33..8c2713b 100644 --- a/docs/game/HOSTING.md +++ b/docs/game/HOSTING.md @@ -18,12 +18,13 @@ A mode is a JSON document, at most 8 KiB: ```json { - "schema": "wikideck.mode/1", + "schema": "wikideck.mode/2", "id": "trending", "version": 1, "name": "Trending", "description": "Live Wikipedia pageview trends power cards up or down.", "tags": ["live-data"], + "engine": "editwar", "rules": { "trendUp": 25, "trendDown": -25 }, "cards": { "preset": "trending", "percentPerPoint": 25, "maxBonus": 3, "penalise": true }, "decks": { "kind": "starter" }, @@ -33,12 +34,14 @@ A mode is a JSON document, at most 8 KiB: | Field | Meaning | |---|---| +| `schema` | `wikideck.mode/2`. Night 1 documents (`wikideck.mode/1`) are rejected with a message saying what to change. | +| `engine` | Required: `editwar` (the Night 1 simultaneous-reveal game, `shared/game`) or `duel` (the Night 2 Magic-style duel, `shared/duel`). Duel modes only allow `constructed` and `draft` with `source: "collections"`: every card is one the players own. | | `id`, `version` | Lowercase slug and a version integer. Bump `version` whenever the rules change, so old match records and leaderboards stay attributable (`#@`). | | `name`, `description`, `tags` | Plain text only: no control characters or `<` `>`. | | `rules` | **Overrides** on top of the engine's `DEFAULT_RULESET` (see `docs/game/ENGINE_API.md`). Objects merge one level deep; arrays and numbers replace. The merged result then goes through the engine's strict `parseRuleset`, so the engine alone decides what's legal (bounded turns, Topics, deck sizes, known keywords and portals only; see DESIGN.md §9 for the keys). | | `cards` | A card-mapping **preset** from a fixed list. `standard` leaves cards as dealt. `live` freezes each card's live trend arrow (DESIGN §1.6, using the ruleset's `trendUp`/`trendDown`) at match start. `trending` does the same and also adds a bounded power bonus from the live pageview trend. The mode only picks a preset and tunes its bounded numbers. | -| `decks` | `starter` (everyone gets a seeded starter deck), `draft` (snake draft from a host-seeded pool of preview cards) or `constructed` (bring your own; see "Not yet" below). | -| `limits` | Concurrency and lobby expiry for this mode on this host. `turnSeconds` only applies to engines without their own turn timer; with tonight's engine, the ruleset's `turnSeconds` (plus 5 s network grace) is the timer. | +| `decks` | `constructed` (each player submits exactly `deckSize` NFT token ids they own; the host verifies ownership and confirmations on the chain, `minConfirmations` default 1, and builds every card from its block), `starter` (Edit War only: a seeded starter deck) or `draft` (snake draft; `source: "preview"` uses preview cards, Edit War only; `source: "collections"` pools both players' owned cards for that match only, and both must own at least `deckSize`). | +| `limits` | Concurrency and lobby expiry for this mode on this host. `rated: true` moves Elo (start 1200, K 24) when both seats are eom.dev accounts; `accountsOnly: true` refuses guest seats (owned-card modes always do). `turnSeconds` only applies to engines without their own turn timer; with tonight's engine, the ruleset's `turnSeconds` (plus 5 s network grace) is the timer. | The schema is strict: unknown fields are rejected, as are prototype keys (`__proto__`, `constructor`, `prototype`) anywhere in the document, nesting deeper than two @@ -46,6 +49,15 @@ levels inside `rules`, more than 48 rule keys, and oversized strings and arrays. **never** evaluates, imports or runs anything another peer sends. Nothing in a mode can name a file, a URL, a script or a function. +### Seats, invites, quick match and polling (Night 2) + +- **Seats:** `POST /modes/:id/lobbies`, `POST /lobbies/:id/join` and `POST /modes/:id/quick` take `{idToken, deck?, private?}` for an eom.dev account (the Dex ID token may also be sent as `Authorization: Bearer `), or `{name, secret}` for a guest in Edit War modes. The reply is `{lobbyId, seat, token, invite, playerId}`; `token` is the seat bearer for every later call. Account player ids are `sha256("acct:" + iss + "\n" + sub)`. +- **Invites:** every lobby gets a 12-character `invite` code. `private: true` hides it from `/lobbies` and quick match. `GET /invites/:code` describes it and `POST /invites/:code/join` joins it (SPA link: `/play/invite/`). +- **Quick match:** `POST /modes/:id/quick` joins the oldest open public lobby someone else opened (`matched: true`), or opens one (`matched: false`) to poll. +- **Polling:** every lobby view has a `version`. `GET /lobbies/:id?v=` answers **204** while nothing changed. Poll; never hold requests open (the node caps concurrent `/api` requests). +- **Ladder:** `GET /modes/:id/ladder` (same as `/leaderboard`): entries carry `rating` (Elo, or null if unrated) plus W/L/D. +- **Records:** `GET /matches/:id` has the seed, rules, both decks (as the engine cards), every action, `engine`, `rated`, and for constructed modes `tokens` (the NFT ids each seat played), so the recap can replay the match. + ## 2. Running your own modes Configure modes with environment variables on your node: @@ -255,10 +267,9 @@ be pinned in consensus. ## Not yet -- `constructed` decks of **owned NFTs**: the policy exists, but tonight the host deals - starter decks for it. Playing with your own cards needs a wallet-signed ownership proof - for the lobby (and then the engine's `cardFromStats`). That's a follow-up once accounts and - wallet linking (#7) settle. +- `constructed` decks of **owned NFTs** are verified on the hosting node only, against its + own account store (Night 2). Playing them on a *peer* needs a wallet-signed deck claim, + because accounts are per node; that's a follow-up. - `trending` never calls Wikipedia when a match starts. The node warms a cache-only trend store in the background, one page every 20 s (configurable, never faster than 15 s), through its existing enrichment cache (6 h TTL), starting with the preview-card pages. A card whose page isn't warm yet gets no bonus. This diff --git a/server/game/engine-port.ts b/server/game/engine-port.ts index 74b50b7..8d0cd53 100644 --- a/server/game/engine-port.ts +++ b/server/game/engine-port.ts @@ -40,4 +40,32 @@ export interface EnginePort