Compare commits

..
Author SHA1 Message Date
claudeandClaude Opus 5.5 3e6d597aef ui-duel: document that browser bot matches are unrated (#79 review)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:38:42 -05:00
claudeandClaude Opus 5.5 ff6c93c808 ui-duel: QA fixes from night-review (#58): hand overflow cue (+N, edge fade), Garrison 0/T in preview, taller cards and 3-line titles on tall phones, larger Doctrine badge
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 23:10:06 -05:00
claudeandClaude Opus 5.5 0f924b7732 ui-duel: even battlefield slots with few cards; keyword icons on two-keyword hand cards; game-over note wraps (#58)
Found by rendering duel-core's engine-wip mid-game locally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:56:40 -05:00
claudeandClaude Opus 5.5 848cfbbaf1 ui-duel: view-only fallback duel bots (Easy, Normal) for the browser bot match (#58)
Checked locally against duel-core's engine-wip: 40 full games through the board
pipeline (adapter, declaration reducers, expand) with every sent action legal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:55:08 -05:00
claudeandClaude Opus 5.5 9c26b8d560 ui-duel: mirror the used slice of duel-core's contract (#72) locally so this PR doesn't stack (#58)
contract.ts copies the unions and fields verbatim; a compile check confirmed
duel-core's PlayerView, DuelAction (both ways), LogEvent, DuelEngineApi and
DuelRuleset are assignable to it. It becomes re-exports once #72 merges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:49:19 -05:00
claudeandClaude Opus 5.5 a57698a7e2 ui-duel: accept untyped duel profiles from the collection and shape-check them (#58)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:17:44 -05:00
claudeandClaude Opus 5.5 75ce8f5ba5 ui-duel: DuelBotMatch (eligible players only, bot sees viewFor only) (#58)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:56:22 -05:00
claudeandClaude Opus 5.5 a7e46583fb ui-duel: DuelBotMatch (eligible players only, bot sees viewFor only) (#58)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:56:01 -05:00
claudeandClaude Opus 5.5 4160086d16 ui-duel: duel-core adapter and DuelBoard (PlayerView + DuelAction[]) for ui-pvp (#58)
Board intents expand to duel-core's atomic actions (toggleAttacker x N,
confirmAttack; block x N, confirmBlocks), sent in order and awaited.
Fallback log uses the first DUEL_DESIGN 8.2 variant until the story
renderer reads engine events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:54:04 -05:00
claudeandClaude Opus 5.5 0fcf0b0a73 ui-duel: follow duel-core contract phases; multi-step targets incl. players (#58)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:51:55 -05:00
claudeandClaude Opus 5.5 0666b08829 ui-duel: engine-agnostic local match driver; Connected icon; game-over uses the engine's log line (#58)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:47:59 -05:00
claudeandClaude Opus 5.5 2fe16a66c8 ui-duel: eligibility gate, DuelCard to board card mapping, zoom face fixes (#58)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:46:26 -05:00
claudeandClaude Opus 5.5 5a7cfba124 ui-duel: duel table, MTG card faces, combat declaration and preview scenes (#58)
Presentational board on its own view model (src/game/duel/model.ts), 360 x 740 first:
both players' Notability, Citations, library and hand always visible; attack in one
tap, block in two, preview then confirm; tap-to-zoom card sheet with rules text,
flavour and an [n] article link; log ticker on phones, log column on desktop.
#duel-preview renders static scenes from card-sample.json for review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:44:33 -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
39 changed files with 3379 additions and 93 deletions
+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 |
+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.
-75
View File
@@ -1,75 +0,0 @@
# WikiDeck Night 1: report
**Night:** 2026-11-16 22:45 → 2026-11-17 01:30 EST. 17 Claude agents on 4 machines, coordinated through Gitea (milestone 63, issues #1–#10).
**Branch:** `claude/wikideck:night/2026-11-16`. Everything below came in through 38 PRs that night-review reviewed and night-lead squash-merged.
**Untouched:** the live deployment, mainnet, and every consensus and protocol file. The off-limits list is in `docs/night/BOUNDARIES.md`.
## What works
| Area | Status | Where |
|---|---|---|
| **The game, "Edit War"** | Playable in the browser against an AI: a lobby, a deck builder with 4 loaner starter decks, matches, results and a tutorial. Works on a 360 px phone. | `src/game/`, PR #26 #30 (landing page, upstream WikiDeck/wikideck#3), #31 (easy and normal browser bots), #45 |
| **Rules engine** | Pure, deterministic TypeScript with the rules as data. `createMatch`, `legalActions`, `applyAction`, `viewFor` and serialisation. 6 keywords and 6 Portals. Property tests, plus a §12 golden match checked by hand. | `shared/game/`, `docs/game/ENGINE_API.md`, #25 #27 #29 #33 #36 (v1.1 as the default), #38 (planning is hidden) |
| **Design** | DESIGN.md v1 (frozen 23:01), then v1.1 tuned from the balance report. | `docs/game/DESIGN.md`, #13 #17 #23 #24 #32 |
| **Card data** | 236 sampled articles, with real distributions, percentile tables and 48 starter pageIds. | `docs/game/CARD_DATA.md`, `card-sample.json`, #20 #28 |
| **Balance** | Bots (random, greedy, lookahead) played thousands of matches per ruleset. On v1 the starter pairings ranged 23–77%, and the first player won 53.4%. The v1.1 re-run measured the first player at **51.2%**, starter decks at **52–53%** and owned decks at **42–51%** against starters, so owning NFTs adds variety, not power. | `docs/game/BALANCE.md`, `shared/bots/` #14 |
| **eom.dev accounts** | Dex OIDC with PKCE: login and logout, and ID tokens verified against the JWKS. Wallet linking signs a message the **client builds**, never text from the server. The account ↔ wallet map is stored off-chain. | `server/account/`, `src/auth/`, #15 #37 #42 |
| **Peer-hosted modes** | Modes are JSON data, never code. A node publishes them at `GET /api/game/modes`, peers are discovered through config, and the hosting node runs the match. It shows "Hosted by", with per-mode and host leaderboards. 3 example modes: classic, snake draft and trending. Lobbies survive restarts. | `shared/game/modes.ts`, `server/game/`, `docs/game/HOSTING.md`, #22 #43 |
| **Private testnet** | 3 nodes on poweredge-r350, LAN only, at height 50. Auto-redeploy followed this branch until the freeze, with rolling restarts that wait for live matches to finish. | `deploy/night/`, #16 #19 #39 #40 |
| **Android app** | Capacitor 7 (`dev.eom.wikideck`). A debug APK runs a full match against the AI in the emulator. CapacitorHttp gets past the node's Origin check with no server change. The SSO deep link round trip works up to Dex. | `android/`, `docs/night/ANDROID.md`, #35 #41 #44 |
| **iOS app** | Capacitor 7 iOS project (SPM) and a simulator build script. The macOS Sequoia VM's install was still running at the end of the night. No Apple ID was used. | `ios/`, `docs/night/IOS.md`, #34 #52 |
## How to try it
- **Browser:** http://192.168.1.32:3101, :3102 or :3103 (LAN only). Open **Play**, dismiss the tutorial, pick a starter deck and play the AI. The three nodes host different modes: A has classic and trending, B has draft, and C has all three.
- **Android:** the APK is at `inspiron-3670:~/worker/jobs/night/mobile-android/apk/wikideck-night1-debug.apk` (debug-signed, testnet build). To rebuild it: `android/build-debug.sh`. Screenshots:
![Android emulator, match vs AI](android/screens.jpg)
- **iOS:** follow Eric's checklist in `docs/night/IOS.md`:
1. resume the VM on inspiron and finish the macOS install
2. sign in with your Apple ID
3. install Xcode
4. run `scripts/ios/build-sim.sh`
No Apple ID was used tonight. The VM got as far as the Sequoia installer downloading the full OS. Per the coordinator, the VM is shut down cleanly before 01:30 with its disk kept. `docs/night/IOS.md` (#52) records the install progress at shutdown, the resume steps and Eric's checklist.
- **Login:** "Log in with eom.dev" uses Dex at `https://dex.eom.dev/`, through the `wikideck` public client that the coordinator applied. You need a membership account that's in `Dex Users`; the SSO issue #7 covers the sign-up path.
## QA (night-review, live testnet)
- **API:** full hosted matches in all 3 modes (classic @A, snake draft @B, trending @C) with two scripted players. Records and leaderboards are correct. Rejected as they should be: forged card, cross-seat token, random token, client `timeout`, foreign Origin, self-join, out-of-turn pick.
- **Browser:** Playwright played 3 full matches against the AI through the real Play UI (360×740 @A ×2, 1280×800 @B). Every one reached results, with no overflow, stuck turns or page errors.
- **Engine fuzz:** 300 random matches per engine branch. 0 `viewFor` leaks (information-flow test), and every replay was deterministic.
- **UX bug found and fixed:** the results card showed tied Topics ("13–13 Lost") with no tie-break explanation. Fixed after the freeze in #51.
## Known issues and gaps
1. **The game ships rules v1.1** (`DEFAULT_RULESET = RULESET_V1_1`, #36), which matches DESIGN.md v1.1. The v1.1 numbers in BALANCE.md (first player 51.2%, starter decks 52–53%, owned decks 42–51%) were measured **before** #38 hid the opponent's queue, so the seat figure needs a re-run. Item 6 (`nostalgic` and `translated` at −1 power) is a v1.2 candidate and isn't in v1.1.
2. **Hosted PvP trusts the host.** The seed is chosen by the host, and DESIGN §4.4's commit–reveal isn't implemented. A malicious host can see both hands. That's documented in HOSTING.md.
3. **Hidden information.** #38 hides the opponent's queue during planning (with a test). The UI and the bots consume only `viewFor` output, and the log never names an opponent's hidden card. Remaining: `obscure` (item 4) and host trust (item 2).
4. **The `obscure` keyword isn't masked in `viewFor`.** Modes reject it, so it can't be turned on.
5. **Game traffic shares the chain's per-node RPC budget,** so one hot client can get everyone 503s (#6).
6. **Wikipedia rate limits:** our egress IP got HTTP 429s on the action API. #19 adds an optional `WIKIDECK_USER_AGENT` with a contact URL, and only the testnet sets it. **The live deployment probably shares that IP and the old generic UA.** Whether to set it in production is Eric's decision.
7. **Mobile polish:**
- the dashed lane drop zone doesn't take taps, only the lane plate does
- the home hero still says "Explore mining" inside the app
- the real SSO login hasn't been done on a device yet
- **Apple licences:** an agent clicked through the **macOS installer licence** in the VM, under Eric's VM approval on #9. Review that if you want to accept it yourself.
- `scripts/ios/build-sim.sh` still runs `sudo xcodebuild -license accept`, which would accept Apple's Xcode licence on Eric's behalf. **Eric should accept it himself** (remove the line first).
- Android allows cleartext HTTP to **any** host (`usesCleartextTraffic="true"`). Before any non-LAN use, restrict it with a `network_security_config` to the testnet host.
8. **Factions are skewed:** owned cards are about 53% Culture and 0% Space, so `viral` and `local` dominate. Factions built on Wikidata P31 are the v1.1+ fix (CARD_DATA findings 6 and 7).
9. **Tooling:** the repo needs **Node 24** (`node:sqlite`). On Node 20, 12 tests fail falsely. Every gate tonight ran in `node:24-alpine`.
**Held for Eric:** #49 (the normal bot uses sim-balance's lookahead). It's approved, but it's a behaviour change that arrived after the freeze.
## Next steps (in priority order)
1. **Re-run balance on the final head** (after #38) and decide v1.2 item 6. The harness is `scripts/sim/` and `shared/bots/`, and it needs about 1 GB on r350, run under the heavy lock.
2. **Hidden information everywhere:** mask `obscure`, and implement the §4.4 commit–reveal seed for hosted PvP.
3. **Separate rate limits for game traffic** on the node, so they don't share the chain's RPC budget.
4. **Finish iOS:** Xcode and a simulator run, then the same match against the AI as on Android.
5. **SSO end to end** on a device with a real eom.dev account, then show account names on the leaderboards.
6. **Factions from Wikidata P31**, then re-run the balance sims (item 6 on the BALANCE list is still open).
7. **Host incentives on-chain:** the proposal in HOSTING.md. It's a protocol change, so it needs its own review.
8. **Production user agent:** decide whether the live node should set `WIKIDECK_USER_AGENT`.
## Process notes
- Every agent shared the `claude` Gitea account, so night-review approved with COMMENT reviews that start with `VERDICT: APPROVED`, naming the head SHA and the gate result.
- **imac's Gitea MCP was down** all night. The council read issues anonymously and reported through PR bodies, and night-lead relayed.
- **tower-plus ran out of memory** at about 23:25, and **r350 twice**. From then on, every heavy check ran on inspiron in `node:24-alpine` under `flock /tmp/night-heavy.lock`.
- Squash merges dropped the history that stacked PRs shared, which caused add/add conflicts (#27, #22, #26). Each was resolved mechanically, with no content changes.
+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.
+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
View File
@@ -0,0 +1,10 @@
// Engine-level chooser for the "normal" browser bot: sim-balance's determinized lookahead
// (shared/bots), fed only the engine's hidden-information PlayerView (viewFor output),
// never the full MatchState (night-lead's rule on #5).
import { makeViewBot } from '../../../shared/bots/game-adapter.ts';
import type { PlayerView } from '../../../shared/game/index.ts';
import type { EngineChoice } from './index.ts';
const lookahead = makeViewBot('lookahead-lite');
export const normalEngineChoice: EngineChoice = (ev, rng) => lookahead(ev.view as PlayerView, rng);
+5 -2
View File
@@ -6,6 +6,7 @@
// Hard rule (night-lead, #5): bots get only `viewFor` output, never the full MatchState.
// The MatchView never contains the human's queued plays either.
import type { MatchView, UIAction } from '../types.ts';
import { normalEngineChoice } from './engine.ts';
export type BotLevel = 'easy' | 'normal';
export type Rng = () => number;
@@ -59,7 +60,7 @@ export function makeUiBot(level: BotLevel, engineChoice?: EngineChoice): Bot {
name: level === 'easy' ? 'Easy' : 'Normal', // the lobby renders `${name} bot`
description: level === 'easy'
? 'Plays big cards, but often makes a random move. Good for learning.'
: 'Plays for the lead in each Topic. It cannot see your hidden plays.',
: 'Looks a few moves ahead and plays for the lead in each Topic. It cannot see your hidden plays.',
choose(view, legal, rand) {
const ev = (view as MatchView & { engine?: { view: unknown } }).engine;
const mapped = legal as (UIAction & WithEngine)[];
@@ -72,4 +73,6 @@ export function makeUiBot(level: BotLevel, engineChoice?: EngineChoice): Bot {
};
}
export const BOTS: Bot[] = [makeUiBot('easy'), makeUiBot('normal')];
// Normal plays sim-balance's lookahead whenever the adapter attaches the engine view; easy stays a
// view-model bot (it measured weaker and more human-beatable than the engine maxpower mix).
export const BOTS: Bot[] = [makeUiBot('easy'), makeUiBot('normal', normalEngineChoice)];
+39
View File
@@ -0,0 +1,39 @@
import { useMemo, useState } from 'react';
import type { DuelAction, LogEvent, PlayerView } from './contract.ts';
import { boardFromView, expand, legalFromActions, plainLog, type Articles } from './adapter.ts';
import { DuelTable } from './DuelTable.tsx';
import type { DuelUIAction } from './model.ts';
/**
* The duel board on duel-core's types, for any controller (ui-pvp's OnlinePlay, the local bot match).
* One board intent can be several atomic actions (toggleAttacker × N, confirmAttack): they go out
* through `onAct` in order, each awaited, each an element of `legal` or legal once the previous ones apply.
*/
export function DuelBoard({ view, legal, onAct, opponentName, playerName = 'You', error, busy, log, logEvents, articles, clock, onExit, onRecap }: {
view: PlayerView; legal: DuelAction[]; onAct: (a: DuelAction) => void | Promise<void>;
opponentName: string; playerName?: string; error?: string; busy?: boolean;
/** Rendered log lines (duel-design's story renderer). If absent, `logEvents` are shown with plain templates. */
log?: string[]; logEvents?: LogEvent[];
/** cardId → article image/url, from the chain. */
articles?: Articles;
clock?: { turn: number; bank: number };
onExit?: () => void; onRecap?: () => void;
}) {
const [sending, setSending] = useState(false);
const [sendError, setSendError] = useState<string>();
const names = useMemo<[string, string]>(() => (view.seat === 0 ? [playerName, opponentName] : [opponentName, playerName]), [view.seat, playerName, opponentName]);
const lines = useMemo(() => log ?? plainLog(logEvents ?? [], names), [log, logEvents, names]);
const board = useMemo(() => boardFromView(view, names, lines, articles, clock), [view, names, lines, articles, clock]);
const boardLegal = useMemo(() => legalFromActions(legal), [legal]);
const act = async (ui: DuelUIAction) => {
const seq = expand(ui, legal);
setSending(true); setSendError(undefined);
try { for (const a of seq) await onAct(a); }
catch (e) { setSendError(e instanceof Error ? e.message : 'That move was not accepted.'); }
finally { setSending(false); }
};
return <DuelTable view={board} legal={boardLegal} onAct={ui => { void act(ui); }} busy={busy || sending}
error={error ?? sendError} onExit={onExit} onRecap={onRecap} />;
}
+80
View File
@@ -0,0 +1,80 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { DuelAction, DuelCard, DuelEngineLike, DuelRulesetLike, Seat } from './contract.ts';
import type { Articles } from './adapter.ts';
import { DuelBoard } from './DuelBoard.tsx';
import { DuelGate } from './DuelGate.tsx';
import { botDeck, hash, mulberry, playerDeck, type BotMatchCard, type DuelBot } from './decks.ts';
export type { BotMatchCard, DuelBot };
const HUMAN: Seat = 0, BOT: Seat = 1;
const BOT_STEP_MS = 300;
/**
* A bot match in the browser, for eligible players only (BRIEF decisions 2–3): the deck must be
* exactly `deckSize` cards the player owns. Off-chain; nothing moves or burns.
* Unrated by design: the whole DuelState (bot hand, library order) lives in the page, so `onFinish` never
* gets a match id and a browser-hosted result must never feed Elo or the ladder (night-review, #79).
*/
export function DuelBotMatch<S, R extends DuelRulesetLike>({ deck, cards, onExit, onFinish, engine, bot, botPool, rules, playerName = 'You', onMine }: {
deck: string[]; cards: BotMatchCard[]; onExit: () => void; onFinish: (matchId?: string) => void;
engine: DuelEngineLike<S, R>; bot: DuelBot; botPool: readonly DuelCard[]; rules: R; playerName?: string; onMine?: () => void;
}) {
const mine = useMemo(() => playerDeck(deck, cards, rules.deckSize), [deck, cards, rules.deckSize]);
const [seed] = useState(() => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`);
const [state, setState] = useState<S | null>(null);
const [error, setError] = useState<string>();
const rng = useRef(mulberry(hash(seed)));
const current = useRef<S | null>(null);
current.current = state;
useEffect(() => {
if (!mine.cards.length) return;
try { setState(engine.createDuel(rules, [mine.cards, botDeck(botPool, rules.deckSize, seed)], seed)); }
catch (e) { setError(e instanceof Error ? e.message : 'This deck can’t be played.'); }
}, [engine, rules, mine.cards, botPool, seed]);
// The bot moves one atomic action at a time, so the board shows its plays and declarations.
useEffect(() => {
if (!state || engine.toAct(state) !== BOT) return;
const t = setTimeout(() => {
const legal = engine.legalActions(state, BOT);
if (!legal.length) return;
let a: DuelAction;
try { a = bot.choose(engine.viewFor(state, BOT), legal, rng.current); } catch { a = legal[0]; }
if (!legal.some(l => JSON.stringify(l) === JSON.stringify(a))) a = legal[0];
if (current.current !== state) return;
const next = engine.applyAction(state, BOT, a);
current.current = next;
setState(next);
}, BOT_STEP_MS);
return () => clearTimeout(t);
}, [state, engine, bot]);
// Applied synchronously through a ref, so a confirmed declaration (toggleAttacker × N, confirmAttack)
// sees each previous action, and an illegal action throws back to DuelBoard, which shows the error.
const onAct = useCallback((a: DuelAction) => {
const s = current.current;
if (!s) return;
const next = engine.applyAction(s, HUMAN, a);
current.current = next;
setError(undefined);
setState(next);
}, [engine]);
const articles = useMemo<Articles>(() => Object.fromEntries(cards.map(c => [c.tokenId, { image: c.imageUrl, url: c.url, extract: c.extract }])), [cards]);
if (!mine.cards.length) {
if (deck.length < rules.deckSize || mine.missing.length) return <DuelGate owned={deck.length - mine.missing.length} deckSize={rules.deckSize} onExit={onExit} onMine={onMine} />;
return <section className="duel-gate"><h2>Card profiles pending</h2>
<p className="muted">These cards don’t have a duel profile yet, so they can’t be played: {mine.pending.join(', ')}. Pick other cards for your deck, or try again shortly.</p>
<div className="play-actions"><button className="button outline" onClick={onExit}>Back</button></div></section>;
}
if (!state) return error ? <section className="duel-gate"><h2>Can’t start this match</h2><p className="muted">{error}</p>
<div className="play-actions"><button className="button outline" onClick={onExit}>Back</button></div></section> : null;
const view = engine.viewFor(state, HUMAN);
return <DuelBoard view={view} legal={engine.legalActions(state, HUMAN)} onAct={onAct} opponentName={`Bot (${bot.name})`} playerName={playerName}
logEvents={engine.logFor(state, HUMAN)} articles={articles} busy={engine.toAct(state) === BOT} error={error}
onExit={engine.isOver(state) ? () => onFinish() : onExit} />;
}
+90
View File
@@ -0,0 +1,90 @@
import { BookMarked, BookOpen, Building2, CalendarClock, Globe2, Home, Hourglass, Languages, Link2, MapPin, Shield, ShieldCheck, Sparkles, Sprout, Star, Swords, TrendingUp, UserRound } from 'lucide-react';
import type { BoardCard, DuelCardType } from './model.ts';
import { cardSummary, typeLine } from './model.ts';
const TYPE_ICONS: Record<DuelCardType, typeof UserRound> = {
Figure: UserRound, Location: MapPin, Event: CalendarClock, Institution: Building2, Doctrine: BookOpen,
};
export const TypeIcon = ({ type, size = 12 }: { type: DuelCardType; size?: number }) => {
const Icon = TYPE_ICONS[type] ?? BookOpen;
return <Icon size={size} aria-hidden="true" />;
};
/** Keyword icons for the board face, where a word doesn't fit 62 px. The words are in the label and the zoom face. */
const KEYWORD_ICONS: Record<string, typeof Star> = {
protected: ShieldCheck, featured: Star, translated: Languages, legacy: Hourglass, stub: Sprout,
'well-sourced': BookMarked, multilingual: Globe2, local: Home, trending: TrendingUp, connected: Link2,
};
export const KeywordIcon = ({ keyword, size = 11 }: { keyword: string; size?: number }) => {
const Icon = KEYWORD_ICONS[keyword.toLowerCase()] ?? Sparkles;
return <Icon size={size} aria-hidden="true" />;
};
export type FaceSize = 'board' | 'hand' | 'zoom';
export type FaceState = { selected?: boolean; attacking?: boolean; blocking?: boolean; target?: boolean; dim?: boolean; fresh?: boolean };
const statClass = (now?: number, base?: number) => (now === undefined || base === undefined ? '' : now > base ? 'up' : now < base ? 'down' : '');
function Stats({ card }: { card: BoardCard }) {
if (card.power === undefined) return null;
const tough = (card.toughness ?? 0) - (card.damage ?? 0);
return <span className="dface-pt" aria-hidden="true">
<b className={statClass(card.power, card.basePower)}>{card.power}</b>/<b className={card.damage ? 'down' : statClass(card.toughness, card.baseToughness)}>{tough}</b>
</span>;
}
function Art({ card, iconSize }: { card: BoardCard; iconSize: number }) {
return <span className="dface-art" aria-hidden="true">
{card.image ? <img src={card.image} alt="" loading="lazy" decoding="async" referrerPolicy="no-referrer"
onError={e => { e.currentTarget.style.display = 'none'; }} /> : null}
<TypeIcon type={card.type} size={iconSize} />
</span>;
}
/**
* The duel card face (MTG layout). Board and hand faces show only what fits a phone: title (2-line
* clamp), cost, type icon, P/T and keyword chips. Rules text and flavour live in the zoom face,
* which the tap-to-zoom sheet shows (critic S4).
*/
export function DuelCardFace({ card, size = 'hand', state = {}, onClick, label, refNumber }: {
card: BoardCard; size?: FaceSize; state?: FaceState; onClick?: () => void; label?: string; refNumber?: number;
}) {
const cls = ['dface', `dface-${size}`, `portal-${card.portal.toLowerCase()}`,
card.tapped && 'is-tapped', card.pending && 'is-pending', state.selected && 'is-selected', state.attacking && 'is-attacking',
state.blocking && 'is-blocking', state.target && 'is-target', state.dim && 'is-dim', state.fresh && 'is-fresh', card.token && 'is-token']
.filter(Boolean).join(' ');
if (size === 'zoom') return <article className={cls} aria-label={cardSummary(card)}>
<div className="dface-namebar"><h3 className="dface-name">{card.title}</h3><span className="dface-cost" aria-label={`Cost ${card.cost} Citations`}>{card.cost}</span></div>
<Art card={card} iconSize={34} />
<p className="dface-typeline"><TypeIcon type={card.type} size={13} /> {typeLine(card)}<span className="dface-portal">{card.portal}</span></p>
<div className="dface-textbox">
{card.keywords.length > 0 && !card.keywords.every(k => card.rulesText.includes(k)) && <p className="dface-keywords">{card.keywords.join('. ')}.</p>}
{card.rulesText && <p className="dface-rules">{card.rulesText}</p>}
{card.flavour && <p className="dface-flavour">{card.flavour}{card.url
? <sup><a href={card.url} target="_blank" rel="noopener noreferrer" aria-label={`Wikipedia article: ${card.title}`}>[{refNumber ?? 1}]</a></sup>
: null}</p>}
</div>
<div className="dface-footer">
<span className="dface-rev">{card.revisionId ? `rev. ${card.revisionId}` : card.token ? 'Token' : ''}</span>
<Stats card={card} />
</div>
</article>;
const kwShown = card.keywords.slice(0, 2);
const Tag = onClick ? 'button' : 'div';
return <Tag {...(onClick ? { type: 'button' as const, onClick, 'aria-pressed': state.selected || state.attacking || state.blocking || undefined } : { role: 'img' })}
className={cls} aria-label={label ?? cardSummary(card)}>
<Art card={card} iconSize={size === 'board' ? 14 : 18} />
<span className="dface-cost" aria-hidden="true">{card.cost}</span>
{state.attacking && <span className="dface-flag attack" aria-hidden="true"><Swords size={11} /></span>}
{state.blocking && <span className="dface-flag block" aria-hidden="true"><Shield size={11} /></span>}
<span className="dface-title">{card.title}</span>
<span className="dface-bottom">
{size === 'board' || kwShown.length > 1
? kwShown.map(k => <span key={k} className="dface-kwicon" title={k}><KeywordIcon keyword={k} size={10} /></span>)
: kwShown.map(k => <span key={k} className="dface-chip">{k}</span>)}
<Stats card={card} />
</span>
</Tag>;
}
+24
View File
@@ -0,0 +1,24 @@
import { Pickaxe } from 'lucide-react';
import { eligibility } from './model.ts';
import './duel.css';
/**
* Shown instead of a board when the player doesn't own a full deck (BRIEF decisions 1–2). There is
* no practice with borrowed cards: the only way forward is mining (or trading) for real cards.
*/
export function DuelGate({ owned, deckSize, onMine, onExit }: { owned: number; deckSize: number; onMine?: () => void; onExit?: () => void }) {
const e = eligibility(owned, deckSize);
const pct = Math.round((Math.min(owned, deckSize) / deckSize) * 100);
return <section className="duel-gate" aria-labelledby="duel-gate-title">
<div className="section-eyebrow">DUEL · {deckSize}-CARD DECKS</div>
<h2 id="duel-gate-title">{e.label}</h2>
<div className="duel-gate-bar" role="progressbar" aria-valuemin={0} aria-valuemax={deckSize} aria-valuenow={Math.min(owned, deckSize)} aria-label="Cards owned"><i style={{ width: `${pct}%` }} /></div>
<p className="muted">A duel deck is exactly {deckSize} cards, and every one is an NFT you own. You need {e.needed} more.
Each block you mine is a new card: a random Wikipedia article, frozen with its stats at the moment it was mined.
Trades with other players count too. Matches never move or burn your cards.</p>
<div className="play-actions">
{onExit && <button className="button outline" onClick={onExit}>Back</button>}
{onMine && <button className="button dark" onClick={onMine}><Pickaxe size={16} /> Mine cards</button>}
</div>
</section>;
}
+27
View File
@@ -0,0 +1,27 @@
import { useState } from 'react';
import { DuelCardFace } from './DuelCardFace.tsx';
import { DuelTable } from './DuelTable.tsx';
import { PREVIEW_POOL, previewView } from './mock.ts';
import type { DuelUIAction } from './model.ts';
type Scene = 'main' | 'attack' | 'block' | 'over' | 'cards';
const SCENES: Scene[] = ['main', 'attack', 'block', 'over', 'cards'];
const ZOOM = ['Jess Harnell', 'Agda (programming language)', "April 2021 nor'easter", 'Pathrail Mosque', 'Hiroshima Electric Railway', 'Heart rot'];
/** Static board scenes from card-sample.json, for screenshots and review (`#duel-preview/<scene>`). Not a match. */
export function DuelPreview() {
const initial = (location.hash.split('/')[1] as Scene) || 'main';
const [scene, setScene] = useState<Scene>(SCENES.includes(initial) ? initial : 'main');
const [acted, setActed] = useState<string[]>([]);
const { view, legal } = previewView(scene === 'cards' ? 'main' : scene);
const onAct = (a: DuelUIAction) => setActed(l => [...l, JSON.stringify(a)]);
return <div className="duel-preview-page" style={{ padding: 0 }}>
<nav className="category-tabs" aria-label="Preview scene" style={{ padding: '4px 8px', display: location.hash.includes('clean') ? 'none' : undefined }}>
{SCENES.map(s => <button key={s} className={s === scene ? 'selected' : ''} onClick={() => { setScene(s); location.hash = `duel-preview/${s}`; }}>{s}</button>)}
{acted.length > 0 && <small style={{ marginLeft: 8 }}>last action: {acted.at(-1)}</small>}
</nav>
{scene === 'cards' ? <div className="duel" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(280px,1fr))', gap: 16, padding: 12 }}>
{ZOOM.map(t => PREVIEW_POOL.find(c => c.title === t)).filter(c => !!c).map((c, i) => <DuelCardFace key={c.id} card={c} size="zoom" refNumber={i + 1} />)}
</div> : <DuelTable key={scene} view={{ ...view, log: [...view.log, ...acted.map(a => `(preview) ${a}`)] }} legal={legal} onAct={onAct} />}
</div>;
}
+251
View File
@@ -0,0 +1,251 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Award, Flag, Hand, Library, LoaderCircle, Quote, ScrollText, Shield, Swords, Timer, X } from 'lucide-react';
import { DuelCardFace } from './DuelCardFace.tsx';
import '../play.css';
import './duel.css';
import {
EMPTY_DECL, blockList, isMyTurn, nextTargets, playerTarget, previewCombat, targetsComplete, tapAttacker, tapBlocker, toggleAttacker,
type Attack, type BoardCard, type Seat, type BoardView, type Declaration, type DuelUIAction, type Legal, type SideView,
} from './model.ts';
type Sheet =
| { kind: 'card'; card: BoardCard; where: 'hand' | 'mine' | 'theirs' }
| { kind: 'combat'; attacks: Attack[]; mode: 'attack' | 'block' }
| { kind: 'log' } | { kind: 'concede' } | null;
const PHASE_LABEL: Record<BoardView['phase'], string> = {
mulligan: 'Opening hand', main: 'Main', attack: 'Combat', block: 'Blocks', over: 'Match over',
};
function SideBar({ side, who, active, target, onTarget }: { side: SideView; who: 'me' | 'opponent'; active: boolean; target?: boolean; onTarget?: () => void }) {
const label = `${who === 'me' ? 'You' : side.name}: ${side.notability} Notability, ${side.citations} of ${side.maxCitations} Citations, ${side.library} in library, ${side.hand} in hand`;
const Tag = target ? 'button' : 'div';
return <Tag className={`duel-side ${who} ${active ? 'is-active' : ''} ${target ? 'is-target' : ''}`} {...(target ? { type: 'button' as const, onClick: onTarget } : { role: 'group' })} aria-label={target ? `Target ${who === 'me' ? 'yourself' : side.name}. ${label}` : label}>
<span className="duel-side-name">{who === 'me' ? 'You' : side.name}</span>
<span className={`duel-stat life ${side.notability <= 5 ? 'low' : ''}`} title="Notability"><Award size={14} aria-hidden="true" /><b>{side.notability}</b></span>
<span className="duel-stat cites" title="Citations"><Quote size={13} aria-hidden="true" /><b>{side.citations}</b><small>/{side.maxCitations}</small></span>
<span className="duel-stat" title="Library"><Library size={13} aria-hidden="true" />{side.library}</span>
<span className="duel-stat" title="Hand"><Hand size={13} aria-hidden="true" />{side.hand}</span>
</Tag>;
}
/**
* The duel table (presentational), 360 × 740 first. Controllers (local bot, PvP host) feed it a BoardView and the
* legal moves, and get DuelUIActions back. Attack: tap a Figure (1 tap). Block: tap your Figure,
* then the attacker (2 taps). Both go through a preview → confirm sheet; no drawn arrows.
*/
export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }: {
view: BoardView; legal: Legal; onAct: (a: DuelUIAction) => void; busy?: boolean; error?: string;
onExit?: () => void; onRecap?: () => void;
}) {
const [sheet, setSheet] = useState<Sheet>(null);
const [decl, setDecl] = useState<Declaration>(EMPTY_DECL);
const [targeting, setTargeting] = useState<{ cardId: string; chosen: string[] }>();
const logRef = useRef<HTMLOListElement>(null);
// Hand overflow cue (QA #58): how many hand cards are past the right edge.
const handRef = useRef<HTMLDivElement>(null);
const [hiddenRight, setHiddenRight] = useState(0);
useEffect(() => {
const el = handRef.current;
if (!el) return;
const measure = () => {
const edge = el.getBoundingClientRect().right;
setHiddenRight([...el.children].filter(c => c.getBoundingClientRect().left > edge - 24).length);
};
measure();
el.addEventListener('scroll', measure, { passive: true });
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;
ro?.observe(el);
return () => { el.removeEventListener('scroll', measure); ro?.disconnect(); };
}, [view.hand.length]);
const mine = isMyTurn(view);
const oppSeat = (1 - view.seat) as Seat;
const attackMode = mine && view.phase === 'attack' && !busy;
const blockMode = !mine && view.phase === 'block' && view.combat.length > 0 && !busy;
const stepKey = `${view.turn}:${view.active}:${view.phase}`;
useEffect(() => { setDecl(EMPTY_DECL); setTargeting(undefined); }, [stepKey]);
useEffect(() => { logRef.current?.lastElementChild?.scrollIntoView?.({ block: 'nearest' }); }, [view.log.length]);
const cards = useMemo(() => new Map([...view.me.battlefield, ...view.opponent.battlefield, ...view.hand].map(c => [c.id, c])), [view]);
const attackingIds = new Set(view.combat.map(a => a.attackerId));
const targets = targeting ? nextTargets(legal.plays[targeting.cardId], targeting.chosen) : null;
const refs = useMemo(() => { const m = new Map<string, number>(); for (const c of cards.values()) if (c.url && !m.has(c.url)) m.set(c.url, m.size + 1); return m; }, [cards]);
const play = (cardId: string, targetIds: string[]) => { setTargeting(undefined); setSheet(null); onAct({ type: 'play', cardId, targetIds }); };
const startPlay = (card: BoardCard) => {
const seqs = legal.plays[card.id];
if (!seqs) return;
if (targetsComplete(seqs, [])) play(card.id, []); else { setTargeting({ cardId: card.id, chosen: [] }); setSheet(null); }
};
const chooseTarget = (id: string) => {
if (!targeting || !targets?.has(id)) return;
const chosen = [...targeting.chosen, id];
if (targetsComplete(legal.plays[targeting.cardId], chosen) && !nextTargets(legal.plays[targeting.cardId], chosen).size) play(targeting.cardId, chosen);
else setTargeting({ ...targeting, chosen });
};
const tapMine = (c: BoardCard) => {
if (targets) { chooseTarget(c.id); return; }
if (attackMode && legal.attackers.includes(c.id)) { setDecl(d => toggleAttacker(d, c.id, legal)); return; }
if (blockMode && (legal.blockers[c.id]?.length || decl.blocks[c.id])) { setDecl(d => tapBlocker(d, c.id, legal)); return; }
setSheet({ kind: 'card', card: c, where: 'mine' });
};
const tapTheirs = (c: BoardCard) => {
if (targets) { chooseTarget(c.id); return; }
if (blockMode && attackingIds.has(c.id) && (decl.picked || Object.values(decl.blocks).includes(c.id))) { setDecl(d => tapAttacker(d, c.id, legal)); return; }
setSheet({ kind: 'card', card: c, where: 'theirs' });
};
const blockedBy = (attackerId: string) => Object.entries(decl.blocks).find(([, a]) => a === attackerId)?.[0];
const pendingAttacks: Attack[] = attackMode ? decl.attackers.map(attackerId => ({ attackerId }))
: blockMode ? view.combat.map(a => ({ attackerId: a.attackerId, blockerId: blockedBy(a.attackerId) })) : view.combat;
const stateFor = (c: BoardCard, side: 'mine' | 'theirs') => {
const t = targets?.has(c.id);
if (side === 'mine') return {
attacking: attackMode ? decl.attackers.includes(c.id) : attackingIds.has(c.id),
blocking: !!decl.blocks[c.id] || view.combat.some(a => a.blockerId === c.id),
selected: decl.picked === c.id,
target: t,
dim: (targets && !t) || (attackMode && c.type === 'Figure' && !legal.attackers.includes(c.id)) || (blockMode && !legal.blockers[c.id]?.length && !decl.blocks[c.id]),
};
const canBeBlocked = !!decl.picked && !!legal.blockers[decl.picked]?.includes(c.id);
return { attacking: attackingIds.has(c.id), target: t || canBeBlocked, blocking: view.combat.some(a => a.blockerId === c.id), dim: (targets && !t) || (!!decl.picked && !canBeBlocked) };
};
const row = (list: BoardCard[], side: 'mine' | 'theirs') => {
const top = list.filter(c => !c.attachedTo);
return <div className={`duel-row ${side}`} aria-label={side === 'mine' ? 'Your battlefield' : 'Opponent battlefield'}>
{top.length ? top.map(c => <div key={c.id} className="duel-slot">
<DuelCardFace card={c} size="board" state={stateFor(c, side)} onClick={() => (side === 'mine' ? tapMine(c) : tapTheirs(c))} />
{!!c.attachments?.length && <span className="duel-attach" aria-label={`${c.attachments.length} Doctrine attached`}>+{c.attachments.length}</span>}
{blockMode && side === 'theirs' && blockedBy(c.id) && <span className="duel-pair" aria-hidden="true">{cards.get(blockedBy(c.id)!)?.title}</span>}
</div>) : <span className="duel-empty">No permanents</span>}
</div>;
};
// ---------- primary action ----------
const nAtt = decl.attackers.length, nBlk = Object.keys(decl.blocks).length;
let note: ReactNode = view.log.at(-1) ?? '';
let primary: { label: string; run: () => void; disabled?: boolean } | null = null;
let secondary: { label: string; run: () => void } | null = null;
if (view.phase === 'over') {
// The engine's own game-over sentence (DUEL_DESIGN §8.2); the board never writes story text itself.
note = <span><b>{view.winner === 'draw' ? 'Draw.' : view.winner === view.seat ? 'You won.' : 'You lost.'}</b> {view.log.at(-1)}</span>;
primary = onRecap ? { label: 'Battle recap', run: onRecap } : onExit ? { label: 'Done', run: onExit } : null;
if (onRecap && onExit) secondary = { label: 'Done', run: onExit };
} else if (busy) {
note = <><LoaderCircle className="spin" size={14} /> {mine ? 'Resolving…' : `${view.opponent.name} is choosing…`}</>;
} else if (legal.mulligan) {
note = 'Keep this hand, or mulligan once: shuffle, draw 7, put 1 on the bottom.';
primary = { label: 'Keep hand', run: () => onAct({ type: 'mulligan', keep: true }) };
secondary = { label: 'Mulligan', run: () => onAct({ type: 'mulligan', keep: false }) };
} else if (targeting) {
const c = cards.get(targeting.cardId);
note = <>{targeting.chosen.length ? 'Now choose the next target' : 'Choose a target'} for <b>{c?.title}</b>.</>;
secondary = { label: 'Cancel', run: () => setTargeting(undefined) };
} else if (attackMode) {
note = nAtt ? `${nAtt} attacking. Tap a Figure to add or remove it.` : legal.attackers.length ? 'Tap Figures to attack with them.' : 'No Figure can attack.';
primary = { label: nAtt ? `Attack with ${nAtt}` : 'No attack', run: () => (nAtt ? setSheet({ kind: 'combat', attacks: pendingAttacks, mode: 'attack' }) : onAct({ type: 'attack', attackerIds: [] })) };
} else if (blockMode) {
note = decl.picked ? <>Now tap the attacker <b>{cards.get(decl.picked)?.title}</b> blocks.</> : `${view.combat.length} attacking. Tap your Figure, then the attacker it blocks.`;
primary = { label: nBlk ? `Review ${nBlk} block${nBlk > 1 ? 's' : ''}` : 'Review: no blocks', run: () => setSheet({ kind: 'combat', attacks: pendingAttacks, mode: 'block' }) };
} else if (mine && view.phase === 'main') {
note = Object.keys(legal.plays).length ? 'Tap a card in your hand to read or play it.' : note;
if (legal.canGoToCombat && legal.attackers.length) { primary = { label: 'Combat', run: () => onAct({ type: 'toCombat' }) }; secondary = legal.canEndTurn ? { label: 'End turn', run: () => onAct({ type: 'endTurn' }) } : null; }
else if (legal.canEndTurn) primary = { label: 'End turn', run: () => onAct({ type: 'endTurn' }) };
} else if (mine && legal.canEndTurn) {
primary = { label: 'End turn', run: () => onAct({ type: 'endTurn' }) };
} else if (!mine) {
note = <><LoaderCircle className="spin" size={14} /> {view.opponent.name}’s turn.</>;
}
const outcome = sheet?.kind === 'combat' ? previewCombat(sheet.attacks, cards) : null;
return <section className="duel" aria-label={`Duel against ${view.opponent.name}`}>
<header className="duel-bar">
<span className="duel-turn">Turn <b>{view.turn}</b> · {PHASE_LABEL[view.phase]}{view.active !== view.seat && view.phase !== 'over' ? ` · ${view.opponent.name}` : ''}</span>
{view.clock && view.phase !== 'over' && <span className={`duel-clock ${view.clock.turn <= 10 ? 'low' : ''}`} aria-label={`${view.clock.turn} seconds left this turn, ${view.clock.bank} in the bank`}><Timer size={13} aria-hidden="true" />{view.clock.turn}s<small>+{Math.floor(view.clock.bank / 60)}:{String(view.clock.bank % 60).padStart(2, '0')}</small></span>}
<button className="icon-button duel-log-button" onClick={() => setSheet({ kind: 'log' })} aria-label="Match log"><ScrollText size={16} /></button>
{view.phase !== 'over' && <button className="icon-button" onClick={() => setSheet({ kind: 'concede' })} aria-label="Concede match"><Flag size={16} /></button>}
</header>
<div className="duel-main">
<div className="duel-field">
<SideBar side={view.opponent} who="opponent" active={view.active !== view.seat} target={targets?.has(playerTarget(oppSeat))} onTarget={() => chooseTarget(playerTarget(oppSeat))} />
{row(view.opponent.battlefield, 'theirs')}
<button className="duel-ticker" onClick={() => setSheet({ kind: 'log' })} aria-label="Open match log">
{(attackMode || blockMode) && <span className="duel-ticker-phase">{attackMode ? <Swords size={12} /> : <Shield size={12} />}</span>}
<span>{view.log.at(-1) ?? 'The match began.'}</span>
</button>
{row(view.me.battlefield, 'mine')}
<SideBar side={view.me} who="me" active={view.active === view.seat} target={targets?.has(playerTarget(view.seat))} onTarget={() => chooseTarget(playerTarget(view.seat))} />
</div>
<aside className="duel-log-aside" aria-label="Match log">
<h3>Log</h3>
<ol ref={logRef} className="duel-log">{view.log.map((l, i) => <li key={i}>{l}</li>)}</ol>
</aside>
</div>
<div className="duel-dock">
<div className="duel-hand-wrap">
<div ref={handRef} className={`duel-hand ${hiddenRight ? 'has-more' : ''}`} aria-label={`Your hand, ${view.hand.length} cards`}>
{view.hand.length ? view.hand.map(c => {
const playable = !!legal.plays[c.id] && !busy;
return <DuelCardFace key={c.id} card={c} size="hand" state={{ dim: !playable || !!targeting, selected: targeting?.cardId === c.id }}
onClick={() => setSheet({ kind: 'card', card: c, where: 'hand' })} />;
}) : <span className="duel-empty">No cards in hand.</span>}
</div>
{hiddenRight > 0 && <button type="button" className="duel-hand-more" aria-label={`${hiddenRight} more cards in hand: scroll right`} onClick={() => handRef.current?.scrollBy({ left: handRef.current.clientWidth * 0.8, behavior: 'smooth' })}>+{hiddenRight}</button>}
</div>
<p className="duel-note" role="status" aria-live="polite">{error ? <span className="dock-error">{error}</span> : note}</p>
<div className="duel-actions">
{secondary && <button className="button outline" onClick={secondary.run}>{secondary.label}</button>}
{primary && <button className="button dark duel-primary" onClick={primary.run} disabled={primary.disabled}>{primary.label}</button>}
</div>
</div>
{sheet && <div className="sheet-backdrop" onClick={e => { if (e.target === e.currentTarget) setSheet(null); }}>
<div className={`sheet duel-sheet ${sheet.kind}`} role="dialog" aria-modal="true" aria-label={sheet.kind === 'card' ? sheet.card.title : sheet.kind === 'log' ? 'Match log' : sheet.kind === 'combat' ? 'Combat preview' : 'Concede'}>
<button className="modal-close" onClick={() => setSheet(null)} aria-label="Close"><X size={18} /></button>
{sheet.kind === 'card' && <>
<DuelCardFace card={sheet.card} size="zoom" refNumber={sheet.card.url ? refs.get(sheet.card.url) : undefined} />
<p className="muted small duel-sheet-meta">{sheet.where === 'theirs' ? `${view.opponent.name}’s card` : sheet.where === 'hand' ? 'In your hand' : 'Your card'}
{sheet.card.tapped ? ' · tapped' : ''}{sheet.card.pending ? ' · Pending review (can’t attack this turn)' : ''}{sheet.card.damage ? ` · ${sheet.card.damage} damage marked` : ''}</p>
{sheet.card.connectedNote && <p className="small duel-sheet-meta">Connected: {sheet.card.connectedNote}</p>}
{sheet.where === 'hand' && <div className="play-actions">
{legal.plays[sheet.card.id] && !busy
? <button className="button dark" onClick={() => startPlay(sheet.card)}>{targetsComplete(legal.plays[sheet.card.id], []) ? `Play for ${sheet.card.cost}` : `Play for ${sheet.card.cost}, then choose a target`}</button>
: <p className="muted small">{!mine ? 'You can play cards on your turn.' : view.phase !== 'main' ? 'Cards are played in your main phase.' : sheet.card.cost > view.me.citations ? `Needs ${sheet.card.cost} Citations; you have ${view.me.citations}.` : 'No legal target.'}</p>}
</div>}
</>}
{sheet.kind === 'combat' && outcome && <>
<h3>{sheet.mode === 'attack' ? 'Declare attackers' : 'Declare blockers'}</h3>
<ul className="duel-preview">
{outcome.rows.map(r => <li key={r.attacker.id}>
<span className={r.attackerDies ? 'gone' : ''}>{r.attacker.title} <small>{r.attacker.power}/{r.attacker.toughness}</small></span>
<span className="vs">{r.blocker ? 'blocked by' : sheet.mode === 'attack' ? '→' : 'unblocked →'}</span>
{r.blocker ? <span className={r.blockerDies ? 'gone' : ''}>{r.blocker.title} <small>{r.blocker.power}/{r.blocker.toughness}</small></span>
: <span>{sheet.mode === 'attack' ? view.opponent.name : 'you'} −{r.attacker.power ?? 0}</span>}
</li>)}
</ul>
<p className="muted small">{sheet.mode === 'attack'
? `If unblocked: ${outcome.toPlayer} damage to ${view.opponent.name} (${view.opponent.notability} → ${Math.max(0, view.opponent.notability - outcome.toPlayer)}). ${view.opponent.name} chooses blocks next.`
: `You take ${outcome.toPlayer} (${view.me.notability} → ${Math.max(0, view.me.notability - outcome.toPlayer)}).${outcome.destroyed.length ? ` Struck through: destroyed.` : ''}`}</p>
<div className="play-actions">
<button className="button outline" onClick={() => setSheet(null)}>Change</button>
<button className="button dark" onClick={() => { setSheet(null); onAct(sheet.mode === 'attack' ? { type: 'attack', attackerIds: decl.attackers } : { type: 'block', blocks: blockList(decl) }); }}>
{sheet.mode === 'attack' ? <><Swords size={15} /> Confirm attack</> : <><Shield size={15} /> Confirm blocks</>}
</button>
</div>
</>}
{sheet.kind === 'log' && <><h3>Match log</h3>
<ol className="duel-log full">{view.log.map((l, i) => <li key={i}>{l}</li>)}</ol></>}
{sheet.kind === 'concede' && <><h3>Concede this match?</h3><p className="muted">It counts as a loss. Nothing on-chain changes.</p>
<div className="play-actions"><button className="button outline" onClick={() => setSheet(null)}>Keep playing</button>
<button className="button dark" onClick={() => { setSheet(null); onAct({ type: 'concede' }); }}><Flag size={15} /> Concede</button></div></>}
</div>
</div>}
</section>;
}
+109
View File
@@ -0,0 +1,109 @@
// duel-core (shared/duel) ↔ the board's view model. The only file that knows engine shapes.
import type { DuelAction, LogEvent, PermanentView, PlayerView, Seat, TargetRef } from './contract.ts';
import { boardCard, type ArticleBits } from './cards.ts';
import type { Attack, BoardCard, BoardView, DuelUIAction, Legal, SideView } from './model.ts';
import { NO_LEGAL } from './model.ts';
export const targetId = (t: TargetRef) => (t.kind === 'card' ? t.uid : `player:${t.seat}`);
const targetRef = (id: string): TargetRef => (id.startsWith('player:') ? { kind: 'player', seat: Number(id.slice(7)) as Seat } : { kind: 'card', uid: id });
export type Articles = Record<string, ArticleBits | undefined>;
function permanentCard(p: PermanentView, all: PermanentView[], articles: Articles): BoardCard {
const keywords: string[] = [...p.keywords];
if (p.connected) keywords.push('Connected');
return boardCard(p.card, articles[p.card.cardId], {
id: p.uid, power: p.card.type === 'Figure' || (p.card.toughness ?? 0) > 0 ? p.power : undefined,
toughness: p.card.type === 'Figure' || (p.card.toughness ?? 0) > 0 ? p.toughness : undefined,
keywords, tapped: p.tapped, pending: p.card.type === 'Figure' && p.sick, damage: p.damage || undefined,
attachedTo: p.attachedTo, attachments: all.filter(x => x.attachedTo === p.uid).map(x => x.uid), token: p.card.token,
connectedNote: p.connected ? `${p.connected.tier} (${p.connected.via}): +${p.connected.bonus}/+${p.connected.bonus}` : undefined,
});
}
export function boardFromView(v: PlayerView, names: [string, string], log: string[], articles: Articles = {}, clock?: BoardView['clock']): BoardView {
const opp = (1 - v.seat) as Seat;
const side = (s: PlayerView['opponent'], name: string, seat: Seat): SideView => ({
name, notability: s.life, citations: s.citations, maxCitations: s.maxCitations, library: s.librarySize, hand: s.handSize,
battlefield: v.battlefield.filter(p => p.controller === seat).map(p => permanentCard(p, v.battlefield, articles)), graveyard: s.graveyard.length,
});
const blockerOf = Object.fromEntries(Object.entries(v.combat.blocks).map(([b, a]) => [a, b]));
const combat: Attack[] = v.combat.attackers.map(a => ({ attackerId: a, blockerId: blockerOf[a] }));
return {
seat: v.seat, turn: v.turn, active: v.active, phase: v.phase,
me: side(v.you, names[v.seat], v.seat), opponent: side(v.opponent, names[opp], opp),
hand: v.you.hand.map(i => boardCard(i.card, articles[i.card.cardId], { id: i.uid })),
combat, log, winner: v.result ? (v.result.winner ?? 'draw') : undefined, clock,
};
}
export function legalFromActions(actions: DuelAction[]): Legal {
if (!actions.length) return NO_LEGAL;
const legal: Legal = { plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false };
for (const a of actions) {
switch (a.type) {
case 'play': (legal.plays[a.uid] ??= []).push((a.targets ?? []).map(targetId)); break;
case 'endPhase': legal.canGoToCombat = true; legal.canEndTurn = true; break;
case 'toggleAttacker': legal.attackers.push(a.uid); break;
case 'confirmAttack': legal.canEndTurn = true; break;
case 'block': (legal.blockers[a.blocker] ??= []).push(a.attacker); break;
case 'keep': case 'mulligan': legal.mulligan = true; break;
}
}
return legal;
}
/**
* One board intent → duel-core's atomic actions, in send order. Single-step intents return the exact
* element of `legal` (so the host's deep-equal check passes); declarations are staged on the board and
* sent here as toggle/block × N then confirm (DUEL_API: declarations are monotonic).
*/
export function expand(ui: DuelUIAction, legal: DuelAction[]): DuelAction[] {
const find = (pred: (a: DuelAction) => boolean) => legal.find(pred);
switch (ui.type) {
case 'mulligan': return [ui.keep ? { type: 'keep' } : { type: 'mulligan' }];
case 'play': {
const want = ui.targetIds.join('|');
const a = find(x => x.type === 'play' && x.uid === ui.cardId && (x.targets ?? []).map(targetId).join('|') === want);
return a ? [a] : [{ type: 'play', uid: ui.cardId, ...(ui.targetIds.length ? { targets: ui.targetIds.map(targetRef) } : {}) }];
}
case 'toCombat': return [{ type: 'endPhase' }];
case 'endTurn': return find(x => x.type === 'endPhase') ? [{ type: 'endPhase' }, { type: 'confirmAttack' }] : [{ type: 'confirmAttack' }];
case 'attack': return [...ui.attackerIds.map(uid => ({ type: 'toggleAttacker', uid }) as DuelAction), { type: 'confirmAttack' }];
case 'block': return [...ui.blocks.map(b => ({ type: 'block', blocker: b.blockerId, attacker: b.attackerId }) as DuelAction), { type: 'confirmBlocks' }];
case 'concede': return [{ type: 'concede' }];
}
}
/**
* Fallback log text, used only until duel-design's story renderer (shared/duel/story, DUEL_DESIGN §8.2)
* can read engine events. First variant of each §8.2 template, real card and match data only.
*/
export function plainLog(events: LogEvent[], names: [string, string]): string[] {
const out: string[] = [];
for (const e of events) {
const n = (s: Seat) => names[s];
switch (e.kind) {
case 'turnStart': out.push(`Turn ${e.turn}.`); break;
case 'mulligan': out.push(`${n(e.seat)} took a mulligan.`); break;
case 'deploy': out.push(`${n(e.seat)} deployed ${e.card.title}.`); break;
case 'cast': out.push(`${n(e.seat)} cited ${e.card.title}.`); break;
case 'adopt': out.push(`${e.to.title} adopted ${e.card.title}.`); break;
case 'tokenCreated': out.push(`${e.source.title} created ${e.card.title}.`); break;
case 'attack': out.push(`${e.attackers.map(a => `${a.title} (${a.power}/${a.toughness})`).join(', ')} attacked.`); break;
case 'block': for (const b of e.blocks) out.push(`${b.blocker.title} blocked ${b.attacker.title}.`); break;
case 'playerDamage': out.push(`${n(e.seat)} lost ${e.amount} Notability (${e.life} remaining).`); break;
case 'lifeGain': out.push(`${n(e.seat)} gained ${e.amount} Notability (${e.life}).`); break;
case 'destroyed': out.push(`${e.card.title} was moved to Deleted.`); break;
case 'bounced': out.push(`${e.card.title} was returned to ${n(e.owner)}'s hand.`); break;
case 'connected': out.push(`${e.card.title} was Connected to ${e.with.title} (${e.tier}).`); break;
case 'concede': out.push(`${n(e.seat)} withdrew.`); break;
case 'gameOver': out.push(e.winner === null ? `The match ended in a draw on turn ${e.turn}.`
: e.reason === 'life' ? `${n((1 - e.winner) as Seat)} was nominated for deletion. The result was delete.`
: e.reason === 'library' ? `${n((1 - e.winner) as Seat)} could not draw a card and lost.`
: `${n(e.winner)} won on turn ${e.turn}.`); break;
default: break;
}
}
return out;
}
+83
View File
@@ -0,0 +1,83 @@
// View-only fallback duel bots for the browser bot match. They see only `viewFor` output (Night 1 rule, #5).
// sim-balance owns the real duel bots (shared/bots/duel-bots.ts); these are swapped for its heuristic
// once a PlayerView lens exists (#64). Deterministic given the rng.
import type { DuelAction, PermanentView, PlayerView, Seat } from './contract.ts';
import type { DuelBot } from './decks.ts';
const value = (p: PermanentView) => p.power + p.toughness + p.keywords.length;
const opp = (s: Seat) => (1 - s) as Seat;
function chooseNormal(v: PlayerView, legal: DuelAction[], rng: () => number): DuelAction {
const me = v.seat, them = opp(me);
const mine = v.battlefield.filter(p => p.controller === me), theirs = v.battlefield.filter(p => p.controller === them);
const find = <T extends DuelAction['type']>(t: T) => legal.filter((a): a is Extract<DuelAction, { type: T }> => a.type === t);
if (find('keep').length) return find('keep')[0];
const plays = find('play');
if (plays.length) {
const hand = new Map(v.you.hand.map(i => [i.uid, i.card]));
// Prefer the most expensive card. Targets: harmful effects (damage, destroy, bounce, tap, fight, a
// negative pump) aim at the opponent's side; everything else (pumps, Adopt) at ours.
const owner = (uid: string) => v.battlefield.find(p => p.uid === uid)?.controller;
const harmful = (effects: unknown[]) => effects.some(e => {
const x = e as { op?: string; power?: number; amount?: number };
return ['damage', 'damageEach', 'destroy', 'bounce', 'tap', 'fight', 'drain'].includes(x.op ?? '') || (x.op === 'pump' && ((x.power ?? x.amount ?? 0) < 0));
});
const score = (a: Extract<DuelAction, { type: 'play' }>) => {
const c = hand.get(a.uid);
if (!c) return -1;
const hostile = harmful(c.effects);
let s = c.cost * 10 + rng();
for (const t of a.targets ?? []) s += ((t.kind === 'card' ? owner(t.uid) : t.seat) === them) === hostile ? 3 : -3;
return s;
};
return plays.reduce((b, a) => (score(a) > score(b) ? a : b));
}
const toggles = find('toggleAttacker');
if (toggles.length || find('confirmAttack').length) {
const blockers = theirs.filter(p => !p.tapped && (p.card.type === 'Figure' || p.toughness > 0));
const ready = mine.filter(p => v.combat.attackers.includes(p.uid) || toggles.some(t => t.uid === p.uid));
const lethal = ready.map(p => p.power).sort((a, b) => b - a).slice(blockers.length).reduce((t, x) => t + x, 0) >= v.opponent.life;
const want = toggles.find(t => {
const c = mine.find(p => p.uid === t.uid)!;
if (v.combat.attackers.includes(c.uid)) return false;
if (lethal) return true;
return c.power > 0 && !blockers.some(b => b.power >= c.toughness && b.toughness > c.power);
});
return want ?? find('confirmAttack')[0] ?? legal[0];
}
const blocks = find('block');
if (blocks.length || find('confirmBlocks').length) {
const used = new Set(Object.keys(v.combat.blocks)), covered = new Set(Object.values(v.combat.blocks));
const incoming = v.combat.attackers.filter(a => !covered.has(a)).reduce((t, a) => t + (theirs.find(p => p.uid === a)?.power ?? 0), 0);
const lethal = incoming >= v.you.life;
let best: DuelAction | undefined, bestScore = 0;
for (const b of blocks) {
if (used.has(b.blocker) || covered.has(b.attacker)) continue;
const B = mine.find(p => p.uid === b.blocker), A = theirs.find(p => p.uid === b.attacker);
if (!A || !B) continue;
const kills = B.power >= A.toughness, dies = A.power >= B.toughness;
const s = kills && !dies ? 10 + value(A) : kills ? (value(A) > value(B) ? 5 : lethal ? 3 : 0) : !dies ? 2 : lethal ? 1 : 0;
if (s > bestScore) { bestScore = s; best = b; }
}
return best ?? find('confirmBlocks')[0] ?? legal[0];
}
return find('endPhase')[0] ?? legal[0];
}
/** Chance that Easy makes a random legal move (never concede) instead of Normal's. */
export const EASY_BLUNDER_RATE = 0.3;
export const NORMAL_BOT: DuelBot = { name: 'Normal', choose: chooseNormal };
export const EASY_BOT: DuelBot = {
name: 'Easy',
choose(v, legal, rng) {
if (rng() < EASY_BLUNDER_RATE) return legal[Math.floor(rng() * legal.length)];
return chooseNormal(v, legal, rng);
},
};
export const DUEL_BOTS: DuelBot[] = [EASY_BOT, NORMAL_BOT];
+50
View File
@@ -0,0 +1,50 @@
// DuelCard (duel-cards, shared/duel/derive.ts) → BoardCard. Declared structurally so this file doesn't
// depend on an unmerged branch; once shared/duel/derive.ts is on the integration branch, `DuelCardLike`
// can become `DuelCard` with no other change.
import type { BoardCard, DuelCardType, Portal } from './model.ts';
import { firstSentence } from './model.ts';
export type DuelCardLike = {
cardId: string; pageId: number | null; revisionId?: number; title: string; type: DuelCardType; subtype?: string | null;
description?: string; token?: boolean;
portal: Portal; cost: number; power: number | null; toughness: number | null; keywords: readonly string[];
rulesText: string; flavor: string;
};
/** What the chain (not the derivation) knows about the card's article: art and link. */
export type ArticleBits = { image?: string; url?: string; extract?: string };
export const articleUrl = (title: string) => `https://en.wikipedia.org/wiki/${encodeURIComponent(title.replace(/ /g, '_'))}`;
const SUBTYPE_LABEL: Record<string, string> = {
organisation: 'Organisation', work: 'Work', sport: 'Sport', election: 'Election', conflict: 'Conflict', disaster: 'Disaster',
period: 'Period', mathematics: 'Mathematics', pathology: 'Pathology', language: 'Language', ideology: 'Ideology', team: 'Team', vehicle: 'Vehicle',
};
/** "(1909–1994)", "(born 1963)", "(c.1872–1919)" in the description → "1909–1994", "1963–", "1872–1919". */
export function lifespan(text: string | undefined): string | undefined {
const m = text?.match(/\((?:c\.\s?)?(\d{3,4})\s?[–-]\s?(?:c\.\s?)?(\d{3,4})(?!\d)[^)]*\)|\(born (\d{3,4})\)/);
if (!m) return undefined;
return m[3] ? `${m[3]}–` : `${m[1]}–${m[2]}`;
}
/** The part after the em dash: "History · 1530–1537", "Society · Election". */
export function subtypeLine(card: Pick<DuelCardLike, 'type' | 'subtype' | 'portal' | 'flavor'>): string {
const extra = card.type === 'Figure' ? lifespan(card.flavor) : card.subtype ? SUBTYPE_LABEL[card.subtype] : undefined;
return extra ? `${card.portal} · ${extra}` : card.portal;
}
export function boardCard(card: DuelCardLike, article: ArticleBits = {}, live: Partial<BoardCard> = {}): BoardCard {
// Figures show P/T; Locations only when they have a Garrison (0/T); other types never.
const body = card.type === 'Figure' || (card.type === 'Location' && (card.toughness ?? 0) > 0);
const power = body ? card.power ?? 0 : undefined, toughness = body ? card.toughness ?? 0 : undefined;
return {
id: card.cardId, title: card.title, type: card.type,
subtype: subtypeLine(card),
portal: card.portal, cost: card.cost, power, toughness, basePower: power, baseToughness: toughness,
keywords: [...card.keywords], rulesText: card.rulesText,
flavour: firstSentence(card.flavor || article.extract || card.description),
// Tokens are not articles: no link.
image: article.image, url: card.token ? undefined : article.url ?? articleUrl(card.title), revisionId: card.revisionId, token: card.token,
...live,
};
}
+146
View File
@@ -0,0 +1,146 @@
/**
* The part of duel-core's contract (shared/duel/types.ts and index.ts, PR #72 at 7904199) that the
* board uses, mirrored so this PR doesn't stack on #72 (HANDBOOK: stub the interface). Field names
* and unions are copied verbatim; engine-only details are widened to `unknown`, so real engine values
* are assignable here. When #72 is on night/2026-11-17 this file becomes re-exports of shared/duel.
*/
export type Seat = 0 | 1;
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
export type Keyword = 'Protected' | 'Featured' | 'Legacy' | 'Multilingual' | 'Translated' | 'Well-sourced' | 'Stub' | 'Local' | 'Trending';
export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin';
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
export type EndReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap';
export interface DuelCard {
cardId: string;
pageId: number | null;
revisionId?: number;
title: string;
description?: string;
type: CardType;
subtype?: string | null;
portal: Portal;
cost: number;
power: number | null;
toughness: number | null;
keywords: Keyword[];
territory?: number;
effects: unknown[];
rulesText: string;
flavor: string;
connect?: unknown;
rarity?: 'Common' | 'Rare' | 'Epic' | 'Legendary';
deriveVersion?: string;
token?: boolean;
}
/** Only deckSize is read here; the engine validates the rest. */
export interface DuelRulesetLike { deckSize: number }
export interface CardInstance { uid: string; owner: Seat; card: DuelCard }
export interface CombatState { attackers: string[]; blocks: Record<string, string> }
export interface DuelResult { winner: Seat | null; reason: EndReason }
export type TargetRef = { kind: 'card'; uid: string } | { kind: 'player'; seat: Seat };
export type DuelAction =
| { type: 'keep' }
| { type: 'mulligan' }
| { type: 'play'; uid: string; targets?: TargetRef[] }
| { type: 'endPhase' }
| { type: 'toggleAttacker'; uid: string }
| { type: 'confirmAttack' }
| { type: 'block'; blocker: string; attacker: string }
| { type: 'confirmBlocks' }
| { type: 'concede' }
| { type: 'timeout' };
export interface CardRef { uid: string; cardId: string; title: string; pageId: number | null; type: CardType; power?: number; toughness?: number }
export type LogEvent = { seq: number; turn: number } & (
| { kind: 'start'; firstSeat: Seat }
| { kind: 'mulligan'; seat: Seat }
| { kind: 'keep'; seat: Seat; handSize: number }
| { kind: 'turnStart'; seat: Seat; citations: number; life: [number, number] }
| { kind: 'draw'; seat: Seat; card?: CardRef }
| { kind: 'deploy'; seat: Seat; card: CardRef }
| { kind: 'cast'; seat: Seat; card: CardRef; targets: TargetRef[] }
| { kind: 'adopt'; seat: Seat; card: CardRef; to: CardRef }
| { kind: 'tokenCreated'; seat: Seat; card: CardRef; source: CardRef }
| { kind: 'connected'; seat: Seat; card: CardRef; with: CardRef; tier: ConnectedTier; via: string; bonus: number }
| { kind: 'rivalry'; card: CardRef; with: CardRef; tier: ConnectedTier; via: string }
| { kind: 'effect'; seat: Seat; source: CardRef; op: string; template?: string; targets: TargetRef[] }
| { kind: 'attack'; seat: Seat; attackers: CardRef[] }
| { kind: 'block'; seat: Seat; blocks: { blocker: CardRef; attacker: CardRef }[] }
| { kind: 'effectDamage'; source: CardRef; target: CardRef; amount: number }
| { kind: 'combatDamage'; source: CardRef; target: CardRef; amount: number }
| { kind: 'playerDamage'; source: CardRef | null; seat: Seat; amount: number; life: number; combat: boolean }
| { kind: 'lifeGain'; source: CardRef; seat: Seat; amount: number; life: number }
| { kind: 'destroyed'; card: CardRef; owner: Seat }
| { kind: 'bounced'; card: CardRef; owner: Seat }
| { kind: 'discard'; seat: Seat; card: CardRef }
| { kind: 'fatigue'; seat: Seat; amount: number }
| { kind: 'concede'; seat: Seat }
| { kind: 'timeout'; seat: Seat }
| { kind: 'gameOver'; winner: Seat | null; reason: EndReason; life: [number, number] }
);
export interface PermanentView {
uid: string;
owner: Seat;
controller: Seat;
card: DuelCard;
tapped: boolean;
sick: boolean;
damage: number;
counters: number;
attachedTo?: string;
power: number;
toughness: number;
keywords: Keyword[];
connected?: { with: string; tier: ConnectedTier; via: string; bonus: number };
}
export interface SideView {
seat: Seat;
life: number;
citations: number;
maxCitations: number;
handSize: number;
librarySize: number;
graveyard: CardInstance[];
bankSeconds: number;
ready: boolean;
mulligansTaken: number;
}
export interface PlayerView {
engine: 'duel';
seat: Seat;
turn: number;
active: Seat;
phase: Phase;
toAct: Seat | null;
you: SideView & { hand: CardInstance[] };
opponent: SideView;
battlefield: PermanentView[];
combat: CombatState;
result: DuelResult | null;
version: number;
rules: unknown;
}
/**
* The slice of `DuelEngineApi` (shared/duel/index.ts) the bot match calls. Method syntax on purpose:
* the real engine (typed on the full DuelState/DuelRuleset/DuelCard) is assignable to it.
*/
export interface DuelEngineLike<S = unknown, R = unknown> {
createDuel(rules: R, decks: [DuelCard[], DuelCard[]], seed: string): S;
legalActions(state: S, seat: Seat): DuelAction[];
applyAction(state: S, seat: Seat, action: DuelAction): S;
toAct(state: S): Seat | null;
isOver(state: S): boolean;
viewFor(state: S, seat: Seat): PlayerView;
logFor(state: S, seat: Seat): LogEvent[];
}
+44
View File
@@ -0,0 +1,44 @@
// Local (in-browser) match driver, engine-agnostic. ./adapter.ts binds it to duel-core's shared/duel.
// The bot gets only its own seat's view (viewFor), never the full state (Night 1 rule, #5).
import type { BoardView, DuelUIAction, Legal, Seat } from './model.ts';
/** The engine as the board needs it. `A` is the engine's atomic action; `S` its state. */
export interface DuelEnginePort<S, A> {
legal(s: S, seat: Seat): A[];
apply(s: S, seat: Seat, a: A): S;
/** Whose input the engine is waiting for, or null when the match is over. */
toAct(s: S): Seat | null;
board(s: S, seat: Seat, names: [string, string]): BoardView;
legalForBoard(actions: A[], view: BoardView): Legal;
/** One board-level intent → the engine's atomic actions, in order. Each must be legal when sent. */
expand(ui: DuelUIAction, actions: A[], view: BoardView): A[];
}
export type BotChoose<S, A> = (s: S, seat: Seat, legal: A[], rng: () => number) => A;
/** Applies a sequence for one seat, re-checking legality at every step. Throws on the first illegal action. */
export function applySequence<S, A>(port: DuelEnginePort<S, A>, s: S, seat: Seat, seq: A[], same: (a: A, b: A) => boolean): S {
for (const a of seq) {
const legal = port.legal(s, seat);
if (!legal.some(l => same(l, a))) throw new Error('That move is no longer legal.');
s = port.apply(s, seat, a);
}
return s;
}
/** Runs bot moves until the human must act or the match ends. Bounded, so a broken bot can't hang the tab. */
export function runBot<S, A>(port: DuelEnginePort<S, A>, s: S, human: Seat, choose: BotChoose<S, A>, rng: () => number, maxSteps = 500): S {
const bot = (human === 0 ? 1 : 0) as Seat;
for (let i = 0; i < maxSteps; i++) {
if (port.toAct(s) !== bot) return s;
const legal = port.legal(s, bot);
if (!legal.length) return s;
s = port.apply(s, bot, choose(s, bot, legal, rng));
}
return s;
}
/** Stable structural equality for plain JSON actions. */
export const sameAction = (a: unknown, b: unknown): boolean => stable(a) === stable(b);
const stable = (v: unknown): string => JSON.stringify(v, (_k, x) =>
x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([p], [q]) => p.localeCompare(q))) : x);
+40
View File
@@ -0,0 +1,40 @@
// Pure deck helpers for the bot match (no React, no CSS), so they are unit-tested under Node.
import type { DuelAction, DuelCard, PlayerView } from './contract.ts';
/** A collection card as ui-pvp passes it (ownership's ChainCard satisfies this). `duel` is the server-derived frozen profile. */
export type BotMatchCard = { tokenId: string; title: string; url?: string; imageUrl?: string; extract?: string; duel?: unknown };
const TYPES = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine'];
/** Shape check for a profile that arrives untyped over the wire (the engine's validateDeck does the rest). */
export function isDuelCard(v: unknown): v is DuelCard {
const c = v as Partial<DuelCard> | null;
return !!c && typeof c === 'object' && typeof c.title === 'string' && TYPES.includes(c.type as string) && typeof c.cost === 'number'
&& Array.isArray(c.keywords) && Array.isArray(c.effects) && typeof c.rulesText === 'string';
}
/** The bot sees only its own seat's view (Night 1 rule, #5). */
export type DuelBot = { name: string; choose(view: PlayerView, legal: DuelAction[], rng: () => number): DuelAction };
export function mulberry(seed: number) {
return () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}
export const hash = (s: string) => { let h = 2166136261; for (const c of s) h = Math.imul(h ^ c.charCodeAt(0), 16777619); return h >>> 0; };
/** The bot's own deck: `size` distinct cards from a pool (the 236 real sample cards), seeded, within the copy limit. */
export function botDeck(pool: readonly DuelCard[], size: number, seed: string): DuelCard[] {
const rng = mulberry(hash(`bot-deck:${seed}`));
const shuffled = [...pool].sort((a, b) => a.cardId.localeCompare(b.cardId));
for (let i = shuffled.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; }
return shuffled.slice(0, size).map(c => ({ ...c, cardId: `bot:${c.cardId}` }));
}
/** Resolves the player's deck: exactly `deckSize` owned cards, each with a frozen profile. Returns problems instead of a partial deck. */
export function playerDeck(deck: string[], cards: BotMatchCard[], deckSize: number): { cards: DuelCard[]; pending: string[]; missing: string[] } {
const byId = new Map(cards.map(c => [c.tokenId, c]));
const out: DuelCard[] = [], pending: string[] = [], missing: string[] = [];
for (const id of deck) {
const c = byId.get(id);
if (!c) missing.push(id); else if (!isDuelCard(c.duel)) pending.push(c.title); else out.push({ ...c.duel, cardId: id });
}
return { cards: out.length === deckSize && deck.length === deckSize ? out : [], pending, missing };
}
+167
View File
@@ -0,0 +1,167 @@
/* Duel board (ui-duel, #58). Mobile-first: everything must read at 360 × 740 with a full 5 + 5 board.
Portals take MTG colour analogues: Arts red, Earth green, History black, Science blue, Society white. */
.duel{--gap:6px;display:flex;flex-direction:column;gap:var(--gap);max-width:1180px;margin:0 auto;padding:6px 8px 0;color:var(--ctp-text);background:var(--ctp-mantle);border:1px solid var(--theme-border);border-radius:12px;min-height:min(100dvh,980px);font-size:13px}
.duel button{font:inherit;color:inherit;cursor:pointer}
.duel-bar{display:flex;align-items:center;gap:6px;min-height:36px}
.duel-turn{font-size:12px;color:var(--ctp-subtext1);margin-right:auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.duel-clock{display:inline-flex;align-items:center;gap:3px;font-size:12px;font-variant-numeric:tabular-nums;color:var(--ctp-subtext1)}
.duel-clock small{color:var(--ctp-overlay1);font-size:10px}
.duel-clock.low{color:var(--ctp-red)}
.duel .icon-button{min-width:36px;min-height:36px}
.duel-main{display:flex;gap:10px;flex:1 1 auto;min-height:0}
.duel-field{display:flex;flex-direction:column;gap:var(--gap);flex:1 1 auto;min-width:0}
/* Player bars: Notability, Citations, library and hand are always visible. */
.duel-side{display:flex;align-items:center;gap:10px;padding:5px 8px;border-radius:8px;background:var(--ctp-base);border:1px solid var(--ctp-surface0);font-size:12px;font-variant-numeric:tabular-nums}
.duel-side.is-target{width:100%;text-align:left;box-shadow:0 0 0 2px var(--ctp-yellow);animation:dface-pulse 1.1s ease-in-out infinite}
.duel-side.is-active{border-color:var(--theme-accent);box-shadow:inset 3px 0 0 var(--theme-accent)}
.duel-side-name{font-weight:700;margin-right:auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.duel-stat{display:inline-flex;align-items:center;gap:3px;color:var(--ctp-subtext1)}
.duel-stat b{font-size:15px;color:var(--ctp-text)}
.duel-stat small{color:var(--ctp-overlay1)}
.duel-stat.life svg{color:var(--ctp-yellow)}
.duel-stat.life.low b{color:var(--ctp-red)}
.duel-stat.cites svg{color:var(--ctp-blue)}
/* Battlefields: one scrollable row per side; 5 cards fit 344 px without scrolling. */
.duel-row{display:flex;gap:4px;overflow-x:auto;overscroll-behavior-x:contain;scrollbar-width:none;min-height:102px;padding:4px 0;align-items:flex-start}
.duel-zoomgrid .dface-zoom{align-self:start}
.duel-row::-webkit-scrollbar{display:none}
.duel-row.theirs{align-items:flex-end}
.duel-slot{position:relative;display:flex;flex-direction:column;align-items:stretch;flex:1 1 0;min-width:62px;max-width:110px}
.duel-empty{flex:1;align-self:center;text-align:center;font-size:12px;color:var(--ctp-overlay1);padding:8px}
.duel-attach{position:absolute;top:-5px;right:-3px;z-index:3;font-size:12px;font-weight:800;padding:1px 5px;border-radius:8px;background:var(--ctp-mauve);color:var(--ctp-crust)}
.duel-pair{font-size:9px;line-height:1.2;color:var(--ctp-green);text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:2px}
.duel-ticker{display:flex;align-items:center;gap:6px;width:100%;min-height:36px;padding:6px 10px;border-radius:8px;background:var(--ctp-crust);border:1px dashed var(--ctp-surface1);text-align:left;font-size:12px;line-height:1.35;color:var(--ctp-subtext1)}
.duel-ticker>span:last-child{overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
.duel-ticker-phase{display:inline-flex;color:var(--theme-accent);flex:0 0 auto}
.duel-log-aside{display:none}
.duel-log{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px;font-size:13px;line-height:1.5;color:var(--ctp-subtext1)}
.duel-log li{padding-left:10px;border-left:2px solid var(--ctp-surface1)}
.duel-log li:last-child{border-left-color:var(--theme-accent);color:var(--ctp-text)}
.duel-log.full{max-height:60vh;overflow:auto}
/* Dock: hand, status line, actions. Sticky so the thumb always reaches it. */
.duel-dock{position:sticky;bottom:0;z-index:5;margin:0 -8px;padding:6px 8px calc(8px + env(safe-area-inset-bottom));background:var(--ctp-mantle);border-top:1px solid var(--theme-border);border-radius:0 0 12px 12px;display:flex;flex-direction:column;gap:6px}
.duel-hand{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;padding:6px 0 2px;min-height:112px}
.duel-hand::-webkit-scrollbar{display:none}
.duel-hand-wrap{position:relative}
.duel-hand.has-more{-webkit-mask-image:linear-gradient(to right,#000 78%,transparent);mask-image:linear-gradient(to right,#000 78%,transparent)}
.duel-hand-more{position:absolute;right:0;top:50%;transform:translateY(-50%);min-width:40px;min-height:40px;border-radius:20px;background:var(--ctp-surface1);color:var(--ctp-text);font-weight:800;font-size:13px;box-shadow:0 2px 8px rgb(0 0 0/.4)}
.duel-note{margin:0;min-height:18px;font-size:12px;line-height:1.35;color:var(--ctp-subtext1);display:flex;align-items:center;gap:6px}
.duel-actions{display:flex;gap:8px;justify-content:flex-end}
.duel-actions .button{min-height:46px;font-size:13px;padding:10px 16px}
.duel-actions .duel-primary{flex:1 1 auto;max-width:280px}
/* ---------- card faces ---------- */
.dface{--portal:var(--ctp-overlay1);--portal-ink:var(--ctp-crust);position:relative;display:flex;flex-direction:column;align-items:stretch;text-align:left;padding:0;background:var(--ctp-base);color:var(--ctp-text);border:1.5px solid color-mix(in srgb,var(--portal) 65%,var(--ctp-surface1));border-radius:8px;overflow:hidden;transition:transform .15s ease,box-shadow .15s ease,opacity .15s ease}
.dface.portal-arts{--portal:var(--ctp-red)}
.dface.portal-earth{--portal:var(--ctp-green)}
.dface.portal-history{--portal:var(--ctp-surface2);--portal-ink:var(--ctp-text)}
.dface.portal-science{--portal:var(--ctp-blue)}
.dface.portal-society{--portal:var(--ctp-rosewater)}
.dface.portal-neutral{--portal:var(--ctp-overlay0);--portal-ink:var(--ctp-text)}
.dface-art{position:relative;display:flex;align-items:center;justify-content:center;height:32px;overflow:hidden;color:var(--portal);background:color-mix(in srgb,var(--portal) 25%,var(--ctp-surface0))}
.dface-art img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
.dface-art svg{position:relative;opacity:.9}
.dface-art:has(img:not([style*="none"])) svg{position:absolute;right:3px;bottom:3px;width:14px;height:14px;padding:2px;border-radius:4px;background:rgb(0 0 0/.55);color:#fff;box-sizing:content-box}
.dface-cost{position:absolute;top:3px;left:3px;z-index:2;min-width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:12px;background:var(--ctp-blue);color:var(--ctp-crust);box-shadow:0 1px 3px rgb(0 0 0/.4)}
.dface-title{font-size:10.5px;font-weight:700;line-height:1.2;padding:3px 4px 0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;min-height:2.4em;overflow-wrap:break-word;hyphens:auto}
.dface-bottom{display:flex;align-items:center;gap:2px;padding:2px 2px 3px;margin-top:auto;min-width:0}
.dface-type{display:inline-flex;color:var(--portal);flex:0 0 auto}
.dface-kwicon{display:inline-flex;align-items:center;justify-content:center;width:15px;height:16px;border-radius:4px;flex:0 0 auto;background:color-mix(in srgb,var(--portal) 30%,var(--ctp-surface0));color:var(--ctp-text)}
.dface-chip{font-size:9px;font-weight:700;padding:1px 3px;border-radius:3px;background:color-mix(in srgb,var(--portal) 30%,var(--ctp-surface0));color:var(--ctp-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
.dface-pt{margin-left:auto;flex:0 0 auto;font-size:12px;font-weight:800;padding:0 3px;letter-spacing:-.3px;border-radius:4px;background:var(--ctp-surface0);font-variant-numeric:tabular-nums}
.dface-pt .up{color:var(--ctp-green)}.dface-pt .down{color:var(--ctp-red)}
.dface-flag{position:absolute;top:3px;right:3px;z-index:2;display:flex;padding:3px;border-radius:50%}
.dface-flag.attack{background:var(--ctp-red);color:var(--ctp-crust)}
.dface-flag.block{background:var(--ctp-green);color:var(--ctp-crust)}
.dface-board{width:100%;min-height:90px}
.dface-hand{flex:0 0 80px;width:80px;min-height:106px}
.dface-hand .dface-art{height:42px}
.dface-hand .dface-title{font-size:11px}
.dface.is-tapped{opacity:.62;filter:saturate(.6)}
.dface.is-tapped::after{content:'';position:absolute;inset:0;background:repeating-linear-gradient(135deg,transparent 0 6px,rgb(0 0 0/.12) 6px 8px);pointer-events:none}
.dface.is-pending .dface-art{filter:grayscale(.7)}
.dface.is-selected{box-shadow:0 0 0 2px var(--theme-accent);transform:translateY(-4px)}
.dface.is-attacking{box-shadow:0 0 0 2px var(--ctp-red);transform:translateY(-4px)}
.duel-row.theirs .dface.is-attacking{transform:translateY(4px)}
.dface.is-blocking{box-shadow:0 0 0 2px var(--ctp-green)}
.dface.is-target{box-shadow:0 0 0 2px var(--ctp-yellow);animation:dface-pulse 1.1s ease-in-out infinite}
.dface.is-dim{opacity:.42}
.dface.is-token{border-style:dashed}
.dface.is-fresh{animation:dface-in .4s ease-out}
.dface:focus-visible{outline:2px solid var(--theme-accent);outline-offset:2px}
@keyframes dface-pulse{50%{box-shadow:0 0 0 4px color-mix(in srgb,var(--ctp-yellow) 55%,transparent)}}
@keyframes dface-in{from{transform:scale(.7);opacity:0}to{transform:none;opacity:1}}
@media (prefers-reduced-motion:reduce){.dface{transition:none}.dface.is-target,.dface.is-fresh{animation:none}}
/* Zoom face: the full MTG layout, in the tap-to-zoom sheet. */
.dface-zoom{width:min(300px,100%);margin:0 auto;border-width:3px;border-radius:14px;background:color-mix(in srgb,var(--portal) 10%,var(--ctp-base));padding:8px;gap:6px}
.dface-namebar{display:flex;align-items:center;gap:8px;padding:4px 8px;border-radius:7px;background:var(--ctp-surface0)}
.dface-name{font-family:Georgia,'Times New Roman',serif;font-size:17px !important;font-weight:700;line-height:1.2;margin:0 !important;flex:1 1 auto;min-width:0}
.dface-zoom .dface-cost{position:static;min-width:26px;height:26px;font-size:15px}
.dface-zoom .dface-art{height:150px;border-radius:6px}
.dface-typeline{display:flex;align-items:center;gap:6px;margin:0;padding:4px 8px;border-radius:7px;background:var(--ctp-surface0);font-size:13px !important;font-weight:600}
.dface-portal{margin-left:auto;font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.5px;padding:2px 6px;border-radius:4px;background:var(--portal);color:var(--portal-ink)}
.dface-textbox{padding:8px 10px;border-radius:7px;background:var(--ctp-crust);display:flex;flex-direction:column;gap:6px;min-height:88px}
.dface-textbox p{margin:0;font-size:13.5px !important;line-height:1.45 !important}
.dface-keywords{font-weight:700}
.dface-flavour{font-family:Georgia,'Times New Roman',serif;font-style:italic;color:var(--ctp-subtext0);border-top:1px solid var(--ctp-surface0);padding-top:6px}
.dface-flavour sup a{font-style:normal;font-family:inherit;color:var(--ctp-blue);text-decoration:none;margin-left:1px;padding:4px 2px}
.dface-footer{display:flex;align-items:center;gap:6px}
.dface-rev{font-size:10px;color:var(--ctp-overlay1);font-variant-numeric:tabular-nums}
.dface-zoom .dface-pt{font-size:18px;padding:2px 10px;border:2px solid var(--portal);background:var(--ctp-base)}
.duel-sheet .duel-sheet-meta{text-align:center;margin:8px 0}
.duel-preview{list-style:none;padding:0;margin:8px 0;display:flex;flex-direction:column;gap:6px}
.duel-preview li{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px;font-size:14px;padding:8px 10px;border-radius:8px;background:var(--ctp-base)}
.duel-preview small{color:var(--ctp-overlay1);font-variant-numeric:tabular-nums}
.duel-preview .vs{color:var(--ctp-subtext0);font-size:12px}
.duel-preview .gone{text-decoration:line-through;color:var(--ctp-red)}
/* Eligibility gate */
.duel-gate{max-width:560px;margin:0 auto;padding:22px 16px;border:1px solid var(--theme-border);border-radius:12px;background:var(--ctp-mantle);color:var(--ctp-text)}
.duel-gate h2{font-size:22px;margin:0 0 8px}
.duel-gate-bar{height:10px;border-radius:5px;background:var(--ctp-surface0);overflow:hidden;margin:12px 0 6px}
.duel-gate-bar i{display:block;height:100%;background:var(--theme-accent)}
/* Tall phones (≥ 720 px): give the spare height to the cards, with 3-line titles (QA #58). */
@media (max-width:899px) and (min-height:720px){
.dface-board{min-height:112px}
.dface-board .dface-art{height:42px}
.dface-board .dface-title{-webkit-line-clamp:3;min-height:3.6em}
.dface-hand{min-height:128px}
.dface-hand .dface-art{height:52px}
.dface-hand .dface-title{-webkit-line-clamp:3;min-height:3.6em}
.duel-hand{min-height:134px}
}
/* Desktop: bigger cards, log always visible beside the field. */
@media (min-width:900px){
.duel{padding:10px 14px 0;font-size:14px}
.duel-log-button{display:none}
.duel-log-aside{display:flex;flex-direction:column;flex:0 0 300px;max-height:calc(100dvh - 240px);min-height:380px;padding:10px 12px;border-radius:10px;background:var(--ctp-base);border:1px solid var(--ctp-surface0)}
.duel-log-aside h3{font-size:12px;letter-spacing:1px;text-transform:uppercase;color:var(--ctp-subtext0);margin:0 0 8px}
.duel-log-aside .duel-log{overflow:auto}
.duel-ticker{display:none}
.duel-row{justify-content:center;min-height:150px;gap:8px}
.duel-slot{min-width:96px;max-width:120px}
.dface-board{min-height:140px}
.dface-board .dface-art{height:62px}
.dface-board .dface-title{font-size:12.5px}
.dface-board .dface-chip{font-size:9px}
.dface-board .dface-kwicon{width:20px;height:20px}
.dface-board .dface-pt{font-size:14px}
.dface-board .dface-cost{min-width:24px;height:24px;font-size:13px}
.dface-hand{flex-basis:104px;width:104px;min-height:138px}
.dface-hand .dface-art{height:60px}
.dface-hand .dface-title{font-size:12.5px}
.duel-hand{justify-content:center;min-height:146px}
.duel-dock{margin:0 -14px;padding:8px 14px 12px}
}
+105
View File
@@ -0,0 +1,105 @@
// Preview data for the duel board: real cards from docs/game/card-sample.json, with a deliberately
// crude stand-in derivation so the board can be built and screenshotted before duel-cards' real
// shared/duel/derive.ts lands. Never used for real matches. No network calls.
import sample from '../../../docs/game/card-sample.json';
import type { BoardCard, BoardView, DuelCardType, Legal, Portal } from './model.ts';
type SampleCard = {
pageId: number; title: string; description?: string | null; revisionId: number; pageBytes: number; languageCount: number;
categories: string[]; instanceOf?: { id: string; label: string }[]; tiers: { attention: number; depth: number; reach: number };
};
const CARDS = (sample as unknown as { cards: SampleCard[] }).cards;
function previewType(c: SampleCard): DuelCardType {
const labels = (c.instanceOf ?? []).map(i => i.label).join(' ');
const d = c.description ?? '';
if (c.instanceOf?.some(i => i.id === 'Q5') || /\btaxon\b/.test(labels) || /^(Species|Genus) of/.test(d)) return 'Figure';
if (/commune|municipality|village|town|river|settlement|mosque|parish|area/i.test(labels + d)) return 'Location';
if (/election|storm|nor.easter|battle|match|final|season|war/i.test(labels + d)) return 'Event';
if (/company|band|group|film|team|organi[sz]ation|party/i.test(labels + d)) return 'Institution';
return 'Doctrine';
}
function previewPortal(c: SampleCard, t: DuelCardType): Portal {
const s = `${c.description ?? ''} ${c.categories.join(' ')}`;
if (/century|deaths|sultan|empire|medieval|monarch|queen|king/i.test(s)) return 'History';
if (/mathemat|algebra|programming|gene|disease|scientist|botanist|archaeolog/i.test(s)) return 'Science';
if (/actor|singer|film|band|music|novel|television/i.test(s)) return 'Arts';
if (/species|genus|river|fungus|plant|orchid|commune|village/i.test(s)) return 'Earth';
if (/politic|election|protest|footballer|team|government/i.test(s)) return 'Society';
return t === 'Figure' ? 'Society' : t === 'Location' ? 'Earth' : 'Neutral';
}
const years = (d?: string | null) => d?.match(/\(([^)]*\d{3,4}[^)]*)\)/)?.[1]?.replace(/^(c\.|born )/, '').replace('born ', '');
export function previewCard(c: SampleCard, suffix = ''): BoardCard {
const type = previewType(c), portal = previewPortal(c, type);
const fame = Math.round((c.tiers.attention * 2 + c.tiers.depth + c.tiers.reach) / 4);
const cost = Math.max(1, Math.min(6, Math.ceil(fame * 0.6)));
const keywords: string[] = [];
if (c.categories.includes('Living people')) keywords.push('Protected');
if (c.tiers.attention >= 9) keywords.push('Featured');
if (c.languageCount >= 20 && keywords.length < 2) keywords.push('Translated');
if (c.categories.some(x => /\d+ deaths/.test(x)) && keywords.length < 2) keywords.push('Legacy');
if ((c.pageBytes < 3000 || c.categories.some(x => /stubs/.test(x))) && keywords.length < 2) keywords.push('Stub');
const k = Math.ceil(cost / 2);
let power: number | undefined, toughness: number | undefined, rulesText = '';
if (type === 'Figure') {
const b = 2 * cost + 1, s = Math.min(0.7, Math.max(0.3, c.tiers.attention / (c.tiers.attention + c.tiers.depth || 1)));
power = Math.max(1, Math.round(b * s)) - (keywords.length > 1 ? 1 : 0); toughness = Math.max(1, b - Math.round(b * s));
} else if (type === 'Location') {
power = 0; toughness = 1 + Math.floor(c.tiers.depth / 3);
rulesText = `Territory. Garrison 0/${toughness}.`;
} else if (type === 'Event') {
rulesText = /storm|nor.easter/i.test(c.description ?? '') ? `Deal ${Math.max(1, k - 1)} damage to each Figure and each Location.`
: /election/i.test(c.description ?? '') ? `Create ${k} 1/1 Society Figure tokens named Elected Member.`
: `Target Figure you control gets +${k}/+0 until end of turn, then fights target Figure you don't control.`;
} else if (type === 'Institution') {
rulesText = cost >= 4 ? 'At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.' : 'Figures you control with power 2 or less get +1/+0.';
} else {
rulesText = /disease/i.test(c.description ?? '') ? `Attach to target Figure. It gets −${k}/−${k}.` : `Adopt. Adopted Figure gets +${k}/+${k}.`;
}
const sub = type === 'Figure' ? [portal, years(c.description)].filter(Boolean).join(' · ') : portal;
return {
id: `${c.pageId}${suffix}`, title: c.title, type, subtype: sub, portal, cost, power, toughness, basePower: power, baseToughness: toughness,
keywords: type === 'Figure' ? keywords.slice(0, 2) : [], rulesText, flavour: c.description ? `${c.description}.` : undefined,
url: `https://en.wikipedia.org/wiki/${encodeURIComponent(c.title.replace(/ /g, '_'))}`, revisionId: c.revisionId,
};
}
export const PREVIEW_POOL: BoardCard[] = CARDS.map(c => previewCard(c));
const byTitle = (t: string) => PREVIEW_POOL.find(c => c.title === t) ?? PREVIEW_POOL[0];
const figures = PREVIEW_POOL.filter(c => c.type === 'Figure');
/** A full 5 + 5 board for screenshots and tests. `scene` picks whose step it is. */
export function previewView(scene: 'main' | 'attack' | 'block' | 'over' = 'main'): { view: BoardView; legal: Legal } {
const mine = [byTitle('Jess Harnell'), byTitle('Dichromorpha viridis'), byTitle('Salahuddin of Aceh'), byTitle('Pathrail Mosque'), byTitle('Hiroshima Electric Railway')]
.map((c, i) => ({ ...c, pending: i === 1 && scene === 'main' }));
const theirs = [byTitle('Isabella of Aragon, Queen of Portugal'), byTitle('Miloje Vasić'), figures[12], byTitle('Topusko'), byTitle('Zbyszek Godlewski')]
.map((c, i) => ({ ...c, id: `${c.id}-o`, damage: i === 1 ? 1 : 0 }));
mine[0] = { ...mine[0], attachments: ['doc-1'], power: (mine[0].power ?? 0) + 2, toughness: (mine[0].toughness ?? 0) + 2 };
const hand = [byTitle('Agda (programming language)'), byTitle('April 2021 nor\'easter'), byTitle('Mary Sophie Young'), byTitle('Charmont-en-Beauce'), byTitle('Heart rot'), byTitle('Joseph Ujlaki')];
const log = [
'Turn 1. Bot (Normal) kept a hand of seven.',
'Turn 3. You cited Pathrail Mosque. Maximum Citations rose to 4.',
'Turn 4. Isabella of Aragon, Queen of Portugal (6/5) attacked. Dichromorpha viridis (4/2) blocked and was reverted.[2]',
'Turn 5. You deployed Jess Harnell. Bot (Normal) lost 3 Notability.',
'Turn 6. Miloje Vasić was assigned 1 damage.',
];
const view: BoardView = {
seat: 0, turn: 6, active: scene === 'block' ? 1 : 0, phase: scene === 'main' ? 'main' : scene === 'attack' ? 'attack' : scene === 'block' ? 'block' : 'over',
me: { name: 'You', notability: 14, citations: scene === 'main' ? 4 : 1, maxCitations: 6, library: 27, hand: hand.length, battlefield: mine, graveyard: 3 },
opponent: { name: 'Bot (Normal)', notability: scene === 'over' ? 0 : 11, citations: 0, maxCitations: 6, library: 26, hand: 4, battlefield: theirs, graveyard: 2 },
hand, combat: scene === 'block' ? [{ attackerId: theirs[0].id }, { attackerId: theirs[1].id }, { attackerId: theirs[2].id }] : [],
log, winner: scene === 'over' ? 0 : undefined, clock: { turn: 42, bank: 251 },
};
const myFigs = mine.filter(c => c.type === 'Figure' && !c.pending).map(c => c.id);
const legal: Legal = scene === 'main' ? {
...emptyLegal(), canGoToCombat: true, canEndTurn: true, attackers: myFigs,
plays: Object.fromEntries(hand.filter(c => c.cost <= 4).map(c => [c.id,
c.type === 'Doctrine' ? mine.filter(m => m.type === 'Figure').map(m => [m.id])
: c.type === 'Event' ? mine.filter(m => m.type === 'Figure').flatMap(m => theirs.filter(t => t.type === 'Figure').map(t => [m.id, t.id])) : [[]]])),
} : scene === 'attack' ? { ...emptyLegal(), attackers: myFigs, canEndTurn: true }
: scene === 'block' ? { ...emptyLegal(), blockers: Object.fromEntries(mine.filter(c => c.type === 'Figure' || c.type === 'Location').map(c => [c.id, view.combat.map(a => a.attackerId)])) }
: emptyLegal();
return { view, legal };
}
const emptyLegal = (): Legal => ({ plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false });
+235
View File
@@ -0,0 +1,235 @@
// ui-duel (#58): the duel board's own view model. Board components read only these types, so the
// engine contract (duel-core, mirrored in ./contract.ts) is mapped in exactly one place: ./adapter.ts.
// Nothing here moves cards on-chain; matches are off-chain and never burn or transfer.
export type DuelCardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
export type Seat = 0 | 1;
/** duel-core's phases (refresh, draw, damage and end are automatic). */
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
/** One card as the board shows it. Hidden cards never reach the board (opponent's hand is a count). */
export type BoardCard = {
id: string;
title: string;
type: DuelCardType;
/** The line after the em dash, e.g. "People · 1961–". */
subtype?: string;
portal: Portal;
cost: number;
power?: number;
toughness?: number;
/** Base stats, to colour buffs and debuffs. */
basePower?: number;
baseToughness?: number;
/** Damage marked this turn. */
damage?: number;
keywords: string[];
rulesText: string;
/** First sentence of the on-chain extract. */
flavour?: string;
image?: string;
url?: string;
revisionId?: number;
tapped?: boolean;
/** "Pending review": entered this turn, can't attack. */
pending?: boolean;
/** Doctrine attached to this card (ids), or the Figure a Doctrine is attached to. */
attachments?: string[];
attachedTo?: string;
token?: boolean;
/** Active Connected bonus, e.g. "Compatriot (Portugal): +1/+1". */
connectedNote?: string;
};
export type SideView = {
name: string;
notability: number;
citations: number;
maxCitations: number;
library: number;
hand: number;
battlefield: BoardCard[];
graveyard: number;
};
export type Attack = { attackerId: string; blockerId?: string };
export type BoardView = {
seat: Seat;
turn: number;
/** Whose turn it is. */
active: Seat;
phase: Phase;
me: SideView;
opponent: SideView;
hand: BoardCard[];
/** Current combat: attackers (opponent's when I'm blocking) and any blocks already declared. */
combat: Attack[];
log: string[];
winner?: Seat | 'draw';
/** Seconds left this turn, and in the bank, for the player to act. */
clock?: { turn: number; bank: number };
};
/** What the board can ask the controller to do. The adapter turns these into engine actions. */
export type DuelUIAction =
| { type: 'mulligan'; keep: boolean }
/** targetIds: card uids or `player:<seat>`, one per chosen-target effect, in order. */
| { type: 'play'; cardId: string; targetIds: string[] }
| { type: 'toCombat' }
| { type: 'attack'; attackerIds: string[] }
| { type: 'block'; blocks: { blockerId: string; attackerId: string }[] }
| { type: 'endTurn' }
| { type: 'concede' };
/** What the engine says is legal right now, in board terms. */
export type Legal = {
/** Hand card id → every legal target sequence ([[]] = needs no target). Absent = can't be played now. */
plays: Record<string, string[][]>;
canGoToCombat: boolean;
/** Figures that may be declared as attackers. */
attackers: string[];
/** blocker id → attacker ids it may block (Featured, Translated and Garrison are the engine's call). */
blockers: Record<string, string[]>;
canEndTurn: boolean;
mulligan: boolean;
};
export const NO_LEGAL: Legal = { plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false };
// ---------- targeting (multi-step: e.g. a sport Event picks your Figure, then theirs) ----------
export const playerTarget = (seat: Seat) => `player:${seat}`;
/** Ids that may be chosen next, given the targets already chosen for this card. */
export function nextTargets(seqs: string[][] | undefined, chosen: string[]): Set<string> {
const out = new Set<string>();
for (const q of seqs ?? []) if (q.length > chosen.length && chosen.every((t, i) => q[i] === t)) out.add(q[chosen.length]);
return out;
}
/** True when `chosen` is a complete legal sequence. */
export const targetsComplete = (seqs: string[][] | undefined, chosen: string[]) =>
!!seqs?.some(q => q.length === chosen.length && q.every((t, i) => t === chosen[i]));
// ---------- combat declaration (pure, so it is unit-tested) ----------
/**
* Attack: one tap toggles a Figure in or out. Block: tap your blocker (1), then the attacker it
* blocks (2). Tapping an assigned blocker again removes it. At most one blocker per attacker and
* one attacker per blocker (BRIEF: single blocks).
*/
export type Declaration = { attackers: string[]; blocks: Record<string, string>; picked?: string };
export const EMPTY_DECL: Declaration = { attackers: [], blocks: {} };
export function toggleAttacker(d: Declaration, id: string, legal: Legal): Declaration {
if (!legal.attackers.includes(id)) return d;
const attackers = d.attackers.includes(id) ? d.attackers.filter(a => a !== id) : [...d.attackers, id];
return { ...d, attackers };
}
/** Tap on one of my cards during blocks. */
export function tapBlocker(d: Declaration, blockerId: string, legal: Legal): Declaration {
if (d.blocks[blockerId]) { const blocks = { ...d.blocks }; delete blocks[blockerId]; return { ...d, blocks, picked: undefined }; }
if (!legal.blockers[blockerId]?.length) return d;
return { ...d, picked: d.picked === blockerId ? undefined : blockerId };
}
/** Tap on an attacker during blocks. With a blocker picked, assign it; the attacker's old blocker is freed. */
export function tapAttacker(d: Declaration, attackerId: string, legal: Legal): Declaration {
const picked = d.picked;
if (!picked) {
// No blocker picked: tapping a blocked attacker clears its block.
const owner = Object.entries(d.blocks).find(([, a]) => a === attackerId)?.[0];
if (!owner) return d;
const blocks = { ...d.blocks }; delete blocks[owner]; return { ...d, blocks };
}
if (!legal.blockers[picked]?.includes(attackerId)) return d;
const blocks = Object.fromEntries(Object.entries(d.blocks).filter(([, a]) => a !== attackerId));
blocks[picked] = attackerId;
return { ...d, blocks, picked: undefined };
}
export const blockList = (d: Declaration) => Object.entries(d.blocks).map(([blockerId, attackerId]) => ({ blockerId, attackerId }));
// ---------- combat preview ----------
export type CombatOutcome = {
/** Damage the defending player takes. */
toPlayer: number;
/** Card ids that would be destroyed. */
destroyed: string[];
rows: { attacker: BoardCard; blocker?: BoardCard; attackerDies: boolean; blockerDies: boolean }[];
};
const has = (c: BoardCard | undefined, kw: string) => !!c?.keywords.some(k => k.toLowerCase() === kw.toLowerCase());
/** Damage a card takes from one source, after Well-sourced (prevent the first 1 each turn). */
const taken = (c: BoardCard, dmg: number) => Math.max(0, dmg - (has(c, 'Well-sourced') && !(c.damage ?? 0) ? 1 : 0));
const dies = (c: BoardCard, dmg: number) => c.toughness !== undefined && (c.damage ?? 0) + taken(c, dmg) >= c.toughness && dmg > 0;
/**
* A preview for the confirm sheet: simultaneous damage, single blocks, no trample or first strike
* (BRIEF). The engine resolves for real; this is only so the player sees what they are confirming.
*/
export function previewCombat(attacks: Attack[], cards: Map<string, BoardCard>): CombatOutcome {
const out: CombatOutcome = { toPlayer: 0, destroyed: [], rows: [] };
for (const { attackerId, blockerId } of attacks) {
const attacker = cards.get(attackerId);
if (!attacker) continue;
const blocker = blockerId ? cards.get(blockerId) : undefined;
if (!blocker) { out.toPlayer += attacker.power ?? 0; out.rows.push({ attacker, attackerDies: false, blockerDies: false }); continue; }
const attackerDies = dies(attacker, blocker.power ?? 0);
const blockerDies = dies(blocker, attacker.power ?? 0);
if (attackerDies) out.destroyed.push(attacker.id);
if (blockerDies) out.destroyed.push(blocker.id);
out.rows.push({ attacker, blocker, attackerDies, blockerDies });
}
return out;
}
// ---------- eligibility (BRIEF decisions 1–3) ----------
export const DEFAULT_DECK_SIZE = 40;
export type Eligibility = { eligible: boolean; owned: number; needed: number; label: string };
/** Bot and PvP matches are only for players who own a full deck. There is no borrowed-card play. */
export function eligibility(owned: number, deckSize = DEFAULT_DECK_SIZE): Eligibility {
const needed = Math.max(0, deckSize - owned);
return { eligible: needed === 0, owned, needed, label: `${Math.min(owned, deckSize)} / ${deckSize} cards` };
}
// ---------- text helpers ----------
/**
* First sentence of an extract, for flavour text. Doesn't split on initials ("J. R. R."), common
* abbreviations or decimals. Falls back to the whole (trimmed) text.
*/
export function firstSentence(text: string | undefined, max = 220): string | undefined {
const t = text?.replace(/\s+/g, ' ').trim();
if (!t) return undefined;
const re = /[.!?](?=\s+[A-Z0-9"“(])/g;
let m: RegExpExecArray | null;
while ((m = re.exec(t))) {
const before = t.slice(0, m.index);
const word = before.split(' ').at(-1) ?? '';
if (/^[A-Z]$/.test(word) || /^(Mr|Mrs|Ms|Dr|St|Jr|Sr|No|Mt|Ft|vs|c|ca|approx|e\.g|i\.e|U\.S|U\.K)$/i.test(word)) continue;
return clip(t.slice(0, m.index + 1), max);
}
return clip(t, max);
}
const clip = (s: string, max: number) => (s.length <= max ? s : `${s.slice(0, max - 1).replace(/\s+\S*$/, '')}…`);
/** "Figure — People · 1961–" */
export const typeLine = (c: Pick<BoardCard, 'type' | 'subtype' | 'portal'>) =>
`${c.type} — ${c.subtype ?? c.portal}`;
/** Accessible one-line summary of a card. */
export function cardSummary(c: BoardCard): string {
const stats = c.power !== undefined ? `, ${c.power}/${c.toughness ?? 0}` : '';
const kw = c.keywords.length ? `, ${c.keywords.join(', ')}` : '';
const state = `${c.tapped ? ', tapped' : ''}${c.pending ? ', pending review' : ''}${c.damage ? `, ${c.damage} damage` : ''}`;
return `${c.title}, ${typeLine(c)}, cost ${c.cost}${stats}${kw}${state}`;
}
export const isMyTurn = (v: BoardView) => v.active === v.seat && v.phase !== 'over';
+1
View File
@@ -206,3 +206,4 @@ html.wd-in-match .auth-wrap,body:has(.match) .auth-wrap{display:none}
.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}
+11 -8
View File
@@ -1,8 +1,11 @@
import './native.ts';
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import './themes.css';
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode><App /></React.StrictMode>);
import './native.ts';
import React, { Suspense, lazy } from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import './themes.css';
// ui-duel review aid: `#duel-preview` renders static duel board scenes from card-sample.json.
const DuelPreview = lazy(() => import('./game/duel/DuelPreview.tsx').then(m => ({ default: m.DuelPreview })));
const root = location.hash.startsWith('#duel-preview') ? <Suspense fallback={null}><DuelPreview /></Suspense> : <App />;
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode>{root}</React.StrictMode>);
+6 -3
View File
@@ -38,6 +38,9 @@ function winRate(a: B, b: B, n: number) {
}
const [easy, normal] = BOTS;
// Normal runs sim-balance's lookahead (~1.5 s of CPU per match), so the default run is small;
// UI_BOTS_FULL=1 plays 100 matches per pairing.
const N = process.env.UI_BOTS_FULL ? 100 : 16;
test('BOTS exports easy and normal in the Bot shape', () => {
assert.deepEqual(BOTS.map(b => b.id), ['easy', 'normal']);
@@ -46,14 +49,14 @@ test('BOTS exports easy and normal in the Bot shape', () => {
});
test('normal bot beats random play more than 80% of the time', () => {
const r = winRate(normal, randomBot, 100);
const r = winRate(normal, randomBot, N);
console.log(`normal vs random ${r}`); assert.ok(r > 0.8, `normal vs random ${r}`);
});
test('easy bot beats random, and normal beats easy', () => {
const e = winRate(easy, randomBot, 100), g = winRate(normal, easy, 100);
const e = winRate(easy, randomBot, 100), g = winRate(normal, easy, N);
console.log(`easy vs random ${e}, normal vs easy ${g}`); assert.ok(e > 0.5, `easy vs random ${e}`);
assert.ok(g > 0.6, `normal vs easy ${g}`);
assert.ok(g > 0.55, `normal vs easy ${g}`);
});
test('bots never concede or un-queue, and end the turn when nothing fits', () => {
+124
View File
@@ -0,0 +1,124 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import type { DuelAction, DuelCard, LogEvent, PermanentView, PlayerView, SideView } from '../src/game/duel/contract.ts';
import { boardFromView, expand, legalFromActions, plainLog } from '../src/game/duel/adapter.ts';
const card = (id: string, extra: Partial<DuelCard> = {}): DuelCard => ({
cardId: id, pageId: 1, revisionId: 100, title: id, type: 'Figure', portal: 'Society', cost: 2, power: 2, toughness: 2,
keywords: [], effects: [], rulesText: '', flavor: 'A thing. More.', ...extra,
});
const perm = (uid: string, controller: 0 | 1, c: DuelCard, extra: Partial<PermanentView> = {}): PermanentView => ({
uid, owner: controller, controller, card: c, tapped: false, sick: false, damage: 0, counters: 0,
power: c.power ?? 0, toughness: c.toughness ?? 0, keywords: c.keywords, ...extra,
});
const side = (seat: 0 | 1, extra: Partial<SideView> = {}): SideView => ({
seat, life: 20, citations: 3, maxCitations: 4, handSize: 2, librarySize: 30, graveyard: [], bankSeconds: 300, ready: true, mulligansTaken: 0, ...extra,
});
function view(): PlayerView {
const fig = card('fig', { keywords: ['Legacy'] });
return {
engine: 'duel', seat: 1, turn: 5, active: 0, phase: 'block', toAct: 1,
you: { ...side(1), hand: [{ uid: '1:7', owner: 1, card: card('ev', { type: 'Event', power: null, toughness: null }) }] },
opponent: side(0, { life: 12 }),
battlefield: [
perm('0:1', 0, fig, { tapped: true, power: 4, toughness: 3 }),
perm('0:2', 0, card('loc', { type: 'Location', power: 0, toughness: 0 })),
perm('1:3', 1, card('mine'), { sick: true, connected: { with: '1:4', tier: 'Compatriot', via: 'Portugal', bonus: 1 } }),
perm('1:4', 1, card('gar', { type: 'Location', power: 0, toughness: 3 })),
perm('1:5', 1, card('doc', { type: 'Doctrine', power: null, toughness: null }), { attachedTo: '1:3' }),
],
combat: { attackers: ['0:1'], blocks: {} }, result: null, version: 9, rules: {},
};
}
test('PlayerView → board: sides from my seat, current stats, Garrison only when T > 0, attachments, Connected', () => {
const b = boardFromView(view(), ['alice', 'bob'], ['Turn 5.']);
assert.equal(b.me.name, 'bob');
assert.equal(b.opponent.name, 'alice');
assert.equal(b.opponent.notability, 12);
assert.deepEqual(b.combat, [{ attackerId: '0:1', blockerId: undefined }]);
const att = b.opponent.battlefield.find(c => c.id === '0:1')!;
assert.equal(att.power, 4); assert.equal(att.basePower, 2); assert.equal(att.tapped, true);
assert.equal(b.opponent.battlefield.find(c => c.id === '0:2')!.power, undefined);
assert.equal(b.me.battlefield.find(c => c.id === '1:4')!.toughness, 3);
const mine = b.me.battlefield.find(c => c.id === '1:3')!;
assert.deepEqual(mine.attachments, ['1:5']);
assert.ok(mine.keywords.includes('Connected'));
assert.equal(mine.pending, true);
assert.equal(mine.connectedNote, 'Compatriot (Portugal): +1/+1');
assert.equal(b.hand[0].id, '1:7');
assert.equal(b.hand[0].flavour, 'A thing.');
});
test('legal actions → board legality, and board intents → atomic action sequences', () => {
const legal: DuelAction[] = [
{ type: 'block', blocker: '1:3', attacker: '0:1' }, { type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' },
];
const l = legalFromActions(legal);
assert.deepEqual(l.blockers, { '1:3': ['0:1'], '1:4': ['0:1'] });
assert.deepEqual(expand({ type: 'block', blocks: [{ blockerId: '1:4', attackerId: '0:1' }] }, legal),
[{ type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' }]);
const main: DuelAction[] = [
{ type: 'play', uid: 'h1' },
{ type: 'play', uid: 'h2', targets: [{ kind: 'card', uid: 'a' }, { kind: 'card', uid: 'x' }] },
{ type: 'play', uid: 'h3', targets: [{ kind: 'player', seat: 0 }] },
{ type: 'endPhase' },
];
const m = legalFromActions(main);
assert.deepEqual(m.plays, { h1: [[]], h2: [['a', 'x']], h3: [['player:0']] });
assert.equal(m.canGoToCombat, true);
// The exact legal element comes back, so the host's deep-equal check passes (no `targets: []`).
assert.strictEqual(expand({ type: 'play', cardId: 'h1', targetIds: [] }, main)[0], main[0]);
assert.strictEqual(expand({ type: 'play', cardId: 'h3', targetIds: ['player:0'] }, main)[0], main[2]);
assert.deepEqual(expand({ type: 'endTurn' }, main), [{ type: 'endPhase' }, { type: 'confirmAttack' }]);
assert.deepEqual(expand({ type: 'attack', attackerIds: ['a', 'b'] }, [{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]),
[{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]);
assert.deepEqual(expand({ type: 'mulligan', keep: true }, [{ type: 'keep' }, { type: 'mulligan' }]), [{ type: 'keep' }]);
assert.equal(legalFromActions([]).canEndTurn, false);
});
test('fallback log: real names and titles only, no adjectives', () => {
const ref = (title: string) => ({ uid: title, cardId: title, title, pageId: 1, type: 'Figure' as const, power: 3, toughness: 2 });
const events: LogEvent[] = [
{ seq: 1, turn: 3, kind: 'turnStart', seat: 0, citations: 3, life: [20, 20] },
{ seq: 2, turn: 3, kind: 'deploy', seat: 0, card: ref('Cho Yang-ho') },
{ seq: 3, turn: 3, kind: 'attack', seat: 0, attackers: [ref('Cho Yang-ho')] },
{ seq: 4, turn: 3, kind: 'playerDamage', source: ref('Cho Yang-ho'), seat: 1, amount: 3, life: 17, combat: true },
{ seq: 5, turn: 3, kind: 'destroyed', card: ref('Dichromorpha viridis'), owner: 1 },
{ seq: 6, turn: 9, kind: 'gameOver', winner: 0, reason: 'life', life: [12, 0] },
];
assert.deepEqual(plainLog(events, ['Eric', 'Bot (Normal)']), [
'Turn 3.', 'Eric deployed Cho Yang-ho.', 'Cho Yang-ho (3/2) attacked.', 'Bot (Normal) lost 3 Notability (17 remaining).',
'Dichromorpha viridis was moved to Deleted.', 'Bot (Normal) was nominated for deletion. The result was delete.',
]);
});
test('bot match decks: exactly deckSize owned, profiled cards; the bot deck is its own and deterministic', async () => {
const { botDeck, playerDeck } = await import('../src/game/duel/decks.ts');
const cards = Array.from({ length: 41 }, (_, i) => ({ tokenId: `t${i}`, title: `Card ${i}`, duel: card(`d${i}`, { pageId: i }) }));
const ids = cards.slice(0, 40).map(c => c.tokenId);
const ok = playerDeck(ids, cards, 40);
assert.equal(ok.cards.length, 40);
assert.equal(ok.cards[0].cardId, 't0'); // the NFT tokenId, not the profile id
assert.equal(playerDeck(ids.slice(0, 39), cards, 40).cards.length, 0); // no partial decks, no filler
assert.deepEqual(playerDeck([...ids.slice(0, 39), 'nope'], cards, 40).missing, ['nope']);
const noProfile = cards.map((c, i) => (i === 3 ? { tokenId: c.tokenId, title: c.title } : c));
assert.deepEqual(playerDeck(ids, noProfile, 40).pending, ['Card 3']);
const pool = Array.from({ length: 236 }, (_, i) => card(`s${i}`, { pageId: i }));
const a = botDeck(pool, 40, 'seed'), b = botDeck(pool, 40, 'seed');
assert.deepEqual(a, b);
assert.equal(new Set(a.map(c => c.cardId)).size, 40);
assert.ok(a.every(c => c.cardId.startsWith('bot:')));
assert.notDeepEqual(botDeck(pool, 40, 'other').map(c => c.cardId), a.map(c => c.cardId));
});
test('bot match: untyped profiles from the wire are shape-checked', async () => {
const { playerDeck, isDuelCard } = await import('../src/game/duel/decks.ts');
assert.equal(isDuelCard(card('x')), true);
assert.equal(isDuelCard({ title: 'x' }), false);
assert.equal(isDuelCard(null), false);
const cards = Array.from({ length: 40 }, (_, i) => ({ tokenId: `t${i}`, title: `C${i}`, duel: i === 5 ? { junk: true } : card(`d${i}`) }));
assert.deepEqual(playerDeck(cards.map(c => c.tokenId), cards, 40).pending, ['C5']);
});
+53
View File
@@ -0,0 +1,53 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { EASY_BOT, NORMAL_BOT } from '../src/game/duel/bots.ts';
import type { DuelAction, DuelCard, PermanentView, PlayerView } from '../src/game/duel/contract.ts';
const card = (id: string, extra: Partial<DuelCard> = {}): DuelCard => ({
cardId: id, pageId: 1, title: id, type: 'Figure', portal: 'Society', cost: 2, power: 2, toughness: 2, keywords: [], effects: [], rulesText: '', flavor: '', ...extra,
});
const perm = (uid: string, controller: 0 | 1, power: number, toughness: number, extra: Partial<PermanentView> = {}): PermanentView => ({
uid, owner: controller, controller, card: card(uid, { power, toughness }), tapped: false, sick: false, damage: 0, counters: 0, power, toughness, keywords: [], ...extra,
});
const side = (seat: 0 | 1, life = 20) => ({ seat, life, citations: 3, maxCitations: 3, handSize: 0, librarySize: 30, graveyard: [], bankSeconds: 300, ready: true, mulligansTaken: 0 });
const view = (p: Partial<PlayerView>): PlayerView => ({
engine: 'duel', seat: 1, turn: 4, active: 1, phase: 'main', toAct: 1, you: { ...side(1), hand: [] }, opponent: side(0),
battlefield: [], combat: { attackers: [], blocks: {} }, result: null, version: 1, rules: {}, ...p,
});
const rng = () => 0.5;
test('normal bot: plays the priciest card, harmful effects at the opponent', () => {
const hand = [{ uid: '1:1', owner: 1 as const, card: card('cheap', { cost: 1 }) },
{ uid: '1:2', owner: 1 as const, card: card('bolt', { type: 'Event', cost: 3, power: null, toughness: null, effects: [{ op: 'damage', amount: 3 }] }) }];
const v = view({ you: { ...side(1), hand }, battlefield: [perm('0:9', 0, 3, 3), perm('1:8', 1, 2, 2)] });
const legal: DuelAction[] = [{ type: 'play', uid: '1:1' },
{ type: 'play', uid: '1:2', targets: [{ kind: 'card', uid: '1:8' }] }, { type: 'play', uid: '1:2', targets: [{ kind: 'card', uid: '0:9' }] }, { type: 'endPhase' }];
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[2]);
});
test('normal bot: attacks unless a blocker eats it, all-in on lethal, then confirms', () => {
const bf = [perm('1:1', 1, 3, 3), perm('1:2', 1, 1, 1), perm('0:1', 0, 2, 4)];
const legal: DuelAction[] = [{ type: 'toggleAttacker', uid: '1:1' }, { type: 'toggleAttacker', uid: '1:2' }, { type: 'confirmAttack' }];
// 1:1 (3/3) faces a 2/4 that survives but doesn't kill: attack. 1:2 (1/1) would die to it for nothing.
const v = view({ phase: 'attack', battlefield: bf });
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[0]);
const after = view({ phase: 'attack', battlefield: bf, combat: { attackers: ['1:1'], blocks: {} } });
assert.deepEqual(NORMAL_BOT.choose(after, legal.slice(1), rng), { type: 'confirmAttack' });
const lethal = view({ phase: 'attack', battlefield: bf, opponent: side(0, 1), combat: { attackers: ['1:1'], blocks: {} } });
assert.deepEqual(NORMAL_BOT.choose(lethal, legal.slice(1), rng), legal[1]);
});
test('normal bot: takes the kill-and-survive block, otherwise no block', () => {
const bf = [perm('0:1', 0, 2, 2), perm('1:1', 1, 3, 3), perm('1:2', 1, 1, 1)];
const v = view({ phase: 'block', active: 0, battlefield: bf, combat: { attackers: ['0:1'], blocks: {} } });
const legal: DuelAction[] = [{ type: 'block', blocker: '1:1', attacker: '0:1' }, { type: 'block', blocker: '1:2', attacker: '0:1' }, { type: 'confirmBlocks' }];
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[0]);
assert.deepEqual(NORMAL_BOT.choose(v, legal.slice(1), rng), { type: 'confirmBlocks' });
});
test('bots always return a listed action and keep their opening hand', () => {
const legal: DuelAction[] = [{ type: 'keep' }, { type: 'mulligan' }];
assert.deepEqual(NORMAL_BOT.choose(view({ phase: 'mulligan' }), legal, rng), { type: 'keep' });
let x = 1; const r = () => ((x = (x * 48271) % 2147483647) / 2147483647);
for (let i = 0; i < 50; i++) assert.ok(legal.includes(EASY_BOT.choose(view({ phase: 'mulligan' }), legal, r)));
});
+120
View File
@@ -0,0 +1,120 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
EMPTY_DECL, NO_LEGAL, blockList, cardSummary, eligibility, firstSentence, previewCombat, tapAttacker, tapBlocker, toggleAttacker, typeLine,
type BoardCard, type Legal,
} from '../src/game/duel/model.ts';
import { PREVIEW_POOL, previewView } from '../src/game/duel/mock.ts';
const fig = (id: string, power: number, toughness: number, extra: Partial<BoardCard> = {}): BoardCard =>
({ id, title: id, type: 'Figure', portal: 'Society', cost: 2, power, toughness, keywords: [], rulesText: '', ...extra });
test('attack declaration: one tap toggles a legal attacker, illegal ones are ignored', () => {
const legal: Legal = { ...NO_LEGAL, attackers: ['a', 'b'] };
let d = toggleAttacker(EMPTY_DECL, 'a', legal);
assert.deepEqual(d.attackers, ['a']);
d = toggleAttacker(d, 'z', legal);
assert.deepEqual(d.attackers, ['a']);
d = toggleAttacker(d, 'b', legal);
d = toggleAttacker(d, 'a', legal);
assert.deepEqual(d.attackers, ['b']);
});
test('block declaration: two taps per blocker, single blocks, re-tap clears', () => {
const legal: Legal = { ...NO_LEGAL, blockers: { x: ['A', 'B'], y: ['A'], z: [] } };
let d = tapBlocker(EMPTY_DECL, 'x', legal);
assert.equal(d.picked, 'x');
d = tapAttacker(d, 'A', legal);
assert.deepEqual(blockList(d), [{ blockerId: 'x', attackerId: 'A' }]);
assert.equal(d.picked, undefined);
// y takes over A; x is freed (at most one blocker per attacker).
d = tapAttacker(tapBlocker(d, 'y', legal), 'A', legal);
assert.deepEqual(blockList(d), [{ blockerId: 'y', attackerId: 'A' }]);
// y can't block B: the tap is ignored and y stays picked.
d = tapAttacker(tapBlocker(EMPTY_DECL, 'y', legal), 'B', legal);
assert.deepEqual(blockList(d), []);
// A blocker with no legal attacker can't be picked.
assert.equal(tapBlocker(EMPTY_DECL, 'z', legal).picked, undefined);
// Re-tapping an assigned blocker removes the block; so does tapping its attacker with nothing picked.
d = tapAttacker(tapBlocker(EMPTY_DECL, 'x', legal), 'B', legal);
assert.deepEqual(blockList(tapBlocker(d, 'x', legal)), []);
assert.deepEqual(blockList(tapAttacker(d, 'B', legal)), []);
// One blocker per attacker, and one attacker per blocker.
d = tapAttacker(tapBlocker(d, 'x', legal), 'A', legal);
assert.equal(blockList(d).length <= 1, true);
});
test('combat preview: simultaneous damage, single blocks, Well-sourced, marked damage', () => {
const cards = new Map([fig('a', 3, 3), fig('b', 2, 2), fig('c', 4, 1), fig('w', 1, 3, { keywords: ['Well-sourced'] }), fig('d', 2, 3, { damage: 1 })].map(c => [c.id, c]));
const out = previewCombat([{ attackerId: 'a', blockerId: 'b' }, { attackerId: 'c' }], cards);
assert.equal(out.toPlayer, 4);
assert.deepEqual(out.destroyed.sort(), ['b']);
// Well-sourced prevents the first 1: a 3-power attacker deals 2 to a 1/3, which survives.
assert.deepEqual(previewCombat([{ attackerId: 'a', blockerId: 'w' }], cards).destroyed, []);
// Damage already marked counts: 2 more kills a 2/3 with 1 damage.
assert.deepEqual(previewCombat([{ attackerId: 'b', blockerId: 'd' }], cards).destroyed.sort(), ['b', 'd']);
});
test('eligibility: exactly the deck size, no borrowed cards, progress label', () => {
assert.deepEqual(eligibility(23), { eligible: false, owned: 23, needed: 17, label: '23 / 40 cards' });
assert.equal(eligibility(40).eligible, true);
assert.equal(eligibility(57).label, '40 / 40 cards');
assert.equal(eligibility(12, 12).eligible, true); // testnet mode file may lower deckSize
});
test('flavour: first sentence of the extract, not split on initials or abbreviations', () => {
assert.equal(firstSentence('J. R. R. Tolkien was an English writer. He wrote books.'), 'J. R. R. Tolkien was an English writer.');
assert.equal(firstSentence('St. Georgen am Längsee is a town. It is in Austria.'), 'St. Georgen am Längsee is a town.');
assert.equal(firstSentence('Pi is about 3.14 in value. More.'), 'Pi is about 3.14 in value.');
assert.equal(firstSentence('No full stop here'), 'No full stop here');
assert.equal(firstSentence(''), undefined);
assert.ok((firstSentence('word '.repeat(100)) ?? '').length <= 220);
});
test('type line and accessible summary', () => {
const c = fig('Barack Obama', 3, 4, { subtype: 'People · 1961–', keywords: ['Protected'], tapped: true });
assert.equal(typeLine(c), 'Figure — People · 1961–');
assert.equal(cardSummary(c), 'Barack Obama, Figure — People · 1961–, cost 2, 3/4, Protected, tapped');
});
test('preview scenes: a full 5 + 5 board with every card from the real sample', () => {
assert.equal(PREVIEW_POOL.length, 236);
for (const scene of ['main', 'attack', 'block', 'over'] as const) {
const { view } = previewView(scene);
assert.equal(view.me.battlefield.length, 5);
assert.equal(view.opponent.battlefield.length, 5);
}
for (const c of PREVIEW_POOL) {
assert.ok(c.keywords.length <= 2, c.title);
assert.ok(c.cost >= 1 && c.cost <= 6, c.title);
}
});
test('DuelCard → board card: type line from real data only, flavour is one sentence', async () => {
const { boardCard, lifespan } = await import('../src/game/duel/cards.ts');
assert.equal(lifespan('Sultan of Aceh (1530–1537/9)'), '1530–1537');
assert.equal(lifespan('American voice actor and singer (born 1963)'), '1963–');
assert.equal(lifespan('American botanist (c.1872–1919)'), '1872–1919');
assert.equal(lifespan('Species of grasshopper'), undefined);
const c = boardCard({ cardId: 't', pageId: 1, revisionId: 9, title: 'Salahuddin of Aceh', type: 'Figure', subtype: null, portal: 'History',
cost: 4, power: 4, toughness: 3, keywords: ['Legacy'], rulesText: 'Legacy.', flavor: 'Sultan of Aceh (1530–1537/9). Second sentence.' });
assert.equal(typeLine(c), 'Figure — History · 1530–1537');
assert.equal(c.flavour, 'Sultan of Aceh (1530–1537/9).');
assert.equal(c.url, 'https://en.wikipedia.org/wiki/Salahuddin_of_Aceh');
const e = boardCard({ cardId: 'e', pageId: 2, revisionId: 9, title: '1954 Gold Coast general election', type: 'Event', subtype: 'election', portal: 'Society',
cost: 4, power: null, toughness: null, keywords: [], rulesText: 'x', flavor: '' });
assert.equal(typeLine(e), 'Event — Society · Election');
assert.equal(e.power, undefined);
});
test('targeting: multi-step sequences (own Figure, then theirs), players as targets', async () => {
const { nextTargets, targetsComplete, playerTarget } = await import('../src/game/duel/model.ts');
const seqs = [['a', 'x'], ['a', 'y'], ['b', 'x']];
assert.deepEqual([...nextTargets(seqs, [])].sort(), ['a', 'b']);
assert.deepEqual([...nextTargets(seqs, ['a'])].sort(), ['x', 'y']);
assert.deepEqual([...nextTargets(seqs, ['b'])], ['x']);
assert.equal(targetsComplete(seqs, ['a']), false);
assert.equal(targetsComplete(seqs, ['a', 'y']), true);
assert.equal(targetsComplete([[]], []), true);
assert.equal(nextTargets([[playerTarget(1)], ['c']], []).has('player:1'), true);
});
+11
View File
@@ -141,3 +141,14 @@ test('the final board shows scoring power, and queued cards preview their lane p
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);
});