Compare commits

..
Author SHA1 Message Date
claudeandClaude Opus 5.5 2f494e399c deploy/night: autodeploy follows night/2026-11-17 by default
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:35:00 -05:00
claudeandClaude Opus 5.5 2af2e7f06f Night 2 handbook: night-lead runs on tower-plus
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:08:17 -05:00
claudeandClaude Opus 5.5 57dc1e60aa Night 2 handbook: ui-pvp runs on inspiron-3670
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:07:59 -05:00
claudeandClaude Opus 5.5 dbf385d217 Night 2: data analyst scripts behind reviews/data.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:07:31 -05:00
claudeandClaude Opus 5.5 e34b09d06d Night 2: plan, design brief, handbook and plan reviews
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 13:05:42 -05:00
claudeanderic 4f7a8a7c74 Night 1: Edit War card game, eom.dev accounts, peer-hosted modes, Android and iOS apps (#22)
Overnight build by 17 Claude agents (2026-11-16 22:45 → 01:30 EST), coordinated in [claude/wikideck milestone 63](https://gitea.eom.dev/claude/wikideck/milestone/63). **For Eric's review. Do not merge without it.** The full write-up is in `docs/night/REPORT.md`.

**What's in it** (38 reviewed PRs, squash-merged into `night/2026-11-16`):
- **Edit War:**
  - a 3-lane, 6-turn card game built on what WikiDeck cards actually hold
  - a pure, deterministic, off-chain rules engine (`shared/game/`, with the API in `docs/game/ENGINE_API.md`); rules are data and v1.1 is the default
  - a mobile-first Play UI with a lobby, deck builder, four loaner starter decks, a match against the AI, results and a tutorial
  - a landing page (fixes #3)
- **Design and balance:** `docs/game/DESIGN.md`, `CARD_DATA.md` (236 sampled articles) and `BALANCE.md` (bot simulations). Starter pairings went from 23–77% on v1 to roughly even on v1.1.
- **eom.dev accounts:** Dex OIDC with PKCE, plus off-chain wallet linking, where the client builds the message it signs (`server/account/`, `src/auth/`).
- **Peer-hosted game modes:** modes are JSON data, never code. Node API at `/api/game/*`, with host credit and leaderboards. Three example modes (`shared/game/modes.ts`, `server/game/`, `docs/game/HOSTING.md`).
- **Mobile:** Capacitor 7 Android app (a debug APK played a full match against the AI in the emulator), and an iOS project waiting on Xcode (`docs/night/ANDROID.md`, `docs/night/IOS.md`).
- **Testnet tooling:** `deploy/night/` (LAN-only, 3 nodes) and an optional `WIKIDECK_USER_AGENT` (the default is unchanged).

**Not touched:** consensus and protocol (`server/chain.ts`, `shared/protocol.ts`, `server/testnet/{consensus,ledger,…}.ts`, `native/`), the live deployment and mainnet. Matches run off-chain and never move or burn NFTs.

**Checks:** the final integration gate passed in `node:24-alpine`: `npm test` 241/242 with 0 fail (1 skipped), and `npm run build` passes. The repo needs Node 24, because Node 20 fails 12 tests falsely.

**Decisions for Eric** (see REPORT.md, Known issues and Next steps):
1. whether the live node should set `WIKIDECK_USER_AGENT`
2. the Xcode licence, which you should accept yourself
3. #49 in the fork, a bot change held after the freeze
4. on-chain host rewards (proposal only, in HOSTING.md)

🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: WikiDeck/wikideck#22

Co-authored-by: Claude <claude@eom.dev>
2026-11-17 17:40:58 +00:00
53 changed files with 2126 additions and 119 deletions
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#1e1e2e</color>
<color name="colorPrimaryDark">#11111b</color>
<color name="colorAccent">#cba6f7</color>
<!-- Behind the status and navigation bars: matches the dark app header. -->
<color name="wikideckChrome">#11111b</color>
</resources>
@@ -13,6 +13,9 @@
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
<!-- Dark behind the status/navigation bars (edge-to-edge margins) to match the app chrome. -->
<item name="android:windowBackground">@color/wikideckChrome</item>
<item name="android:windowLightStatusBar">false</item>
</style>
+1 -1
View File
@@ -16,7 +16,7 @@ A 3-node **testnet-only** fixture on poweredge-r350. It is reachable on the LAN
- `compose.lan.yaml` also sets, per node:
- `WIKIDECK_USER_AGENT`, a Wikimedia-policy UA with a project URL (#19). Without it, Wikipedia returned 429 to our egress and templates failed.
- the game-mode env from #22: A = classic and trending, B = draft, C = all three.
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-16 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-17 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
- `testnet.sh` has `up`, `mine N [workers]`, `status` and `down`. Run it from the repo root on a checkout of the integration branch. `up` rebuilds the image from that checkout; the ledgers persist in the named volumes.
Never point this at mainnet or the live `wikideck` namespace.
+1 -1
View File
@@ -6,7 +6,7 @@
# because lobbies are in memory and a restart ends games in progress.
# Head detection uses the public Gitea API, which also works where SSH auth isn't available.
set -u
BRANCH=${BRANCH:-night/2026-11-16}
BRANCH=${BRANCH:-night/2026-11-17}
API=${API:-https://gitea.eom.dev/api/v1/repos/claude/wikideck}
INTERVAL=${INTERVAL:-180}
LOG=${LOG:-/tmp/wikideck-night-autodeploy.log}
+4 -2
View File
@@ -15,6 +15,8 @@ Owner: sim-balance (claude/wikideck#4). Harness: `shared/bots/`, `scripts/sim/`
## v1.1 re-run on the real engine hooks (00:31)
> **Seat figures are pre-#38.** Every first-player and seat number in this report was measured on an engine before #38, which removed `opponent.queuedCount` from `PlayerView`. The bots never read the queue split (`stateFromView` uses the total hand, and an invariance test covers it), so the effect should be nil. A re-run on the merged head is still the clean number, and it is open for v1.2.
**Engine:** `night/engine/v1-1` @ 4a0dbd0, with `RULESET_V1_1` (DESIGN #32): `viral {base 1, cap 3}`, `encyclopedic {sides 1}`, `rising.powerDelta -1`, `cultureKeyword: home`, `costThresholds [26,39,51,63,78]`. It is the same focused run as above: the §2.1 starters plus 4 owned decks (cost thresholds and Culture keyword per v1.1), 2,000 matches per ruleset.
| | v1 | **v1.1 (#32, exact)** | v1.1 + item 6 |
@@ -22,7 +24,7 @@ Owner: sim-balance (claude/wikideck#4). Harness: `shared/bots/`, `scripts/sim/`
| starter deck WR, overall (FG / Head / Pio / Star) | 65 / 40 / 57 / 54 | **52 / 52 / 52 / 53** ✅ | 50 / 56 / 50 / 52 |
| starter pairings, min–max | 23–77% | 39–61% (only FG–Head 61%, n = 51, is outside 45–55) | 42–58% |
| owned vs starters (FG / Head / Pio / Star) | 37 / 54 / 40 / 41 | 51 / 42 / 47 / 43 | 51 / 41 / 46 / 48 |
| first player | 53.4% | **51.2% [48.8–53.6]** ✅ | 51.0% [48.6–53.5] |
| first player (pre-#38) | 53.4% | **51.2% [48.8–53.6]** ✅ | 51.0% [48.6–53.5] |
| decided in the first third | 4.1% | 3.3% | 4.1% |
| greedy > maxpower, lookahead-lite > greedy | 62%, 60% | 63%, 65% | 51%, 70% |
@@ -110,7 +112,7 @@ Raw tables:
### TL;DR for the council (report v1, 00:25; see the v1.1 re-run above for the updated recommendation)
1. **Seat and initiative are fine:** 51.5% [49.6–53.5] for the turn-1 initiative holder (n = 2,421 symmetric games), and seat 0 51.2%. Draws are 0.4%. The tie-break (total power) decides 4.7% of games. *This full-field run started before the bot-side queue-count fix (PR #14); the effect is at most a 0.02 nudge to the heuristic. The focused starters run, after the fix, gives a borderline 53.4% [51.0–55.8] under v1 and **51.0% [48.6–53.4]** under the recommended v1.1. Initiative only matters through reveal order, and v1.1 removes most of the order-sensitive power.*
1. **Seat and initiative are fine (pre-#38):** 51.5% [49.6–53.5] for the turn-1 initiative holder (n = 2,421 symmetric games), and seat 0 51.2%. Draws are 0.4%. The tie-break (total power) decides 4.7% of games. *This full-field run started before the bot-side queue-count fix (PR #14); the effect is at most a 0.02 nudge to the heuristic. The focused starters run, after the fix, gives a borderline 53.4% [51.0–55.8] under v1 and **51.0% [48.6–53.4]** under the recommended v1.1. Initiative only matters through reveal order, and v1.1 removes most of the order-sensitive power.*
2. **Keyword values are lopsided, confirming the critic's figures within 0.2:**
| keyword | power per card |
+84 -26
View File
@@ -66,9 +66,15 @@ down. A `null` attention gives `pct_attention = null`.
### 1.2 Fame → Cost
`fame` = the integer mean (rounded half up) of the non-null percentiles.
`cost` = 1 + the number of thresholds in `costThresholds` (5 ascending values, default
`[15, 35, 55, 75, 90]`) that are ≤ `fame`. So cost runs 1–6.
The defaults aim at a pool cost spread of about 15/20/20/20/15/10 %. They are retuned from the
sample's fame distribution.
`[26, 39, 51, 63, 78]` in v1.1) that are ≤ `fame`. So cost runs 1–6.
**Thresholds are data, not guesses (v1.1).** `fame` is a *mean* of up to 3 percentiles, so it clusters
around 50 even though each percentile is uniform. The v1.0 values `[15, 35, 55, 75, 90]` treated fame as
uniform, so 82% of the pool landed on cost 2–4 (3/23/37/22/10/5 %). `costThresholds` is therefore set to
the fame values at the **15/35/55/75/90 % points of the reference sample** (the same `card-sample.json`
whose `percentiles` table §1.1 uses). That's the integer set that brings the sample's cost spread closest
to the target 15/20/20/20/15/10 %. The v1.1 defaults come from the 236-card sample (fame 8–98) and
give 13/20/22/20/15/10 %. Whenever council-data refreshes the sample, the percentile table and
`costThresholds` are regenerated together and ship as one change. Pinned loaners (§2.1) are unaffected.
### 1.3 Power
`power` = `powerByCost[cost]`, default `[_, 1, 2, 4, 6, 8, 10]` (cost 1 → 1 … cost 6 → 10). The
@@ -96,7 +102,9 @@ mono-faction deck gains no consistency edge (§10: no v1 keyword scales with fac
which means there is **no down arrow in v1**: 69% of cards trend negative, so a ▼ would mostly land as
a quiet penalty on famous owned cards; modes can turn it back on), otherwise 0. A `null` value gives 0. Trend also needs `live.dailyAverage ≥ trendMinDaily` (default
**20**), because percentages on tiny articles are noise; otherwise trend is 0. The host computes it **once at match start**, and it is frozen for
the match. It shows as an arrow (▲/▼), not a number. It adds to power in every Topic.
the match. It shows as an arrow (▲), not a number. It adds to power in every Topic. *Why no ▼ by default:* 69% of the sample has a
negative `trendPercent`, and only busy (mostly owned, famous) cards pass `trendMinDaily`, so a ▼ would quietly penalise collectors.
Modes may turn it back on with e.g. `trendDown: -25`.
### 1.7 Rarity
The hash-derived `rarity` (`shared/protocol.ts:38`) is **cosmetic in v1** (frame colour only). Mining luck must not
@@ -155,7 +163,7 @@ The engine does no I/O and only ever sees one version of each card.
These are the default `starterDecks`: four 12-card loaner decks.
- **Every deck has the same curve:** costs `1,1,2,2,3,3,3,4,4,5,5,6`. That's an average of 3.25, with 5 cards of cost 4 or more and 2 of cost 1.
- **Every deck has the same shape:** 6 cards from each of two factions, and 4 cards for each home stat. So every deck can play on-topic in every lane.
- **Loaner values are pinned.** council-data's percentile table and `starter-cards.json` don't exist yet, so a loaner carries
- **Loaner values are pinned.** Cost, home and faction are hand-set (not derived from `starter-cards.json`), so a loaner carries
`pinned: { cost, home, faction }`. For `check: 'loaner'` the engine takes these instead of §1.1–1.5.
Everything after them still applies: `powerByCost`, `onTopicBonus`, `vanillaBonus`, the §10.1 keyword choice and `keywordParams`.
A mode that changes those numbers changes loaners exactly as it changes owned cards.
@@ -168,10 +176,12 @@ These are the default `starterDecks`: four 12-card loaner decks.
The decks below pin their values on purpose, for two reasons. Famous, recognisable articles would all derive to cost 5–6.
And the random sample has no Space cards (CARD_DATA.md finding 6).
- **v1.1 note (factions):** CARD_DATA.md finding 6 shows the legacy `category()` split as Culture 53%, People 30%, Nature 9%,
History 5%, Science 3%, Space 0%. Owned decks will therefore be about 50% viral and 30% local. Viral is the weakest keyword, so a typical owned deck
History 5%, Science 3%, Space 0%. In v1, owned decks were therefore about 50% viral and 30% local. Viral was the weakest keyword, so a typical owned deck
may be *weaker* than the starter decks. That's the wrong way round for "NFTs give variety, not power". v1 ships as is.
For v1.1, sim-balance runs a **realistic owned deck** (12 cards drawn from `card-sample.json` with its real category mix)
against each starter. If it wins under 45%, viral gets buffed first (e.g. cap 3, or a minimum of +1). The P31-based factions council-data proposes (People, Places, Nature, Works & Culture,
against each starter. **v1.1 fix:** viral gets a base of +1, and Culture cards take a keyword by home stat (§10.1), so owned decks
now have all six keywords in the mix. **BALANCE.md v1.1:** starters 52–53% overall, and owned vs starters 42–51%
(weakest vs Headliners and Stargazers; v1.2 candidates: `nostalgic`/`translated` `powerDelta -1`, `local.amount 2`). The P31-based factions council-data proposes (People, Places, Nature, Works & Culture,
Structures, Events & Ideas) are the v2 fix, and would need the host to fetch P31 (it isn't in `PageEnrichment`).
Keywords follow from §10.1: cost 1 → vanilla, otherwise the faction keyword (shown in brackets).
@@ -208,7 +218,7 @@ Keywords follow from §10.1: cost 1 → vanilla, otherwise the faction keyword (
| 5 | Great Wall of China | History | reach |
| 6 | World War II | History | depth |
**C. Headliners: People (local) + Culture (viral)**
**C. Headliners: People (local) + Culture (by home stat: attention → viral, depth → encyclopedic, reach → translated)**
| Cost | Card | Faction | Home |
|---|---|---|---|
| 1 | Haiku | Culture | attention |
@@ -311,6 +321,8 @@ The match lasts `turns` turns (default **6**, hard cap). Each turn has these pha
- Each player queues an ordered list of plays `(handIndex, topic)`.
- Total cost must be ≤ their energy, and each Topic needs room on that player's side.
- Plays can be undone freely until **Commit**. Passing is an empty commit.
- **Hidden means nothing leaks.** While you plan, the opponent's hand count and energy don't change
visibly. Only the bare fact "opponent is ready" (`committed`) is shown. No queue count, no spent energy.
- The turn timer is `turnSeconds` (default **25**). On timeout, whatever is queued is committed.
4. **Reveal (interleaved)**
- Plays reveal **one at a time, alternating**: the initiative player's 1st, the other player's
@@ -360,13 +372,14 @@ the last turn's, and every "at scoring" Portal resolves **before** Topics are ju
| Line | Why it isn't dominant |
|---|---|
| All-famous (all max-stat) deck | It becomes an all-cost-5/6 deck with dead early turns. Cheap cards are more efficient **per energy**, expensive cards **per card**. Only 9 cards are seen per match (3 + 6 draws), so both matter. An all-cost-5/6 deck is **weak by design**: it has four dead turns (sim-balance interim: 0–15%). There is no hard deck rule in v1; the deck builder warns when a deck has fewer than 4 cards of cost ≤ 2, and every starter deck is curve-shaped (§2.1). **sim-balance target: a **top-heavy curve** (half the deck at cost 4 or more) vs curve ≥ 40%.** `energyByTurn [2..7]` is a v1.1 candidate. |
| All-cheap flood (cost 1–2) | Weak by design: only 9 slots and 9 cards seen. Critic's sim under these rules: swarm vs curve about 7–11%. Its home is Culture's wide-turn keyword (§10). |
| All one faction | No v1 keyword scales with faction count. `factionSynergyCap` is reserved for modes. Culture, the largest pool, has the weakest keyword (viral). |
| "Always play the highest-power card" | It ignores the on-topic bonus, lane capacity and the hidden Portals. Critic's sim: 18–21% against a smart bot (target < 55%). |
| All-famous (all max-stat) deck | It becomes an all-cost-5/6 deck with four dead early turns. Cheap cards are more efficient **per energy**, expensive cards **per card**, and only 9 cards are seen per match (3 + 6 draws). So a pure cost-5/6 deck is **weak by design**: **BALANCE.md v1: 15%**, and no lever (power curve, energy ramp) fixes it without breaking curve or swarm decks. There is no hard deck rule; the deck builder warns below 4 cards of cost ≤ 2, and every starter is curve-shaped (§2.1). **Target met:** a **top-heavy curve** (half the deck at cost 4 or more) wins **57%** (target ≥ 40%). `energyByTurn [2..7]` was rejected for v1.1: it lifts heavy decks but kills swarm (20%). |
| All-cheap flood (cost 1–2) | Weak by design: only 9 slots and 9 cards seen. **BALANCE.md v1: 2%** (critic's sim 7–11%). Every lever that revives it breaks curve decks (sweep in BALANCE.md). viral (base +1, v1.1) is its consolation, not its fix. |
| All one faction | No v1 keyword scales with faction count. `factionSynergyCap` is reserved for modes. Culture, the largest pool, splits over three keywords by home stat (§10.1), so it has no single keyword to stack. |
| Owning NFTs buys power (pay-to-win) | Power depends only on cost (§1.3), and cost follows a fixed curve. **BALANCE.md v1.1 re-run (real `RULESET_V1_1`):** each starter deck averages **52–53%** overall. A realistic owned deck from `card-sample.json` wins **42–51%** against the starters (n ≈ 55 per pairing, ±13 pp). So owning cards buys variety, not power. v1.2 levers if owned decks should be a little stronger: `local.amount 2`, and `nostalgic`/`translated` `powerDelta -1` (the two strongest keywords, about +1.65 net per card). |
| "Always play the highest-power card" | It ignores the on-topic bonus, lane capacity and the hidden Portals. **BALANCE.md v1:** the naive max-power line wins **40%** against greedy, and lookahead-lite beats greedy **60–70%**, so skill shows (target < 55%). Critic's sim: 18–21% against a smart bot. |
| Stall or pass | Passing leaves lanes to any 1-power card. Two passing players draw. |
| Mirror the AI | Hidden simultaneous commits: you only see the opponent's cards after you commit. |
| Seat or initiative | Planning is simultaneous and initiative strictly alternates (each seat has it for 3 of the 6 turns). Target: each seat wins 48–52%. |
| Seat or initiative | Planning is simultaneous and initiative strictly alternates (each seat has it for 3 of the 6 turns). **BALANCE.md v1.1 re-run (real `RULESET_V1_1`): first player 51.2% [48.8–53.6]** (target 48–52%; v1 was 53.4%). |
| Forged or shopped stats | They only raise cost (§1.3), the host check falls back to live stats (§1.10), and trend is capped at ±1. |
| Inflated live pageviews | Worth at most +1, frozen at match start, and only counts for articles with ≥ 20 views a day. |
| Swinginess | No effect may change a lane by more than 6 power or move cards between lanes in v1 (a keyword-design rule for §10). |
@@ -379,7 +392,7 @@ The engine takes a `RulesConfig` object. Peer-hosted modes override it (§11). D
```json
{
"version": "1.0",
"version": "1.1",
"deckSize": 12, "maxCopiesPerPage": 2, "maxLoaners": 12,
"openingHand": 3, "handLimit": 7, "mulligan": false,
"turns": 6, "turnSeconds": 25, "afkTurns": 2,
@@ -388,10 +401,10 @@ The engine takes a `RulesConfig` object. Peer-hosted modes override it (§11). D
"topicPool": [ /* inline Topic objects {id, name, stat, portal}; default = the 9 in §10.3 */ ],
"keywordParams": { /* per-keyword numbers, keyed by keyword id (§10) */ },
"portalParams": { /* per-Portal numbers, keyed by Topic id (§10.3) */ },
"costThresholds": [15, 35, 55, 75, 90],
"costThresholds": [26, 39, 51, 63, 78],
"powerByCost": [0, 1, 2, 4, 6, 8, 10],
"onTopicBonus": [0, 1, 1, 2, 2, 3, 3], "vanillaBonus": 1,
"keywordsEnabled": ["viral","rising","local","encyclopedic","nostalgic","translated"], "ownedCards": true,
"keywordsEnabled": ["viral","rising","local","encyclopedic","nostalgic","translated"], "cultureKeyword": "home", "ownedCards": true,
"trendUp": 25, "trendDown": -200, "trendMinDaily": 20, "uncheckedCostCap": 4,
"factionSynergyCap": 3,
"verifyStats": true,
@@ -418,7 +431,12 @@ Topics carry only a **stat**, never a faction. Every keyword below that mentions
First rule that matches:
1. `cost == 1` → **no keyword** (vanilla). The card gets +`vanillaBonus` power (default **1**), so a cost-1 card is 2.
2. `"edition"` is in `keywordsEnabled` (off by default) and the deck holds another card with the same `pageId` → **edition**.
3. Otherwise → the card's **faction keyword** from 10.2, if it's in `keywordsEnabled`. If not, the card is vanilla, *without* `vanillaBonus`.
3. If the faction is **Culture** and `cultureKeyword` is `"home"` (v1.1 default) → the keyword for its **home stat**:
attention → **viral**, depth → **encyclopedic**, reach → **translated**. (`"faction"` gives v1 behaviour: every Culture card is viral.)
4. Otherwise → the card's **faction keyword** from 10.2.
In steps 3–4, if the chosen keyword isn't in `keywordsEnabled`, the card is vanilla, *without* `vanillaBonus`.
*Why step 3:* Culture is about half of all owned cards. Without it, owned decks are half viral and see only 2 of the 6 keywords.
Rarity plays no part here (it's cosmetic, §1.7). Keywords don't lower power, and v1 has no per-keyword power deltas.
If sim shows that a keyword is worth more than about 1 power on average, sim-balance sets `keywordParams.<id>.powerDelta` (default 0, range −3 to 0).
@@ -427,16 +445,16 @@ If sim shows that a keyword is worth more than about 1 power on average, sim-bal
| Faction | id (card word) | Trigger | Reminder text | Cap | Order-sensitive? |
|---|---|---|---|---|---|
| Culture | **viral** | On reveal | +1 power for each other card you revealed earlier this turn. | +2 | yes: your queue order |
| Culture | **viral** | On reveal | +1 power, plus +1 for each other card you revealed earlier this turn. | +3 | yes: your queue order |
| Nature | **rising** | End of turn | +1 power. | +2 total | no |
| People | **local** | Ongoing | +1 power while on-topic (the Topic's stat is its home stat). | +1 | no |
| Science | **encyclopedic** | On reveal | +2 power if there are no other cards here (either side). | +2 | **yes: interleaving** |
| Science | **encyclopedic** | On reveal | +2 power if you have no other cards here. | +2 | **yes: interleaving** |
| History | **nostalgic** | On reveal | +2 power if you are losing here. | +2 | **yes: interleaving** |
| Space | **translated** | On reveal | +1 power to your most recently revealed card in each *other* Topic. | +2 | yes |
Why this set: every keyword is one line and one trigger, and only adds power. The largest swing is +2 on one card,
so no lane moves by more than 2 from a keyword. Nothing scales with faction count, so a mono-Culture deck gets no
consistency edge (`factionSynergyCap` is unused in v1). Viral is Culture's weakest keyword, and it rewards wide turns.
so no lane moves by more than 3 from a keyword (viral at its cap). Nothing scales with faction count, so a mono-Culture deck gets no
consistency edge (`factionSynergyCap` is unused). Viral rewards wide turns, and Culture cards are spread over three keywords (§10.1 step 3).
Three keywords (encyclopedic, nostalgic, translated) react to the interleaved reveal (§5.4), so initiative and queue order matter.
Precise rules (for engine-b):
@@ -444,10 +462,12 @@ Precise rules (for engine-b):
including earlier reveals this turn). The bonuses it grants are permanent counters.
- **Ongoing** is a condition, recalculated whenever power is read.
- **End of turn** resolves in §5.5 order: the initiative player's cards first, then Topic 1→3, then reveal order.
- **viral:** counts the owner's cards revealed earlier in *this* turn's Reveal phase, in any Topic. Cards that went back to hand don't count.
- **viral:** gain = min(`base` + `amount` × N, `cap`), where N = the owner's cards revealed earlier in *this* turn's Reveal phase, in any Topic.
Cards that went back to hand don't count. v1.1: base 1, amount 1, cap 3 (v1 was base 0, cap 2).
- **rising:** stops after it has gained +2 in total.
- **local:** "on-topic" is exactly the §1.4/§6 condition. It's simply an extra +1 on top of `onTopicBonus`.
- **encyclopedic:** "no other cards here" means both sides of this Topic are empty, apart from this card, when it reveals.
- **encyclopedic:** with `sides: 1` (v1.1 default), "no other cards here" means **your** side of this Topic is empty, apart from this card,
when it reveals; the opponent's cards don't matter. `sides: 2` is v1 (both sides empty).
- **nostalgic:** "losing here" means the opponent's Topic power here is strictly greater than yours, counted just *before* this card is added.
The consensus tie-break doesn't count: a tie is not losing.
- **translated:** "most recently revealed" means the highest global reveal sequence number among your cards in that Topic. Topics where you have no card are skipped.
@@ -463,13 +483,18 @@ These are engine-b's existing implementations. The faction-based versions of `lo
**`keywordParams` defaults** (keyed by keyword id; modes may change them within the §11 ranges):
```json
{ "viral": {"amount": 1, "cap": 2, "powerDelta": 0}, "rising": {"amount": 1, "cap": 2, "powerDelta": 0},
"local": {"amount": 1, "powerDelta": 0}, "encyclopedic": {"amount": 2, "powerDelta": 0},
{ "viral": {"base": 1, "amount": 1, "cap": 3, "powerDelta": 0}, "rising": {"amount": 1, "cap": 2, "powerDelta": -1},
"local": {"amount": 1, "powerDelta": 0}, "encyclopedic": {"amount": 2, "sides": 1, "powerDelta": 0},
"nostalgic": {"amount": 2, "powerDelta": 0}, "translated": {"amount": 1, "powerDelta": 0},
"edition": {"amount": 2, "powerDelta": 0}, "obscure": {"powerDelta": 0}, "wildcard": {"powerDelta": 0} }
```
End-of-turn effects on the last turn resolve **before** scoring (§7).
**v1.2 candidates** (not in v1.1; decide on a larger run, per BALANCE.md's v1.1 re-run): the keyword values are still uneven:
translated +1.64 and nostalgic +1.69 per card vs local +0.69 (critic's target was ±0.3). The starter decks stay even only because each one
pairs a strong keyword with a weak one. The first levers are `nostalgic.powerDelta -1` and `translated.powerDelta -1`, plus `local.amount 2`
if owned decks stay under 45% against Headliners. Both are config only.
### 10.3 Portals (Topic modifiers) and the default Topic pool
Each Topic has `{ id, name, stat, portal | null }`. The default `topicPool` has 9 Topics, one plain and two with
Portals for each stat. A Portal applies from the moment its Topic is revealed (§3), except where it says otherwise.
@@ -529,7 +554,8 @@ A **mode** is data, published by a node operator and run by the match host:
| `trendUp` / `trendDown` | 0–200 / −200–0 |
| `factionSynergyCap` | 0–6 |
| `keywordsEnabled` | any subset of the 9 implemented ids (the 6 v1 defaults + edition, obscure, wildcard); a card whose keyword is disabled is vanilla, *without* `vanillaBonus` |
| `keywordParams`, `portalParams` | only the keys listed in §10 / §10.3; amounts and caps 0–6, `powerDelta` −3–0 |
| `keywordParams`, `portalParams` | only the keys listed in §10 / §10.3; amounts and caps 0–6, `viral.base` 0–3, `encyclopedic.sides` 1–2, `powerDelta` −3–0 |
| `cultureKeyword` | `"home"` or `"faction"` |
| `verifyStats` | the host may only turn this off for modes that use only loaners (`maxLoaners == deckSize` and owned cards banned) |
| `topicPool` | 3–20 Topics, Portal kinds only from 10.3 |
@@ -552,6 +578,9 @@ Example modes (good defaults for operators to publish):
## 12. Worked example match *(owner: council-designer-b)*
**Ruleset for this example: v1.0** (the golden test pins it): `cultureKeyword "faction"`, `viral {base 0, cap 2}`,
`encyclopedic {sides 2}`, `rising.powerDelta 0`; everything else as §9. *(The v1.1 numbers are in §12.1.)*
These are the §1–9 rules as of this PR:
- `powerByCost [0,1,2,4,6,8,10]`, `onTopicBonus [0,1,1,2,2,3,3]`, `vanillaBonus 1`
- `laneCapacity 3`, `energyCarryMax 1`, interleaved reveals, alternating initiative, `portalReveal [2,3,4]`
@@ -613,3 +642,32 @@ Final card values:
- after turn 5, T2 is a 9–9 tie with Bo leading by consensus
- Ana's carried energy is 1 at the start of turns 4, 5 and 6
- Bo's carried energy is 1 at the start of turn 3
### 12.1 The same match under the v1.1 ruleset
Same cards, Topics, hands and commit lists; ruleset = §9 defaults (v1.1: `viral {base 1, cap 3}`, `encyclopedic {sides 1}`,
`rising.powerDelta -1`, `cultureKeyword "home"`). The example's Culture cards (Jazz, Pop music, Mona Lisa) are attention-home, so they stay viral.
Energy and carry are unchanged.
What changes:
- **rising −1:** Coral reef is 1 base and ends at 1+1+2 = **4**; Fern is 3 base and ends at 3+2+1 = **6**.
- **viral base 1:** Jazz +2 (Mars earlier), Pop music +1 (base only), Mona Lisa +2 (Fern earlier).
- **nostalgic still fires** for Library (Ana is losing T1 8–13 just before it). **encyclopedic still doesn't** (Einstein is already on Ana's side of T2).
| After turn | T1 | T2 | T3 |
|---|---|---|---|
| 1 | 3–0 | 0–3 | 0–0 |
| 2 | 4–0 | 0–3 | 3–0 |
| 3 | 7–0 | 0–9 | 3–3 |
| 4 | 8–0 | 9–9 | 3–10 |
| 5 | 8–8: **Ana leads** (consensus: on-topic 2 vs 0) | 9–10 | 13–11 |
| 6, before scoring | 18–14 | 13–18 | 13–11 |
| **final** (Main Page +1 per card in T2) | **18–14** | **15–21** | **13–11** |
**Ana still wins 2–1.** The moments in v1.1:
- **Carry-over:** unchanged.
- **Consensus:** moves to **T1 after turn 5** (8–8). Ana has two on-topic depth cards there (Octopus, Coral reef) and Bo has only the off-topic Jupiter.
- **Interleaving:** unchanged in kind. If Ana had revealed Library before Fern, T1 would have been 8–8 at that moment, a tie is not losing,
so nostalgic would not fire and T1 would end 16–14.
**v1.1 golden test:** expected `lanePower [[18,14],[15,21],[13,11]]`, winner p0. Also assert the T1 8–8 consensus lead for p0 after turn 5.
(Cross-checked by council-critic with the #27 engine, `tower-plus:scratchpad/critic/golden11.ts`, and by hand by designer-b.)
+1 -1
View File
@@ -174,7 +174,7 @@ interface CardInPlay { card: GameCard; owner: 0 | 1; lane: number; turn: number;
interface PlayerView {
you: 0 | 1; ruleset; turn; phase; initiative;
energy: number; energyLeft: number; hand: GameCard[]; queue: { cardId; lane }[]; committed; deckCount;
opponent: { handCount; deckCount; queuedCount; committed }; // never their cards or queue
opponent: { handCount; deckCount; committed }; // §5.3: nothing about their queue (cards, count or energy) until reveal
lanes: { topic: TopicDef /* stat always; id/name/portal masked until portalRevealed */, portalRevealed, cards: [mine, theirs],
cardPower: [number[], number[]], power: [mine, theirs], leader: 'you' | 'opponent' | null }[];
result: MatchResult | null;
+15
View File
@@ -121,6 +121,15 @@ also gets a fresh bearer token per lobby; only its hash is kept. When eom.dev ac
shows peer modes with "Hosted by …" and links to the peer's own site to play there. No node
proxies another node's matches.
### Restarts
Live lobbies, drafts and matches survive a node restart. The node saves them to
`$WIKIDECK_DATA_DIR/game/live.json` every 15 s and on SIGTERM/SIGINT, and restores them on start.
Player tokens keep working, and turn and draft timers restart from the moment the node is back.
A lobby is dropped instead of restored if its mode is no longer hosted with the same `version`
and rules, so a match never continues under different rules. A hard crash can lose up to 15 s
of moves.
## 4. Credit for hosts
Every mode shows **"Hosted by &lt;operator&gt;"** (with the node's origin), its player counts,
@@ -255,3 +264,9 @@ be pinned in consensus.
starting with the preview-card pages. A card whose page isn't warm yet gets no bonus. This
keeps load on the shared, rate-limited Wikipedia egress tiny: a few dozen pages per 6 hours per node.
- Spectating and rematches.
- **Separate game RPC budget.** `/api/game` sits behind the node's global `/api` admission
budget (`WIKIDECK_RPC_REQUESTS_PER_SECOND`, 10 writes/s node-wide), so a flood of game
traffic can delay chain RPC (and the reverse). At human speed this is fine. The fix is to give
game routes their own `RpcBudget`, which means mounting them ahead of the shared budget in
`server/testnet/http.ts`: a change to that shared file, so it's proposed in #6 rather than made
tonight.
+40
View File
@@ -0,0 +1,40 @@
# WikiDeck Android app (Night 1)
A Capacitor 7 shell (`dev.eom.wikideck`) around the React UI. It talks to a WikiDeck node over native HTTP.
![Android emulator screenshots](android/screens.jpg)
## Build a debug APK
You need JDK 21 (a full JDK with `javac`), the Android SDK (platform 35 and build-tools 35) and `ANDROID_HOME`.
```
android/build-debug.sh # testnet build: VITE_WIKIDECK_NETWORK=testnet, genesis 1792411200, node http://192.168.1.32:3101
adb install -r android/app/build/outputs/apk/debug/app-debug.apk
```
- **Settings:** override any of them with env vars, for example `VITE_NODE_URL=http://192.168.1.32:3102 android/build-debug.sh`.
- **Network:** without `VITE_WIKIDECK_NETWORK=testnet`, the bundle is a **mainnet** build.
- **Signing:** debug signing only. Nothing is published.
## How it works (`src/native.ts`, imported first in `main.tsx`; does nothing on the web)
- **Node URL:** relative `fetch('/api/…')` and `fetch('/auth/…')` calls go to `VITE_NODE_URL`. The default is the Night-1 testnet node. A runtime override is available through `setNodeUrl()`, stored in localStorage.
- **Native HTTP (`CapacitorHttp`):** fetches go through Android's HTTP stack. There's no CORS, and no WebView `Origin` header, so the node's POST origin check passes without any server change.
- Verified: a POST from the app returns 400 (validation), while the same POST with `Origin: https://localhost` returns 403.
- The interceptor merges headers (`content-length: 0, 384`). `native.ts` drops that header so `StateClient`'s size check works, and byte limits are still enforced while streaming.
- **Mining:** RandomX is desktop-only. `isNativeApp()` hides the mining panel, and `html.native-app` lets CSS target the app.
- **SSO:** "Log in with eom.dev" opens Dex in a Custom Tab (`setNativeBrowser(Browser)`). Dex redirects to `dev.eom.wikideck:/oauth/callback` (intent filter, `singleTask`), and `completeLogin()` has the node exchange the code.
- **Android behaviour:**
- The **back button** closes an open dialog first, then goes back in history, then minimizes the app.
- The **keyboard** uses `adjustResize`.
- **Edge-to-edge** margins are on, with a dark window behind the system bars.
## Emulator (inspiron-3670, user space)
The SDK, AVD and JDK are under `~/worker/jobs/night/mobile-android/{sdk,avd,jdk}`, and `env.sh` sets the paths.
```
emulator -avd wikideck -no-window -no-audio -gpu swiftshader_indirect # headless, KVM
adb exec-out screencap -p > shot.png
```
To inspect the WebView, forward DevTools with `adb forward tcp:9222 localabstract:webview_devtools_remote_$(adb shell pidof dev.eom.wikideck)`.
## Known gaps
- **Real SSO login:** needs an eom.dev account and wasn't done tonight. The deep-link round trip was verified up to Dex's `invalid_grant` for a dummy code.
- **Touch targets in the Play UI:** the dashed "Play here" lane zone doesn't respond to taps; only the lane plate does (reported on #5).
- **Mining copy on the home hero:** "Explore mining" still shows in the app.
+19 -2
View File
@@ -81,8 +81,25 @@ Note: the VNC keyboard via `vncdotool` drops Shift (everything types lowercase,
- **SSO (#7):** `Info.plist` registers the `dev.eom.wikideck` URL scheme; redirect `dev.eom.wikideck:/oauth/callback`
returns to the app via `@capacitor/app`'s `appUrlOpen`.
## Progress at shutdown
_(filled in before 01:25)_
## Progress at shutdown (01:06, 2026-11-17)
- **23:21** recovery `.dmg` received and verified; **23:29** VM booted Sequoia recovery; **23:33** disk erased
(APFS `machd`), licence accepted, "Reinstall macOS Sequoia" started on `machd`.
- **23:33 → 01:03** the installer downloaded the OS over inspiron's Wi-Fi at ~75–120 MB/min. The VM disk grew from
21 MB to **9.7 GB**. Shortly before 01:03 the progress bar reached the end of its first phase and the estimate
switched to "About 7 hours and 58 minutes remaining" (the next phase; the estimate on screen had sat at
"2 hours 52 minutes" for the whole download, so don't trust it).
- **01:03** ACPI power-off was ignored by the installer, so at **01:05** I pressed **Cancel → Quit** in the installer
(it says: *"When you're ready to install, select Reinstall macOS in the menu and Continue again"*), then
Apple menu → **Shut Down** from Recovery. QEMU exited cleanly at **01:06**. `qemu-img check`: no errors.
- **macOS is not installed yet.** No user account exists, so there is no `CREDENTIALS.txt` and SSH isn't on yet.
The partial download stays on `machd` (9.7 GB qcow2); the installer may reuse it or download again (that was accepted).
**To resume** (inspiron-3670):
```
cd ~/worker/jobs/macos && setsid ./boot-macos.sh > qemu.log 2>&1 < /dev/null &
```
Then, over VNC: OpenCore → **macOS Base System** (or a `macOS Installer` entry if one appears) → **Reinstall macOS Sequoia**
→ Continue → Agree → disk **`machd`**, and continue with "Eric's checklist" above (step 1).
## What's verified
- `BaseSystem.dmg` sha256 matches macos-fetch's `SHA256SUMS`; converted `BaseSystem.img` is 3,221,110,784 bytes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

+144
View File
@@ -0,0 +1,144 @@
# WikiDeck Night 2: design brief (locked decisions)
**Night 2:** 2026-11-17, 21:30 to **02:00 EST, hard stop**.
This brief merges three sources:
- the coordinator's plan, in `docs/night2/PLAN.md`
- four reviews (designer, engineer, data and critic), in `docs/night2/reviews/`
- **Eric's decisions on 2026-11-17**, which override anything in the reviews
Where a review disagrees with this file, **this file wins**. Where this file is silent, follow the reviews, in this order:
1. engineer, for architecture
2. designer, for rules
3. data, for derivation
4. critic, for process
## Eric's decisions (non-negotiable)
1. **A full 40-card, Magic-style game.**
- A deck is exactly 40 cards, and every card in it is an NFT the player owns.
- There are no loaners, Basics, filler or proxies.
2. **Players can't play until they own enough cards.**
- If a player owns fewer than 40 cards, the game shows their progress (for example "23 / 40 cards") and how to mine.
- There is no "practice with borrowed cards".
- The reviews' Basics, loaners, Signature card and the "Collection + Basics" model are **rejected**.
3. **PvP is first-class.** Bot matches exist, but only for eligible players.
4. **The mobile app must be able to mine.**
- Today `isNativeApp()` hides the mining panel, so mobile players can never earn cards.
- Fix it in the Android app.
- Write in `docs/night2/MOBILE_MINING.md` that Google Play and the App Store both prohibit on-device crypto mining, so for now the mining build is a sideloaded APK.
5. **Tone: lean in, Cards Against Humanity style.**
- Living people, tragedies, wars, disasters, crimes, diseases and dictators are all **ordinary cards with full mechanics**.
- There are no `solemn` flags, no special-casing and no softened verbs.
- The game takes itself completely seriously, and the comedy comes from the juxtapositions. Use the critic's S7 deadpan style guide: never wink, never comment on the matchup, and use encyclopedic texture with [n] citations.
- "Casualties" is fine.
- **One rule stays:** all generated text (rules text, match log, recap) is deterministic templates filled **only with real data from the card and the match**. Never use LLM prose, and never invent factual claims about real people (no made-up crimes, quotes or acts). Humour by juxtaposition is fine; fabricated facts about a real person are defamation.
6. **iOS is paused.** Don't touch `ios/` or the macOS VM.
7. **Wikimedia politeness by default** (the engineer's §4 and the data analyst's §5), including the mint-path bug (§9 below).
## Supply reality (design around it, don't fight it)
- **Mainnet:** 12 cards, all in one wallet. Consensus mints at most about 96 cards a day, network-wide. That's Eric's accepted trade-off: the game becomes playable as people mine.
- **Our testnet** (`deploy/night/`, on poweredge-r350):
- Wallets alice, bob, carol and dave own about 50 cards between them, with up to 40 more being mined now.
- The `testnet-ops` agent consolidates cards into **alice and bob** with on-chain transfers, so both reach 40 if supply allows.
- Deck size is **ruleset data** (`deckSize`, default 40). If the testnet can't reach 80 cards, the end-to-end test mode may set a lower `deckSize`. That's a testnet mode file only; production stays at 40.
- **Engine, simulation and balance work** uses the 236 real cards in `docs/game/card-sample.json` as the card pool. Build 40-card random decks from it. This needs no chain.
## Game rules core (designer §2, adapted to 40 cards)
- **Life:** each player starts with 20 Notability; at 0 you lose. Drawing from an empty library loses (the MTG rule). These are ruleset keys.
- **Opening:** hands of 7, with one mulligan (shuffle, draw 7, bottom 1). The first player skips their first draw.
- **Turn:** refresh, draw, main, combat, end.
- **Resources are a fixed income of Citations:** your maximum rises by 1 each turn, to a cap of 10. There are no land cards, so no land screw.
- Locations ramp at most +2 in total.
- Hand limit is 7.
- **Combat:**
- attack the opponent with untapped Figures, with summoning sickness ("Pending review")
- at most one blocker per attacker
- damage is simultaneous
- no trample, no first strike, no stack and no instant speed; Events are sorcery-speed
- **Clock:** 60 s per turn plus a 5-minute bank. No turn cap is required. If the sims show stalls, add `turnCap` as a ruleset key.
- **Card types** (designer §3 and data §1):
- **Figure:** a creature
- **Location:** a permanent with Territory or Garrison
- **Event:** sorcery-speed
- **Institution:** an artifact
- **Doctrine:** an Aura that attaches to a Figure, so *Tetrated dodecahedron* can buff *Cho Yang-ho*
- Classify with data §1's P31 → P279 anchor classes, falling back to categories, then the description, then Doctrine.
- Fix the `\bhuman\b` → People bug.
- Freeze each card's derived profile the first time the card is seen.
- **Factions ("Portals"):** designer §3.2. There are no colour restrictions in deckbuilding.
- **Stats:** data §2. Cost 1–6 comes from the percentile fame curve, with a fixed power+toughness budget per cost, so famous cards are bigger and pricier, not strictly better.
- **Keywords:** designer §3.4 and data §2, at most 2 per card, each triggered by real data:
- Protected
- Featured
- Translated
- Legacy
- Stub
- Well-sourced
- Multilingual
- Local
- **Connected:** the data team's tiers (data §4): Linked, Compatriot, Contemporary and Kin, from cached Wikidata claims and links.
- It gives +1/+1, or +2/+2 for a direct link.
- Aim for it to fire in 15–30% of pairs, tuned in the simulator.
- **Flavour text:** the first sentence of the on-chain `article.extract`.
## Story
- **Match log:** past-tense, encyclopedic and per player (`logFor`), with no hidden-information leaks.
- **Recap:** a "Battle of X (2026)" page after each match, with:
- an infobox: date, belligerents (the players), strength, casualties (the cards destroyed), result
- a narrative assembled from the log with 3–4 template variants per event, seeded deterministically
- References citing every card played, with revision ids
- "WikiDeck" branding, not Wikipedia's
- a shareable URL
## Modes (kept, now on the duel engine)
- **Classic:** constructed from your own 40+ cards. It's ranked.
- **Draft:** both players must be eligible. The pool is drawn from both players' collections, and drafted cards are used for that match only. Nothing moves on-chain.
- **Trending:** live pageview momentum changes stats (designer §5), from a daily refreshed cache.
- **Peer-hosted house rules:** stay data-only, with a versioned schema. Night 1 mode files are rejected cleanly.
## PvP (engineer §3)
- **Seats and ownership:**
- Seats are tied to eom.dev accounts (Dex) and their linked wallets.
- The host verifies **ownership on the server** (`ownership.ts`, using `ledger.nft()`) and builds each card from the chain.
- **Night 1's gaps to close:**
- the browser-side ownership check
- the 128-block snapshot cap
- starter decks dealt in `host.ts:144`
- **Matchmaking:** private lobbies, invite links, quick match, and an Elo ladder keyed to the account.
- **Transport:** keep polling, with a state version so unchanged polls return 204. Don't use long-polling.
## Wikimedia (engineer §4 and data §5)
**One process-wide client:**
- 1 request per second, burst 3, 1 request in flight per host
- priority lanes: mint, then interactive, then background
- `maxlag=5`
- honour `Retry-After`
- a circuit breaker after 3 consecutive 429s
- a daily cap
- a sqlite cache on disk with ETags
- a User-Agent with an operator contact (a config key that operators must set; the testnet uses the project URL)
**The mint path changes transport only:** request parameters stay byte-identical, and the cache is never used for mint data.
**Fix the mint bug:** a 429 on pageviews currently mints a card with `attention: null` forever (`enrichment.ts:145-164`). Fail and retry instead.
**Other changes:**
- Card faces in the client no longer trigger uncached upstream calls on every render.
- An article prefetch pool for mining templates (data §8).
**Tests make zero network calls.**
## Cut order if late
1. the Elo ladder (keep W/L)
2. quick match (keep invites)
3. Trending's live stats
4. the Kin and Contemporary tiers of Connected
5. recap polish (keep the plain log)
**Never cut:**
- the duel core
- 40-card owned-deck validation on the server
- PvP over invite links
- the Wikimedia client and mint fix
- mobile mining
- the recap (the story is the point)
+88
View File
@@ -0,0 +1,88 @@
# WikiDeck Night 2: team handbook
Read this whole file, then `docs/night2/BRIEF.md` (the locked design decisions). Then read the review sections your issue names in `docs/night2/reviews/`.
**Window:** 2026-11-17 21:30 until **02:00 EST, hard stop**.
**Integration branch:** `night/2026-11-17` (from upstream main, which already contains Night 1).
**Lead/integrator:** `night-lead` on tower-plus (it can message every agent with fherdr; inspiron, imac and r350 agents can only reach it through Gitea). The coordinator is Eric's Claude session on tower-plus.
**Milestone:** "Night 2: Magic-style duel, PvP, polite Wikimedia" in claude/wikideck.
**Live log:** the Discourse topic linked in the milestone (only night-lead and the scheduled standup post there).
## Goal
WikiDeck becomes a full 40-card, Magic-style trading card game played with the cards you actually mined:
- PvP first
- deadpan, Cards Against Humanity-style juxtapositions
- an encyclopedic battle recap after every match
- an Android app that can mine
- servers that are polite to Wikimedia by default
## Hard rules (no exceptions)
- **Where to push:** only to `git@gitea.eom.dev:claude/wikideck.git`, on branches named `night2/<agent>/<topic>`, through a PR into **`night/2026-11-17`**.
- Never push to `WikiDeck/wikideck`, `main` or the Night 1 branch.
- Only `night-lead` merges, using squash.
- **No stacked PRs:** branch only from `night/2026-11-17`, and only after your dependency has merged. If you need unmerged code, stub the interface.
- **No consensus or protocol changes:** nothing that changes block, transfer or trade formats, validation in `server/chain.ts`, `server/testnet/consensus.ts` or `shared/protocol.ts`, or what a mint fetches and stores. The game runs **off-chain**, and matches never move or burn cards.
- **Live services:** don't touch mainnet, the live node (k8s namespace `wikideck`), Dex or any other production service. The testnet is private, on poweredge-r350 (`deploy/night/README.md`).
- **iOS is paused:** don't touch `ios/` or the macOS VM.
- **Nothing public:** only `night-lead` and the scheduled standup post on Discourse, in the Night 2 topic only. No purchases, sign-ups or secrets in git.
- **The printer and CNC:** inspiron-3670 drives a 3D printer and a CNC router. Never start, resume or send a print or cut.
- **Wikimedia:** tests make **zero** network calls. Don't script loops against Wikipedia or Wikidata. Use `docs/game/card-sample.json` and cached data. Our IP was rate-limited on Night 1.
- **Git identity** in every clone:
```
git config user.name Claude
git config user.email claude@eom.dev
git config commit.gpgsign false
```
End commit messages with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
- **Before opening a PR:** run `npm test` and `npm run build` on **Node 24**. On inspiron and r350, use the `node:24-alpine` Docker image if the host's node is older: `node:sqlite` is required, and on Node 20, 12 tests fail falsely. Don't add npm dependencies; ask night-lead.
- **Tests go in** `tests/<agent>-*.test.ts` (top level).
- **Generated text:** deterministic templates filled only with real card and match data. No LLM prose, and no invented facts about real people (BRIEF, decision 5). Otherwise, lean in: no softening of tragedies or living people.
## How we coordinate
**Gitea is the shared brain.** The machines don't share a filesystem.
- **Your issue is your inbox.**
- Prefix every comment with `[<agent>]`.
- Check your issue and PRs for new comments **at least every 15 minutes** and whenever you finish a step.
- **Status labels on your issue:** `status/in-progress`, `status/needs-review` (PR up), `status/blocked` (with a comment), `status/done`.
- **Need another team?** Comment on their issue with `[from <you>]`.
- **Contracts beat conversations.** Interfaces are files on the integration branch, e.g. `shared/duel/types.ts` and `docs/game/DUEL_API.md`. Read them before asking.
- **Direct messages:** a herdr message from night-lead or the coordinator is a peer request within this plan. Act on it.
- **Stuck for more than 10 minutes?** Label `status/blocked`, comment, and move on to something else.
## Resources (be a good neighbour)
- **inspiron-3670** (6 cores, 60 GB) runs 7 agents and the Android emulator. Wrap heavy commands in `flock /tmp/night-heavy.lock <cmd>` (npm ci, builds, gradle, docker build).
- **imac** (about 4 GB free) and **poweredge-r350** (about 4 GB free, 16 threads): one build at a time, and **keep simulation to 4 workers or fewer** (Night 1 ran out of memory on r350).
- **Avoid permission prompts:** nobody answers them. Don't chain `cd <dir> && <write>`; use absolute paths or `git -C`. Keep one purpose per shell command.
## Timeline (EST)
| Time | Milestone |
|---|---|
| 21:30 | Kickoff. Preflight: Gitea MCP works, Node 24, clone. Comment `starting` on your issue. |
| **22:15** | **Contracts merged:** `shared/duel/types.ts` and `docs/game/DUEL_API.md` (duel-core), plus `docs/game/DUEL_DESIGN.md` v1 (duel-design: keywords, text templates and tone, with BRIEF.md as the base). The `ownership.ts` signature is agreed by 22:00. |
| 23:15 | Engine alpha. The simulation starts. The UI plays against a bot. |
| 00:00 | Wikimedia client merged. Host binds the duel. The PvP UI is wired to the host. |
| 00:45 | Balance v1 (tuning is data-only). Mobile mining runs in the emulator. |
| **01:15** | **Code freeze:** fixes only. Balance re-runs on the frozen head SHA. QA runs PvP end to end on the testnet with alice and bob. |
| 01:45 | Final report comment on every issue. night-lead writes `docs/night2/REPORT.md` and opens the upstream PR (never merges it). |
| **02:00** | **Stop.** Push, comment, exit. |
## Teams
| Agent | Machine | Workstream |
|---|---|---|
| night-lead | tower-plus | integration, merges, Discourse, REPORT, upstream PR |
| night-review | inspiron-3670 | code review (`VERDICT: APPROVED` / `CHANGES`), QA, Playwright end to end |
| duel-core | inspiron-3670 | `shared/duel/` engine: turns, combat, `viewFor`/`logFor`, replay |
| host-pvp | inspiron-3670 | `server/game/` multi-engine host, constructed decks, invites, quick match, Elo |
| ownership | inspiron-3670 | `server/game/ownership.ts` and `collection.ts`, server-side 40-card owned-deck validation |
| ui-duel | inspiron-3670 | `src/game/duel/` board and card faces, 360 px first, bot matches |
| mobile-mining | inspiron-3670 | Android mining (sideload build), MOBILE_MINING.md |
| duel-design | imac | DUEL_DESIGN.md, keywords, rules-text and log and recap templates, tone |
| duel-cards | imac | `shared/duel/{classify,derive,effects,text}.ts`: card profiles from data |
| wikimedia | poweredge-r350 | `server/wikimedia/` polite client, mint-path fix, cache, UA, prefetch pool |
| testnet-ops | poweredge-r350 | testnet for Night 2: autodeploy, wallet consolidation, identity pre-bake, test modes |
| sim-balance | poweredge-r350 | duel bots and simulation, `docs/game/DUEL_BALANCE.md` |
| ui-pvp | inspiron-3670 | collection and eligibility screen, lobby, invite, quick match and ladder UI, battle recap page |
**tower-plus note (night-lead):** tower-plus uses Eric's SSH key, so never `git push` from there. Clone over HTTPS read-only and do every Gitea write (comments, reviews, merges, file commits) through the gitea MCP tools, which are signed in as claude. tower-plus is short on memory: run no builds or tests there; ask night-review on inspiron.
+120
View File
@@ -0,0 +1,120 @@
# WikiDeck Night 2: proposed game redesign (for review)
Status: **draft, under review.** Written by the coordinator on 2026-11-17 from Eric's feedback on Night 1's game, Edit War. Night 2 runs unattended on 2026-11-17 from 21:30 to 02:00 EST.
## Eric's feedback on Edit War (the requirements)
1. **Real cards:** a player's deck is made of the cards they actually mined and own. Loaners existed for the demo; the real game uses real cards.
2. **PvP:** players must be able to play each other, not only the AI. Hosted lobbies exist (`src/game/OnlinePlay.tsx`, `server/game/host.ts`) but are buried.
3. **Story:** Edit War "doesn't really tell much of a story with the actual cards".
4. **Feel:** Magic: The Gathering is the model for how it should feel.
5. **Modes:** keep the different modes (classic, draft, trending); Eric likes them.
6. **Tone:** "The fact that I can use a Tetrated Dodecahedron in a game with Barack Obama is funny. Lean into this. The game should take itself seriously, but the end result is going to be entertaining for this reason." (Eric's original v2 post also mentions using his *Tetrated dodecahedron* card to buff his *Cho Yang-ho* card, and node operators running house rules.)
7. **Wikipedia limits:** our servers must respect Wikimedia rate limits by default instead of getting cut off. Night 1 hit HTTP 429 from our shared IP.
8. **iOS:** paused (Apple licence acceptance). Out of scope.
## Hard constraints
- **Consensus is fixed:**
- No changes to the chain, block format, mint stats snapshot or consensus files (see `docs/night/BOUNDARIES.md`).
- Everything game-related is derived off-chain from what a card already holds.
- **Where work happens:** in the `claude/wikideck` fork, through reviewed PRs. Eric merges upstream.
- **No live deployment:** don't touch mainnet or the live node at wikideck.eom.dev.
- **Budget:** 4.5 hours, about 10 agents across 4 machines (tower-plus, imac, inspiron-3670, poweredge-r350). Night 1 used 17 agents for 2.75 h and about 10% of the weekly usage budget; 75% remains.
## Facts the design must face
- **Card data:** what a card holds is shown in `shared/enrichment.ts` (PageEnrichment / MintStatsSnapshot) and `shared/testnet.ts` (BlockHeader).
- **Article:** pageId, title, extract, image, category, revisionId.
- **Mint snapshot:** pageBytes, languageCount, 6 months of pageviews with trendPercent and dailyAverage, and the attention, depth and reach scores.
- **Night 1 also used:** the Wikidata id, P31 "instance of", and live pageviews, all fetched off-chain.
- Real distributions are in `docs/game/CARD_DATA.md`: compressed scores, a skewed category split, and a reach of 0 for 18% of cards.
- **SUPPLY:**
- One card is minted per block, with a consensus target of one block per 15 minutes: at most about 96 new cards a day, network-wide.
- **Mainnet today has 12 cards in total, all owned by one wallet**, all mined on 2026-11-01.
- A "deck of your own mined cards" in the Magic sense (40–60 cards) is impossible for anyone for a long time.
- **This is the biggest viability question; see Open problem 1.**
- **Cards are unique NFTs:** each card is one specific mint, and the same article can be minted more than once (`pageId` repeats).
- **Night 1 code to reuse:**
- the deterministic rules engine and its rules-as-data style (`shared/game/`)
- the bots and the balance simulator (`shared/bots/`, `scripts/sim/`)
- hosted lobbies and modes (`server/game/`)
- Dex accounts (`server/account/`)
- the Android shell (`android/`)
## Proposed design
### A. Card identity from the article (MTG-style types)
The card type comes from Wikidata P31, with a fallback to Wikipedia categories:
| Article is a… | Card type | MTG analogue |
|---|---|---|
| person, character, animal species | **Figure** | creature |
| place, region, celestial body, structure | **Location** | land (resource) and/or permanent |
| event, battle, election, disaster | **Event** | instant/sorcery |
| creative work, organisation, company, team, product | **Institution** | artifact |
| concept, theory, mathematical object, ideology, field | **Doctrine** | enchantment |
**Factions (colours):** the 6 P31-based factions proposed in CARD_DATA.md, plus a neutral fallback.
**Stats from data:**
- **Power and toughness** come from percentile attention, depth and reach. For example, attention drives power, and depth drives toughness and staying power.
- **Cost** follows the curve: high-stat cards cost more.
**Rules text:**
- Generated deterministically from a fixed table of templates keyed on type, faction, category keywords, trend, language count, dates (birth/death, founding, event date), coordinates, and so on.
- It is written in MTG's terse register.
- **Flavour text:** the first sentence of the article's extract.
### B. Story mechanics
- **Connected:** two cards whose articles link to each other, or share a Wikidata property such as country, field or era, gain a bonus together. Barack Obama with the White House; Tetrated dodecahedron with Polyhedron.
- **Citations:** a resource or counter flavoured as sources.
- **Edit wars and vandalism:** removal and interaction effects.
- **Deadpan tone:** the game is completely straight, like an encyclopedia or an MTG judge. The comedy comes from the matchups, never from jokes in the text.
- **Match log:** written as a dry encyclopedic account.
- **After each match:** a Wikipedia-style article, *"Battle of the Tetrated Dodecahedron (2026)"*. It has:
- an infobox: date, belligerents, commanders (the players), strength (the cards), result
- a short deterministic narrative built from the match log
- a "References" list citing every card's real article
- These recaps are shareable.
### C. Game structure
- **Duel:** two players, a life total, turns with attack and block, and permanents on a battlefield.
- **Resources:** from Locations and/or a fixed per-turn income, designed to avoid MTG's "land screw" (no resource cards, no game).
- **Deck size and composition:** depends on Open problem 1.
### D. PvP first
- **Matchmaking:** a queue, invite-by-link and a ranked ladder (Elo or Glicko).
- **Identity:** the eom.dev account, with linked wallets as the card source.
- **Hosting:** the hosting node runs the match, so there's no client trust.
- **AI opponents:** still available for practice and onboarding.
### E. Modes (kept)
- **Classic:** constructed from owned cards.
- **Draft:** players draft from a shared pool, so they don't need large collections.
- **Trending:** stats boosted by live pageviews.
- **Peer-hosted house rules:** remain data-only.
### F. Wikimedia politeness by default
- **One client:** a single throttled Wikimedia client used by every server-side caller (`server/wiki.ts`, `server/enrichment.ts`, P31 lookups, link lookups).
- **Throttling:**
- a conservative rate limit by default (for example 1 request/s and 1 concurrent request per node, configurable)
- `maxlag`
- honour `Retry-After` with backoff
- batch up to 50 titles per request
- an on-disk cache with ETags and conditional requests
- a daily refresh for live stats
- **User-Agent:** a default UA that identifies the node and an operator contact, as Wikimedia's policy asks.
- **Volume:** a design budget for requests per match and per mint.
## Open problems for the review team
1. **Supply versus "real cards only".** What makes a real-cards game playable when a player owns 0–12 cards and the network mints at most about 96 a day? Options to evaluate (add others):
- (a) A small deck size, such as 7–10 cards, with recursion and reuse.
- (b) Your owned cards are your "commanders" or champions, and a shared pool of common public-domain article cards fills the rest. This conflicts with Eric's requirement, so it would have to be argued.
- (c) Draft as the main mode, where the pool is drawn from the whole chain's minted cards and ownership gives cosmetic credit or a guaranteed pick.
- (d) A collection-as-deck where every owned card counts, scaled by size.
- (e) Card copies or "editions" (no consensus change possible, so off-chain only?).
Recommend one, and say what Eric must decide.
2. Is MTG-style attack/block too complex to build, balance and make readable in one night? What is the smallest rules core that still feels like Magic?
3. Is P31 typing reliable enough? Check against the real sample in `docs/game/card-sample.json` and `docs/game/starter-cards.json`. Plan for unclassified cards, which were 14% of Night 1's sample.
4. Can "Connected" link lookups be done within the Wikimedia budget? Where does the data come from, and when is it fetched and cached?
5. Can the generated rules text be both deterministic and good? Does it need an LLM? LocalAI exists on the cluster, but determinism and the consensus boundary matter.
6. What scope is realistic for 4.5 hours with about 10 agents, and what gets cut first?
+44
View File
@@ -0,0 +1,44 @@
"""How often random card pairs share cheap relations. Usage: python3 -I connected.py <card-sample.json>"""
import json, sys, re, itertools, collections, importlib.util, os
cards = json.load(open(sys.argv[1]))['cards']
spec = importlib.util.spec_from_file_location('ty', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'types.py'))
ty = importlib.util.module_from_spec(spec); spec.loader.exec_module(ty)
GENERIC = re.compile(r'stubs|living people|\d+ (births|deaths)$|articles|wikidata|pages', re.I)
COUNTRIES = ['United States','American','England','English','British','France','French','Germany','German','Japan','Japanese','China','Chinese',
'India','Indian','Brazil','Poland','Polish','Italy','Italian','Spain','Spanish','Austria','Canada','Canadian','Australia','Australian','Russia','Russian',
'Mexico','Mexican','Iran','Pakistan','Bangladesh','Sweden','Swedish','Norway','Estonia','Ukraine','Croatia','Philippines','Cuba','Israel','Portugal','Scotland','Wales','Ireland','Kazakhstan','Malaysia','Argentin','Belgi','Iceland','Bermuda','Thailand','Singapore','Sri Lanka','Slovenia','Moldova','Cyprus','Macedonia','Mauritania','Congo','Gibraltar','Hong Kong','New Zealand','Korea','Indonesia','Aceh']
NORM = {'American':'United States','English':'England','British':'United Kingdom','England':'United Kingdom','Scotland':'United Kingdom','Wales':'United Kingdom',
'French':'France','German':'Germany','Japanese':'Japan','Chinese':'China','Indian':'India','Polish':'Poland','Italian':'Italy','Spanish':'Spain',
'Canadian':'Canada','Australian':'Australia','Russian':'Russia','Mexican':'Mexico','Swedish':'Sweden'}
Y = re.compile(r'\b(1[0-9]{3}|20[0-2][0-9])')
def feats(c):
txt = (c['description'] or '') + ' | ' + ' | '.join(c['categories'])
ctry = {NORM.get(k, k) for k in COUNTRIES if k in txt}
cents = {int(y) // 100 for y in Y.findall(c['title'] + ' ' + txt)}
cats = {x for x in c['categories'] if not GENERIC.search(x)}
p31 = {i['id'] for i in c['instanceOf']}
return dict(ctry=ctry, cent=cents, cats=cats, allcats=set(c['categories']), p31=p31, type=ty.classify(c)[0])
F = [feats(c) for c in cards]; pairs = list(itertools.combinations(range(len(cards)), 2)); N = len(pairs)
def rate(f):
k = sum(1 for i, j in pairs if f(F[i], F[j])); return f'{k}/{N} ({100*k/N:.2f}%)'
print('pairs', N)
print('share any category (incl. generic)', rate(lambda a, b: a['allcats'] & b['allcats']))
print('share specific category', rate(lambda a, b: a['cats'] & b['cats']))
print('share P31 class', rate(lambda a, b: a['p31'] & b['p31']))
print('share P31 excl human/taxon', rate(lambda a, b: a['p31'] & b['p31'] - {'Q5', 'Q16521'}))
print('share country (text proxy for P17/P27)', rate(lambda a, b: a['ctry'] & b['ctry']))
print('share century (text proxy for dates)', rate(lambda a, b: a['cent'] & b['cent']))
print('share type', rate(lambda a, b: a['type'] == b['type']))
print('country OR century OR specific cat', rate(lambda a, b: (a['ctry'] & b['ctry']) or (a['cent'] & b['cent']) or (a['cats'] & b['cats'])))
print('cards with >=1 country', sum(1 for f in F if f['ctry']), 'with >=1 century', sum(1 for f in F if f['cent']))
# deck-level: chance that a random 10-card hand-pair (10 vs 10, own deck) has >=1 connected pair within a deck
import random; random.seed(1)
def deck_hits(pred, size=10, trials=2000):
h = 0
for _ in range(trials):
s = random.sample(range(len(F)), size)
if any(pred(F[i], F[j]) for i, j in itertools.combinations(s, 2)): h += 1
return f'{100*h/trials:.0f}%'
pc = lambda a, b: (a['ctry'] & b['ctry'])
print('10-card deck has >=1 same-country pair', deck_hits(pc), '| specific category', deck_hits(lambda a, b: a['cats'] & b['cats']),
'| country-or-century', deck_hits(lambda a, b: (a['ctry'] & b['ctry']) or (a['cent'] & b['cent'])))
+23
View File
@@ -0,0 +1,23 @@
"""Field availability for rules-text generation in card-sample.json. Usage: python3 -I fields.py <card-sample.json>"""
import json, sys, re, statistics, collections
cards = json.load(open(sys.argv[1]))['cards']; n = len(cards)
Y = re.compile(r'\b(1[0-9]{3}|20[0-2][0-9])\b')
def share(f): k = sum(1 for c in cards if f(c)); return f'{k}/{n} ({100*k/n:.0f}%)'
print('description non-empty', share(lambda c: bool(c['description'])))
print('wikidataId', share(lambda c: bool(c['wikidataId'])))
print('P31 present', share(lambda c: bool(c['instanceOf'])))
print('>=1 non-hidden category', share(lambda c: len(c['categories']) > 0))
print('categories truncated (cllimit 50)', share(lambda c: c['categoriesTruncated']))
print('median categories', statistics.median(len(c['categories']) for c in cards))
print('year in title', share(lambda c: Y.search(c['title'])))
print('year in description', share(lambda c: Y.search(c['description'] or '')))
print('year in categories', share(lambda c: any(Y.search(x) for x in c['categories'])))
print('year anywhere (title/desc/cats)', share(lambda c: Y.search(c['title'] + ' ' + (c['description'] or '') + ' ' + ' '.join(c['categories']))))
print('births/deaths category', share(lambda c: any(re.search(r'\d+ (births|deaths)', x) for x in c['categories'])))
print('establishments/completed category', share(lambda c: any(re.search(r'establishments|completed in|disestablish|opened in', x) for x in c['categories'])))
print('living people', share(lambda c: 'Living people' in c['categories']))
print('stub category', share(lambda c: any('stubs' in x for x in c['categories'])))
print('country/nationality word in desc or cats', share(lambda c: re.search(r'American|British|English|French|German|Japan|China|Chinese|India|Brazil|Poland|Polish|Italy|Italian|Spain|Spanish|Austria|Canada|Australia|Russia|United States', (c['description'] or '') + ' '.join(c['categories']))))
print('legacy category on-chain', collections.Counter(c['legacyCategory'] for c in cards))
print('pageviews available', share(lambda c: c['pageviews']['status'] == 'available'))
print('languagesTruncated', share(lambda c: c['languagesTruncated']))
+59
View File
@@ -0,0 +1,59 @@
"""Proposed percentile -> cost/power/toughness derivation, evaluated on card-sample.json.
Usage: python3 -I stats.py <card-sample.json>"""
import json, sys, collections, statistics, itertools
d = json.load(open(sys.argv[1])); cards = d['cards']; P = d['percentiles']
def pct(s, v): # DESIGN 1.1 counting: cut points strictly below + half of equal
if v is None: return None
cut = P[s]; return int(sum(c < v for c in cut) + sum(c == v for c in cut) / 2)
TH = [26, 39, 51, 63, 78] # v1.1 costThresholds (fame -> cost 1..6)
BUDGET = [None, 3, 4, 6, 8, 10, 12] # P+T per cost, MTG vanilla curve (2/1, 2/2, 3/3, 4/4, 5/5, 6/6)
def derive(c):
a, dp, r = (pct(k, c['stats'][k]) for k in ('attention', 'depth', 'reach'))
vals = [x for x in (a, dp, r) if x is not None]
fame = int(sum(vals) / len(vals) + 0.5)
cost = 1 + sum(t <= fame for t in TH)
b = BUDGET[cost]
kw = 'Multilingual' if r >= 75 else ('Local' if c['stats']['reach'] == 0 else None)
if kw == 'Multilingual': b -= 1 # evasion-like keyword is paid for out of the body
if kw == 'Local': b += 0 # Local = gains +1/+1 next to a same-country Location (conditional, no tax)
share = (a if a is not None else 50) / max(1, (a if a is not None else 50) + dp) # attention vs depth
pw = min(b - 1, max(1, round(b * share))); t = b - pw
return dict(title=c['title'], a=a, d=dp, r=r, fame=fame, cost=cost, P=pw, T=t, kw=kw,
trend=c['pageviews']['trendPercent'], daily=c['pageviews']['dailyAverage'])
rows = [derive(c) for c in cards]; n = len(rows)
def naive(c): # straw man: power = attention tier, toughness = depth tier, cost from their sum
ti = c['tiers']; pw = (ti['attention'] or 1 + 1) // 2 + 0; t = (ti['depth'] + 1) // 2
return dict(cost=max(1, min(6, round((pw + t) / 2))), P=pw, T=t)
nv = [naive(c) for c in cards]
def dominated_pairs(rs, use_kw=False):
k = 0
for x, y in itertools.permutations(rs, 2):
if x['cost'] <= y['cost'] and x['P'] >= y['P'] and x['T'] >= y['T'] and \
(x['cost'] < y['cost'] or x['P'] > y['P'] or x['T'] > y['T']) and (not use_kw or x.get('kw') == y.get('kw')):
k += 1
return k
print('cost distribution', sorted(collections.Counter(r['cost'] for r in rows).items()))
print('power distribution', sorted(collections.Counter(r['P'] for r in rows).items()))
print('toughness distribution', sorted(collections.Counter(r['T'] for r in rows).items()))
print('keywords', collections.Counter(r['kw'] for r in rows))
print('P/T by cost:')
for cst in range(1, 7):
g = [r for r in rows if r['cost'] == cst]
if g: print(' ', cst, len(g), collections.Counter(f"{r['P']}/{r['T']}" for r in g).most_common(6))
pairs = n * (n - 1)
print('strict-dominance pairs proposed', dominated_pairs(rows), 'of', pairs, '; same-keyword only', dominated_pairs(rows, True))
print('strict-dominance pairs naive ', dominated_pairs(nv), 'of', pairs)
# efficiency by fame quintile
q = sorted(rows, key=lambda r: r['fame'])
print('fame quintile: mean cost, mean (P+T)/cost proposed | naive (P+T)/cost')
idx = sorted(range(n), key=lambda i: rows[i]['fame'])
for k in range(5):
sl = idx[k * n // 5:(k + 1) * n // 5]
print(f" Q{k+1} fame {rows[sl[0]]['fame']}-{rows[sl[-1]]['fame']}: cost {statistics.mean(rows[i]['cost'] for i in sl):.2f} "
f"eff {statistics.mean((rows[i]['P']+rows[i]['T'])/rows[i]['cost'] for i in sl):.2f} | naive eff "
f"{statistics.mean((nv[i]['P']+nv[i]['T'])/nv[i]['cost'] for i in sl):.2f}")
top = sorted(rows, key=lambda r: -r['fame'])[:6] + sorted(rows, key=lambda r: r['fame'])[:3]
print('examples (top fame, bottom fame):')
for r in top: print(f" {r['title'][:34]:34s} a{r['a']} d{r['d']} r{r['r']} fame{r['fame']} cost{r['cost']} {r['P']}/{r['T']} {r['kw'] or ''}")
tr = [r for r in rows if r['trend'] is not None and r['trend'] >= 25 and (r['daily'] or 0) >= 20]
print('trending (+25% and daily>=20):', len(tr), f'{100*len(tr)/n:.1f}%')
+79
View File
@@ -0,0 +1,79 @@
"""Classify card-sample.json into Figure/Location/Event/Institution/Doctrine.
Order: P31 label rules (first rule that matches ANY P31 label wins, rule order = priority),
then category keywords, then description keywords, then deterministic fallback.
Usage: python3 -I types.py <card-sample.json> [--list]"""
import json, re, sys, collections
RULES_P31 = [ # (type, regex on a P31 label). Order matters: specific before generic.
('Doctrine', r'aspect of|aspect in|disease|clinical sign|list article|chemical entity'),
('Event', r'election|protest|battle|war\b|storm|nor.easter|cyclone|tornado|earthquake|disaster|event|match|final\b|'
r'season|championship|tournament|\brace\b|grand prix|scandal|annexation|treaty|incident|festival|referendum|'
r'conference|ceremony|time period|delegation'),
('Institution', r'artificial satellite|space station|space telescope|spacecraft|space probe'),
('Location', r'planet|natural satellite|\bstar\b|galaxy|nebula|planetary system|astronomical object|rainforest|reef|'
r'civili[sz]ation|empire|historical country|archaeological site|'
r'human settlement|settlement|village|town|city|commune|municipal|parish|county|district|region|province|'
r'township|hamlet|townland|census area|local government|community of|island|river|lake|mountain|plateau|'
r'waterfall|valley|bay|peak|geographical feature|historic district|park|state park|square|road|highway|'
r'building|castle|mosque|church|temple|cathedral|house|home|museum|station|bridge|monument|historic site|'
r'military base|battery|refinery|shopping|stadium|arch|tower|fort|palace|columbari|council'),
('Figure', r'^human$|fictional character|stock character|person|deity|orisha|loa\b|taxon|species|genus|breed|'
r'^family$|organism'),
('Institution', r'company|business|organi[sz]ation|association|society|party|agency|studio|band|musical group|team|club|'
r'university|college|school|institute|diocese|ecclesiastical|manufacturer|newspaper|magazine|film|album|'
r'song|single|musical work|composition|television|series|book|novel|video game|painting|award|position|'
r'aircraft|ship|steamship|vehicle|automobile|tram|railway line|route|typeface|software|product|brand'),
('Doctrine', r'concept|theory|theorem|mathematical|programming language|language|gene|protein|chemical|compound|'
r'disease|clinical sign|ideology|religion|discipline|field|cuisine|food|dish|drink|aspect|list article|'
r'particle|process|genre|form\b|game\b|branch of|class of|type of|tabular'),
]
RULES_CAT = [ # fallback on non-hidden category titles (lowercase)
('Figure', r'\bbirth|\bdeaths\b|living people|people from|\bspecies\b|described in \d|\bgenera\b|deities|characters'),
('Event', r'\belections\b|protests|\bbattles\b|disasters|\braces\b|\bseasons\b|\bevents\b|scandals|annexations|competitions'),
('Location', r'villages|communes|parishes|local government|populated places|geography|rivers|islands|buildings and structures|bridges|'
r'stations|parks|districts|townships|cities and towns|historic places'),
('Institution', r'companies|organi[sz]ations|\bfilms\b|albums|songs|novels|newspapers|television series|musical groups|'
r'aircraft|ships|typefaces|software|awards|teams|clubs'),
('Doctrine', r'theory|structures$|algebra|terminology|cuisine|drinks|desserts|ecology|languages|diseases|conditions|'
r'concepts|ranks|etymology|maps|atlases'),
]
RULES_DESC = [
('Figure', r'\b(painter|politician|actor|writer|player|born|species|genus)\b'),
('Event', r'\b(race|election|battle|match|protest|storm|war|competition)\b'),
('Location', r'\b(village|town|city|river|island|building|church|columbarium|station|park)\b'),
('Institution', r'\b(company|band|film|album|organi[sz]ation|team|aircraft|ship|newspaper)\b'),
('Doctrine', r'\b(concept|theory|structure|dessert|drink|dish|technique|class of)\b'),
]
TYPES = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine']
def classify(card):
labels = [i['label'].lower() for i in card.get('instanceOf') or []]
for t, rx in RULES_P31:
for l in labels:
if re.search(rx, l): return t, 'p31', l
cats = [c.lower() for c in card.get('categories') or [] if 'stubs' not in c.lower()]
for t, rx in RULES_CAT:
for c in cats:
if re.search(rx, c): return t, 'category', c
desc = (card.get('description') or '').lower()
for t, rx in RULES_DESC:
if re.search(rx, desc): return t, 'description', desc
# deterministic last resort: Doctrine (the residual "idea" class); never hash-random.
return 'Doctrine', 'fallback', ''
if __name__ == '__main__':
d = json.load(open(sys.argv[1])); cards = d['cards']
res = [(c, *classify(c)) for c in cards]
n = len(res)
by_t = collections.Counter(r[1] for r in res); by_src = collections.Counter(r[2] for r in res)
print('n', n)
for t in TYPES: print(f'{t:12s} {by_t[t]:4d} {100*by_t[t]/n:5.1f}%')
for s in ['p31', 'category', 'description', 'fallback']: print(f'src {s:12s} {by_src[s]:4d} {100*by_src[s]/n:5.1f}%')
print('labels w/o p31 match but has p31:', sum(1 for c,t,s,w in res if s!='p31' and c['instanceOf']))
print('cross-tab old faction x new type')
ct = collections.Counter((c['faction'], t) for c,t,s,w in res)
for f in sorted({c['faction'] for c in cards}):
print(f' {f:14s}', {t: ct[(f,t)] for t in TYPES if ct[(f,t)]})
if '--list' in sys.argv:
for c,t,s,w in res:
if [i['label'] for i in c['instanceOf']] == ['human']: continue
print(f"{t[:5]} {s[:4]} | {c['title'][:42]:42s} | {w[:40]}")
+171
View File
@@ -0,0 +1,171 @@
# Night 2 plan: critic / player-advocate review
Reviewer: critic. Sources: night2/PLAN.md, wd/docs/game/{DESIGN,CARD_DATA}.md, card-sample.json, wd/docs/night/{HANDBOOK,BOUNDARIES}.md, Night 1 report (`~/Desktop/night/night-lead/REPORT.md`; it is not in wd/docs/night). Ranked by severity, most severe first.
## Facts the plan doesn't state, but which decide everything
- **Mined cards are random articles.** `server/wiki.ts` uses `generator=random`. Nobody chooses Barack Obama. The real pool looks like card-sample.json: 34% stubs, villages, beetles, French communes, local elections. "Tetrated dodecahedron vs Obama" will be rare. The everyday matchup is *Dichromorpha viridis vs 1954 Gold Coast general election*. That's still funny in a deadpan way, but the design and its examples must be built for it, not for celebrity cards.
- **Supply is about zero, not 96 a day.** 12 cards in 16 days, all in one wallet (Eric's), all from day 1. Mining has effectively stopped.
- **Mobile can't mine.** `App.tsx` hides the mining panel when `isNativeApp()`, so an Android player can never get a real card.
- **14% of sampled cards are living people** (33/236 in "Living people"). Events include ongoing protests with deaths (*2024–2026 Cuban protests*, *2025 Tehreek-e-Labbaik Pakistan protests*), a *sex scandal*, an *annexation*, and *Organization of the Luftwaffe (1933–1945)*. The safety rules (§6) are needed tonight, not someday.
---
## S1 (blocker). "Real cards" + PvP is impossible today. This is Eric's decision, not the agents'.
Under a literal reading of point 1, exactly one person on Earth can play, and PvP has no opponent. Each option, measured against the request:
- **(a) Small decks of 7–10:** literal and honest. But only Eric qualifies, and with exactly 12 cards there's no deckbuilding, which is half of what makes MTG feel like MTG.
- **(b) Owned "commanders" plus a public filler pool:** this *is* the loaner system Eric just said was only for the demo, renamed. If agents choose it without asking, it's a quiet betrayal of the request.
- **(c) Draft from the chain's cards:** the cards are real mined cards, but the pool is the same 12 cards every match. It's degenerate until supply grows. On testnet, about 50 cards, it's fine.
- **(e) Off-chain editions:** prints cards with no proof of work and no consensus. It undermines what "mined" means. Reject it.
- **(d) Collection-as-deck:** this is (a) with scaling. Fine as the mechanism, but it doesn't solve the 0–3 card player.
**Fix:** before 21:30, put these questions to Eric. Per standing preference, agents don't start building until Eric gives an explicit go.
1. "Does Classic and ranked PvP require 100% owned mined cards? (Recommend: yes.)"
2. "Can a player with fewer than N owned cards play casual or practice matches with clearly labelled **proxies**? They're never ranked, never shown as owned, and appear greyed out with the stamp 'Proxy'. (Recommend: yes, for practice, AI and invite-link casual only.)"
3. "Is Draft from the whole chain's minted cards 'real cards'? Ownership would earn the first pick and a credit line in the recap. (Recommend: yes.)"
4. "Can your 12 cards be used as public bot and ghost decks? (They're your wallet.)"
5. "Should we fix the supply side, so mobile users can get real cards, given that mobile can't mine? Options: a desktop-mining CTA, gifting by transfer (an on-chain action by Eric, not by agents), or an unlock condition such as 'mine 1 card to enter ranked'."
**Default if Eric doesn't answer:** take the most literal reading. Ranked and Classic use owned cards only. Practice and AI use proxies, which look different. Draft uses chain-minted cards only. No editions. Record the decision in DESIGN.md §0 in Eric's own words.
**Design implication either way:** the format must be fun with a small deck. Recommend **one format with no deck minimum**: a 10-card deck at most, and if you own fewer, you play what you own plus visible proxies, casual only. The engine must handle running out of cards gracefully. Draw from a reshuffled graveyard (DESIGN-style "recursion") instead of losing to an empty library.
## S2 (blocker). PvP has no population. A ranked ladder tonight is wasted work, and unsafe.
Elo with one eligible player is theatre. Night 1's REPORT (known issues 2–3) also says hosted PvP trusts the host: the host picks the seed, there's no commit–reveal, and the UI log is built from full state and leaks hand contents. A ladder on top of that is cheatable.
**Fix, in order:**
1. **Invite-by-link casual PvP** first, made prominent on the Play screen. Eric can test it with a second account on testnet.
2. **Async "ghost" matches.** You play a bot piloting a real wallet's real deck (with that owner's opt-in), and the result is posted to the owner. This is the PvP that a population of five can actually have.
3. The **queue backfills with a bot after 30 s**, *labelled as a bot*. Never pass a bot off as a human.
4. Defer the ranked ladder until commit–reveal and `viewFor`-only logs land. Cut it tonight.
## S3 (high). An MTG clone built in one night will be worse than Edit War
Edit War had a real hook: each lane is judged by one Wikipedia stat. The plan replaces it with generic power/toughness/cost. MTG is fun because of hand-designed cards, the stack and instant-speed interaction, and deckbuilding across thousands of cards. Tonight has none of that: procedurally generated text, 12 cards, and no stack.
**Fix: name the smallest core that still feels like Magic**, and only that:
- Two players, 20 life, and a resource that grows by 1 a turn automatically. Locations add +1 when played (no land screw).
- Board of 5 per side. Figures attack. The defender makes one block per attacker, chosen by tapping a blocker and then an attacker. No first strike, trample or multi-block in v1.
- Events are **sorcery-speed only**. No stack, no priority passes, no opponent-turn interaction. Every response window doubles PvP round-trips and the time needed for UI work.
- One keyword per card at most, from a list of about 8 (Night 1 used 6, with property tests).
- **Keep a Wikipedia hook that MTG doesn't have**, or this is "MTG with worse cards". Candidate: home stat as the creature's "evasion" (an attention attacker can only be blocked by a card with attention ≥ its own), or the trend arrow as haste. One hook, kept and tested.
- **Keep Edit War playable as a mode.** The code exists; deleting it removes a working fallback.
## S4 (high). 360 px readability
An MTG board (two battlefields, hand, life, resources, rules text, combat arrows) doesn't fit 360 px if the cards carry generated paragraphs.
**Fix:**
- The card face on the battlefield shows: title (2-line clamp), type icon, cost, P/T, one keyword chip. The rules text and flavour live **only** in the tap-to-zoom sheet.
- Rules text has a hard limit of 90 characters, enforced by a test over the whole sample.
- Combat uses a "declare attackers → defender blocks → preview outcome → confirm" sheet, not drawn arrows.
- The QA gate is a 360×640 screenshot of a full board (5 + 5) on Android, attached to the UI PR.
## S5 (high). Night 1 process lessons the plan doesn't apply
What went wrong (REPORT plus handbook):
- The design froze at 23:01, but the balance numbers were measured before the #38 change, so the shipped seat-advantage figure is stale.
- 3 OOMs (tower-plus, and r350 twice).
- imac's Gitea MCP was down all night, so the council had to relay through night-lead.
- Squash merges of stacked PRs caused add/add conflicts.
- Wikimedia 429s came from our own sampler.
- On Node 20, 12 tests failed falsely.
**Fixes:**
- **Freeze rules on a schedule, and gate them on evidence.** Design frozen by 22:30 (one hour, not 45 minutes: this is a bigger redesign). Engine API by 22:45. The balance re-run happens on the final head, after the last engine PR, and its numbers go in the report with the SHA they were measured on.
- **Fewer, wider agents.** 7–8, not 10:
- designer and critic as one council pair
- an engine agent
- a card-derivation and text-generator agent (it owns the safety rules)
- a UI agent
- a PvP/host agent
- a wiki-client agent
- a lead and a review agent
Night 1's 17 agents produced conflict and relay overhead.
- **Pre-flight at 21:30:**
- run `get_me` on Gitea MCP on every machine
- `node:24-alpine` is the only test image
- all heavy work runs under `flock` on inspiron
- no stacked PRs: rebase-and-merge, or wait for the parent to merge
- **No network in tests.** Every test and sim reads card-sample.json and starter-cards.json, plus a new red-team fixture (§6). The **only** process allowed to call Wikimedia tonight is the new throttled client's own smoke test, at 1 request/s.
- **Use testnet for real-cards testing.** It has about 50 mined cards across wallets the team controls. Seed 3–4 test wallets with 1, 3, 8 and 20 cards by transfer *on testnet*. Never simulate mainnet supply by copying Eric's wallet.
- **Mainnet is read-only, and only if needed at all.** Read the 12 cards' public data so Eric's own deck can go into a fixture. Nothing is written.
## S6 (high). Ethics and safety: content rules for the deadpan generator
The joke only works if the game is respectful about the subject and absurd only in the juxtaposition. These rules are **requirements** with tests, owned by the card-text agent:
1. **No free-form generated prose about real people or events.** Templates only. No LLM, including LocalAI. That also keeps the output deterministic. The only article-derived prose is the extract's first sentence, quoted verbatim and attributed.
2. **Figures are never harmed, killed or humiliated in text.** Log verbs for a Figure leaving play come from an editorial whitelist: "was reverted", "left the battlefield", "was archived", "was withdrawn from the record". Banned for any card: killed, died, destroyed (for Figures), executed, assassinated, murdered, humiliated, crushed, slaughtered, raped, lynched. "Destroy target Institution" is fine.
3. **Mechanics never derive from sensitive attributes.** Category-keyword templates for Figures come from an **allowlist** of neutral occupation and field words (politicians, mathematicians, footballers, painters, alumni). Never derive a mechanic from: crime, conviction, scandal, illness, disability, cause of death, ethnicity, religion, sexuality, gender, nationality as a trait, victimhood.
- Country is allowed **only** as a neutral "Connected" link (shared P27/P17). It must never carry a modifier such as "French: −1".
- Birth and death years may appear in the type line ("Figure — 1949–2019"). Nothing triggers on death.
4. **Solemn subjects get a `solemn` flag.** It's set by P31 class (war, battle with casualties, massacre, genocide, terrorist attack, mass shooting, disaster, epidemic/pandemic, aviation or maritime accident, protest with deaths, war crime, the Holocaust) or by category words (massacres, genocides, terrorist incidents, disasters in, deaths in, murders, sexual abuse, victims, suicides).
- Solemn cards are playable. They get one fixed neutral effect ("Commemoration: gain 1 Citation; draw a card"), no damage or removal text, a plain log line ("entered the record"), and they are **never** used to name a battle or shown in a recap headline.
- Events in general never "deal damage to" a Figure. Removal comes from Doctrines and Institutions ("Revert", "Edit war").
5. **Glorification guard.** No "leader", "inspire" or "rally" keywords keyed on heads of state, military leaders or dictators. Every Figure's keyword comes from stats, type and faction only. A *Adolf Hitler* card must be a plain statted Figure with no buff-allies text. Test it.
6. **Living people (BLP):** the flavour text is the extract sentence only, and the recap uses only the card title. Any `Living people` card mentioned in a recap is linked to its article and nothing is asserted about the person. Card actions in text are attributed to "the *Barack Obama* card" or the commander, not to the person.
7. **Mint-time vandalism.** The extract is frozen at mint and may be a vandalised revision. Render flavour from the cached **current** extract when possible. Give node operators a data-only `hiddenFlavour: [pageId]` list and a report link on the card zoom sheet.
8. **Recap pages must not impersonate Wikipedia.**
- No Wikipedia wordmark or puzzle-globe logo, and no "From Wikipedia, the free encyclopedia".
- The header reads "WikiDeck match record", with a hatnote: *"This article is about a WikiDeck match. For the polyhedron, see Tetrated dodecahedron."* That's funny, honest, and keeps us clear of the trademark.
- CC BY-SA attribution for extracts and images, in References.
9. **Player privacy.** Shareable recaps are opt-in per match. Commanders show as the account display name or "Anonymous", never a wallet address unless the player chooses.
10. **Red-team fixture plus a sign-off gate.** `tests/fixtures/sensitive-cards.json` holds hand-written PageEnrichment for: Barack Obama, Donald Trump, Adolf Hitler, Jesus, Muhammad, Yemọja, September 11 attacks, The Holocaust, Sandy Hook Elementary School shooting, 2004 Indian Ocean earthquake and tsunami, COVID-19 pandemic, a living child actor, Pullman porter affair, *2024–2026 Cuban protests*, Cho Yang-ho, and Tetrated dodecahedron.
- A test snapshots their full rules text, log lines and a recap, then asserts the banned-verb list and the solemn rules.
- The snapshot file goes into the morning report **for Eric to read before anything is shared publicly**.
## S7 (medium). Tone: how deadpan fails, with examples
- **Failure modes:**
- *Wacky:* puns, exclamation marks, emoji, winks.
- *Cringe:* the generator "noticing" the joke ("In a surprising twist…").
- *Dull:* logs that read like a stack trace.
- *Mean:* adjectives about the losing side.
- **Rule:** the text never comments on how odd the matchup is. The comedy is entirely in the nouns.
- **Card rules text.**
- DO: "*Tetrated dodecahedron* — Doctrine — Ideas. Figures you control with Depth 7 or more get +1/+1."
- DO: "*Barack Obama* — Figure — People, 1961– · 3/4 · Connected (+1/+1 while you control a Connected card)."
- DON'T: "Yes He Can! Obama gets +2 power because he's the president!"
- DON'T: "This shape is so complex it hurts your opponent's brain."
- **Match log.**
- DO: "Turn 6. *Cho Yang-ho* (4/5) attacked. *Dichromorpha viridis* (1/2) blocked and was reverted. Commander Eric cited *Tetrated dodecahedron*: *Cho Yang-ho* +1/+1 until end of turn."
- DON'T: "Cho Yang-ho SQUASHED the grasshopper lol." Also don't use "killed", or use any adjective (brutal, humiliating, heroic).
- **Recap.**
- DO: "The **Battle of the Tetrated Dodecahedron** was a WikiDeck engagement fought on 17 November 2026 between the forces of Eric and Bot (Normal). It lasted nine turns and ended in a decisive victory for Eric.[1] Contemporary accounts note the deployment of *Barack Obama* in the fourth turn.[2]"
- The infobox field is "Cards withdrawn", **not** "Casualties". Battles are named after the decisive non-Figure, non-solemn card; fall back to "Match of 17 November 2026".
- DON'T: "Obama was humiliated by a shape," or "the bloodiest battle in WikiDeck history."
- **Dull guard:** vary sentences by deterministic seed across 3–4 synonymous templates per event, and use citation numbers [n] that link to the card's real article. That small Wikipedia texture is most of the charm.
## S8 (medium). "Connected" will almost never fire on random articles
Two random articles almost never link to each other. Fetching `prop=links` per card is costly, at hundreds of links a page, and it doesn't fit the 1 request/s budget.
**Fix:**
- Connect cards on cheap shared Wikidata claims fetched once per card at first sight and cached for good: country (P17/P27), century (from P569/P571/P585), and same P31 superclass or faction. Leave out the article link graph tonight.
- Measure the fire rate on card-sample.json (random pairs) and on Eric's 12. Target 15–30% of pairs. If it's lower, the mechanic is invisible.
## S9 (medium). Wikimedia politeness (point 7): good plan, three gaps
1. The plan never says **who decides the production UA**. REPORT next step 8 leaves it to Eric. Ship the default as `WikiDeck/<version> (node: <PUBLIC_ORIGIN>; operator contact required)`, refuse to start the enrichment client without a contact configured, and leave production config to Eric.
2. Rate limits must be **per egress IP**, but all of Eric's nodes share one IP. Use one shared limiter per host IP: a single node acts as the Wikimedia proxy for the cluster, or the budget is split statically.
3. Set a request budget per match: **zero Wikimedia calls during a match.** All P31, claims and trend data are fetched at deck validation or lobby time from the cache. Trending's live stats come from the daily refresh.
## S10 (medium). Modes under the new engine (point 5)
Draft and Trending must be re-specified, not just "kept":
- Draft with a 12-card pool must deal from **all chain-minted cards**, or Eric must decide (S1-3).
- Trending uses the daily cache (S9).
- The house-rules JSON schema changes with the engine. Version it (`rulesetVersion: 2`) so Night 1 mode files on testnet nodes are rejected cleanly instead of misread.
## S11 (low). Story (point 3) depends on the recap
The plan's "story" is Connected plus the recap. Given S8, the recap and log carry the whole of point 3, so prioritise them over the ladder. The recap is cheap (a deterministic template over the match log) and is the most "Eric" deliverable.
## Scope: what gets built, and what gets cut first
**Build, in this order:**
1. The throttled Wikimedia client and cache. Nothing else calls Wikipedia.
2. Card derivation (type, faction, P/T, cost, keyword) with safety rules and the red-team test.
3. The smallest MTG core engine plus bots.
4. A 360 px match UI.
5. Invite-link PvP and ghost or bot matches.
6. The match log and battle recap.
7. Draft and Trending ported.
**Cut first:** the ranked ladder and Elo, the Wikipedia link graph, instant-speed Events, the Citations resource as a second currency (fold it into one keyword), and the "editions" idea.
## Decisions for Eric (to ask before kickoff, all in one message)
1. Real-cards strictness (S1 questions 1–3).
2. Use of his 12 cards as public bot and ghost decks.
3. A mobile path to owning cards.
4. Keep Edit War as a mode? (Recommend: yes.)
5. Sign-off on the safety rules in S6, especially solemn Events and living persons.
6. Production User-Agent and contact.
7. Are shareable recaps public by default? (Recommend: opt-in.)
+272
View File
@@ -0,0 +1,272 @@
# Night 2 plan review: data analyst
Inputs: `docs/game/card-sample.json` (236 random illustrated cards), `starter-cards.json`, `shared/enrichment.ts`, `shared/testnet.ts`, `server/{wiki,enrichment,wikimedia-user-agent}.ts`, `server/testnet/{http,miner}.ts`.
Scripts (all `python3 -I`, offline, no API calls): `night2/analysis/types.py`, `stats.py`, `fields.py`, `connected.py`.
**Caveat:** the type rules were tuned on this same sample, so the in-sample accuracy is optimistic. Anything marked *(memory)* comes from my knowledge of the Wikimedia APIs, not from a live check, because we are rate-limited.
## 1. Typing (P31, then categories, then description, then a residual)
The classifier in `analysis/types.py` checks the rules in **priority order**. The first rule that matches *any* P31 label wins. If nothing matches, it tries non-stub category titles, then the description. If all three fail, the card becomes **Doctrine**, which is the residual "idea" class and is deterministic, never hash-random.
| Type | n | share | Mostly |
|---|---|---|---|
| Figure | 86 | 36.4% | human 64, taxon 16, breed, deity, stock character, family |
| Location | 78 | 33.1% | villages, communes, rivers, buildings, parks, roads |
| Institution | 32 | 13.6% | companies, bands, films, parties, aircraft, ships, awards |
| Event | 21 | 8.9% | elections, protests, storms, matches, team seasons |
| Doctrine | 19 | 8.1% | genes, diseases, maths, cuisine, lists, etymology |
| Decided by | n | share |
|---|---|---|
| P31 | 222 | 94.1% |
| category fallback | 12 | 5.1% |
| description fallback | 2 | 0.8% |
| residual (Doctrine) | 0 | 0% |
- **Unclassified rate:** 0% in-sample, down from 14% ("Other") under Night 1's faction rules. 13 cards have no P31, and one card's P31 matched no rule.
- **Accuracy:** I judge about 8 of 236 (about 3–4%) to be debatable or wrong.
- **Expected out of sample:** about 5–10% would reach the category or residual steps on regex alone. That is why the P279 step below matters.
**Hard or misclassified examples:**
| # | Card | P31 | Result | Problem |
|---|---|---|---|---|
| 1 | Buky, Lunugala, Žižki, Laukhella | human settlement | Location | **Existing bug:** Night 1's `\bhuman\b` faction rule puts these 4 villages in *People*. Use `^human$`. |
| 2 | Lewis and Elizabeth Bolton House | single-family detached home | Location | Night 1 calls it *Works* because the label contains "single". Substring rules bite. |
| 3 | Corruption in Kazakhstan | aspect in a geographic region | Doctrine | "region" pulls it to Location unless an "aspect of/in" rule runs first. |
| 4 | 2023 Seville municipal election | municipal election | Event | "municipal" pulls it to Location unless Event outranks Location. Rule order is load-bearing. |
| 5 | Agda (programming language) | functional PL; free software | Institution | Several P31 labels disagree (Doctrine vs product). Tie-breaking is by type priority, not by label order. |
| 6 | Diocese of Mindelo | Diocese of the Catholic Church | Location | "church" matches. It is really an organisation (Institution). |
| 7 | Region Östergötland | county council of Sweden | Location | A governing body, so Institution. "county" matches first. |
| 8 | Christianity in the 5th century | events in a specific year or time period | Event | A history overview. Doctrine fits better. |
| 9 | NRHP listings in Yates County | Wikimedia list article | Doctrine | A list is not a thing. Consider a neutral "Index" type or rerolling at mint (consensus says no). |
| 10 | Dojikko; Tracheal collapse | stock character; type of animal disease | Figure; Doctrine | A trope as a Figure is fun but debatable. The disease was a Figure until "animal" was removed from the Figure rule. |
| 11 | Figueiredo (Guimarães) | former freguesia of Portugal | Location (via category) | Local admin-unit names defeat English regexes. Only the categories rescued it. |
| 12 | *(memory)* Rosetta Stone (stele), Apollo 11 (crewed spaceflight), ISS (space station) | | residual, residual, Institution | Famous starter cards fall through, or hit "station" and become a Location, unless explicit rules come first. |
**Proposed rules** (as implemented in `analysis/types.py`):
1. **Doctrine overrides first:** `aspect of|in`, `disease`, `clinical sign`, `list article`, `chemical entity`.
2. **Event:** `election`, `protest`, `battle`, `war`, `storm`, `match`, `final`, `season`, `race`, `grand prix`, `scandal`, `annexation`, `time period`, `delegation`.
3. **Institution overrides:** artificial satellites, space stations and space probes.
4. **Location:** settlement and administrative-unit words, geography, celestial bodies, `civilization`, `empire`, `historical country`, built structures.
5. **Figure:** `^human$`, `taxon`, `species`, `genus`, `breed`, `deity`, `character`, `^family$`.
6. **Institution:** organisations, companies, teams, creative works, vehicles, positions, awards, typefaces.
7. **Doctrine:** concepts, theories, genes, languages, cuisine, genre, form, process, `type of`, `class of`.
**Production recommendation** (the regex rules above are the fallback):
- Resolve each P31 class through **P279 (subclass of), up to 4 hops**, against a curated table of about 200 anchor classes. For example: Q5 → Figure, Q16521 → Figure, Q486972 (human settlement) → Location, Q1656682 (event) → Event, Q43229 (organisation) → Institution, Q17537576 (creative work) → Institution, Q151885 (concept) → Doctrine.
- **Class cache:** the sample has only **141 distinct P31 classes in 236 cards**. Class lookups saturate quickly, cost under 0.1 requests per card amortised, and are cached forever.
- **Fallback chain:** P279 anchors → label regex → category regex → description regex → **Doctrine**.
- **Freeze the result per card:** store it in the card profile (§3) so that a later Wikidata edit cannot retype a card someone owns.
**Deck consequence:** Event and Doctrine are scarce.
| Type | P(none in 10 random cards) | P(none in 7) |
|---|---|---|
| Event | 39% | 52% |
| Doctrine | 43% | 55% |
| Institution | 23% | 36% |
| Location | 1.8% | 6% |
| Figure | 1.1% | 4% |
- **Instants and enchantments:** a deck built from random mints often has none. The core loop must not need them.
- **Resources:** this argues for a fixed per-turn income (as plan C says). With Locations as the only resource, about 6% of 7-card decks would have no resource at all.
## 2. Stats: percentiles → cost, power, toughness (`analysis/stats.py`)
**Facts that drive the design:**
- **No independent signal in the raw fields.** pageBytes, languageCount and monthly views are monotonic in depth, reach and attention, so their percentiles are identical. They add nothing beyond the three scores.
- **attention and depth correlate** (ρ 0.61), and **reach is independent** of both.
- **trendPercent is live, small and noisy.** Only 2.1% of cards pass the Night 1 gate (+25% and ≥20 views a day).
- **A new independent-ish signal** is available from the on-chain `months[]`: the volatility (coefficient of variation) of the 6 monthly views, median 0.22. Its ρ is −0.52 with attention, −0.30 with depth and −0.19 with reach. It could drive a "Volatile" keyword.
**Proposal:**
1. `pct_s` for attention, depth and reach, using the §1.1 counting against the sample's 99 cut points (unchanged from Night 1).
2. `fame` = the mean of the three percentiles. Cost = 1–6, using the v1.1 `costThresholds` [26, 39, 51, 63, 78] (unchanged).
3. **The body budget depends on cost only:** P+T = [3, 4, 6, 8, 10, 12] for costs 1–6, which is MTG's vanilla curve (2/1, 2/2, 3/3, 4/4, 5/5, 6/6).
4. **The shape comes from the stats:** power = round(budget × pct_a / (pct_a + pct_d)), clamped to [1, budget−1], and toughness is the remainder. Attention reads as "loud", depth as "sturdy".
5. **Reach gives a keyword, paid for from the body.**
- **pct_r ≥ 75 → Multilingual** (evasion-like), costing −1 from the budget.
- **reach = 0 → Local** (a conditional bonus with a same-country Location, no tax).
- Local covers the 18% of cards with reach 0.
6. **Non-Figures use the same budget as effect size:**
- **Event:** deals ⌈budget/2⌉.
- **Location:** P=0 with T=budget, or a per-turn bonus.
- **Doctrine:** ±1 effects, scaled by cost.
- **Institution:** a utility ability.
7. **Trend:** ±1 power, in Trending mode only, using live data frozen at match start.
**Resulting distribution (236 cards, every card rated as if it had a body):**
| cost | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| cards | 30 (13%) | 48 (20%) | 51 (22%) | 48 (20%) | 35 (15%) | 24 (10%) |
| most common P/T | 2/1, 1/2 | 1/3, 3/1, 2/2 | 3/3, 4/2, 2/4, 5/1 | 3/5, 4/4, 5/3 | 5/5, 4/5, 5/4 | 6/5, 6/6, 5/6 |
| Measure | Value |
|---|---|
| power, 1..7 | 38 / 43 / 53 / 33 / 42 / 26 / 1 |
| toughness, 1..7 | 43 / 43 / 50 / 30 / 53 / 16 / 1 |
| keywords | none 139, Multilingual 55, Local 42 |
**"Famous isn't strictly better" check:**
- **Strict dominance** means another card with cost ≤, power ≥ and toughness ≥, and strictly better in at least one.
- **Proposal:** 0 of 55,460 ordered pairs among cards with the same keyword. All 945 raw pairs are cases where a keyword costs one point of body, which is intended.
- **Straw man:** with P and T taken directly from the attention and depth tiers and cost derived from their sum, **3,058 pairs**.
- **Efficiency, (P+T)/cost by fame quintile:** Q1 2.64 (the cheap 2/1s), then Q2–Q5 at 1.90, 1.96, 1.95 and 1.89.
- **Famous cards are bigger and pricier, never more efficient.** Pallas's cat (fame 98) is a cost-6 6/5 Multilingual. Dr. John L. Butler House (fame 8) is a cost-1 1/2 Local.
- **Remaining risk:** in a small-deck game with fixed income, a 6-drop can still dominate the late game. Balance that in the simulator (Night 1's `scripts/sim/`), not in derivation.
## 3. Rules-text inputs (`analysis/fields.py`)
| Field | Where | Reliability (sample) | Use for abilities | Extra cost |
|---|---|---|---|---|
| title, extract (≤900 chars), image, legacy category, pageId, revisionId | **on-chain** (`Article`) | 100%. Extract ≥40 chars by filter. | Flavour text is the first sentence of the extract. Years and "(born …)" can be parsed from the extract. | 0 |
| pageBytes, languageCount, 6 months of views, dailyAverage, trendPercent, attention/depth/reach | **on-chain** (`MintStatsSnapshot`) | 100% (attention null under 1%) | Cost and body, Multilingual/Local, Volatile, Rising/Fading | 0 |
| description (short) | live: WP `prop=description` | 90% | Keywords such as "Species of", "Village in", "film by" | in the batched meta query |
| non-hidden categories | live: WP `prop=categories` | 100%, median 5 | Year in 55% of cards; births/deaths 25%; establishments 10%; stub 34%; country words 52% | same query |
| wikidataId | live: `pageprops` | 100% | Key for all Wikidata data | same query |
| P31 (instance of) | live: Wikidata | 94% | **Type** | 1 per 50 cards |
| Dates: P569/P570 birth and death, P571 inception, P585/P580 point in time and start | live: Wikidata | *(memory)* Common for humans, organisations and events; rare for taxa and concepts | Era keywords ("Ancient", "19th-c."), "Contemporary" links | same `wbgetentities` |
| Coordinates: P625, or WP `prop=coordinates` | live | *(memory)* Nearly all Locations, few others | "Adjacent" (distance), hemisphere, lat/long flavour | in the batched meta query |
| Country: P17 / P27 | live | *(memory)* Most places, people and organisations | "Compatriot" connection | same `wbgetentities` |
| Outlinks: `prop=links` | live | 100% | Connected (§4) | 1–6 per card, continuation |
**Request cost per card, first sight, cached forever:**
- **Batched, amortised:** about 1.5 requests per card.
- 1/50 for the WP meta query (description, categories, pageprops, coordinates)
- 1/50 for `wbgetentities&props=claims`
- under 0.1 for class/P279 lookups
- about 1.2 for outlinks
- **Unbatched (a single card at a time):** about 4 requests.
- **Payload warning *(memory)*:** `props=claims` for famous items can be **hundreds of KB to over 1 MB** (Q76, Barack Obama). It cannot filter by property.
- **Option 1:** a WDQS SPARQL `VALUES` query for the ~12 needed properties, covering up to about 100 items per query.
- **Option 2:** accept the size and only ever fetch each item once.
**Request cost per match**, two decks of 10 cards:
- **Warm caches:** **0–1**. That is the links matrix (§4) if per-card outlinks aren't cached.
- **Trending mode:** add up to **20 per-article pageview requests** for today's figures. These can't be batched, so refresh them in a daily background job, never at match start.
- **Cold worst case:** about 23 requests, which is 23 s at 1 request per second. So prefetch when a card is minted or received, or when a deck is saved, never at queue time.
**Frozen vs live:**
- **On-chain (frozen by consensus):** only `article` and `statsSnapshot`.
- **Everything else is mutable.** That covers type, dates, country, categories and links.
- **Card profile:** freeze it once into an off-chain record, `{tokenId, pageId, mintRevisionId, fetchedRevisionId, wikidataRev, type, faction, dates, country, coords, outlinks hash}`. Cache it forever, and log it in the match record so replays and recaps are deterministic.
- **Why not the mint revision:** fetching categories or links *as of* the mint revision needs `action=parse&oldid=`, which is costly because of the parser-cache miss *(memory)*. Freeze at first sight instead, and record which revision was used.
- **Agreement between hosts:** different hosts could freeze different profiles. To fix that, a node publishes its signed profile file per tokenId, and hosts adopt the first one seen.
## 4. Connected: cheap relationship detection (`analysis/connected.py`)
**Measured on random pairs** (27,730 pairs):
| Relation | Pairs | In a 10-card deck (≥1 pair) |
|---|---|---|
| any shared category (including generic ones such as "Living people" or "1948 births") | 1.96% | |
| shared **specific** category | **0.04%** | 2% |
| same P31 class | 7.9% (mostly human/taxon) | |
| same P31, excluding human and taxon | 0.22% | |
| same country (text proxy for P17/P27) | 7.4% | 91% |
| same century (text proxy for dates) | 16.6% | |
| country OR century OR specific category | 21.5% | 99% |
**Direct article links between two random cards will almost never fire.**
- Shared specific categories are already 0.04%, and links are rarer still between random stubs.
- Obama ↔ White House only works because both are famous starter-style titles.
- **Proposed tiers:**
- **Linked (rare, strong):** a direct link in either direction.
- **Compatriot:** same P17 or P27.
- **Contemporary:** same century, from P569, P571 or P585.
- **Kin:** same P31, excluding human and taxon.
**Methods compared:**
| Method | Cost | Notes |
|---|---|---|
| Pairwise links matrix: `action=query&titles=A1…An&prop=links&pltitles=A1…An&pllimit=max` | **1 request per match** for up to 50 titles; at most 400 edges for 20 cards, under the 500 limit | Gives both directions for every pair. Uses current revisions. Misses links that go through redirects, unless you add `redirects` and also check the redirect titles. |
| Per-card outlinks (`prop=links`, ns0), cached | 1–6 requests per card, once | Intersection is local and free, so it scales to the whole chain. Network-wide this is at most 96 × about 2 ≈ 200 requests a day. **Recommended.** |
| `prop=linkshere` (backlinks) | Famous pages: thousands to millions, many continuations | **Avoid.** Outlinks from both sides already cover A↔B. |
| Shared Wikidata values (P17, P27, P131, P106, P101, P361, dates) | Included in the card profile fetch | Most useful in practice. Gives readable reasons ("both Polish"). |
| Categories | Included in the meta fetch | Too sparse except for generic categories, which are meaningless. Use only for era and country when Wikidata lacks them. |
**Caching:**
- **On first use:** compute each card's outlinks and profile once, keyed by `(pageId, fetchedRevisionId)`, and pin them to the `tokenId` forever.
- **During a match:** the host computes the edge list at match start from cached profiles, which needs no requests, and writes it into the match log.
- **Re-fetching:** never re-fetch for an owned card. An optional "re-sync" can be a deliberate, logged action.
## 5. Wikimedia politeness *(memory: not checked live tonight)*
**Rules:**
- **User-Agent policy:**
- The policy asks for a descriptive UA with contact details: `Tool/version (https://site; contact@…) lib/ver`.
- Generic or library-default UAs may be throttled or blocked. Browsers must use `Api-User-Agent`.
- **Finding:** our defaults have **no contact at all**. That covers `Wikideck/0.1 (experimental Wikipedia article cards)`, the enrichment UA, and the sampler UA `WikiDeckCardDataSampler/0.1`. Contact is opt-in only, through `WIKIDECK_USER_AGENT`. This is likely part of why the shared IP got 429.
- **Action API etiquette:**
- Make requests **serially**, not in parallel. There is no fixed read limit, but use "reasonable" volume.
- Send `maxlag=5` on non-interactive requests, and on a `maxlag` error wait for `Retry-After`.
- Batch: `titles`/`pageids` take 50 per request (500 with the bot flag), and `pltitles` 50 likewise.
- Use continuation, `Accept-Encoding: gzip`, and `formatversion=2`.
- **REST API (`/api/rest_v1`):** the historical guidance was ≤200 requests per second per client. Since 2025 Wikimedia has tightened limits on unauthenticated automated traffic and enforces them per IP/UA. Treat any published number as a ceiling, not a target.
- **API Portal or token traffic:** I recall anonymous traffic at about 500 requests an hour and a personal token at about 5,000 an hour. **Unverified.**
- **Pageviews (AQS):**
- The documented limit was about 100 requests per second per client.
- It is **per article and has no batching**.
- Daily data lands once a day, a few hours after 00:00 UTC, so refreshing more than once a day is waste.
- **Wikidata:**
- `wbgetentities` takes up to 50 ids per request; use `props=` to slim the response.
- WDQS allows about 60 s of query time per minute and 5 concurrent queries per client, and blocks after repeated errors.
- **Always:** honour `429`/`503` with `Retry-After`, use exponential backoff, and cache.
**Concrete node defaults:**
| Setting | Default |
|---|---|
| Client | one shared `WikimediaClient` per **process, and budget per egress IP** (several nodes or agents behind one IP must share it) |
| Rate | token bucket: **1 request/s sustained, burst 3**, **1 in-flight per host** (en.wikipedia.org, wikimedia.org, wikidata.org) |
| Daily cap | 20,000 requests a day per node (configurable). Past it, serve from cache or 503. |
| maxlag | `maxlag=5` on every Action API call from background jobs |
| 429/503 | honour `Retry-After`, else 5 s × 2ⁿ up to 15 min. **Circuit breaker:** after 3 consecutive 429s, stop all Wikimedia calls for 10 min. |
| Batching | 50 pageids/titles, 50 Wikidata ids, links matrix per match |
| UA | `WikiDeck-node/<ver> (+https://<node host>; <operator contact>)`. **Start-up warns loudly**, or refuses in prod, unless a contact is set. |
| Cache | on disk. Profiles and outlinks are immutable (keyed by tokenId and revision). Pageviews keyed by (title, day). ETag / `If-None-Match` on REST. |
| Background | one daily job after about 06:00 UTC refreshes live views for cards in active decks only |
**Mining load: a real issue the plan doesn't list.**
- **What a template costs:** `POST /api/mining/template` calls `wikipediaArticles.random()`, plus `getFresh()` enrichment, on **every template**. That is 3 or more Wikimedia requests (`server/testnet/http.ts:122`).
- **How often:** each miner asks for a new template whenever the tip changes (`server/testnet/miner.ts:89`).
- **Load:** M miners make **about 3M requests per block, all in a burst at each new tip**, or 288·M a day. With 100 miners that is 28,800 a day, which breaks the cap above.
- **Fix:** prefetch a small pool of article+snapshot pairs in the background at 1 request/s, and serve each template from the pool.
- `grnlimit=10` yields about 4.4 usable articles per request.
- This changes no consensus rules.
- Wikimedia load then stays at about 2–3 requests per block, whatever the number of miners.
## 6. Supply
- **Production:** at most 96 blocks a day means at most 96 cards a day: 672 a week, about 2,900 a month, 35k a year.
- **Mainnet reality:** 12 cards, all mined on 2026-11-01. That is **0.75 a day averaged over 16 days**; mining has effectively stopped.
- **Model:** with M equal-hashrate miners, each expects 96/M cards a day, so the time to N cards = **N·M/96 days**. This assumes continuous full block production.
| Active miners M | N=7 | N=10 | N=20 | N=40 | N=60 |
|---|---|---|---|---|---|
| 1 | 1.8 h | 2.5 h | 5 h | 10 h | 15 h |
| 10 | 0.7 d | 1.0 d | 2.1 d | 4.2 d | 6.3 d |
| 50 | 3.6 d | 5.2 d | 10 d | 21 d | 31 d |
| 100 | 7.3 d | 10 d | 21 d | 42 d | 63 d |
| 500 | 36 d | 52 d | 104 d | 208 d | 313 d |
**Caveats:**
- **Mining is a Poisson lottery.** At M=100, 10 cards take a mean of 10.4 days, but about 15 days at the 90th percentile.
- **Hashrate is skewed.** The *median* miner gets well under 96/M; a phone-class CPU gets about 0. Non-miners only get cards through trades.
**Implications for deck size:**
- **Rule of thumb:** a deck size D is reachable in T days only if D ≤ 96·T/M.
- For a 1-week ramp with 100 miners, D ≤ 6.7.
- **40–60-card constructed decks** need M ≤ about 12, or months of play.
- **Recommendation: a 7–10-card constructed deck**, plan option (a).
- Every card is unique anyway, so this is effectively Highlander, with recursion and reuse.
- **Collection-as-deck**, option (d), covers players with fewer than 7 cards.
- **Draft, option (c), is supply-friendly**, but only once the chain holds enough cards.
- An 8-player draft of 3×15 needs 360 cards (about 4 days of full production); a 2-player draft needs about 60.
- **Today's 12 cards cannot feed even one draft.**
- **The cold start is the blocker, not the steady state.** Eric must decide one of two things for launch week:
- accept a loaner or shared pool (plan option (b), which conflicts with requirement 1), or
- accept that PvP only works after someone mines continuously for a day or two.
+278
View File
@@ -0,0 +1,278 @@
# Night 2 review: game designer
**Verdict: approve the direction with changes.** Do the MTG-style duel, the article-derived types, the Connected bonus and the battle recap. The plan has one gap: it has no answer to supply, and Open problem 1 decides whether any of the rest gets played. My answer is a **15-card deck made of your owned article cards plus Basics**. Basics are non-article "process" cards, the equivalent of MTG basic lands. **Draft** from the chain's whole register is the front door for players who own few cards. Rules core: **no stack, no land cards, fixed income, attack/block with single blocks, 16 Notability.** Everything below is data in the existing rules-as-data style.
---
## 1. Supply (Open problem 1)
**The facts:** mainnet holds 12 cards, all in one wallet. At most about 96 a day can be mined, and the real rate is far lower. For months nearly every player will own 0–3 cards. No version of "real cards only" fills a 40-card deck. The question is how the rules bend.
### Recommendation: "Collection + Basics" (options a and d, with the MTG basic-land argument)
- **Deck:** exactly **15 cards**.
- **Article slots:** any number of your owned mints, up to 15. Each mint can appear once, since it is unique. Different mints of the same `pageId` can appear up to 2 times.
- **Basics** fill the rest, at most 3 copies of each.
- Owned and loaner copies no longer mix (v1 §2 is retired).
- **Basics are not articles.** They are a fixed set of 8 Wikipedia process cards that nobody owns and anyone can use in any number. Listed in §2.4.
- **The argument for Eric:** in Magic, about 40% of every deck is basic lands that nobody collects, and the deck is still "your deck". Here, **every article in your deck is one you mined**. The letter of the requirement holds for articles. It bends only in that the deck isn't made *only* of articles.
- **Signature card:** before the match you name one owned article as your Signature. It **starts in your opening hand**, in addition to the 5 cards you draw.
- So a player with 1 card plays that card in every game.
- The recap's infobox lists it under "Commanders".
- **Small deck, high visibility:** a typical game lasts about 8 turns each, so you see 5 + 8 = 13 of your 15 cards. Your owned cards nearly always show up.
- **Running out of cards doesn't lose the game.** When your library is empty, shuffle your Deleted pile (the graveyard) into it. This is option (a)'s "recursion and reuse".
- **Power parity:** an article and a Basic of the same cost are worth about the same, with articles roughly 10% ahead from keywords and Connected (sim target: an all-Basics deck wins 42–48% against a 12-article deck).
- Owning cards buys **variety, story and a modest edge**. It doesn't decide games. Ranked Glicko absorbs the rest.
### What a new player does
| Owns | Practice / AI | Casual PvP | Ranked | Draft |
|---|---|---|---|---|
| 0 cards | Tutorial: the Basics deck plus 3 Archive cards, the existing loaners in a grey "Not owned" frame | Basics-only deck allowed | no (one article needed) | **yes: main path** |
| 1–5 | any | Collection + Basics; the Signature guarantees their card | yes | yes, plus the owner perk |
| 6–15 | any | mostly articles | yes | yes |
Casual matchmaking groups players by article count (0–2 / 3–7 / 8+). Ranked has one ladder.
### Fallbacks, in order
- **Fallback A (if all-Basics games test as dull):** the "Archive ramp".
- Up to `max(0, 8 − owned)` Archive loaner articles may fill slots, and they shrink as you own more.
- Archive cards are grey-framed and listed in the recap as "(Archive, not owned)".
- This is option (b) with a sunset clause. **Eric must accept it explicitly.**
- **Fallback B (strictest "real mints" reading):** "Register as shared library".
- Both players draw from one shared library: every mint on the chain, whoever owns it, plus Basics.
- Your owned cards sit in a Command zone. You can cast them at any time, and they return there with +1 cost tax.
- Every article in play is then a real mint, but your *deck* is no longer yours. It also needs ≥ 30 mints before games stop repeating.
### What Eric must decide
1. Are Basics acceptable as a deck's "lands"? I recommend yes.
2. Archive loaners below 8 owned cards: allowed, or Basics only? I recommend Basics only at launch, with Fallback A behind a ruleset flag.
3. Can owning cards give a small edge in ranked? I recommend yes, capped by the parity target above.
---
## 2. Rules core (Open problem 2)
**Is MTG combat too complex for one night?** Not if the rules are cut to the bone: no stack, single blocks and one main phase. It is the only part that gives "feels like Magic", so keep it. The lane engine, `Topic` and `Portal` are retired. `rng.ts`, `ruleset.ts`, `modes.ts`, `validateDeck`, `replay`, `viewFor` and serialisation carry over.
### 2.1 Setup and turn
- **Notability:** each player starts at **16** Notability (the life total). Reaching 0 loses.
- The log reads: "*X* was nominated for deletion. The result was **delete**."
- **Opening hand:** draw 5, plus your Signature. One free mulligan: shuffle, draw 5, put 1 on the bottom.
- **First player:** skips the first draw. The second player gets **Second Opinion**, a 0-cost token: "Gain 1 Citation this turn".
- **Turn:** (1) **Refresh:** Citation maximum +1 (to at most 7, plus Territory), Citations refill, permanents untap. (2) **Draw** 1. (3) **Main:** play cards in any order. (4) **Combat.** (5) **End:** damage clears, "until end of turn" effects end, hand limit 7. No second main phase.
- **Resources:** fixed income, the Hearthstone model. **No land cards, so no land screw.**
- Locations add ramp (+1 maximum each, at most +2 from Territory in total). Max Citations is 9.
- **Summoning sickness:** a Figure can't attack the turn it enters ("Pending review"). Trending removes this.
### 2.2 Combat
- **Attack:** the active player taps any untapped Figures to attack. They attack the opponent only, not permanents.
- **Block:** the defender assigns at most one blocker to each attacker. Each blocker blocks one attacker. Locations with Garrison may block.
- **Damage:** simultaneous. Blocked pairs trade damage, and an unblocked attacker deals its power to Notability.
- No trample and no first strike in v1. That is about 150 lines of engine, and it is easy for bots.
### 2.3 Interaction without a stack
- **There is no priority, and nothing happens at instant speed.** That is the right call for online PvP on phones, because priority passes cost latency and clock time. Events are sorcery-speed.
- **v2, cut tonight:** *Pending changes*, Events set face-down that trigger on a condition (like Hearthstone's Secrets). They add interaction on the opponent's turn without priority passes.
### 2.4 Basics (the 8 process cards, max 3 copies each)
| Basic | Type | Cost | Text |
|---|---|---|---|
| Anonymous Editor | Figure | 1 | 1/2 |
| Established Editor | Figure | 3 | 3/3 |
| Administrator | Figure | 5 | 4/5. When this enters, destroy target Figure with power 2 or less. |
| Citation | Event | 1 | Put a +1/+1 counter on target Figure. |
| Revert | Event | 2 | Return target Figure or Doctrine with cost 3 or less to its owner's hand. |
| Talk Page | Event | 2 | Draw 2 cards, then discard 1. |
| Speedy Deletion | Event | 4 | Destroy target Figure. |
| Sandbox | Location | 1 | Territory. Garrison 0/1. |
### 2.5 Length
- **Clock:** 60 s per turn plus a 5-minute bank per player.
- **Turn cap:** at the end of turn 12 (each player's), the player with more Notability wins. A tie goes to the higher total power on the battlefield, then to the second player.
- **Sim target:** median 7–9 turns each, 6–12 minutes, decided before the turn cap in ≥ 85% of games.
- **Tunable:** Notability (14–20) and the maximum Citations are ruleset keys.
---
## 3. Derivation: article to card (Open problems 3 and 5)
All of it is deterministic: no LLM, fixed tables, and a versioned `deriveVersion`.
**Inputs:**
- the snapshot (as v1)
- `description`, `categories` and `pageBytes`, already in `PageEnrichment`
- the Wikidata entity's **claims**, fetched in the same `wbgetentities` call (≤ 50 ids per request) that Night 1 already used for P31, so no extra requests
The host caches the claims per `(wikidataId, lastrevid)` and freezes them into the `CardInput` at deck validation.
### 3.1 Type: the first rule that matches wins
1. **Exact Q-id table:**
- Q5 human, Q95074 fictional character, Q16521 taxon, Q23038290 fossil taxon, Q8436 family, deities → **Figure**
- Q486972 human settlement → **Location**
2. **P31 label regex,** reusing `factionRules`, grouped by type:
- People and Nature taxa → Figure
- Places and Structures → Location
- Events and Sport matches/seasons/finals → Event
- Works, Organisations, Sport teams and companies → Institution
- Ideas & Tech → Doctrine
3. **P279 "subclass of" labels,** with the same regexes. Concepts such as *Monoid* have no P31 and only P279. This is why 13 sample cards have no P31.
4. **Description regex,** present on 90% of the sample:
- `^Species of|genus of` → Figure
- `(actor|politician|player|singer|writer)\b` → Figure
- `^(Commune|Village|Town|Municipality|River) in` → Location
- `election|storm|battle` → Event
5. **Categories:** `\d+ births|deaths|Living people` → Figure, `Communes of|Villages in|Populated places` → Location, `establishments` → Institution, `elections|disasters|battles` → Event.
6. **Otherwise Doctrine (Neutral).** An abstract thing is the safest default.
**Bug to fix:** the People regex `\bhuman\b` matches "human settlement". As a result *Buky*, *Lunugala*, *Žižki* and *Laukhella* are People in the sample today (4 of 68). Run the exact Q-id step first. Then score the sample's 236 cards in CI and hand-check the 34 "Other" cards. Target ≥ 95% plausible.
### 3.2 Portal (the faction or colour), orthogonal to type
Five **Portals**, each with an MTG colour analogue, plus **Neutral**:
- **Arts** (red)
- **Earth** (green)
- **History** (black)
- **Science** (blue)
- **Society** (white)
**How a card gets one:**
- **Score:** count keyword hits in description + categories + P31/P106 labels, using fixed regex lists in data. For example:
- History: `\d+(st|nd|rd|th)-century|deaths|sultan|empire|castle|medieval`
- Science: `mathemat|algebra|programming|gene|chemi|disease|scientist`
- **Ties** go to the type default: Figure → Society, Location → Earth, Event → History, Institution → Arts, Doctrine → Science.
- **Zero hits:** the card is Neutral.
**Deck rule: none.** You can't ask for colour discipline from a 3-card collection. Portals matter only through effects, for example "Figures from your Portal get +1/+0".
### 3.3 Cost and stats
- **Percentiles, `fame` and cost 1–6:** exactly as v1 §1.1–1.2, using the existing `costThresholds`.
- **Figure:**
- budget `B = 2·cost + 1` (3/5/7/9/11/13)
- `s = clamp(pct_att/(pct_att+pct_depth), 0.3, 0.7)`
- `power = max(1, round(B·s))`, `toughness = B − power`
- each keyword costs 1 point from the larger stat (minimum 1)
- at most 2 keywords
- fame sets cost, never efficiency: v1's anti-inflation principle is kept
- **Location:**
- cost `ceil(cost/2)` (1–3)
- Territory
- Garrison 0/T, where `T = 1 + floor(pct_depth/25)`
- can't attack
- **Event, Institution and Doctrine:** magnitude `k = ceil(cost/2)` (1–3) inside the templates in §3.5.
### 3.4 Keywords, in priority order, max 2
Rates are measured on the 236-card sample.
| Keyword | Trigger | Rules text | Sample rate |
|---|---|---|---|
| **Protected** | category `Living people` | Can't be targeted by Events an opponent controls. | 14% |
| **Featured** (flying) | pct_attention ≥ 85 | Can be blocked only by Featured or Translated Figures. | ~15% |
| **Translated** (reach) | languageCount ≥ 20 | Can block Featured Figures. | 12% |
| **Legacy** | P570 present or a `\d+ deaths` category | When this is destroyed, draw a card. | 12% |
| **Stub** | category contains "stubs" or pageBytes < 3000 | At the start of your turn, put a +1/+1 counter on this (at most 2). | 34% |
| **Well-sourced** | pct_depth ≥ 85 | Prevent the first 1 damage dealt to this each turn. | ~15% |
| **Trending** (haste) | Trending mode only: live ▲ | Can attack the turn it enters. | mode |
### 3.5 Templates by type
Text is set in MTG's terse register. Subtype regexes run over the P31/P279 labels and the description.
- **Event:**
- conflict (`battle|war|siege|annexation|protest|riot`): "Deal k+1 damage to target Figure or Location."
- disaster (`storm|nor.easter|cyclone|earthquake|flood|tornado`): "Deal k−1 (min 1) damage to each Figure and each Location."
- election (`election|referendum|straw poll`): "Create k 1/1 Society Figure tokens named Elected Member."
- sport (`match|final|season|tournament`): "Target Figure you control gets +k/+0 until end of turn, then fights target Figure you don't control."
- period (`events in a specific year|ceremony|festival`): "Draw k cards."
- default: "Target Figure gets +k/+k until end of turn."
- **Institution** (a permanent, like an artifact):
- organisation/company/party/military: "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member." (for cost ≥ 4; below that, "When this enters, …")
- creative work: "Figures you control that are Connected to this get +1/+1. When this enters, draw a card."
- team/club: "Figures you control with power 2 or less get +1/+0."
- vehicles and ships (v2: Crew): "Figures you control have Featured while attacking."
- **Doctrine** (an Aura, the mechanic in Eric's Tetrated dodecahedron → Cho Yang-ho anecdote):
- **Adopt:** "Attach to target Figure. Adopted Figure gets +k/+k." If the Figure leaves, the Doctrine goes to Deleted.
- Riders by subtype:
- mathematics: "and has Well-sourced"
- language/software: "Whenever it deals combat damage to a player, draw a card"
- ideology/religion: "Other Figures you control from the same Portal get +1/+0"
- **Pathology** (`disease|clinical sign|gene|chemical`) is inverted: "Attach to target Figure. It gets −k/−k."
- **Flavour text:** the first sentence of the extract, or `description` if the extract is missing (the sample has none).
### 3.6 Example cards from `card-sample.json`
Tiers and stats are taken from the file. The final numbers come from the real percentile function.
| Card | Derivation | Generated card |
|---|---|---|
| **Tom Ewell** (person) | Q5 → Figure. "actor" → **Arts**. Tiers 10/9/10 → fame ≈ 92 → cost 6. B = 13, s ≈ .53 → 7/6. Featured (att), Translated (30 langs), Legacy (1994 deaths) apply; capped at 2 by priority: Featured, Legacy. | **Tom Ewell**, 6, Figure — Arts. **6/5**. *Featured. Legacy.* "American actor (1909–1994)." *(description; extract not in sample)* |
| **Salahuddin of Aceh** (person) | Q5 → Figure. "16th-century", "Sultans" → **History**. 7/6/7 → fame ≈ 62 → cost 4. B = 9 → 5/4. Legacy (1548 deaths) → 4/4. | **Salahuddin of Aceh**, 4, Figure — History. **4/4**. *Legacy.* "Sultan of Aceh (1530–1537/9)." |
| **Monoid** (maths/concept) | No P31 → P279 "algebraic structure" → Doctrine. "Algebraic structures", "Category theory" → **Science**. 10/10/10 → cost 6, k = 3. Maths rider. | **Monoid**, 6, Doctrine — Science. *Adopt.* Adopted Figure gets +3/+3 and has Well-sourced. "Algebraic structure with an associative operation and an identity element." |
| **Agda (programming language)** | P31 programming language → Doctrine. **Science**. 10/9/9 → cost 6. Language rider. | **Agda**, 6, Doctrine — Science. Adopted Figure gets +3/+3. Whenever it deals combat damage to a player, draw a card. |
| **Dichromorpha viridis** | Q16521 taxon → Figure. "Species of grasshopper" → **Earth**. 7/1/6 → fame ≈ 45 → cost 3. B = 7, s clamped to .7 → 5/2. Stub (1,347 B) → 4/2. | **Dichromorpha viridis**, 3, Figure — Earth. **4/2**. *Stub.* "Species of grasshopper." |
| **April 2021 nor'easter** | P31 nor'easter → Event, disaster. "2021 in Maine" … → **Earth**. 6/10/2 → cost 4, k = 2. | **April 2021 nor'easter**, 4, Event — Earth. Deal 1 damage to each Figure and each Location. *(k−1 = 1: the sim decides whether disasters need k instead)* |
| **1954 Gold Coast general election** | legislative election → Event, election. **Society**. 7/4/5 → cost 4, k = 2. | 4, Event — Society. Create two 1/1 Society Figure tokens named Elected Member. |
| **Pathrail Mosque** | mosque → Location. "15th-century mosques" → **History** (2 hits) vs Society (1). Derived cost 4 → Location cost 2. pct_depth ≈ 55 → Garrison 0/3. | **Pathrail Mosque**, 2, Location — History. Territory. Garrison 0/3. |
| **Tatsunoko Production** | animation studio → Institution, organisation. **Arts**. 10/10/9 → cost 6. | **Tatsunoko Production**, 6, Institution — Arts. At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member. *(the sim may want 2/2 at cost 6)* |
| **Charmont-en-Beauce** | commune of France → Location. **Earth**. 2/2/10 → cost 1. Stub ignored (Locations take no keywords). | **Charmont-en-Beauce**, 1, Location — Earth. Territory. Garrison 0/2. |
**Readability:** a Figure shows cost, P/T, Portal, the type line and up to 2 keyword words. The full text is behind a tap. This is still one phone-sized face.
---
## 4. Story mechanics (Open problem 4, design side)
### 4.1 Connected
- **Data:** the frozen claims (§3). Each card gets `qid` and `connectKeys` at derivation. The engine intersects keys without any I/O.
- Keys come from P17/P27/P131/P495 (place), P106/P101/P921/P136 (field), P361 (part of), P171 (parent taxon) and `C<century>` (from P569/P570/P571/P580/P585).
- Century counts only between cards of **different** types, because it is too common otherwise.
- Wikipedia link tables are not used in v1, which gives zero extra requests.
- **Direct connection:** one card's claims cite the other card's `qid`, for example Barack Obama with the White House (residence).
- **Bonuses:**
- A Figure gets **+1/+1** while you control another card Connected to it; **+2/+2** if the connection is Direct.
- A Doctrine adopted by a Figure Connected to it gives its bonus twice.
- A Connected creative-work Institution buffs, as in §3.5.
- **The card shows why:** "Connected — Pathrail Mosque (country: Bangladesh)".
- **Rivalry (log only, v1):** an opposing pair that is Connected is noted in the log and the recap ("The two had previously been associated through …").
- **Tuning:** sim on random 15-card decks from the sample. Target 0.5–2 Connected pairs per deck. Drop the noisiest keys (P17 = United States, or France) if the rate is above that.
### 4.2 Match log
Past tense, third person, no adjectives about real people, numbered references. Card names are *italic* links, and the first mention is "the card *X*". Examples:
> Turn 3. *Tom Ewell* (American actor, 1909–1994) was deployed by eric.[1]
> Turn 4. *Monoid* was adopted by *Salahuddin of Aceh*, which became a 7/7.[2][3]
> Turn 5. The *April 2021 nor'easter* dealt 1 damage to each Figure. *Dichromorpha viridis* was destroyed.[4][5]
There is one template per engine event type (about 25 strings). It is generated from the deterministic event list, so `replay` regenerates it exactly.
### 4.3 Battle recap ("Battle of X (2026)")
- **Title:**
- "Battle of {Location}": the winner's highest-cost Location at the end, else any Location in play.
- With no Location: "{Signature of the winner} campaign".
- The prefix is "Skirmish at" under 6 turns and "Siege of" over 10.
- **Infobox:** date, Location, result ("Decisive victory" if the margin is ≥ 10, "Pyrrhic victory" if the winner has ≤ 3 Notability, "Victory by decision" at the turn cap), belligerents (players), commanders (Signatures), strength (cards deployed), casualties (cards destroyed).
- **Sections:** Background (Portals, Signatures); Course of the battle (the 3–5 largest swings); Aftermath (final Notability, rating change); See also (Connected pairs); References (every card's real article with `revisionId`, plus the mint id).
- **Branding:** Wikipedia-*style* typography, but **no Wikipedia or Wikimedia logo or name in the masthead.** Footer: "This page records a WikiDeck match. Card names refer to Wikipedia articles; the events described are game events."
---
## 5. Modes in the new structure
- **Classic:** Collection + Basics, 15 cards, Signature. Ranked (Glicko-2) and casual queue, plus invite-by-link.
- **Draft (front door):**
- **Pool:** the host's **Register**, every mint on its chain whoever owns it. That means real mined cards for players with none.
- **Picks:** an open pool of 20 cards, made of min(Register, 16) random mints plus Basics. The two players snake-pick 10 each, at 20 s per pick, and the deck is their 10 picks + 5 Basics of their choice.
- **Owner perk:** if you own a mint in the pool, you may take it as your first pick, once, and the recap credits it "from the collection of X".
- **Small Register:** mainnet's 12 mints still work, padded with Basics. If the Register has fewer than 16 mints, the ruleset may allow Archive padding (Fallback A).
- **Trending:** any deck policy. Live trend frozen at match start, through the throttled client and its daily cache:
- **▲** (trend ≥ +25% and daily ≥ 20): Trending (haste) and +1/+0
- **▼** (≤ −50%, daily ≥ 20): −1/−0
- the 20/day floor keeps noise out (CARD_DATA finding 6)
- **House rules:** unchanged, data-only. New keys: `startingNotability`, `deckSize`, `maxCitations`, `turnCap`, `basicsAllowed`, `archiveRamp`, `connectedBonus`.
## 6. Scope for tonight (designer's cut order)
**Must:** the duel engine (§2); derivation (§3.1–3.5) with the classifier test on the sample; the 8 Basics; Connected with frozen claims; the match log; the recap page; Classic + Draft through PvP lobbies; a greedy combat bot.
**Cut first:** Rivalry text, Trending's ▼, Pathology inversion, Institution subtypes beyond the default. **Defer:** Pending changes, vehicles/Crew, the Archive ramp (flag only).
## 7. Risks
1. **The engine rewrite is the night's critical path.** The lane engine, bots and golden tests don't transfer. Mitigation: freeze the §2 rules at 21:45, then one engine owner and one bot/sim owner from the first hour.
2. **Famous cards all cost 6** (Tom Ewell, Monoid, Agda, Tatsunoko). Collections of notable articles are top-heavy. Mitigation: the Signature in hand plus fixed income make 6-drops castable by turn 6. Watch the sim's curve.
3. **Basics games are generic.** For 0–2 card owners, Classic has little story. That is exactly why Draft is the front door, and why Fallback A exists.
4. **The classifier is wrong ~5–10% of the time** (the human-settlement bug, P279-only concepts). Show the type line with a "derived from: P31 = …" tooltip so mistakes read as data, not bugs. Correct it by `deriveVersion` bumps, never by hand.
5. **Claims are live data, not the mint snapshot.** Card text can drift between nodes. Freeze the claims per card at first sight with `claimsRevision`, and log it. The host's copy is authoritative for its matches.
6. **Real people in shareable recaps:** this is a living-persons and tone risk. Use mechanical verbs only ("was destroyed", "attacked"), use "the card X", and add no commentary.
7. **Collector advantage in ranked:** enforce the parity target in the sim before ranked opens.
8. **Connected density** may be near zero in random collections (good for surprise) or everywhere through country keys (noise). Tune the keys from the sim. Don't guess.
+246
View File
@@ -0,0 +1,246 @@
# Night 2 plan review: lead engineer (feasibility and scope)
Reviewed against `wd` @ 4f7a8a7 (upstream main with Night 1). Paths are repo-relative. `docs/night/REPORT.md` does **not exist** in this checkout, so Night 1 lessons come from HANDBOOK/BOUNDARIES and the coordinator's notes.
**Verdict:** the plan is feasible in 4.5 h **if** the duel engine is a *new sibling package* with no stack and sorcery-speed only, PvP stays on the self host, and the Wikimedia client is handled as transport-only for the mint path. Three facts change the plan:
1. **Owned cards cannot reach PvP today.** The host never accepts a player deck (see §2).
2. **Card data is not trustworthy.** Article and stats are claims made by the miner: consensus only checks internal consistency.
3. **The browser drives most Wikimedia traffic.** Every card face triggers a server enrichment fetch.
---
## 1. Engine: reuse, rewrite, smallest change
**Reusable as is:**
- `shared/game/rng.ts` (mulberry32, `Rng.fromSeed`, exported via `index.ts:3`)
- the clone-on-apply pattern
- the `(ruleset, decks, seed, actions)` replay contract: `replay` at `engine.ts:433`, `applyAction` at `engine.ts:291`
- zod `parseRuleset` (`ruleset.ts:83`)
- `percentile`/`fame`/`costFor` in `derive.ts:52-79`
- the generated sample percentiles (`card-data.ts`, `scripts/game-card-data.mjs`)
The host is **engine-agnostic** through `EnginePort` (`server/game/engine-port.ts:9-43`), so a second engine plugs in with a new binding file instead of host surgery. Bots are also engine-agnostic (`shared/bots/types.ts` `EngineAdapter`, with `toAct`, `assume` and `evaluate`), and a sequential duel fits that adapter *better* than Edit War does: `game-adapter.ts:243` fakes `toAct` from `committed`.
**Must be rewritten:**
- **Everything lane- or Topic-shaped:**
- `MatchState.lanes` / `LaneState` (`types.ts:136-170`)
- the simultaneous queue/commit/reveal turn (`engine.ts:291-363`)
- Topic scoring (`finish`, `engine.ts:366`)
- Portals and keywords (`keywords.ts`, 241 lines, hooks assume lanes and `onReveal`)
- **`GameCard`** (`types.ts:24-43`): a duel card needs `type`, `toughness`, rules-text ids and flavour, and `validateDeck` (`engine.ts:27`) hard-codes cost 0–6, power 0–30, Faction and lane fields.
- **UI boards** (`src/game/MatchBoard.tsx`, `adapter.ts`).
- **`parseModeRuleset`** host checks (`engine-binding.ts:31-43`), which are Edit War-specific: `turns × turnSeconds ≤ 240`, `topicCount`.
**Recommendation: build `shared/duel/` as a sibling package and leave `shared/game/` untouched.**
- Edit War stays playable: its 6 test files keep passing and its modes keep working.
- Two engine agents don't conflict with anyone.
- Duel exposes the same API names (`createMatch`, `legalActions`, `applyAction`, `viewFor`, `replay`, `validateDeck`, `isOver`, `result`), so `EnginePort` and `EngineAdapter` bindings are thin files.
**Smallest core that still feels like Magic (one night):**
- **Turn:** start (untap, income, draw) → main → combat → end. No second main phase, no stack, no instants and no priority passing. Events are sorcery-speed only.
- **Triggers** resolve immediately in a fixed order: active player first, then reveal `seq`, as Edit War's `onReveal` already does.
- **Resources:** fixed income ramp, `incomeByTurn` as data (Edit War's `energyByTurn` idea, `types.ts:70`), with no carry. A Location is a permanent that gives +1 income. No land cards means no land screw.
- **Figures** have power, toughness and summoning sickness; damage clears at end of turn. **Institutions and Doctrines** are permanents with `ongoing` statics (port the pure `ongoing` hook contract, `keywords.ts:16`). Life is 20 by default (data).
- **Actions must be atomic** so that `legalActions` stays small. That matters because the host checks each action by deep-equal against the full list (`host.ts:187-189`), and the bots enumerate it:
- `play {cardId, target?}`
- `toggleAttacker {id}`, then `confirmAttack`
- `block {blocker, attacker}`, then `confirmBlocks`
- `endPhase`, `concede`, `timeout`
Never enumerate whole block assignments, which explode combinatorially.
- **Empty library** behaviour is data: `libraryEmpty: 'lose' | 'reshuffle' | 'fatigue'`. This keeps option (a), small decks with recursion, open with no code change.
- **`legalActions` is `[]` for the seat without priority.** The host sweep already treats "has legal actions" as "is the one waiting" (`host.ts:264`), so timeouts work without host changes.
**Determinism, rules-as-data, `viewFor` and information hiding all carry over.**
- Hidden information is simpler than in Edit War: there is no simultaneous hidden queue, only the hand and library order.
- **New requirement: `logFor(state, seat)`.** Edit War's `viewFor` returns no log at all (`engine.ts:395-419`). The plan's "dry encyclopedic match log" and the recap both need a per-seat log that masks the opponent's `draw` card ids.
- **Card typing (P31) and "Connected" are not on-chain**, so they must be *frozen into the deck at match start*, exactly as the trend arrow is today (`host.ts:318-334`). Match records already store the derived decks (`host.ts:361-363`), so replay stays exact even if Wikidata changes later.
- **Other host limits:** the host's 2000-action cap (`host.ts:344`) is fine for about 15 turns of atomic actions. `MatchRecord` needs an `engine` field.
- **Multi-engine host** (about 15 lines):
- `ModeHost` holds one `engine` (`host.ts:53`); change to `HostedMode {mode, rules, engine}` and `Lobby.engine`.
- Add an optional `engine: 'editwar' | 'duel'` to `ModeSchema` (`modes.ts:88`, default `editwar`).
- Caveat: the schema is `.strict()`, so un-upgraded peers will count duel modes as `rejected` in discovery. That is acceptable on the testnet.
## 2. "The cards a player owns": the trace and the gaps
**Today's path:**
1. The client computes ownership itself. `src/App.tsx:130` filters `snapshot.blocks` (from `GET /api/state`, `http.ts:68` → `legacySnapshot(limits.legacyBlocks)`) by the **browser-local wallet** address.
2. `PlaySection` gets `owned` (`App.tsx:203`) and merges `cardFromBlock` into the deck-builder pool (`PlaySection.tsx:42`). `cardFromBlock` derives in the browser, marks the card `unchecked` with its cost capped, and computes rarity from `powHash` client-side (`cards.ts:39-46`).
3. Owned cards are used **only in browser-local bot matches** (`MatchScreen`).
**Gaps:**
- **G1. No player decks in PvP.** `ModeHost.join` deals `engine.starterDeck` to both seats for every non-draft policy (`host.ts:144`). The `constructed` policy (`modes.ts:64`, which is also the default, `modes.ts:99`) is **unimplemented**: no create/join route takes a deck (`router.ts:123-131`). Ownership is therefore never verified server-side, because it is never used.
- **G2. Accounts are not wired to the game.**
- Linked wallets live in `accounts.sqlite` (`server/account/store.ts:126-130`), but nothing in `server/game/` reads them.
- `gameRouter` receives only `{dataDir, enrichment}` (`http.ts:154`), with no ledger and no account store.
- The `AccountStore` is created privately inside `createAccountRouter` (`router.ts:19`), so it must be injectable to be shared.
- The `auth` middleware is local to that router (`router.ts:25-33`); export it, or call `verifyIdToken` directly.
- **G3. Host identity is not the account.** The player id is `sha256(localStorage secret HMAC hostOrigin)` (`online.ts:161`, `host.ts:380`), so a ladder keyed on it can be farmed trivially by sybils. Also, `Authorization: Bearer` is already taken by seat tokens with a 16–64 character regex (`router.ts:98-101`). Pass the Dex ID token in the **body** at create/join instead.
- **G4. Collection truncation.** `/api/state` returns at most 128 blocks (`server/resources.ts:20`), so older owned cards silently disappear from Play. Use `ledger.deck(address)`, paged by 24 (`ledger.ts:293`), or a new authed `GET /api/game/collection`.
- **G5. Chain card data is a miner claim.**
- The ledger accepts any peer-valid block. `template()` (`ledger.ts:255`) is advisory, and nothing binds a block to a node-issued template.
- `articleSchema` (`consensus.ts:43-56`) does not cross-check `pageId` against `title`.
- `statsSnapshotSchema` (`consensus.ts:59-93`) only checks internal consistency (`deriveStats` of the declared bytes, languages and views).
- So a custom miner can mint "Barack Obama" with any stats. DESIGN §1.10 plausibility exists only as types: `verifyStats` and `check: 'verified'` are never read (no hits outside `types.ts`, `ruleset.ts`, `engine.ts:22` and `derive.ts`).
- **G6. Per-node account stores.** Peer hosts have their own `accounts.sqlite`, so a wallet linked on node A is unknown on node B. Sending a Dex ID token to a peer also lets that peer replay it on other nodes until it expires, since every node shares the `wikideck` audience.
**Recommended (MVP, self host only):**
- Create and join take `{idToken, deck: tokenId[]}`. The host:
1. verifies the token (`verifyIdToken`);
2. loads `wallets(sub)` from the account store;
3. for each token, checks `ledger.nft(token)` (`canonical-index.ts:163`): owner ∈ wallets and `confirmations ≥ rules.minConfirmations` (1 casual, 3 rated);
4. builds `CardInput` **from the block**, never from client card JSON, then derives and freezes.
- Put this in a new `server/game/ownership.ts` exposing a pure `resolveDeck(deps, sub, tokenIds)`. `host.ts` calls it from `startMatch`.
- Plausibility (G5), stretch:
- Check `pageId → title` and `revisionId → size` with **one batched request per 50 cards** (`prop=revisions&revids=…&rvprop=size|ids`). Revisions are immutable, so the result can be cached forever and verifies `pageBytes` exactly.
- Past monthly pageviews are also immutable, so they can be checked exactly at one request per card.
- On a mismatch, the card is marked `unverified` and its cost is capped.
- Peers (stretch): replace the ID token with a wallet-signed deck claim `["wikideck:deck-claim:v1", NETWORK, hostOrigin, nonce, tokenIds]`. The client builds the message itself, like `shared/account-link.ts`. This needs no account on the peer and cannot be replayed on another host.
## 3. PvP: what exists, what's needed, transport
**What exists:**
- **`server/game/host.ts`:** in-memory lobbies, snake draft, the turn timer and AFK handling via `timeoutAction` (`host.ts:263-270`), legal-action enforcement, live-lobby persistence across restarts (`index.ts:205-226`), JSONL match records with replayable audit (`store.ts`) and a W/L leaderboard (`store.ts:64-68`).
- **`router.ts`:** rate-limited (`router.ts:90-94`).
- **UI:** `OnlinePlay.tsx` is a lobby list (polled every 4 s), create/join, draft and a match board. It is reachable only from inside the Play section.
**What's needed:**
| Feature | Minimal design | Files | Size |
|---|---|---|---|
| Invite link | `createLobby({private:true})` is excluded from `openLobbies` (`host.ts:108-112`); the UI route `/play/join/<lobbyId>` works because the SPA catch-all serves `index.html` (`http.ts:157`), and `join` already takes an id | host, router, OnlinePlay | S |
| Quick match | `POST /modes/:id/quick` joins the oldest open lobby within the rating window, else creates one; no separate queue structure | host, router | S |
| Rated ladder | Elo (K=24, start 1200) per mode, keyed by account id, recomputed by replaying `matches.jsonl` in order at startup (deterministic, no new store); rated only when both seats are account-verified and `rated:true` in mode limits; Glicko-2 is not worth the night | store.ts, host.ts | M |
| Account seat identity | `idToken` in the create/join body → player id `sha256('acct:'+iss+sub)`; guests keep the secret but are unrated | host.ts, online.ts | S |
| Duel binding | `server/game/duel-binding.ts` plus multi-engine `HostedMode` | new file, host.ts | S |
**Transport is polling:** the client polls every 1 s (`OnlinePlay.tsx:11, 45-50`), with no WebSocket or SSE anywhere. It is adequate for a sequential duel: about 0.5 s average hand-off latency.
Three caveats:
1. **Cost.** Each poll runs `viewFor` and `legalActions` and returns the full view. Add a monotonic `version` to the lobby and `GET …?v=N` → `204` when unchanged. Poll every 500 ms while waiting on the opponent and every 3 s otherwise.
2. **Do not long-poll under `/api`.** `RpcBudget` caps the whole node at 32 active `/api` requests (`resources.ts:17`, applied at `http.ts:54`), so 16 matches holding long-polls would starve the node. Real push would need SSE mounted *outside* `/api` (a `server/testnet/http.ts` shared-hook change): a stretch only.
3. **Rate limits.** Two humans behind one NAT, or QA agents on one machine, see 1 req/s × 2 against `plays` 240/min and the global 300/min per IP (`http.ts:56`). That is OK, but QA should not run more than 2 matches per IP.
## 4. Wikimedia politeness
**Every call site** (grep over `server`, `src`, `scripts`, `shared` and `android`; the browser never calls Wikimedia APIs directly, because CSP `connect-src 'self'` at `http.ts:50` forbids it):
| # | Where | Upstream | Trigger | Limits today |
|---|---|---|---|---|
| W1 | `server/wiki.ts:73-78` `random()` | en Action API, `generator=random` ×10 | **mint template** `http.ts:122` | ≤4 concurrent, 3 attempts, 3.5 s timeout, no 429/Retry-After, no maxlag |
| W2 | `server/enrichment.ts:134-138` `load()` metadata | en Action API, `pageids=1` | `getFresh` at **mint** `http.ts:123`; `get` from `/api/wikipedia/:id` `http.ts:93-98`; TrendCache | ≤4 active, 8 pending, then **reject**; in-memory LRU of 128 entries, 6 h TTL; errors cached 30 s |
| W3 | `server/enrichment.ts:148` pageviews | `wikimedia.org` REST, monthly | same as W2 | same |
| W4 | `server/game/trends.ts:37-56` via `index.ts:174-186` | W2+W3 | background, one page per 20 s | about 8.6k requests/day steady if the queue stays warm |
| W5 | **browser:** `src/Card.tsx:24` → `src/useEnrichment.ts:10` → `/api/wikipedia/:id` | W2+W3 | **every card face rendered** (collection, explorer, hero) | per-tab cache 5 min; server limit is 60/min **per client IP** only, with no node-wide upstream budget |
| W6 | `scripts/night/card_sample.py:13-38` | en API, Wikidata `wbgetentities`, REST daily views | offline research | 1 req/s, honours Retry-After, disk cache (its docstring says "~4 req/s"; the code does 1) |
| W7 | browser `<img>` from `upload.wikimedia.org` (`Card.tsx:28`, CSP `http.ts:49`) | CDN | each render | hotlinking; acceptable, but the plan should cache thumbnails or use `pithumbsize` |
**Likely cause of the Night 1 429:** W5 fan-out (each grid page means N cards × 2 upstream requests, with a 128-entry LRU thrashing across users) plus W4, multiplied by several testnet nodes sharing one egress IP. Each node also uses the default UA, `Wikideck/0.1 (experimental …)` (`wikimedia-user-agent.ts:4-5`), which has **no contact**. That breaks the Wikimedia UA policy and is the kind of client that gets blocked first.
**Design: `server/wikimedia/client.ts`, one process-wide `WikimediaClient`.**
- **Rate:** a token bucket per upstream host. Defaults (env-configurable):
- `en.wikipedia.org`: **1 req/s, burst 2**
- `www.wikidata.org`: 1 req/s
- `wikimedia.org` REST: 5 req/s
- **Concurrency:** **1 in flight per host** by default (`WIKIDECK_WIKIMEDIA_CONCURRENCY`). The Action API etiquette is serial requests.
- **Co-located nodes:** document `WIKIDECK_WIKIMEDIA_RPS=0.3` for nodes behind a shared IP (testnet compose).
- **Priority lanes**, with a bounded queue (64):
- `mint`: always first; the timeout starts at dispatch; the queue wait is capped at 15 s, and the miner tolerates it (30 s timeout, `miner.ts:57`)
- `interactive`: on overflow, serve stale cache or 503
- `background`: trends, P31, links, plausibility; dropped when the queue is full
- **maxlag:** add `maxlag=5` to every Action API request (en and Wikidata). Detect `error.code==='maxlag'` (HTTP 200 with a JSON error), wait for `Retry-After` (default 5 s) and retry at most 3 times. REST has no maxlag.
- **429 and 503:** parse `Retry-After` (seconds or HTTP-date), then **pause the whole host bucket** (circuit-open) for max(Retry-After, exponential backoff 2^n s with jitter, cap 10 min). Log once per pause and expose a counter in `/healthz`-adjacent ops output.
- **Batching:**
- `pageids=`/`titles=`/`revids=` up to 50 for cheap props: `info`, `pageprops` (`wikibase_item`), `description`, `revisions|size`.
- P31 via `wbgetentities&ids=Q1|…(50)&props=claims` is heavy (Obama's claims alone are megabytes). Use `wbgetclaims&property=P31` per entity (small, cached for 30 days), or one WDQS `VALUES` query per ≤50 QIDs.
- **"Connected"** costs one request per deck pair: `prop=links&titles=<≤50 deck titles>&pltitles=<same>&pllimit=max` returns exactly the intra-set links. Cache it by the sorted pageId set.
- **Never batch** `langlinks` or `categories`: their limits are shared across the batch, which forces continuation and changes `languagesTruncated` semantics.
- **Persistent cache:** `node:sqlite` (already used by accounts; Node 24) at `$WIKIDECK_DATA_DIR/wikimedia-cache.sqlite`. Key = canonical URL with sorted params and without `maxlag`. Store the body, ETag and Last-Modified; send `If-None-Match` (REST returns ETags; the Action API mostly doesn't); serve stale-while-revalidate for `interactive`. TTLs:
| Data | TTL |
|---|---|
| metadata | 24 h |
| monthly pageviews | until month rollover (already the rule, `enrichment.ts:70`); closed months are immutable |
| P31 | 30 d |
| links | 7 d |
| revision size | forever |
| random | never |
Raise the 128-entry cap (`enrichment.ts:51`) once the cache is on disk.
- **UA:** `WikiDeck/<pkg version> (+https://gitea.eom.dev/WikiDeck/wikideck; <WIKIDECK_OPERATOR_CONTACT or PUBLIC_ORIGIN>) node/<ver>`.
- Keep `WIKIDECK_USER_AGENT` as an override, still sanitized as at `wikimedia-user-agent.ts:8-12`.
- Warn at startup if there is no operator contact.
- Update `tests/testnet-user-agent.test.ts`, which pins today's fallback strings.
- **Volume budget:**
- mint: 3 requests (≤5 with random retries)
- match: **0 synchronous** (cache-only at match start; unknown data means "no bonus" or a fallback type, as `trends.ts` already does)
- per new card first seen: ≤1 batched metadata/plausibility share + 1 P31
- per deck save: 1 links request
- card-face render: 0 when cached
**Consensus boundary (checked carefully):**
- **Validation never touches Wikimedia.** `consensus.ts:43-93` is pure, and the only callers of `wikipediaArticles` and `wikipediaEnrichment` are `http.ts:96, 122-123, 154`. Throttling, caching and retry therefore **cannot affect block validation or fork choice**.
- **The mint template's *content* becomes immutable chain data.** The client must be *transport-only* on the mint path:
1. Keep W1/W2/W3 request params byte-identical: `grnlimit`, `exchars=900`, `pithumbsize`, `cllimit=20` (no hidden filter, which feeds `category()` at `wiki.ts:17`), `clshow=!hidden`, `cllimit=50`, `lllimit=500`. They determine `article.category`, `languageCount` and `languagesTruncated`, and the percentile calibration. `tests/enrichment.test.ts:42-52` already pins part of this; add a golden URL test for W1. Adding `maxlag` is safe because it changes only error behaviour.
2. `getFresh` must bypass the persistent cache. `snapshotStats` stamps `capturedAt = new Date()` (`shared/enrichment.ts:41`), so cached data would be misdated.
3. **Existing bug that throttling would amplify.** A 429/5xx on the pageviews call is swallowed into `status:'unavailable'` (`enrichment.ts:145-164`). On the mint path that **permanently mints a card with `attention: null`**. With the new client, mint must fail the template (503, the miner retries) on 429/5xx/timeout, and record "unavailable" only on a genuine 404 or no-data. Both outcomes are valid blocks, so this is template policy, not a consensus change; it needs one owner and a test.
## 5. Scope: 4.5 h, about 10 agents, one integration branch
**Rules learned from Night 1:**
- **No stacked PRs.** Squash-merge makes every child PR conflict. Branch only from `night/2026-11-17` after the dependency has merged.
- **Contracts first:** `shared/duel/types.ts` and `docs/game/DUEL_API.md` merge by 22:15.
- **Node 24 everywhere** (`node:sqlite`; the Dockerfile uses `node:24-alpine`). Check `node -v` before `npm ci`.
- **No new npm dependencies.** The lead alone owns lockfile regeneration.
- **Test files:** top-level `tests/<team>-*.test.ts` only (`scripts/run-tests.mjs:7`).
**Workstreams** (9 workers plus the lead; ✱ = touches a shared file, one line or a small edit):
| WS | Owner paths | Delivers | Depends on |
|---|---|---|---|
| A duel-core | `shared/duel/{types,engine,ruleset,index}.ts`, `tests/duel-core*.test.ts`, `docs/game/DUEL_API.md` | turn and combat engine, `viewFor`/`logFor`, `replay`; **types PR by 22:15**, alpha by 23:15 | — |
| B duel-cards | `shared/duel/{derive,classify,effects,text}.ts`, `tests/duel-cards*.test.ts` | P31 → type table (from `card-sample.json` `instanceOf`, 236 cards), category fallback, P/T and cost curve, ≤8 effect templates, deterministic MTG-register rules text, flavour from `article.extract` | A types |
| C sim-balance | `shared/bots/duel-adapter.ts`, `scripts/sim/*duel*`, `docs/game/DUEL_BALANCE.md` | greedy and MC bots on duel; win rate by type and faction; ruleset number tuning (data-only PRs) | A alpha (23:15) |
| D wikimedia | `server/wikimedia/*`, `server/wiki.ts`, `server/enrichment.ts`, `server/wikimedia-user-agent.ts`, `tests/wikimedia-*.test.ts` | §4 client, mint-path fix, sqlite cache, UA; `trends.ts` unchanged (it goes through enrichment) | — (starts 21:30) |
| E identity | `server/game/identity.ts`, `scripts/night2/prebake-identity.ts` | background P31, links and plausibility via D's `background` lane; persistent per-token identity; pre-bakes testnet and mainnet cards | D interface (stub until merged), B input type |
| F ownership | `server/game/ownership.ts`, `server/game/collection.ts`, ✱`server/account/router.ts` (inject store, export auth), ✱`http.ts` (pass `{ledger, accounts}` into `gameRouter`) | `resolveDeck`, `GET /api/game/collection`, chain-pool draft source (option c) | — |
| G host-pvp | `server/game/{host,router,store,index,duel-binding}.ts`, `shared/game/modes.ts` (`engine` field), `deploy/night2/modes/*.json` | multi-engine host, constructed decks via F, account seats, private lobbies, invite, quick match, Elo, `?v=` polling | F function signature (agree by 22:00), A types |
| H ui-duel | `src/game/duel/*` (board, card face with type line, P/T, text, flavour; adapter; local bot practice) | playable vs bot in the browser | A types → A alpha |
| I ui-pvp+story | `src/game/OnlinePlay.tsx`, `online.ts`, `PlaySection.tsx`, `Leaderboards.tsx`, `src/game/recap/*`, `shared/duel/recap.ts` | collection deck picker, invite and quick-match UI, ladder, "Battle of X (2026)" recap rendered client-side by `replay` of `GET /matches/:id` (`router.ts:137`) | G API (stub), A log format |
| Lead | integration branch, `docs/night/*`, QA, REPORT | merges, lockfile, end-to-end on testnet with 2 Dex accounts | — |
Overlap is limited to the ✱ lines. `host.ts` is G's alone: F ships pure functions that G calls.
**Timeline (EST):**
| Time | Milestone |
|---|---|
| 21:30 | A, D and F start |
| 22:15 | types contract merged; B, G, H and I build against it |
| 23:15 | engine alpha; C starts sims; H plays vs bot |
| 00:00 | D merged; E live; G binds duel; I wired to G |
| 00:45 | balance v1 (data-only tuning) |
| 01:15 | **freeze** |
| 01:15–01:45 | QA PvP plus recap |
| 01:50 | REPORT |
| 02:00 | stop |
**Cut first, in order:**
1. WDQS/shared-property "Connected": keep article-link Connected only, or none.
2. Plausibility verification (G5): trust chain stats and document the gap.
3. Quick match: invite link and open lobbies suffice.
4. Elo ladder: keep W/L keyed by account.
5. Peer-hosted duel and wallet-signed deck claims.
6. Recap infobox polish: keep the plain encyclopedic log.
**Never cut:**
- the Wikimedia client (requirement 7: low risk, independent, and protects every later night)
- server-side ownership verification
- the duel core
- self-hosted PvP with owned or draft decks
- bot practice
**Biggest risks:**
1. Duel engine plus balance in about 2 h of real build time. Mitigation: no stack, atomic actions, effects as ≤8 templates.
2. UI combat readability. H must start on mock views at 22:15, not wait for the alpha.
3. Supply: 12 mainnet cards make a constructed duel unplayable without option (c) or (a). Make deck size and `libraryEmpty` ruleset data so Eric's decision is a mode file, not code.
+9 -4
View File
@@ -1,18 +1,23 @@
/** Binds the mode host to the real engine through its public API (shared/game/index.ts). */
import { DEFAULT_RULESET, parseRuleset, starterDeck, loanerCard, STARTER_POOL, validateDeck, createMatch,
import { DEFAULT_RULESET, parseRuleset, starterDeck, previewPool as engineLoaners, validateDeck, createMatch,
legalActions, applyAction, isOver, result, viewFor, Rng,
type Action, type GameCard, type MatchState, type Ruleset } from '../../shared/game/index.ts';
import type { EnginePort, Seat } from './engine-port.ts';
/**
* Deterministic pool of loaner (non-NFT) cards for draft modes: seeded shuffles of the
* starter pool, one copy per round, never exceeding the ruleset's per-page copy limit.
* Deterministic pool of loaner (non-NFT) cards for draft modes: seeded shuffles of the engine's
* frozen loaner cards (`previewPool(rules)`, derived with the mode's rules), one copy per round,
* never exceeding the ruleset's per-page copy limit. Copies get distinct cardIds.
*/
export function previewPool(rules: Ruleset, seed: string, size: number): GameCard[] {
const rng = Rng.fromSeed(`draft-pool:${seed}`);
const loaners = engineLoaners(rules);
const pool: GameCard[] = [];
for (let copy = 0; pool.length < size && copy < rules.maxCopiesPerPage; copy++) {
for (const spec of rng.shuffle(STARTER_POOL)) { if (pool.length >= size) break; pool.push(loanerCard(spec, copy)); }
for (const card of rng.shuffle(loaners)) {
if (pool.length >= size) break;
pool.push({ ...card, cardId: `${card.cardId}:${copy}` });
}
}
return pool;
}
+39
View File
@@ -212,6 +212,45 @@ export class ModeHost {
return r;
}
/**
* Live lobbies and matches as JSON, so a restart (e.g. a redeploy) doesn't lose games.
* Only the host's own data dir ever holds this; token hashes, never tokens, are stored.
*/
snapshot(): string {
const live = [...this.lobbies.values()].filter(l => l.phase === 'waiting' || l.phase === 'drafting' || l.phase === 'playing');
return JSON.stringify({ schema: 'wikideck-live-lobbies/1', savedAt: this.now(), lobbies: live.map(l => ({
...l, mode: { id: l.mode.id, version: l.mode.version },
players: l.players.map(p => ({ ...p, tokenHash: p.tokenHash.toString('hex') })) })) });
}
/**
* Restore a snapshot written by `snapshot()`. Lobbies whose mode is no longer hosted with the
* same version and rules are dropped. Timers restart from now, so nobody times out because
* the node was down. Returns how many lobbies were restored.
*/
restore(json: string): number {
const data = JSON.parse(json) as { schema?: string; lobbies?: any[] };
if (data.schema !== 'wikideck-live-lobbies/1' || !Array.isArray(data.lobbies)) return 0;
const now = this.now();
let restored = 0;
for (const raw of data.lobbies.slice(0, this.maxLobbies)) {
const h = this.hosted.get(raw?.mode?.id);
if (!h || h.mode.version !== raw.mode.version || JSON.stringify(h.rules) !== JSON.stringify(raw.rules)) continue;
if (typeof raw.id !== 'string' || !LOBBY_ID.test(raw.id) || this.lobbies.has(raw.id)) continue;
if (!['waiting', 'drafting', 'playing'].includes(raw.phase) || !Array.isArray(raw.players) || raw.players.length < 1 || raw.players.length > 2) continue;
const lobby: Lobby = { ...raw, mode: h.mode, rules: h.rules,
players: raw.players.map((p: any) => ({ id: String(p.id), name: String(p.name), seen: now, tokenHash: Buffer.from(String(p.tokenHash), 'hex') })),
lastMove: now, createdAt: raw.phase === 'waiting' ? now : raw.createdAt, turnStartedAt: now };
if (lobby.players.some(p => p.tokenHash.length !== 32)) continue;
if (lobby.draft && lobby.mode.decks.kind === 'draft') lobby.draft.deadline = now + lobby.mode.decks.pickSeconds * 1000;
if (lobby.phase === 'playing' && (lobby.state === undefined || !lobby.decks)) continue;
if (lobby.phase === 'drafting' && !lobby.draft) continue;
this.lobbies.set(lobby.id, lobby);
restored++;
}
return restored;
}
/** Expire idle lobbies, auto-pick stalled drafts, forfeit stalled matches, drop old lobbies. */
sweep(): void {
const now = this.now();
+33 -1
View File
@@ -3,6 +3,7 @@
* app.use('/api/game', await (await import('../game/index.ts')).gameRouter({ dataDir, enrichment: wikipediaEnrichment }));
*/
import { join } from 'node:path';
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import type express from 'express';
import { loadModes, hostIdentity, gamePeers } from './config.ts';
import { ModeDiscovery } from './discovery.ts';
@@ -15,7 +16,7 @@ import { TrendCache } from './trends.ts';
type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> };
export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment;
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean }): Promise<express.Router> {
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise<express.Router> {
const env = options.env ?? process.env;
const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding;
const modes = loadModes(env);
@@ -39,7 +40,38 @@ export async function gameRouter(options: { dataDir: string | null; enrichment?:
store: new MatchStore(options.dataDir ? join(options.dataDir, 'game') : null),
liveData: trends ? async pageId => trends!.get(pageId) : undefined });
const discovery = new ModeDiscovery({ peers: gamePeers(env) });
if (options.dataDir) persistLive(host, join(options.dataDir, 'game'), options.handleSignals !== false);
const timer = setInterval(() => host.sweep(), 5_000);
timer.unref();
return createGameRouter(host, discovery);
}
const MAX_LIVE_BYTES = 32 * 1024 * 1024;
/**
* Keep live lobbies and matches across restarts: restore `live.json` on start, save it every
* 15 s and synchronously on SIGTERM/SIGINT. These listeners are registered when the router is
* mounted, before the node's own shutdown handler, so the save finishes before it exits.
*/
export function persistLive(host: ModeHost, directory: string, handleSignals: boolean): { save(): void } {
const file = join(directory, 'live.json');
if (existsSync(file)) {
try {
const text = readFileSync(file, 'utf8');
if (text.length <= MAX_LIVE_BYTES) console.log(`Game modes: restored ${host.restore(text)} live lobbies`);
} catch (e) { console.error(`Game modes: could not restore live lobbies: ${(e as Error).message.slice(0, 200)}`); }
// Keep the file we restored from for inspection; the next save writes a fresh one.
try { renameSync(file, `${file}.restored`); } catch { /* ignore */ }
}
const save = () => {
try {
const tmp = `${file}.tmp`;
writeFileSync(tmp, host.snapshot(), { mode: 0o600 });
renameSync(tmp, file);
} catch (e) { console.error(`Game modes: could not save live lobbies: ${(e as Error).message.slice(0, 200)}`); }
};
const timer = setInterval(save, 15_000);
timer.unref();
if (handleSignals) for (const signal of ['SIGTERM', 'SIGINT'] as const) process.once(signal, save);
return { save };
}
+3 -1
View File
@@ -75,7 +75,9 @@ export function stateFromView(view: PlayerView, rng: Rng, filler: readonly GameC
const me = view.you, them = other(me);
const players = [] as unknown as [PlayerState, PlayerState];
players[me] = { deck: draw(view.deckCount), hand: view.hand, energy: view.energy, queue: view.queue, committed: view.committed, afk: 0, carry: 0 };
players[them] = { deck: draw(view.opponent.deckCount), hand: draw(view.opponent.handCount + view.opponent.queuedCount), energy: view.energy, queue: [], committed: false, afk: 0, carry: 0 };
// Before #38 handCount excludes queued cards and queuedCount exists; after #38 handCount is the full hand.
const o = view.opponent as { handCount: number; deckCount: number; queuedCount?: number };
players[them] = { deck: draw(o.deckCount), hand: draw(o.handCount + (o.queuedCount ?? 0)), energy: view.energy, queue: [], committed: false, afk: 0, carry: 0 };
let seq = 0;
const lanes = view.lanes.map(l => {
const cards = [] as unknown as [CardInPlay[], CardInPlay[]];
+4 -10
View File
@@ -3,7 +3,8 @@
* Pure and deterministic. The engine itself never reads raw 0–100 stats; hosts call
* deriveCard() before createMatch. Owner: engine-b.
*/
import { FACTION_KEYWORD, V1_KEYWORDS } from './keywords.ts';
import { FACTION_KEYWORD } from './keywords.ts';
import { DEFAULT_RULESET } from './ruleset.ts';
import { STATS, type Faction, type GameCard, type Rarity, type Stat } from './types.ts';
/** §1.4 tie-break order: depth and reach are the hardest to inflate. */
@@ -44,15 +45,8 @@ export interface DerivationRules {
uncheckedCostCap: number;
}
export const DEFAULT_DERIVATION: DerivationRules = {
costThresholds: [15, 35, 55, 75, 90],
powerByCost: [0, 1, 2, 4, 6, 8, 10],
vanillaBonus: 1,
keywordsEnabled: V1_KEYWORDS,
keywordParams: {},
trendUp: 25, trendDown: -200, trendMinDaily: 20, // −200: no down arrow in v1 (§1.6)
uncheckedCostCap: 4,
};
/** Derivation defaults are the engine's DEFAULT_RULESET (a Ruleset is a DerivationRules). */
export const DEFAULT_DERIVATION: DerivationRules = DEFAULT_RULESET;
/** §1.1: cut points strictly below, plus half of those equal, rounded down. */
export function percentile(score: number, cuts: readonly number[]): number {
+1 -1
View File
@@ -399,7 +399,7 @@ export function viewFor(state: MatchState, you: PlayerId): PlayerView {
you, ruleset: state.ruleset, turn: state.turn, phase: state.phase, initiative: state.initiative,
energy: me.energy, energyLeft: me.energy - queuedCost(me), hand: me.hand, queue: me.queue,
committed: me.committed, deckCount: me.deck.length,
opponent: { handCount: opp.hand.length - opp.queue.length, deckCount: opp.deck.length, queuedCount: opp.queue.length, committed: opp.committed },
opponent: { handCount: opp.hand.length, deckCount: opp.deck.length, committed: opp.committed },
lanes: state.lanes.map((lane, index) => {
const power = lanePower(state, index);
const mine = power[you], theirs = power[them];
+1 -1
View File
@@ -1,7 +1,7 @@
/** Public entry point of the WikiDeck game engine. Other teams import only from here. See docs/game/ENGINE_API.md. */
export * from './types.ts';
export { Rng, seedFromString, normalizeSeed, type RngState } from './rng.ts';
export { DEFAULT_RULESET, RULESET_V1_0, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts';
export { DEFAULT_RULESET, RULESET_V1_0, RULESET_V1_1, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts';
export {
ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor,
serialize, deserialize, replay, validateDeck, cardPower, lanePower, laneLeader, laneCapacity, scoringPower, topicsLed, other, placeCard, revealPortal,
+19 -2
View File
@@ -127,5 +127,22 @@ export const RULESET_V1_0: Ruleset = {
starterDecks: 'default',
};
/** DESIGN §9 defaults: the current rules version. */
export const DEFAULT_RULESET: Ruleset = RULESET_V1_0;
/**
* DESIGN §9 v1.1 (PR #32): config-only changes on top of v1.0. costThresholds are fame quantiles of the
* 236-card card-sample percentile table (#28), so they ship together with that table (shared/game/card-data.ts).
*/
export const RULESET_V1_1: Ruleset = {
...RULESET_V1_0,
version: '1.1',
costThresholds: [26, 39, 51, 63, 78],
cultureKeyword: 'home',
keywordParams: {
...RULESET_V1_0.keywordParams,
viral: { base: 1, amount: 1, cap: 3, powerDelta: 0 },
rising: { amount: 1, cap: 2, powerDelta: -1 },
encyclopedic: { amount: 2, sides: 1, powerDelta: 0 },
},
};
/** DESIGN §9 defaults: the current rules version (v1.1, BALANCE.md 00:45: ship #32 as is). */
export const DEFAULT_RULESET: Ruleset = RULESET_V1_1;
+5 -1
View File
@@ -210,7 +210,11 @@ export interface PlayerView {
queue: QueuedPlay[];
committed: boolean;
deckCount: number;
opponent: { handCount: number; deckCount: number; queuedCount: number; committed: boolean };
/**
* DESIGN §5.3: planning is hidden. handCount still counts queued cards and no
* opponent energy is exposed, so nothing changes while they queue; only `committed` does.
*/
opponent: { handCount: number; deckCount: number; committed: boolean };
lanes: {
/** Always visible; `portal` is null until the Portal is revealed. */
topic: TopicDef;
+2
View File
@@ -16,6 +16,7 @@ import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/netwo
import { StateClient } from '../shared/rpc-client.ts';
import { PlaySection } from './game/PlaySection.tsx';
import { isNativeApp } from './native.ts';
import { Landing } from './Landing.tsx';
import './App.css';
import './testnet.css';
@@ -182,6 +183,7 @@ export default function App() {
<div className="hero-copy"><span className="eyebrow"><span /> MINE · COLLECT · TRADE CARDS</span><h1>Mine with your CPU.<br />Collect <span>the world.</span></h1><p>Turn illustrated Wikipedia discoveries into collectible cards. Mine with RandomX, build a collection around what you love, and trade cards directly with other collectors.</p><div className="hero-actions"><button className="button dark" onClick={goMine}><Pickaxe size={17} /> Explore mining <ArrowUpRight size={17} /></button><button className="text-button" onClick={() => setDialog('guide')}>How it works <ArrowRight size={16} /></button></div><div className="hero-foot"><span><Check size={13} /> CPU-friendly RandomX</span><span><Check size={13} /> Direct card-for-card trades</span></div></div>
<div className="hero-visual"><div className="orbit orbit-one" /><div className="orbit orbit-two" /><span className="orbit-spark spark-one">✳</span><span className="orbit-spark spark-two">+</span><div className="floating-label label-top"><Sparkles size={12} /> Preview cards · not owned</div><div className="hero-card back-card"><Card card={samples[2]} onClick={() => setSelected(samples[2])} /></div><div className="hero-card front-card"><Card card={samples[0]} onClick={() => setSelected(samples[0])} /></div><div className="floating-label label-bottom"><Sparkles size={15} /> A world worth collecting <ArrowUpRight size={13} /></div></div>
</section>
<Landing onPlay={() => setView('Play')} />
<section className="metrics" aria-label="Canonical chain statistics">
<div><span className="metric-icon"><Layers3 size={19} /></span><div><span>Native NFTs minted</span><strong>{snapshot?.blocks.length.toLocaleString() ?? '—'}<small>canonical chain</small></strong></div></div>
<div><span className="metric-icon"><Globe2 size={19} /></span><div><span>Block height</span><strong>{snapshot ? `#${snapshot.blocks.at(-1)?.height ?? 0}` : '—'}<small>current tip</small></strong></div></div>
+24
View File
@@ -0,0 +1,24 @@
import { BookOpen, Globe2, Megaphone, Play, Swords } from 'lucide-react';
import './landing.css';
/** Game landing block (upstream WikiDeck/wikideck#3): explains Edit War and leads into Play. */
export function Landing({ onPlay, onHowToPlay }: { onPlay: () => void; onHowToPlay?: () => void }) {
return <section className="game-landing" aria-labelledby="game-landing-title">
<div className="game-landing-copy">
<div className="section-eyebrow"><Swords size={12} /> PLAY · EDIT WAR</div>
<h2 id="game-landing-title">Your cards are a deck. Play it.</h2>
<p>Edit War is a quick two-player card game, about 3–6 minutes a match. Each card is a Wikipedia article.
Its power comes from how famous the article is, and it is strongest in a Topic that matches its best stat.</p>
<ol className="game-landing-steps">
<li><span>1</span><div><strong>Three Topics</strong><p>Each is judged on one stat: <Megaphone size={12} aria-hidden="true" /> attention, <BookOpen size={12} aria-hidden="true" /> depth or <Globe2 size={12} aria-hidden="true" /> reach.</p></div></li>
<li><span>2</span><div><strong>Six turns</strong><p>Energy grows each turn. You and your opponent plan at the same time, then cards reveal one by one.</p></div></li>
<li><span>3</span><div><strong>Win two Topics</strong><p>Lead in more Topics than your opponent when turn 6 ends.</p></div></li>
</ol>
<p className="game-landing-note">No cards yet? Pick a starter deck and play right away. Matches are off-chain: no card is ever moved or burned.</p>
<div className="game-landing-actions">
<button className="button dark game-landing-play" onClick={onPlay}><Play size={15} /> Play now</button>
{onHowToPlay && <button className="text-button" onClick={onHowToPlay}>How to play</button>}
</div>
</div>
</section>;
}
+6 -4
View File
@@ -1,7 +1,7 @@
import { useEffect, useState, useSyncExternalStore } from 'react';
import { Link2, LoaderCircle, LogIn, LogOut, UserRound } from 'lucide-react';
import { getWallet, subscribeWallet, type Wallet } from '../wallet.ts';
import { account, completeLogin, isCallback, linkWallet, login, logout, subscribeAuth, type Account } from './session.ts';
import { account, authError, clearAuthError, completeLogin, isCallback, linkWallet, login, logout, subscribeAuth, type Account } from './session.ts';
import './auth.css';
export function useAccount(): Account | undefined {
@@ -20,6 +20,8 @@ const short = (s: string) => `${s.slice(0, 6)}…${s.slice(-4)}`;
export function LoginButton() {
const me = useAccount();
// Login failures from the web callback or a native deep link (completeLogin) land here.
const loginError = useSyncExternalStore(subscribeAuth, authError, () => '');
const [busy, setBusy] = useState(false);
const [open, setOpen] = useState(false);
const [notice, setNotice] = useState('');
@@ -30,7 +32,7 @@ export function LoginButton() {
setBusy(true);
completeLogin(location.href)
.then(({ returnTo }) => history.replaceState(null, '', returnTo))
.catch(e => { history.replaceState(null, '', '/'); setNotice(e instanceof Error ? e.message : 'Login failed'); })
.catch(() => { history.replaceState(null, '', '/'); })
.finally(() => setBusy(false));
}, []);
useEffect(() => {
@@ -39,7 +41,7 @@ export function LoginButton() {
}, []);
const run = async (fn: () => Promise<unknown>) => {
setBusy(true); setNotice('');
setBusy(true); setNotice(''); clearAuthError();
try { await fn(); } catch (e) { setNotice(e instanceof Error ? e.message : 'Request failed'); }
finally { setBusy(false); }
};
@@ -49,7 +51,7 @@ export function LoginButton() {
<span className="wallet-avatar">{busy ? <LoaderCircle className="spin" size={14} /> : <LogIn size={14} />}</span>
<span className="auth-label">Log in with eom.dev</span>
</button>
{notice && <span className="auth-notice" role="alert">{notice}</span>}
{(notice || loginError) && <span className="auth-notice" role="alert">{notice || loginError}</span>}
</span>;
const linked = wallet && me.wallets.some(w => w.address === wallet.address);
+16
View File
@@ -33,6 +33,11 @@ function save(s: Session | undefined) {
try { if (s) sessionStorage.setItem(SESSION_KEY, JSON.stringify(s)); else sessionStorage.removeItem(SESSION_KEY); } catch { /* memory only */ }
notify();
}
let loginError = '';
/** Last login failure (expired, state mismatch, cancelled, invalid_grant…), for the UI; '' when none. */
export const authError = (): string => loginError;
export function clearAuthError(): void { if (loginError) { loginError = ''; notify(); } }
export function account(): Account | undefined {
if (current && current.expiresAt <= Date.now() + 30_000) save(undefined);
return current?.account;
@@ -102,6 +107,17 @@ export const isCallback = (url: string) => {
/** Finish a login from the redirect URL. Web: called on load. Capacitor: call from App 'appUrlOpen'. */
export async function completeLogin(url: string): Promise<{ returnTo: string }> {
try {
const result = await finishLogin(url);
clearAuthError();
return result;
} catch (e) {
loginError = (e instanceof Error ? e.message : 'Login failed').slice(0, 200); notify();
throw e;
}
}
async function finishLogin(url: string): Promise<{ returnTo: string }> {
const params = new URL(url).searchParams;
const raw = sessionStorage.getItem(PENDING_KEY);
sessionStorage.removeItem(PENDING_KEY); // single use
+13 -9
View File
@@ -7,8 +7,8 @@ import type { LaneView, MatchView, UIAction, UICard } from './types.ts';
type Sheet = { kind: 'card'; card: UICard; side: 'mine' | 'theirs' } | { kind: 'lane'; lane: LaneView } | { kind: 'concede' } | null;
/** The match screen itself: board, thumb dock and bottom sheets. Controllers (local bot / hosted lobby) feed it. */
export function MatchBoard({ title, opponent, view, legal, onAct, problem, error, onTopicBonus }: {
title: string; opponent: string; view: MatchView; legal: UIAction[]; onAct: (a: UIAction) => void;
export function MatchBoard({ title, opponent, view, legal, onAct, problem, error, onTopicBonus, onResults }: {
onResults?: () => void; title: string; opponent: string; view: MatchView; legal: UIAction[]; onAct: (a: UIAction) => void;
problem?: (a: UIAction) => string | null; error?: string; onTopicBonus: number[];
}) {
const [selected, setSelected] = useState<string>();
@@ -45,12 +45,13 @@ export function MatchBoard({ title, opponent, view, legal, onAct, problem, error
else setSheet({ kind: 'lane', lane });
};
const ending = view.waitingForOpponent;
const queuedCount = view.lanes.reduce((n, l) => n + l.staged.length, 0);
const lastEvent = view.log.at(-1);
return <section className="match" aria-label={title}>
<header className="match-bar">
<span className="match-turn"><Hourglass size={14} /> Turn <b>{view.turn}</b>/{view.maxTurns}</span>
<span className="match-opp" aria-label={`Opponent: ${view.oppHandCount} cards in hand, ${view.oppDeckCount} in deck`}>{opponent} · <Layers3 size={13} /> {view.oppHandCount}{view.oppQueued ? ` · ${view.oppQueued} queued` : ''}</span>
<span className="match-opp" aria-label={`Opponent: ${view.oppHandCount} cards in hand, ${view.oppDeckCount} in deck`}>{opponent} · <Layers3 size={13} /> {view.oppHandCount}</span>
<button className="icon-button" onClick={() => setSheet({ kind: 'concede' })} aria-label="Concede match"><Flag size={16} /></button>
</header>
{banner && <div className="turn-banner" role="status">{banner}</div>}
@@ -67,11 +68,11 @@ export function MatchBoard({ title, opponent, view, legal, onAct, problem, error
</div>
<button className={`lane-plate ${lead}`} onClick={() => tapLane(lane)}
aria-label={target ? `Play ${sel!.title} to ${lane.name}${onTopic ? `, on-topic +${topicBonus}` : ''}` : `${lane.name} Topic (${STAT_LABEL[lane.stat]}): you ${lane.myPower}, opponent ${lane.theirPower}. ${lane.modifier?.text ?? lane.portalNote ?? ''}`}>
<span className="lane-score theirs" aria-hidden="true"><small>Opp</small>{lane.theirPower}</span>
<span className="lane-score theirs" aria-hidden="true"><small>Opp</small>{lane.theirPower}{!!lane.scoringBonus?.[1] && <small className="lane-bonus">+{lane.scoringBonus[1]}</small>}</span>
<span className="lane-name"><StatIcon stat={lane.stat} size={13} /><span>{lane.name}</span>{!lane.revealed && <small>?</small>}
{lane.modifier && <small className="lane-rule">{lane.modifier.text}</small>}
{lane.myPower === lane.theirPower && lane.leader && <small className="lane-tie">Tie: {lane.leader === 'you' ? 'you lead' : 'they lead'} on-topic</small>}</span>
<span className="lane-score mine" aria-hidden="true"><small>You</small>{lane.myPower}</span>
<span className="lane-score mine" aria-hidden="true"><small>You</small>{lane.myPower}{!!lane.scoringBonus?.[0] && <small className="lane-bonus">+{lane.scoringBonus[0]}</small>}</span>
</button>
<div className="lane-side mine" aria-label={`Your cards in ${lane.name}`}>
{lane.mine.map(c => <GameCard key={c.id} card={c} size="board" fresh={fresh.has(c.id)} onClick={() => setSheet({ kind: 'card', card: c, side: 'mine' })} />)}
@@ -84,7 +85,8 @@ export function MatchBoard({ title, opponent, view, legal, onAct, problem, error
<div className="play-dock match-dock">
<p className="dock-note" role="status" aria-live="polite">
{error ? <span className="dock-error">{error}</span>
{view.over ? <>Final board. Topic totals include at-scoring Portals (+N).</>
: error ? <span className="dock-error">{error}</span>
: ending ? <><LoaderCircle className="spin" size={14} /> Opponent is choosing…</>
: sel ? <><Zap size={12} /> <b>{sel.title}</b>{sel.keyword ? ` · ${sel.keyword.name}: ${sel.keyword.text}` : ''} Tap a lane.</>
: lastEvent}
@@ -100,9 +102,11 @@ export function MatchBoard({ title, opponent, view, legal, onAct, problem, error
<b>{view.energy}</b>
</span>
<span className="deck-count"><Layers3 size={13} /> {view.deckCount}</span>
<button className="button dark end-turn" disabled={ending || view.over} onClick={() => { setSelected(undefined); act({ type: 'endTurn' }); }}>
{ending ? 'Waiting…' : view.turn === view.maxTurns ? 'End match' : 'End turn'}
</button>
{view.over ? <button className="button dark end-turn" onClick={onResults} disabled={!onResults}>See results</button>
: <button className={`button ${queuedCount ? 'dark' : 'outline'} end-turn`} disabled={ending} onClick={() => { setSelected(undefined); act({ type: 'endTurn' }); }}
aria-label={queuedCount ? undefined : 'Pass this turn without playing a card'}>
{ending ? 'Waiting…' : !queuedCount ? 'Pass' : view.turn === view.maxTurns ? 'End match' : 'End turn'}
</button>}
</div>
</div>
+1 -2
View File
@@ -23,7 +23,6 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
const view = useMemo(() => engine.view(state, 0), [state]);
const legal = useMemo(() => engine.legal(state, 0), [state]);
useEffect(() => { if (engine.isOver(state)) { const t = setTimeout(() => onFinish(engine.result(state, 0)), 900); return () => clearTimeout(t); } }, [state, onFinish]);
// The bot moves once the player has committed (it never sees the player's queued plays).
useEffect(() => {
@@ -47,5 +46,5 @@ export function MatchScreen({ mode, deck, opponentDeck, bot, seed, onFinish }: {
catch (e) { setError(e instanceof Error ? e.message : 'That move isn’t allowed.'); }
};
return <MatchBoard title={`${mode.name} match`} opponent={`${bot.name} bot`} view={view} legal={legal} onAct={act} error={error}
problem={a => engine.problem(state, 0, a)} onTopicBonus={mode.ruleset.onTopicBonus} />;
problem={a => engine.problem(state, 0, a)} onResults={engine.isOver(state) ? () => onFinish(engine.result(state, 0)) : undefined} onTopicBonus={mode.ruleset.onTopicBonus} />;
}
+3 -13
View File
@@ -23,7 +23,6 @@ export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const inFlight = useRef(false);
const finished = useRef(false);
const done = status?.phase === 'finished' || status?.phase === 'expired';
const refreshLobbies = useCallback(() => {
@@ -50,17 +49,7 @@ export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
return () => clearInterval(t);
}, [seat, poll, done]);
// Once finished, stop polling and show results after a beat. The timer must survive later
// re-renders, so it is only cleared on unmount.
const finishTimer = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => {
const st = status?.state;
if (finished.current || !status || !seat || status.phase !== 'finished' || !st?.result) return;
finished.current = true;
const names = st.lanes.map(l => l.topic.name);
finishTimer.current = setTimeout(() => onFinish(resultView(st.result!, seat.seat, names, st.lanes.map(l => l.leader))), 900);
}, [status, seat, onFinish]);
useEffect(() => () => clearTimeout(finishTimer.current), []);
// Once finished, stop polling; the final board stays up until the player opens the results.
const enter = async (fn: () => Promise<LobbySeat>) => {
setBusy(true); setError('');
@@ -106,7 +95,8 @@ export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
return void send(() => online.act(seat, engineAction(a, seat.seat)));
};
return <MatchBoard title={`${mode.name} online match`} opponent={opp.slice(0, 24)} view={view} legal={legal} onAct={act}
error={error} onTopicBonus={status.state.ruleset.onTopicBonus} />;
error={error} onTopicBonus={status.state.ruleset.onTopicBonus}
onResults={status.state.result ? () => onFinish(resultView(status.state!.result!, seat.seat, status.state!.lanes.map(l => l.topic.name), status.state!.lanes.map(l => l.leader))) : undefined} />;
}
// ----- draft -----
+1 -1
View File
@@ -14,7 +14,7 @@ export function Results({ result, modeName, onRematch, onLobby }: { result: Resu
: `You won ${won} of ${result.lanes.length} Topics${tiebreak ? ', so total power decided it' : ''}.`}</p>
<ol className="result-lanes">
{result.lanes.map(l => <li key={l.name} className={l.winner === 0 ? 'won' : l.winner === 1 ? 'lost' : 'tied'}>
<span>{l.name}</span><b>{l.myPower} – {l.theirPower}</b><small>{l.winner === 0 ? 'Won' : l.winner === 1 ? 'Lost' : 'Tied'}</small>
<span>{l.name}</span><b>{l.myPower} – {l.theirPower}</b><small>{l.winner === 0 ? 'Won' : l.winner === 1 ? 'Lost' : 'Tied'}</small>{l.winner !== null && l.myPower === l.theirPower && <small className="tie-note">Tie, decided by on-topic cards</small>}
</li>)}
</ol>
<p className="muted small">Matches are off-chain. No card was moved or burned.</p>
+10 -3
View File
@@ -88,6 +88,9 @@ function capacityFromView(v: PlayerView, i: number): number {
export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capacity?: (lane: number) => number } = {}): MatchView {
const rules = v.ruleset;
const me = v.you;
const opp = me === 0 ? 1 : 0;
// After the last turn, show scoring power (incl. "at scoring" Portals) from the result, from my side.
const final = v.result ? v.result.lanePower.map(p => [p[me], p[opp]] as [number, number]) : undefined;
const onBoard = (c: CardInPlay, power: number, stat: string, allOnTopic: boolean) =>
toUICard(c.card, rules, { id: `${c.owner}:${c.card.cardId}`, power, onTopic: allOnTopic || c.card.home === stat }); // both seats may share loaner cardIds
const lanes: LaneView[] = v.lanes.map((lane, i) => {
@@ -101,9 +104,13 @@ export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capaci
theirs: lane.cards[1].map((c, k) => onBoard(c, lane.cardPower[1][k], lane.topic.stat, allOn)),
staged: v.queue.filter(q => q.lane === i).flatMap(q => {
const c = v.hand.find(h => h.cardId === q.cardId);
return c ? [toUICard(c, rules)] : [];
if (!c) return [];
const onTopic = allOn || c.home === lane.topic.stat;
const power = Math.max(0, c.power + c.trend + (onTopic ? rules.onTopicBonus[c.cost] ?? 0 : 0));
return [toUICard(c, rules, { power, onTopic })];
}),
myPower: lane.power[0], theirPower: lane.power[1], leader: lane.leader,
myPower: final ? final[i][0] : lane.power[0], theirPower: final ? final[i][1] : lane.power[1], leader: lane.leader,
scoringBonus: final ? [final[i][0] - lane.power[0], final[i][1] - lane.power[1]] as [number, number] : undefined,
capacity: opts.capacity ? opts.capacity(i) : capacityFromView(v, i),
};
});
@@ -112,7 +119,7 @@ export function viewFromPlayerView(v: PlayerView, opts: { log?: string[]; capaci
me, turn: v.turn, maxTurns: rules.turns, energy: v.energyLeft, maxEnergy: v.energy,
saved: Math.max(0, v.energy - (rules.energyByTurn[v.turn - 1] ?? 0) - rules.bonusEnergy),
hand: v.hand.filter(c => !queued.has(c.cardId)).map(c => toUICard(c, rules)), deckCount: v.deckCount,
oppHandCount: v.opponent.handCount, oppDeckCount: v.opponent.deckCount, oppQueued: v.opponent.queuedCount,
oppHandCount: v.opponent.handCount, oppDeckCount: v.opponent.deckCount,
lanes, log: opts.log ?? [], waitingForOpponent: v.committed && v.phase !== 'over', over: v.phase === 'over',
};
}
+2
View File
@@ -205,3 +205,5 @@ html.wd-in-match .auth-wrap,body:has(.match) .auth-wrap{display:none}
@media(max-width:480px){.hide-narrow{display:none}.play-actions{flex-wrap:nowrap}.play-actions .button{padding-inline:12px}}
.show-narrow{display:none}
@media(max-width:480px){.show-narrow{display:inline}.play-actions .button{min-width:0}}
.lane-bonus{color:var(--ctp-yellow)!important;margin-left:2px}
.result-lanes .tie-note{font-size:10px;color:var(--ctp-yellow);line-height:1.3}
+1 -1
View File
@@ -39,6 +39,7 @@ export type LaneView = {
theirPower: number;
leader: 'you' | 'opponent' | null;
capacity: number;
scoringBonus?: [number, number]; // at-scoring Portal adjustments (mine, theirs), match over only
};
export type MatchView = {
@@ -52,7 +53,6 @@ export type MatchView = {
deckCount: number;
oppHandCount: number;
oppDeckCount: number;
oppQueued: number;
lanes: LaneView[];
log: string[]; // newest last, this seat's events only
waitingForOpponent: boolean;
+15
View File
@@ -0,0 +1,15 @@
.game-landing{margin:24px 0;padding:24px;border:1px solid var(--theme-border);border-radius:12px;background:var(--ctp-mantle)}
.game-landing .section-eyebrow{display:flex;align-items:center;gap:6px;color:var(--theme-accent)}
.game-landing h2{font-size:24px;line-height:1.25;letter-spacing:-.5px;margin:12px 0}
.game-landing p{font-size:13px;line-height:1.75;color:var(--ctp-subtext0);margin:0 0 14px;max-width:720px}
.game-landing-steps{list-style:none;padding:0;margin:18px 0;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}
.game-landing-steps li{display:flex;gap:12px;align-items:flex-start;padding:14px;border-radius:10px;background:var(--ctp-base);border:1px solid var(--theme-border)}
.game-landing-steps li>span{flex:none;display:grid;place-items:center;width:28px;height:28px;border-radius:50%;background:var(--theme-accent);color:var(--ctp-base);font-weight:700;font-size:13px}
.game-landing-steps strong{display:block;font-size:14px;color:var(--ctp-text);margin-bottom:4px}
.game-landing-steps p{font-size:12px;line-height:1.6;margin:0}
.game-landing-steps svg{vertical-align:-2px}
.game-landing-note{font-size:12px!important}
.game-landing-actions{display:flex;align-items:center;gap:18px;flex-wrap:wrap}
.game-landing .game-landing-play{min-height:44px;height:auto;padding:12px 22px;font-size:12px;gap:8px}
@media(max-width:800px){.game-landing-steps{grid-template-columns:1fr}}
@media(max-width:480px){.game-landing{padding:18px 16px}.game-landing h2{font-size:20px}.game-landing .game-landing-play{width:100%;justify-content:center}}
+10
View File
@@ -2,6 +2,7 @@
// On the web it does nothing: relative `/api/...` requests keep going to the serving origin.
import { Capacitor } from '@capacitor/core';
import { App } from '@capacitor/app';
import { Browser } from '@capacitor/browser';
import './native.css';
/** True inside the Android/iOS app shell. Use it to hide desktop-only features such as RandomX mining. */
@@ -84,4 +85,13 @@ if (isNativeApp()) {
if (parsed.protocol !== 'dev.eom.wikideck:') return;
if (deepLinkHandlers.size) deepLinkHandlers.forEach(h => h(parsed)); else pendingDeepLink = parsed;
});
// eom.dev SSO (src/auth, sso team). Imported lazily so this module still runs before anything else.
// Login opens Dex in the system browser (Custom Tab); the redirect comes back as a deep link.
const auth = import('./auth/session.ts');
void auth.then(({ setNativeBrowser }) => setNativeBrowser(Browser));
onDeepLink(url => {
void auth.then(({ isCallback, completeLogin }) => {
if (isCallback(url.href)) return completeLogin(url.href);
}).catch(error => console.warn('[native] SSO callback failed', error));
});
}
+21
View File
@@ -31,3 +31,24 @@ test('account native: login opens the system browser with PKCE and the app redir
assert.equal(auth.isCallback(`dev.eom.wikideck:/oauth/callback?code=c&state=${pending.state}`), true);
} finally { Object.assign(g, saved); }
});
test('account native: completeLogin failures are exposed to the UI via authError', async () => {
const g = globalThis as Record<string, unknown>;
const saved = { Capacitor: g.Capacitor, sessionStorage: g.sessionStorage };
const store = new Map<string, string>();
g.sessionStorage = { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); },
removeItem: (k: string) => { store.delete(k); } };
g.Capacitor = { isNativePlatform: () => true, Plugins: {} };
try {
const auth = await import('../src/auth/session.ts');
let events = 0; const off = auth.subscribeAuth(() => { events++; });
store.set('wikideck.auth.pending', JSON.stringify({ state: 'real-state', nonce: 'n', verifier: 'v', redirectUri: 'dev.eom.wikideck:/oauth/callback',
returnTo: '/', createdAt: Date.now() }));
await assert.rejects(auth.completeLogin('dev.eom.wikideck:/oauth/callback?code=c&state=forged'), /state mismatch/);
assert.match(auth.authError(), /state mismatch/);
assert.ok(events >= 1, 'subscribers are notified');
auth.clearAuthError();
assert.equal(auth.authError(), '');
off();
} finally { Object.assign(g, saved); }
});
+24 -1
View File
@@ -88,7 +88,6 @@ test('queued plays are hidden until reveal; undo refunds; committed seats get no
assert.ok(play, 'turn 1 should have a 1-cost play');
state = applyAction(state, play);
assert.equal(viewFor(state, 0).energyLeft, 0);
assert.equal(viewFor(state, 1).opponent.queuedCount, 1);
assert.equal(JSON.stringify(viewFor(state, 1)).includes(`"${play.cardId}"`), false);
assert.equal(viewFor(applyAction(state, { type: 'undo', player: 0, cardId: play.cardId }), 0).energyLeft, 1);
state = commit(state, 0);
@@ -111,6 +110,30 @@ test('viewFor never leaks the opponent hand, deck order, queue, seed or RNG stat
assert.deepEqual(view.hand.map(c => c.cardId), state.players[0].hand.map(c => c.cardId));
});
test('planning is hidden: the opponent view is identical before and after queuing, until commit', () => {
for (let seed = 0; seed < 10; seed++) {
let state = createMatch(DEFAULT_RULESET, decks(`plan-${seed}`), seed);
for (let turn = 0; turn < 4 && !isOver(state); turn++) {
const before = JSON.stringify(viewFor(state, 1));
let queued = 0;
for (;;) {
const play = legalActions(state, 0).find(a => a.type === 'play');
if (!play) break;
state = applyAction(state, play);
queued++;
assert.equal(JSON.stringify(viewFor(state, 1)), before, `seed ${seed} turn ${state.turn}: view changed after ${queued} queued`);
}
if (queued) {
const undo = legalActions(state, 0).find(a => a.type === 'undo')!;
assert.equal(JSON.stringify(viewFor(applyAction(state, undo), 1)), before, 'undo must not show either');
}
state = commit(state, 0);
assert.equal(viewFor(state, 1).opponent.committed, true);
state = commit(state, 1);
}
}
});
test('energy: energyByTurn + carry (max 1) of unspent energy', () => {
let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 3);
const first = state.players[0].hand[0].cardId;
+15 -15
View File
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
DEFAULT_DERIVATION, percentile, percentiles, fame, costFor, homeStat, trendFor, keywordFor, deriveCard, deriveDeck,
RULESET_V1_0, percentile, percentiles, fame, costFor, homeStat, trendFor, keywordFor, deriveCard, deriveDeck,
type CardInput, type PercentileTable, type DerivationRules, type Faction,
} from '../shared/game/index.ts';
import { forAll } from './game/property.ts';
@@ -9,7 +9,7 @@ import { forAll } from './game/property.ts';
/** Cut points 1..99: score s sits at percentile ~s, which makes examples readable. */
const LINEAR = Array.from({ length: 99 }, (_, i) => i + 1);
const TABLE: PercentileTable = { attention: LINEAR, depth: LINEAR, reach: LINEAR };
const RULES = DEFAULT_DERIVATION;
const RULES: DerivationRules = RULESET_V1_0; // pinned: these examples are v1.0 numbers
const LIVE = { trendPercent: null, dailyAverage: null };
function input(stats: CardInput['snapshot']['stats'], overrides: Partial<CardInput> = {}): CardInput {
@@ -76,10 +76,10 @@ test('keyword choice: cost 1 vanilla, faction keyword otherwise, disabled → pl
test('deriveCard: cost, power, vanillaBonus, home, trend and source', () => {
// pct 80/70/60 → fame 70 → cost 4 → power 6, Science → encyclopedic
const card = deriveCard(input({ attention: 81, depth: 71, reach: 61 }, { live: { trendPercent: 40, dailyAverage: 50 } }), TABLE);
const card = deriveCard(input({ attention: 81, depth: 71, reach: 61 }, { live: { trendPercent: 40, dailyAverage: 50 } }), TABLE, RULES);
assert.deepEqual(card, { cardId: 'c1', pageId: 1, title: 'T', faction: 'Science', rarity: 'Common',
cost: 4, power: 6, home: 'attention', trend: 1, keyword: 'encyclopedic', source: 'owned', check: 'verified' });
const cheap = deriveCard(input({ attention: 5, depth: 5, reach: 5 }, { check: 'loaner' }), TABLE);
const cheap = deriveCard(input({ attention: 5, depth: 5, reach: 5 }, { check: 'loaner' }), TABLE, RULES);
assert.deepEqual([cheap.cost, cheap.power, cheap.keyword, cheap.source], [1, 2, null, 'loaner']);
const disabled = deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE, { ...RULES, keywordsEnabled: [] });
assert.deepEqual([disabled.power, disabled.keyword], [6, null]);
@@ -87,14 +87,14 @@ test('deriveCard: cost, power, vanillaBonus, home, trend and source', () => {
test('rarity is cosmetic: it never changes cost, power or keyword (§1.7)', () => {
const stats = { attention: 40, depth: 60, reach: 20 };
const cards = (['Common', 'Rare', 'Epic', 'Legendary'] as const).map(rarity => deriveCard(input(stats, { rarity }), TABLE));
const cards = (['Common', 'Rare', 'Epic', 'Legendary'] as const).map(rarity => deriveCard(input(stats, { rarity }), TABLE, RULES));
for (const card of cards) assert.deepEqual({ ...card, rarity: 'Common' }, { ...cards[0], rarity: 'Common' });
});
test('unchecked cards are capped at uncheckedCostCap and keep their home stat (§1.10)', () => {
const stats = { attention: 100, depth: 100, reach: 99 };
const checked = deriveCard(input(stats), TABLE);
const unchecked = deriveCard(input(stats, { check: 'unchecked' }), TABLE);
const checked = deriveCard(input(stats), TABLE, RULES);
const unchecked = deriveCard(input(stats, { check: 'unchecked' }), TABLE, RULES);
assert.equal(checked.cost, 6);
assert.equal(unchecked.cost, 4);
assert.equal(unchecked.power, RULES.powerByCost[4]);
@@ -114,18 +114,18 @@ test('deriveDeck marks copies for Edition when it is enabled', () => {
const c = { ...a, cardId: 'c', pageId: 8 };
const rules = { ...RULES, keywordsEnabled: [...RULES.keywordsEnabled, 'edition'] };
assert.deepEqual(deriveDeck([a, b, c], TABLE, rules).map(card => card.keyword), ['edition', 'edition', 'viral']);
assert.deepEqual(deriveDeck([a, b, c], TABLE).map(card => card.keyword), ['viral', 'viral', 'viral']);
assert.deepEqual(deriveDeck([a, b, c], TABLE, RULES).map(card => card.keyword), ['viral', 'viral', 'viral']);
});
test('power depends only on cost: forged stats only move a card up the curve (§1.3)', () => {
forAll(300, g => {
const stats = { attention: g.bool(0.1) ? null : g.int(0, 100), depth: g.int(0, 100), reach: g.int(0, 100) };
const card = deriveCard(input(stats, { category: g.pick(['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const) }), TABLE);
const card = deriveCard(input(stats, { category: g.pick(['Space', 'Nature', 'People', 'Science', 'History', 'Culture'] as const) }), TABLE, RULES);
assert.ok(card.cost >= 1 && card.cost <= 6);
assert.equal(card.power, RULES.powerByCost[card.cost] + (card.cost === 1 ? RULES.vanillaBonus : 0));
assert.ok(stats[card.home] !== null, 'home is never a null stat');
const bumped = { ...stats, depth: Math.min(100, stats.depth + g.int(1, 30)) };
assert.ok(deriveCard(input(bumped), TABLE).cost >= card.cost, 'raising a stat never lowers cost');
assert.ok(deriveCard(input(bumped), TABLE, RULES).cost >= card.cost, 'raising a stat never lowers cost');
});
});
@@ -136,19 +136,19 @@ test('deriveCard rejects a rules config with no power for the derived cost', ()
test('pinned values replace §1.1–1.5 for loaners only (§2.1)', () => {
const pinned = { cost: 5, home: 'reach' as const, faction: 'History' as const };
const stats = { attention: 5, depth: 5, reach: 5 };
const loaner = deriveCard(input(stats, { check: 'loaner', pinned, rarity: 'Epic', live: { trendPercent: 99, dailyAverage: 999 } }), TABLE);
const loaner = deriveCard(input(stats, { check: 'loaner', pinned, rarity: 'Epic', live: { trendPercent: 99, dailyAverage: 999 } }), TABLE, RULES);
assert.deepEqual([loaner.cost, loaner.power, loaner.home, loaner.faction, loaner.keyword, loaner.rarity, loaner.trend, loaner.source],
[5, 8, 'reach', 'History', 'nostalgic', 'Common', 0, 'loaner']);
const owned = deriveCard(input(stats, { pinned }), TABLE);
const owned = deriveCard(input(stats, { pinned }), TABLE, RULES);
assert.deepEqual([owned.cost, owned.faction], [1, 'Science'], 'pinned is ignored when check !== loaner');
const cheap = deriveCard(input(stats, { check: 'loaner', pinned: { ...pinned, cost: 1 } }), TABLE);
const cheap = deriveCard(input(stats, { check: 'loaner', pinned: { ...pinned, cost: 1 } }), TABLE, RULES);
assert.deepEqual([cheap.power, cheap.keyword], [2, null], 'vanillaBonus still applies to pinned cost-1');
});
test('cultureKeyword (v1.1 hook): home gives Culture cards {attention: viral, depth: encyclopedic, reach: translated}', () => {
const home = { ...RULES, cultureKeyword: 'home' as const };
const culture = (stats: CardInput['snapshot']['stats']) => input(stats, { category: 'Culture' });
assert.equal(deriveCard(culture({ attention: 80, depth: 40, reach: 40 }), TABLE).keyword, 'viral', 'v1 default: faction');
assert.equal(deriveCard(culture({ attention: 80, depth: 40, reach: 40 }), TABLE, RULES).keyword, 'viral', 'v1 default: faction');
assert.equal(deriveCard(culture({ attention: 80, depth: 40, reach: 40 }), TABLE, home).keyword, 'viral');
assert.equal(deriveCard(culture({ attention: 40, depth: 80, reach: 40 }), TABLE, home).keyword, 'encyclopedic');
assert.equal(deriveCard(culture({ attention: 40, depth: 40, reach: 80 }), TABLE, home).keyword, 'translated');
@@ -160,7 +160,7 @@ test('a full Ruleset works as DerivationRules (hosts can derive with the mode ru
const { DEFAULT_RULESET } = await import('../shared/game/index.ts');
const a = deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE, DEFAULT_RULESET);
const b = deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE);
assert.deepEqual(a, b);
assert.deepEqual(a, b, 'default derivation rules are DEFAULT_RULESET');
});
test('parseRuleset accepts a stored pre-v1.1 ruleset without cultureKeyword (defaults to faction)', async () => {
+32 -5
View File
@@ -8,7 +8,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
RULESET_V1_0, applyAction, createMatch, isOver, lanePower, result, starterDeck, topicsLed,
RULESET_V1_0, RULESET_V1_1, applyAction, createMatch, isOver, lanePower, result, starterDeck, topicsLed,
type Action, type GameCard, type MatchState, type PlayerId, type Ruleset, type Stat, type Faction,
} from '../shared/game/index.ts';
@@ -54,16 +54,19 @@ const PLAN: [PlayerId, string, number][][] = [
[[1, 'Fern', T1], [0, 'Library of Alexandria', T1], [1, 'Mona Lisa', T2], [0, 'Periodic table', T2]],
];
function setup(): MatchState {
const rules: Ruleset = structuredClone(RULESET_V1_0); // §12 is pinned to the v1.0 ruleset
function setup(base: Ruleset = RULESET_V1_0): MatchState {
const rules: Ruleset = structuredClone(base); // §12 is pinned to the v1.0 ruleset; §12.1 passes v1.1
const state = createMatch(rules, [starterDeck('golden-a'), starterDeck('golden-b')], 1);
const pool = state.ruleset.topicPool;
const find = (id: string) => pool.find(t => t.id === id) ?? assert.fail(`topic ${id} missing from the default pool`);
const topics = [find('archive'), find('main-page'), find('translations')];
state.lanes = topics.map(topic => ({ topic, portalRevealed: false, cards: [[], []] }));
// Inject: every card the example plays starts in hand, nothing left to draw.
state.players[0].hand = structuredClone(ANA);
state.players[1].hand = structuredClone(BO);
// The §12 table gives v1.0-derived cards; under another ruleset apply its keyword powerDelta (§10.1).
const adjust = (cards: GameCard[]) => cards.map(c => ({ ...c,
power: c.power + (c.keyword ? (rules.keywordParams[c.keyword]?.powerDelta ?? 0) : 0) }));
state.players[0].hand = adjust(structuredClone(ANA));
state.players[1].hand = adjust(structuredClone(BO));
for (const p of state.players) p.deck = [];
state.initiative = 0; // Ana has initiative on odd turns
return state;
@@ -122,3 +125,27 @@ test('§12 golden: per-turn Topic powers match the table', opts, () => {
assert.deepEqual(state.lanes.map((_, lane) => lanePower(state, lane)), expected[turn], `after turn ${turn + 1}`);
});
});
test('§12.1 golden (v1.1 ruleset): 18–14, 15–21, 13–11; Ana wins 2–1; T1 8–8 consensus to Ana after turn 5', () => {
let state = setup(RULESET_V1_1);
const after: [number, number][][] = [];
for (const plays of PLAN) {
state = playTurn(state, plays);
after.push(state.lanes.map((_, lane) => lanePower(state, lane)));
}
assert.deepEqual(after.slice(0, 5), [
[[3, 0], [0, 3], [0, 0]],
[[4, 0], [0, 3], [3, 0]],
[[7, 0], [0, 9], [3, 3]],
[[8, 0], [9, 9], [3, 10]],
[[8, 8], [9, 10], [13, 11]],
]);
const r = result(state)!;
assert.deepEqual(r.lanePower, [[18, 14], [15, 21], [13, 11]]);
assert.equal(r.winner, 0);
// Replay turns 1–5 to check the T1 consensus lead.
let five = setup(RULESET_V1_1);
for (const plays of PLAN.slice(0, 5)) five = playTurn(five, plays);
assert.deepEqual(lanePower(five, T1), [8, 8]);
assert.deepEqual(topicsLed(five), [2, 1]); // T1 by consensus + T3; Bo leads T2
});
+10 -6
View File
@@ -2,7 +2,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
DEFAULT_DERIVATION, DEFAULT_RULESET, FACTION_KEYWORD, STARTER_DECKS, createMatch, starterDeckById, validateDeck,
DEFAULT_DERIVATION, DEFAULT_RULESET, RULESET_V1_0, RULESET_V1_1, keywordFor, STARTER_DECKS, createMatch, starterDeckById, validateDeck,
} from '../shared/game/index.ts';
const countBy = (keys: string[]) => keys.reduce<Record<string, number>>((m, k) => ({ ...m, [k]: (m[k] ?? 0) + 1 }), {});
@@ -19,14 +19,17 @@ test('four starter decks, each with the frozen curve, 6+6 factions and 4 cards p
}
});
test('starter cards follow §10.1 and the power curve like owned cards', () => {
for (const def of STARTER_DECKS) for (const card of starterDeckById(def.id)) {
for (const [label, rules] of [['v1.0', RULESET_V1_0], ['v1.1', RULESET_V1_1]] as const)
test(`starter cards follow §10.1 and the power curve like owned cards (${label})`, () => {
for (const def of STARTER_DECKS) for (const card of starterDeckById(def.id, rules)) {
assert.equal(card.source, 'loaner');
assert.equal(card.rarity, 'Common');
assert.equal(card.trend, 0);
assert.match(card.cardId, /^loaner:[a-z0-9-]+$/);
if (card.cost === 1) assert.deepEqual([card.keyword, card.power], [null, 2]);
else assert.deepEqual([card.keyword, card.power], [FACTION_KEYWORD[card.faction], DEFAULT_DERIVATION.powerByCost[card.cost]]);
if (card.cost === 1) { assert.deepEqual([card.keyword, card.power], [null, 2]); continue; }
const { keyword } = keywordFor(card.faction, card.cost, false, rules, card.home);
assert.equal(card.keyword, keyword);
assert.equal(card.power, rules.powerByCost[card.cost] + (rules.keywordParams[keyword!]?.powerDelta ?? 0));
}
});
@@ -67,7 +70,8 @@ test('previewPool derives the frozen starter-cards.json loaners through §1', as
assert.equal(c.source, 'loaner');
assert.match(c.cardId, /^loaner:\d+$/);
assert.ok(c.cost >= 1 && c.cost <= 6);
assert.equal(c.power, DEFAULT_DERIVATION.powerByCost[c.cost] + (c.keyword === null && c.cost === 1 ? DEFAULT_DERIVATION.vanillaBonus : 0));
const delta = c.keyword ? (DEFAULT_DERIVATION.keywordParams[c.keyword]?.powerDelta ?? 0) : 0;
assert.equal(c.power, DEFAULT_DERIVATION.powerByCost[c.cost] + (c.keyword === null && c.cost === 1 ? DEFAULT_DERIVATION.vanillaBonus : 0) + delta);
}
// 12 of them make a legal loaner deck.
assert.deepEqual(validateDeck(DEFAULT_RULESET, pool.slice(0, 12)), []);
+2 -2
View File
@@ -1,6 +1,6 @@
/** Hand-built boards for keyword and Portal unit tests (engine-b). */
import {
DEFAULT_RULESET, KEYWORDS, PORTALS, Rng, cardPower, createMatch, lanePower, starterDeck,
RULESET_V1_0, KEYWORDS, PORTALS, Rng, cardPower, createMatch, lanePower, starterDeck,
type CardInPlay, type EffectContext, type GameCard, type MatchState, type PlayerId, type Stat, type TopicDef,
} from '../../shared/game/index.ts';
@@ -9,7 +9,7 @@ export const topic = (stat: Stat, portal: string | null = null, id = portal ?? `
/** Empty board, turn 1; lanes are depth / attention / reach plain Topics unless given. */
export function board(topics: TopicDef[] = [topic('depth'), topic('attention'), topic('reach')], revealed = true): MatchState {
const state = createMatch(DEFAULT_RULESET, [starterDeck('a'), starterDeck('b')], 'keyword-test');
const state = createMatch(RULESET_V1_0, [starterDeck('a'), starterDeck('b')], 'keyword-test'); // unit tests use v1.0 numbers
state.lanes = topics.map(t => ({ topic: t, portalRevealed: revealed, cards: [[], []] as [CardInPlay[], CardInPlay[]] }));
return state;
}
+61 -2
View File
@@ -5,7 +5,7 @@ import express from 'express';
import type { AddressInfo } from 'node:net';
import { gameRouter } from '../server/game/index.ts';
import { previewPool } from '../server/game/engine-binding.ts';
import { DEFAULT_RULESET, STARTER_POOL, replay, parseRuleset } from '../shared/game/index.ts';
import { DEFAULT_RULESET, replay, parseRuleset, previewPool as engineLoaners } from '../shared/game/index.ts';
import { parseMode, resolveRuleset, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
import { ModeListSchema } from '../shared/game/modes.ts';
@@ -134,7 +134,8 @@ test('modes api: draft preview pool is deterministic and deck-legal', () => {
assert.deepEqual(p1, p2);
assert.equal(p1.length, 30);
assert.equal(new Set(p1.map(c => c.cardId)).size, 30);
assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, STARTER_POOL.length * DEFAULT_RULESET.maxCopiesPerPage);
assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, engineLoaners(DEFAULT_RULESET).length * DEFAULT_RULESET.maxCopiesPerPage);
assert.ok(p1.every(c => c.check === 'loaner' && c.source === 'loaner'), 'only engine loaner data');
});
test('modes api: the rule examples in HOSTING.md are valid modes', () => {
@@ -207,3 +208,61 @@ test('modes api: mode rules are checked beyond the engine schema and rejected, n
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, { keywordsEnabled: ['viral', 'edition', 'wildcard'] }, parseModeRuleset));
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, {}, parseModeRuleset));
});
test('modes api: live matches survive a node restart (snapshot on shutdown, restore on start)', async () => {
const { ModeHost } = await import('../server/game/host.ts');
const { MatchStore } = await import('../server/game/store.ts');
const { engineBinding } = await import('../server/game/engine-binding.ts');
const { persistLive } = await import('../server/game/index.ts');
const { mkdtempSync, rmSync, existsSync } = await import('node:fs');
const { tmpdir } = await import('node:os');
const { join } = await import('node:path');
const dir = mkdtempSync(join(tmpdir(), 'modes-live-'));
try {
const modes = [parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } }),
parseMode({ schema: MODE_SCHEMA_VERSION, id: 'draft', version: 1, name: 'D', description: 'x', decks: { kind: 'draft', poolSize: 30 }, rules: { deckSize: 10, openingHand: 4 } })];
const make = () => new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes, engine: engineBinding, store: new MatchStore(dir) });
const first = make();
persistLive(first, dir, false);
const a = first.createLobby('classic', alice);
const b = await first.join(a.lobbyId, bob);
// Random seed: the opening hand may have nothing playable on turn 1, so fall back to commit.
const legal = (first.view(a.lobbyId, a.token) as any).legalActions;
await first.act(a.lobbyId, a.token, legal.find((x: any) => x.type === 'play') ?? legal.find((x: any) => x.type === 'commit'));
const d = first.createLobby('draft', alice);
const e = await first.join(d.lobbyId, bob);
const pick = (first.view(d.lobbyId, d.token) as any).draft;
await first.pick(d.lobbyId, [d.token, e.token][pick.toPick]!, 0);
const waiting = first.createLobby('classic', { name: 'Cy', secret: 'cy-secret-0123456789abcdefghij' });
const before = first.view(a.lobbyId, b.token) as any;
persistLive(first, dir, false).save();
// "Restart": a fresh host restores the snapshot. Same tokens keep working.
const second = make();
persistLive(second, dir, false);
assert.ok(existsSync(join(dir, 'live.json.restored')));
const after = second.view(a.lobbyId, b.token) as any;
assert.equal(after.phase, 'playing');
assert.deepEqual(after.state, before.state, 'match state restored exactly');
assert.equal((second.view(d.lobbyId, d.token) as any).phase, 'drafting');
assert.equal((second.view(waiting.lobbyId) as any).phase, 'waiting');
// Finish the restored match: the record replays.
for (let i = 0; i < 200; i++) {
const v = second.view(a.lobbyId, a.token) as any;
if (v.phase !== 'playing') break;
for (const t of [a.token, b.token]) {
const w = second.view(a.lobbyId, t) as any;
const c = w.legalActions?.find((x: any) => x.type === 'commit');
if (c) await second.act(a.lobbyId, t, c);
}
}
const end = second.view(a.lobbyId, a.token) as any;
assert.equal(end.phase, 'finished');
const rec = second.matchRecord(end.matchId);
assert.equal(replay(rec.rules as any, rec.decks as any, rec.seed, rec.actions.map(x => x.action) as any).result?.winner ?? null, rec.winner);
// Rules changed under a mode → its lobbies are dropped, not run under different rules.
const changed = new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, engine: engineBinding, store: new MatchStore(null),
modes: [parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' }, rules: { turns: 5 } })] });
assert.equal(changed.restore(second.snapshot()), 0);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
+16
View File
@@ -0,0 +1,16 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
test('landing explains Edit War and offers a thumb-sized Play button (upstream #3)', async () => {
const read = (file: string) => readFile(new URL(`../${file}`, import.meta.url), 'utf8');
const [landing, css, app] = await Promise.all([read('src/Landing.tsx'), read('src/landing.css'), read('src/App.tsx')]);
assert.match(app, /<Landing onPlay=\{\(\) => setView\('Play'\)\} \/>/, 'App mounts the landing block and its button opens Play');
assert.match(landing, /export function Landing\(\{ onPlay/);
assert.match(landing, /onClick=\{onPlay\}/);
assert.match(landing, /Play now/);
for (const idea of ['Three Topics', 'Six turns', 'Win two Topics', 'starter deck', 'off-chain']) assert.ok(landing.includes(idea), idea);
assert.doesNotMatch(css, /:hover/, 'no hover-only interactions');
assert.match(css, /min-height:44px/, 'tap target is at least 44px');
assert.doesNotMatch(css, /#[0-9a-f]{3,6}\b/i, 'colours come from the Catppuccin theme variables');
});
+27 -1
View File
@@ -61,7 +61,6 @@ test('my view never shows the opponent’s queued cards', () => {
s = engine.apply(s, 1, play!);
const mine = engine.view(s, 0);
assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0);
assert.equal(mine.oppQueued, 1);
const theirs = engine.view(s, 1);
assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1);
assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand');
@@ -126,3 +125,30 @@ test('leaderboard parsers cap and sanitise host data', async () => {
assert.deepEqual(parseLeaderboard({ entries: [{ name: '', wins: 2 }] }), [{ name: 'Anonymous', wins: 2, losses: 0, draws: 0, played: 0 }]);
assert.deepEqual(parseLeaderboard(42), []);
});
test('the final board shows scoring power, and queued cards preview their lane power', () => {
const s = playOut('final-board');
const v = engine.view(s, 0), r = engine.result(s, 0);
assert.ok(v.over);
v.lanes.forEach((l, i) => { assert.equal(l.myPower, r.lanes[i].myPower); assert.equal(l.theirPower, r.lanes[i].theirPower); });
let m = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('q')], 'queued-power');
const play = engine.legal(m, 0).find(a => a.type === 'play');
if (play?.type === 'play') {
m = engine.apply(m, 0, play);
const lane = engine.view(m, 0).lanes[play.lane];
const [q] = lane.staged;
const bonus = q.home === lane.stat ? DEFAULT_RULESET.onTopicBonus[q.cost] : 0;
assert.equal(q.power, q.basePower + q.trend + bonus);
}
});
test('results explain a tied Topic decided by the on-topic tie-break', async () => {
const { renderToStaticMarkup } = await import('react-dom/server');
const { createElement } = await import('react');
const { Results } = await import('../src/game/Results.tsx');
const html = renderToStaticMarkup(createElement(Results, { modeName: 'Standard', onRematch() {}, onLobby() {}, result: {
winner: 1, turns: 6, reason: 'topics', totalPower: [37, 42],
lanes: [{ name: 'Current Events', myPower: 13, theirPower: 13, winner: 1 }, { name: 'Archive', myPower: 10, theirPower: 10, winner: 0 },
{ name: 'Stub', myPower: 14, theirPower: 19, winner: 1 }] } }));
assert.equal(html.match(/Tie, decided by on-topic cards/g)?.length, 2);
});