forked from WikiDeck/wikideck
Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00195e9f14 | ||
|
|
3d133cbd14 | ||
|
|
83ae18a17f | ||
|
|
a0a051c10a | ||
|
|
b67192a08b | ||
|
|
2f1bba5e4c | ||
|
|
ec75875f0d | ||
|
|
a61c1a1342 | ||
|
|
75791f5861 | ||
|
|
7474b1c71d | ||
|
|
2cfdd9f437 | ||
|
|
26ad924565 | ||
|
|
86e544ea2e | ||
|
|
4bbc341bcb | ||
|
|
52c40bd3e3 | ||
|
|
bd6c7094b1 | ||
|
|
361efaa1d6 | ||
|
|
0f774f13b3 | ||
|
|
974c2651bf | ||
|
|
c9c901c7f2 | ||
|
|
8e448c26f2 | ||
|
|
4a4941c6ff | ||
|
|
6bd2dab74b | ||
|
|
4657a58800 | ||
|
|
df6bd04042 | ||
|
|
482de6ce3c | ||
|
|
5a83d34c59 | ||
|
|
a0bd095c4e | ||
|
|
b5c90d2dc1 | ||
|
|
ae50e62535 | ||
|
|
feae445f5a | ||
|
|
e7e51aecdb | ||
|
|
6fb9a2e8b4 | ||
|
|
b2ec917af4 | ||
|
|
c1a1325564 | ||
|
|
2e7b05bdad | ||
|
|
53d30e5cae | ||
|
|
7390a17a91 | ||
|
|
f507b0eaed | ||
|
|
1d3c5e5743 |
@@ -15,8 +15,6 @@ 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 |
|
||||
@@ -24,7 +22,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 (pre-#38) | 53.4% | **51.2% [48.8–53.6]** ✅ | 51.0% [48.6–53.5] |
|
||||
| first player | 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% |
|
||||
|
||||
@@ -112,7 +110,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 (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.*
|
||||
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.*
|
||||
2. **Keyword values are lopsided, confirming the critic's figures within 0.2:**
|
||||
|
||||
| keyword | power per card |
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
# Ownership and collection API (Night 2, #57)
|
||||
|
||||
Server-side checks that a player owns the cards they play. Off-chain only: nothing here moves, burns or locks a card, and nothing changes consensus.
|
||||
|
||||
## The rules (ruleset data)
|
||||
|
||||
| Key | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `deckSize` | 40 | A constructed deck has exactly this many cards. A testnet mode file may lower it. |
|
||||
| `maxCopiesPerPage` | 4 | The MTG-style copy limit. Cards minted from the same Wikipedia `pageId` are separate cards, but at most this many go in one deck. |
|
||||
| `minConfirmations` | 1 | The confirmations each card's mint block needs. Rated play uses `RATED_MIN_CONFIRMATIONS` = 3. |
|
||||
|
||||
## `server/game/ownership.ts` (used by the PvP host)
|
||||
|
||||
```ts
|
||||
verifyAccount(deps, idToken: unknown): Promise<Account>
|
||||
resolveDeck(deps, account, tokenIds: unknown, opts?: Partial<OwnershipRules>): Promise<ChainCard[]>
|
||||
collection(deps, account, opts?: { minConfirmations?: number }): Promise<ChainCard[]>
|
||||
```
|
||||
|
||||
- **`deps`** is `{ ledger, accounts, verifyIdToken }`. In production, `server/testnet/http.ts` builds it from the node's `Ledger`, the shared `AccountStore`, and `accountVerifier()` from `server/account/router.ts`. It passes the result to `gameRouter({ ownership })`.
|
||||
- **`resolveDeck`** accepts token ids only, never card JSON. For each card it checks:
|
||||
- the card is on the canonical chain (`ledger.nft()`);
|
||||
- its current owner (after transfers) is one of the account's linked wallets;
|
||||
- it has enough confirmations;
|
||||
- the deck size and copy limit.
|
||||
|
||||
Each card is rebuilt from its own block (`article` and `statsSnapshot`). The cards come back in the order given.
|
||||
- **Errors** are thrown as `DeckError { code, status, tokenIds, pageId? }`. `tokenIds` lists every offending card of that class.
|
||||
|
||||
| `code` | `status` |
|
||||
|---|---|
|
||||
| `auth` | 401 |
|
||||
| `size` | 400 |
|
||||
| `duplicate-token` | 400 |
|
||||
| `unknown-token` (not on chain, or malformed) | 400 |
|
||||
| `not-owned` (includes "no linked wallet") | 403 |
|
||||
| `unconfirmed` | 400 |
|
||||
| `copy-limit` | 400 |
|
||||
|
||||
`OwnershipUnavailable` (503) means Dex is unreachable or the chain tip kept moving during a read.
|
||||
- **`collection`** pages `ledger.deck()` (24 per page) across every linked wallet at one canonical tip, restarting if the tip moves. There is no 128-block snapshot cap.
|
||||
|
||||
## `GET /api/game/collection`
|
||||
|
||||
`Authorization: Bearer <Dex ID token>` (the same token as `/api/account/me`). Optional: `?minConfirmations=N`.
|
||||
|
||||
```ts
|
||||
{
|
||||
tip, wallets: string[],
|
||||
deckSize: 40, copyLimit: 4, maxCopiesPerPage: 4, minConfirmations: 1,
|
||||
owned: number, // confirmed cards across all linked wallets
|
||||
playable: number, // Σ min(copies, copyLimit) per pageId
|
||||
needed: number, // max(0, deckSize - playable)
|
||||
eligible: boolean, // playable >= deckSize
|
||||
cards: ChainCard[] // tokenId, owner, confirmations, pageId, title, revisionId, url, extract, imageUrl?,
|
||||
// height, blockHash, createdAt, powHash, article, statsSnapshot
|
||||
}
|
||||
```
|
||||
|
||||
| Case | Response |
|
||||
|---|---|
|
||||
| No linked wallets | 200 with `cards: []` and `needed: 40` |
|
||||
| Missing or invalid token | 401 |
|
||||
| Dex unreachable | 503 |
|
||||
| Bad query | 400 |
|
||||
|
||||
The UI shows `playable / deckSize`, for example "23 / 40 cards", and how to mine.
|
||||
|
||||
## Not covered (known gaps)
|
||||
|
||||
- **Peer hosts.** Account stores are per node, and a Dex token sent to a peer could be replayed elsewhere (engineer review §2, G6). This API is for the self-hosted node only. The stretch fix is a wallet-signed deck claim.
|
||||
- **Plausibility of minted stats** (G5): `pageId` → `title` and `revisionId` → `size` are not cross-checked yet.
|
||||
+2
-19
@@ -81,25 +81,8 @@ 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 (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).
|
||||
## Progress at shutdown
|
||||
_(filled in before 01:25)_
|
||||
|
||||
## What's verified
|
||||
- `BaseSystem.dmg` sha256 matches macos-fetch's `SHA256SUMS`; converted `BaseSystem.img` is 3,221,110,784 bytes.
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# 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:
|
||||
|
||||

|
||||
- **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.
|
||||
@@ -1,144 +0,0 @@
|
||||
# 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)
|
||||
@@ -1,88 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,120 +0,0 @@
|
||||
# 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?
|
||||
@@ -1,44 +0,0 @@
|
||||
"""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'])))
|
||||
@@ -1,23 +0,0 @@
|
||||
"""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']))
|
||||
@@ -1,59 +0,0 @@
|
||||
"""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}%')
|
||||
@@ -1,79 +0,0 @@
|
||||
"""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]}")
|
||||
@@ -1,171 +0,0 @@
|
||||
# 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.)
|
||||
@@ -1,272 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,278 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,246 +0,0 @@
|
||||
# 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.
|
||||
@@ -12,28 +12,12 @@ export type AccountDeps = { config?: OidcConfig; keys?: DexKeys; store?: Account
|
||||
type Authed = Request & { account?: Account };
|
||||
const hex64 = z.string().regex(/^[a-f0-9]{64}$/);
|
||||
|
||||
/**
|
||||
* Verifies a Dex ID token and records the account. Shared with the game routes
|
||||
* (server/game/collection.ts, the PvP host) so every route uses the same store and keys.
|
||||
* Throws TokenError (status 401) for a bad token; other errors mean Dex is unreachable.
|
||||
*/
|
||||
export function accountVerifier(config: OidcConfig, keys: Pick<DexKeys, 'key'>, store: Pick<AccountStore, 'upsert'>,
|
||||
now: () => number = Date.now): (idToken: string) => Promise<Account> {
|
||||
return async idToken => {
|
||||
const claims = await verifyIdToken(idToken, keys, config, { now: now() });
|
||||
const account: Account = { sub: claims.sub, issuer: claims.iss, name: displayName(claims), username: claims.preferred_username ?? '' };
|
||||
store.upsert(account);
|
||||
return account;
|
||||
};
|
||||
}
|
||||
|
||||
export function createAccountRouter(deps: AccountDeps = {}): Router {
|
||||
const config = deps.config ?? oidcConfig();
|
||||
const now = deps.now ?? Date.now;
|
||||
const keys = deps.keys ?? new DexKeys(config, deps.fetcher, now);
|
||||
const store = deps.store ?? new AccountStore(resolve(deps.dataDir ?? 'data', 'accounts.sqlite'), now);
|
||||
const router = Router();
|
||||
const verify = accountVerifier(config, keys, store, now);
|
||||
|
||||
const toAccount = (claims: Awaited<ReturnType<typeof verifyIdToken>>): Account =>
|
||||
({ sub: claims.sub, issuer: claims.iss, name: displayName(claims), username: claims.preferred_username ?? '' });
|
||||
@@ -42,7 +26,8 @@ export function createAccountRouter(deps: AccountDeps = {}): Router {
|
||||
try {
|
||||
const m = /^Bearer ([A-Za-z0-9_.-]+)$/.exec(req.get('authorization') ?? '');
|
||||
if (!m) throw new TokenError('Log in with your eom.dev account');
|
||||
req.account = await verify(m[1]);
|
||||
req.account = toAccount(await verifyIdToken(m[1], keys, config, { now: now() }));
|
||||
store.upsert(req.account);
|
||||
next();
|
||||
} catch (e) { next(e); }
|
||||
};
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
/**
|
||||
* GET /api/game/collection Authorization: Bearer <Dex ID token> [?minConfirmations=N]
|
||||
*
|
||||
* Every card the account's linked wallets own (no 128-block cap) and whether that is enough to
|
||||
* build a deck. Eligibility counts the copy limit: 40 copies of one article is 4 playable cards.
|
||||
*/
|
||||
import { Router, type Request, type Response } from 'express';
|
||||
import { DeckError, collectionAt, ownershipRules, playableCount, verifyAccount,
|
||||
type ChainCard, type OwnershipDeps, type OwnershipRules } from './ownership.ts';
|
||||
|
||||
export type CollectionResponse = {
|
||||
tip: string;
|
||||
wallets: string[];
|
||||
deckSize: number;
|
||||
/** Max copies per pageId. `maxCopiesPerPage` is the same value under the ruleset's name. */
|
||||
copyLimit: number;
|
||||
maxCopiesPerPage: number;
|
||||
minConfirmations: number;
|
||||
/** Confirmed cards across all linked wallets. */
|
||||
owned: number;
|
||||
/** Σ min(copies, copyLimit) per pageId: the most cards a legal deck can draw from. */
|
||||
playable: number;
|
||||
/** max(0, deckSize - playable). */
|
||||
needed: number;
|
||||
/** playable >= deckSize. */
|
||||
eligible: boolean;
|
||||
/** `duel` is present when the server has a frozen profile for the card (see collectionRouter's `duelCard`). */
|
||||
cards: (ChainCard & { duel?: unknown })[];
|
||||
};
|
||||
|
||||
export function collectionResponse(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, sub: string,
|
||||
rules?: Partial<OwnershipRules>): CollectionResponse {
|
||||
const r = ownershipRules(rules);
|
||||
const { tip, wallets, cards } = collectionAt(deps, { sub }, { minConfirmations: r.minConfirmations });
|
||||
const playable = playableCount(cards, r.maxCopiesPerPage);
|
||||
return { tip, wallets, deckSize: r.deckSize, copyLimit: r.maxCopiesPerPage, maxCopiesPerPage: r.maxCopiesPerPage,
|
||||
minConfirmations: r.minConfirmations, owned: cards.length, playable, needed: Math.max(0, r.deckSize - playable),
|
||||
eligible: playable >= r.deckSize, cards };
|
||||
}
|
||||
|
||||
export type CollectionRouterDeps = OwnershipDeps & {
|
||||
rules?: Partial<OwnershipRules>;
|
||||
/**
|
||||
* Optional: the same chain card → duel card function the PvP host uses, so the browser shows and
|
||||
* plays exactly what PvP would. Return undefined while a card's profile is pending; it must not fetch.
|
||||
*/
|
||||
duelCard?: (card: ChainCard) => unknown;
|
||||
};
|
||||
|
||||
export function collectionRouter(deps: CollectionRouterDeps): Router {
|
||||
const router = Router();
|
||||
router.get('/', async (req: Request, res: Response) => {
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
const q = req.query.minConfirmations;
|
||||
if (q !== undefined && (typeof q !== 'string' || !/^[1-9]\d{0,3}$/.test(q))) { res.status(400).json({ error: 'Invalid minConfirmations' }); return; }
|
||||
const m = /^Bearer ([A-Za-z0-9_.-]{1,8192})$/.exec(req.get('authorization') ?? '');
|
||||
try {
|
||||
const account = await verifyAccount(deps, m?.[1]);
|
||||
const body = collectionResponse(deps, account.sub, { ...deps.rules, ...(q ? { minConfirmations: Number(q) } : {}) });
|
||||
if (deps.duelCard) {
|
||||
const toDuel = deps.duelCard;
|
||||
body.cards = body.cards.map(c => {
|
||||
let duel: unknown;
|
||||
try { duel = toDuel(c); } catch { duel = undefined; }
|
||||
return duel === undefined ? c : { ...c, duel };
|
||||
});
|
||||
}
|
||||
res.json(body);
|
||||
} catch (e) {
|
||||
const err = e as Error & { status?: number };
|
||||
const status = e instanceof DeckError ? err.status! : err.status === 503 ? 503 : 500;
|
||||
res.status(status).json({ error: status === 500 ? 'Collection unavailable' : err.message });
|
||||
}
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -12,14 +12,11 @@ import { createGameRouter } from './router.ts';
|
||||
import { MatchStore } from './store.ts';
|
||||
import type { EnginePort } from './engine-port.ts';
|
||||
import { TrendCache } from './trends.ts';
|
||||
import type { OwnershipDeps } from './ownership.ts';
|
||||
|
||||
type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> };
|
||||
|
||||
export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment;
|
||||
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean;
|
||||
/** Server-side ownership (#57) for ./ownership.ts verifyAccount/resolveDeck/collection; absent in Night 1 tests. */
|
||||
ownership?: OwnershipDeps }): Promise<express.Router> {
|
||||
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise<express.Router> {
|
||||
const env = options.env ?? process.env;
|
||||
const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding;
|
||||
const modes = loadModes(env);
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
/**
|
||||
* Server-side ownership for constructed play (Night 2, #57). Signature agreed with host-pvp (#56).
|
||||
*
|
||||
* The host never trusts card data from a client. A deck arrives as token ids only; each one
|
||||
* must be on the canonical chain, owned by one of the account's linked wallets, and confirmed
|
||||
* enough. The card is then rebuilt from its own block (article + mint stats snapshot).
|
||||
*
|
||||
* Off-chain only: nothing here moves, burns or locks a card, and nothing touches consensus.
|
||||
* No Wikipedia calls; the only I/O is the injected ID-token verifier (Dex JWKS, cached).
|
||||
*/
|
||||
import type { Account } from '../account/store.ts';
|
||||
import type { Article } from '../../shared/protocol.ts';
|
||||
import type { MintStatsSnapshot } from '../../shared/enrichment.ts';
|
||||
import type { TestnetBlock } from '../../shared/testnet.ts';
|
||||
|
||||
export type OwnershipRules = {
|
||||
/** Exact deck size for constructed play. Production is 40; a testnet mode file may lower it. */
|
||||
deckSize: number;
|
||||
/** MTG-style copy limit: cards minted from the same Wikipedia pageId. */
|
||||
maxCopiesPerPage: number;
|
||||
/** Minimum confirmations of each card's mint block (1 casual, 3 rated). */
|
||||
minConfirmations: number;
|
||||
};
|
||||
export const DEFAULT_OWNERSHIP_RULES: Readonly<OwnershipRules> = Object.freeze({ deckSize: 40, maxCopiesPerPage: 4, minConfirmations: 1 });
|
||||
export const RATED_MIN_CONFIRMATIONS = 3;
|
||||
/** Upper bound on any deck request we will even look at (a deck is 40; this only guards the loop). */
|
||||
export const MAX_DECK_TOKENS = 200;
|
||||
/** Guard against an unbounded collection. Far above anything the chain can mint for one player soon. */
|
||||
export const MAX_COLLECTION = 20_000;
|
||||
/** server/testnet/ledger.ts MAX_DECK_PAGE. */
|
||||
const PAGE = 24;
|
||||
/** A tip change mid-scan restarts the scan; give up after this many rather than loop forever. */
|
||||
const MAX_RESTARTS = 4;
|
||||
|
||||
// Structural: server/testnet/ledger.ts `Ledger` and server/account/store.ts `AccountStore`
|
||||
// satisfy these, and tests pass in-memory fixtures.
|
||||
export type OwnershipLedger = {
|
||||
nft(tokenId: string): { block: TestnetBlock; owner: string; sequence: number; confirmations: number } | undefined;
|
||||
deck(address: string, offset: number, limit: number): {
|
||||
tip: string; total: number; next: number | null;
|
||||
nfts: { block: TestnetBlock; sequence: number; confirmations: number }[];
|
||||
};
|
||||
summary(): { tip: string; height: number };
|
||||
};
|
||||
export type OwnershipAccounts = { wallets(sub: string): { address: string }[]; upsert?(a: Account): void };
|
||||
export type OwnershipDeps = {
|
||||
ledger: OwnershipLedger;
|
||||
accounts: OwnershipAccounts;
|
||||
/** server/account/router.ts accountVerifier(); throws an error with status 401 for a bad token. */
|
||||
verifyIdToken(idToken: string): Promise<Account>;
|
||||
};
|
||||
|
||||
/** One owned NFT as built from its canonical block (never from client JSON). */
|
||||
export type ChainCard = {
|
||||
tokenId: string;
|
||||
/** Current owner (after transfers), one of the account's linked wallets. */
|
||||
owner: string;
|
||||
confirmations: number;
|
||||
pageId: number;
|
||||
title: string;
|
||||
revisionId: number;
|
||||
url: string;
|
||||
extract: string;
|
||||
imageUrl?: string;
|
||||
height: number;
|
||||
blockHash: string;
|
||||
createdAt: number;
|
||||
powHash: string;
|
||||
article: Article;
|
||||
statsSnapshot: MintStatsSnapshot;
|
||||
};
|
||||
|
||||
export type DeckErrorCode = 'auth' | 'size' | 'duplicate-token' | 'unknown-token' | 'not-owned' | 'unconfirmed' | 'copy-limit';
|
||||
const STATUS: Record<DeckErrorCode, 400 | 401 | 403> = {
|
||||
auth: 401, size: 400, 'duplicate-token': 400, 'unknown-token': 400, 'not-owned': 403, unconfirmed: 400, 'copy-limit': 400,
|
||||
};
|
||||
export class DeckError extends Error {
|
||||
readonly code: DeckErrorCode;
|
||||
/** Every offending token of this class, so the UI can highlight them. */
|
||||
readonly tokenIds: string[];
|
||||
readonly status: 400 | 401 | 403;
|
||||
readonly pageId?: number;
|
||||
constructor(code: DeckErrorCode, message: string, tokenIds: string[] = [], pageId?: number) {
|
||||
super(message);
|
||||
this.name = 'DeckError';
|
||||
this.code = code; this.tokenIds = tokenIds; this.status = STATUS[code];
|
||||
if (pageId !== undefined) this.pageId = pageId;
|
||||
}
|
||||
}
|
||||
/** Thrown when Dex or the ledger cannot answer right now (not the player's fault). */
|
||||
export class OwnershipUnavailable extends Error { readonly status = 503; }
|
||||
|
||||
const TOKEN = /^[a-f0-9]{64}$/;
|
||||
const isInt = (n: unknown, min: number, max: number): n is number => Number.isSafeInteger(n) && (n as number) >= min && (n as number) <= max;
|
||||
|
||||
/** Merges partial rules over the defaults and rejects nonsense (mode files are data, so validate). */
|
||||
export function ownershipRules(rules: Partial<OwnershipRules> = {}): OwnershipRules {
|
||||
const defined = Object.fromEntries(Object.entries(rules).filter(([, v]) => v !== undefined)) as Partial<OwnershipRules>;
|
||||
const r = { ...DEFAULT_OWNERSHIP_RULES, ...defined };
|
||||
if (!isInt(r.deckSize, 1, MAX_DECK_TOKENS)) throw new RangeError(`deckSize must be 1..${MAX_DECK_TOKENS}`);
|
||||
if (!isInt(r.maxCopiesPerPage, 1, MAX_DECK_TOKENS)) throw new RangeError(`maxCopiesPerPage must be 1..${MAX_DECK_TOKENS}`);
|
||||
if (!isInt(r.minConfirmations, 1, 1_000_000)) throw new RangeError('minConfirmations must be >= 1');
|
||||
return r;
|
||||
}
|
||||
|
||||
/** Builds the card from the canonical block. `owner` is the current owner from the index, not the miner. */
|
||||
export function cardFromChain(nft: { block: TestnetBlock; confirmations: number }, owner: string): ChainCard {
|
||||
const b = structuredClone(nft.block);
|
||||
const card: ChainCard = { tokenId: b.tokenId, owner, confirmations: nft.confirmations,
|
||||
pageId: b.article.pageId, title: b.article.title, revisionId: b.article.revisionId, url: b.article.url, extract: b.article.extract,
|
||||
height: b.height, blockHash: b.hash, createdAt: b.createdAt, powHash: b.powHash, article: b.article, statsSnapshot: b.statsSnapshot };
|
||||
if (b.article.image) card.imageUrl = b.article.image;
|
||||
return card;
|
||||
}
|
||||
|
||||
/** Verifies a Dex ID token from a request body. Throws DeckError('auth') or OwnershipUnavailable. */
|
||||
export async function verifyAccount(deps: Pick<OwnershipDeps, 'verifyIdToken'>, idToken: unknown): Promise<Account> {
|
||||
if (typeof idToken !== 'string' || !idToken || idToken.length > 8192) throw new DeckError('auth', 'Log in with your eom.dev account to play with your cards');
|
||||
try { return await deps.verifyIdToken(idToken); }
|
||||
catch (e) {
|
||||
if ((e as { status?: number }).status === 401) throw new DeckError('auth', (e as Error).message || 'Log in again with your eom.dev account');
|
||||
throw new OwnershipUnavailable('eom.dev login is temporarily unavailable');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies a constructed deck for an already-verified account. Resolves to the cards in the
|
||||
* order given, or throws the first class of DeckError found (listing every offending token).
|
||||
*/
|
||||
export async function resolveDeck(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>, tokenIds: unknown,
|
||||
opts?: Partial<OwnershipRules>): Promise<ChainCard[]> {
|
||||
const r = ownershipRules(opts);
|
||||
if (!Array.isArray(tokenIds) || tokenIds.length > MAX_DECK_TOKENS) throw new DeckError('size', `A deck is exactly ${r.deckSize} cards`);
|
||||
const invalid = tokenIds.filter(t => typeof t !== 'string' || !TOKEN.test(t)).map(t => String(t).slice(0, 80)).slice(0, 10);
|
||||
if (invalid.length) throw new DeckError('unknown-token', 'Invalid card identifier', invalid);
|
||||
const ids = tokenIds as string[];
|
||||
if (ids.length !== r.deckSize) throw new DeckError('size', `A deck is exactly ${r.deckSize} cards (got ${ids.length})`);
|
||||
const seen = new Set<string>(), dupes = new Set<string>();
|
||||
for (const id of ids) (seen.has(id) ? dupes : seen).add(id);
|
||||
if (dupes.size) throw new DeckError('duplicate-token', 'The same card appears more than once', [...dupes]);
|
||||
|
||||
const wallets = new Set(deps.accounts.wallets(account.sub).map(w => w.address));
|
||||
if (!wallets.size) throw new DeckError('not-owned', 'Link a wallet to your eom.dev account to play with your cards', ids);
|
||||
|
||||
const cards: ChainCard[] = [], missing: string[] = [], foreign: string[] = [], young: string[] = [];
|
||||
for (const id of ids) {
|
||||
const nft = deps.ledger.nft(id);
|
||||
if (!nft || nft.block.tokenId !== id) { missing.push(id); continue; }
|
||||
if (!wallets.has(nft.owner)) { foreign.push(id); continue; }
|
||||
if (nft.confirmations < r.minConfirmations) { young.push(id); continue; }
|
||||
cards.push(cardFromChain(nft, nft.owner));
|
||||
}
|
||||
if (missing.length) throw new DeckError('unknown-token', 'Card not found on the canonical chain', missing);
|
||||
if (foreign.length) throw new DeckError('not-owned', 'Card is not owned by a wallet linked to this account', foreign);
|
||||
if (young.length) throw new DeckError('unconfirmed', `Card needs ${r.minConfirmations} confirmation${r.minConfirmations === 1 ? '' : 's'}`, young);
|
||||
|
||||
const byPage = new Map<number, string[]>();
|
||||
for (const c of cards) byPage.set(c.pageId, [...(byPage.get(c.pageId) ?? []), c.tokenId]);
|
||||
for (const [pageId, tokens] of byPage)
|
||||
if (tokens.length > r.maxCopiesPerPage) throw new DeckError('copy-limit', `At most ${r.maxCopiesPerPage} copies of the same article`, tokens, pageId);
|
||||
return cards;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every card the account owns across its linked wallets, read at one canonical tip (restarting
|
||||
* if the tip moves), with no snapshot cap. Only cards with `minConfirmations` (default 1).
|
||||
*/
|
||||
export async function collection(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>,
|
||||
opts: { minConfirmations?: number } = {}): Promise<ChainCard[]> {
|
||||
return collectionAt(deps, account, opts).cards;
|
||||
}
|
||||
|
||||
/** collection() plus the tip and wallets it was read at. Synchronous. */
|
||||
export function collectionAt(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>,
|
||||
opts: { minConfirmations?: number } = {}): { tip: string; wallets: string[]; cards: ChainCard[] } {
|
||||
const minConfirmations = ownershipRules({ minConfirmations: opts.minConfirmations }).minConfirmations;
|
||||
const wallets = [...new Set(deps.accounts.wallets(account.sub).map(w => w.address))];
|
||||
for (let attempt = 0; attempt <= MAX_RESTARTS; attempt++) {
|
||||
const tip = deps.ledger.summary().tip;
|
||||
const cards = scan(deps.ledger, wallets, tip, minConfirmations);
|
||||
if (cards) return { tip, wallets, cards };
|
||||
}
|
||||
throw new OwnershipUnavailable('The chain is moving too fast to read a consistent collection; try again');
|
||||
}
|
||||
|
||||
/** Returns null if the tip moved during the scan. */
|
||||
function scan(ledger: OwnershipLedger, wallets: string[], tip: string, minConfirmations: number): ChainCard[] | null {
|
||||
const cards: ChainCard[] = [];
|
||||
for (const address of wallets) {
|
||||
let offset: number | null = 0;
|
||||
while (offset !== null) {
|
||||
const page = ledger.deck(address, offset, PAGE);
|
||||
if (page.tip !== tip) return null;
|
||||
for (const nft of page.nfts) {
|
||||
if (nft.confirmations >= minConfirmations) cards.push(cardFromChain(nft, address));
|
||||
if (cards.length > MAX_COLLECTION) throw new OwnershipUnavailable('Collection too large to list');
|
||||
}
|
||||
// Defensive: a page that makes no progress would loop forever.
|
||||
offset = page.next !== null && page.next > offset ? page.next : null;
|
||||
}
|
||||
}
|
||||
return cards;
|
||||
}
|
||||
|
||||
/** How many of these cards a legal deck could use under the copy limit: Σ min(copies, limit) per pageId. */
|
||||
export function playableCount(cards: Pick<ChainCard, 'pageId'>[], maxCopiesPerPage: number): number {
|
||||
const perPage = new Map<number, number>();
|
||||
for (const c of cards) perPage.set(c.pageId, (perPage.get(c.pageId) ?? 0) + 1);
|
||||
let n = 0; for (const count of perPage.values()) n += Math.min(count, maxCopiesPerPage);
|
||||
return n;
|
||||
}
|
||||
+3
-10
@@ -17,10 +17,7 @@ import { IS_MAINNET, PROFILE } from '../../shared/network.ts';
|
||||
import { assertLaunchAllowed, launchManifest } from '../launch.ts';
|
||||
import { resourceConfig, RpcBudget, RpcError } from '../resources.ts';
|
||||
import { trustedProxies, operationsPort, startOperations } from '../operations.ts';
|
||||
import { accountVerifier, createAccountRouter } from '../account/router.ts';
|
||||
import { AccountStore } from '../account/store.ts';
|
||||
import { DexKeys, oidcConfig } from '../account/oidc.ts';
|
||||
import { collectionRouter } from '../game/collection.ts';
|
||||
import { createAccountRouter } from '../account/router.ts';
|
||||
|
||||
const root = fileURLToPath(new URL('../../', import.meta.url));
|
||||
assertLaunchAllowed();
|
||||
@@ -153,12 +150,8 @@ app.post('/p2p/transaction',workLimit,async(req,res)=>{
|
||||
const id=await ledger.submitTransaction(transaction);
|
||||
res.status(202).json({id,status:'pending'});
|
||||
});
|
||||
// One account store and one Dex key cache, shared by the account and game routes (#57).
|
||||
const oidc=oidcConfig(), dexKeys=new DexKeys(oidc), accounts=new AccountStore(resolve(dataDir,'accounts.sqlite'));
|
||||
const ownership={ledger,accounts,verifyIdToken:accountVerifier(oidc,dexKeys,accounts)};
|
||||
app.use('/api/account',createAccountRouter({config:oidc,keys:dexKeys,store:accounts}));
|
||||
app.use('/api/game/collection',collectionRouter(ownership));
|
||||
app.use('/api/game',await (await import('../game/index.ts')).gameRouter({dataDir,enrichment:wikipediaEnrichment,ownership}));
|
||||
app.use('/api/account',createAccountRouter({dataDir}));
|
||||
app.use('/api/game',await (await import('../game/index.ts')).gameRouter({dataDir,enrichment:wikipediaEnrichment}));
|
||||
app.use(['/api','/p2p'],(_req,res)=>{res.status(404).json({error:'Unknown testnet endpoint'});});
|
||||
app.use(express.static(resolve(root,'dist')));
|
||||
app.get('/{*path}',(_req,res)=>res.sendFile(resolve(root,'dist/index.html')));
|
||||
|
||||
+2
-6
@@ -10,7 +10,7 @@ import { Card, samples, imageCredit, type CardData } from './Card.tsx';
|
||||
import { WalletPanel } from './WalletPanel.tsx';
|
||||
import { useModalFocus } from './useModalFocus.ts';
|
||||
import { ThemePicker } from './ThemePicker.tsx';
|
||||
import { LoginButton, useAccount } from './auth/LoginButton.tsx';
|
||||
import { LoginButton } from './auth/LoginButton.tsx';
|
||||
import { TradeDesk } from './TradeDesk.tsx';
|
||||
import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/network.ts';
|
||||
import { StateClient } from '../shared/rpc-client.ts';
|
||||
@@ -48,7 +48,6 @@ function transferProblem(state: TestnetSnapshot, card: CardData, address: string
|
||||
|
||||
export default function App() {
|
||||
const [view, setView] = useState<View>('Discover');
|
||||
const linkedAccount = useAccount();
|
||||
const [wallet, setWallet] = useState<Wallet>();
|
||||
const [snapshot, setSnapshot] = useState<TestnetSnapshot>();
|
||||
const [rpcAvailable, setRpcAvailable] = useState(false);
|
||||
@@ -128,10 +127,7 @@ export default function App() {
|
||||
} catch (e) { setTransferError(message(e)); }
|
||||
finally { transferInFlight.current = false; setTransferBusy(false); }
|
||||
};
|
||||
// Every canonical card owned by this browser's wallet or any wallet linked to the eom.dev account (#57).
|
||||
// The full canonical chain is paged in by StateClient, so nothing is capped at 128 blocks.
|
||||
const mine = new Set([wallet?.address, ...(linkedAccount?.wallets ?? []).map(w => w.address)].filter(Boolean));
|
||||
const owned = snapshot?.blocks.filter(b => mine.has(testnetOwnerOf(snapshot, b.tokenId) ?? '')) ?? [];
|
||||
const owned = snapshot?.blocks.filter(b => wallet && testnetOwnerOf(snapshot, b.tokenId) === wallet.address) ?? [];
|
||||
const visibleCards = view === 'My collection' ? owned.map(asCard)
|
||||
: snapshot?.blocks.length ? [...snapshot.blocks].reverse().slice(0, 12).map(asCard) : samples;
|
||||
const filtered = visibleCards.filter(c => (category === 'All cards' || c.article.category === category) &&
|
||||
|
||||
@@ -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>{l.winner !== null && l.myPower === l.theirPower && <small className="tie-note">Tie, decided by on-topic cards</small>}
|
||||
<span>{l.name}</span><b>{l.myPower} – {l.theirPower}</b><small>{l.winner === 0 ? 'Won' : l.winner === 1 ? 'Lost' : 'Tied'}</small>
|
||||
</li>)}
|
||||
</ol>
|
||||
<p className="muted small">Matches are off-chain. No card was moved or burned.</p>
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
// 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);
|
||||
@@ -6,7 +6,6 @@
|
||||
// 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;
|
||||
@@ -60,7 +59,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.'
|
||||
: 'Looks a few moves ahead and plays for the lead in each Topic. It cannot see your hidden plays.',
|
||||
: '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)[];
|
||||
@@ -73,6 +72,4 @@ export function makeUiBot(level: BotLevel, engineChoice?: EngineChoice): Bot {
|
||||
};
|
||||
}
|
||||
|
||||
// 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)];
|
||||
export const BOTS: Bot[] = [makeUiBot('easy'), makeUiBot('normal')];
|
||||
|
||||
@@ -206,4 +206,3 @@ 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}
|
||||
|
||||
@@ -1,291 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import express from 'express';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { resolveDeck, collection, verifyAccount, playableCount, ownershipRules, DEFAULT_OWNERSHIP_RULES,
|
||||
DeckError, OwnershipUnavailable, type OwnershipDeps, type OwnershipLedger } from '../server/game/ownership.ts';
|
||||
import { collectionRouter, collectionResponse } from '../server/game/collection.ts';
|
||||
import type { Account } from '../server/account/store.ts';
|
||||
import type { TestnetBlock } from '../shared/testnet.ts';
|
||||
|
||||
// In-memory fixture: the same shape as Ledger.nft/deck/summary and AccountStore.wallets. No network.
|
||||
const hex = (s: string) => createHash('sha256').update(s).digest('hex');
|
||||
const ALICE = hex('alice'), ALICE2 = hex('alice-2'), BOB = hex('bob');
|
||||
|
||||
function block(n: number, pageId: number, miner: string): TestnetBlock {
|
||||
return {
|
||||
version: 6, network: 'testnet', chainId: 'test', height: n, previousHash: hex(`b${n - 1}`), createdAt: 1_800_000_000 + n,
|
||||
article: { pageId, title: `Article ${pageId}`, extract: `Extract ${pageId}.`, url: `https://en.wikipedia.org/?curid=${pageId}`,
|
||||
revisionId: 1000 + pageId, source: 'live', category: 'History' },
|
||||
statsSnapshot: { capturedAt: '2026-11-17T00:00:00Z', revisionId: 1000 + pageId, pageBytes: 5000 + pageId, languageCount: 3,
|
||||
languagesTruncated: false, pageviews: null } as unknown as TestnetBlock['statsSnapshot'],
|
||||
owner: miner, publicKey: 'pk', nonce: 0, target: 'f'.repeat(64), key: '0'.repeat(64), transactionsRoot: '0'.repeat(64),
|
||||
stateRoot: '0'.repeat(64), hash: hex(`b${n}`), tokenId: hex(`t${n}`), powHash: hex(`p${n}`), signature: 'sig', transactions: [],
|
||||
} as unknown as TestnetBlock;
|
||||
}
|
||||
|
||||
class FakeLedger implements OwnershipLedger {
|
||||
tip = 'tip-0';
|
||||
height = 0;
|
||||
cards: { block: TestnetBlock; owner: string }[] = [];
|
||||
deckCalls = 0;
|
||||
onDeck?: () => void;
|
||||
mint(owner: string, pageId: number): string {
|
||||
const b = block(++this.height, pageId, owner);
|
||||
this.cards.push({ block: b, owner });
|
||||
this.tip = `tip-${this.height}`;
|
||||
return b.tokenId;
|
||||
}
|
||||
mineEmpty(n = 1) { this.height += n; this.tip = `tip-${this.height}`; }
|
||||
transfer(token: string, to: string) { this.cards.find(c => c.block.tokenId === token)!.owner = to; }
|
||||
private conf(b: TestnetBlock) { return this.height - b.height + 1; }
|
||||
nft(token: string) {
|
||||
const c = this.cards.find(x => x.block.tokenId === token);
|
||||
return c ? { block: structuredClone(c.block), owner: c.owner, sequence: 0, confirmations: this.conf(c.block) } : undefined;
|
||||
}
|
||||
deck(address: string, offset: number, limit: number) {
|
||||
this.deckCalls++;
|
||||
assert.ok(limit <= 24, 'ledger pages are at most 24');
|
||||
const mine = this.cards.filter(c => c.owner === address);
|
||||
const nfts = mine.slice(offset, offset + limit).map(c => ({ block: structuredClone(c.block), sequence: 0, confirmations: this.conf(c.block) }));
|
||||
const result = { tip: this.tip, total: mine.length, next: offset + nfts.length < mine.length ? offset + nfts.length : null, nfts };
|
||||
this.onDeck?.();
|
||||
return result;
|
||||
}
|
||||
summary() { return { tip: this.tip, height: this.height, network: 'testnet', chainId: 'test' }; }
|
||||
}
|
||||
|
||||
function fixture(wallets: Record<string, string[]> = { alice: [ALICE, ALICE2], bob: [BOB] }) {
|
||||
const ledger = new FakeLedger();
|
||||
const deps: OwnershipDeps = { ledger, accounts: { wallets: sub => (wallets[sub] ?? []).map(address => ({ address })) },
|
||||
verifyIdToken: async (t: string): Promise<Account> => {
|
||||
const m = /^good\.token\.(\w+)$/.exec(t);
|
||||
if (m) return { sub: m[1], issuer: 'https://dex.example/', name: m[1], username: m[1] };
|
||||
if (t === 'dex.is.down') throw new Error('fetch failed');
|
||||
throw Object.assign(new Error('Token expired'), { status: 401 });
|
||||
} };
|
||||
return { ledger, deps };
|
||||
}
|
||||
/** n cards for `owner`, distinct pageIds starting at `firstPage`. */
|
||||
const mintMany = (l: FakeLedger, owner: string, n: number, firstPage = 1) => Array.from({ length: n }, (_, i) => l.mint(owner, firstPage + i));
|
||||
|
||||
const ALICE_ACCT = { sub: 'alice' }, BOB_ACCT = { sub: 'bob' };
|
||||
async function rejects(p: Promise<unknown>, code: string, tokenIds?: string[]) {
|
||||
await assert.rejects(p, (e: unknown) => {
|
||||
assert.ok(e instanceof DeckError, String(e));
|
||||
assert.equal(e.code, code);
|
||||
if (tokenIds) assert.deepEqual(e.tokenIds, tokenIds);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
test('defaults are a 40-card deck, 4 copies per article, 1 confirmation', () => {
|
||||
assert.deepEqual({ ...DEFAULT_OWNERSHIP_RULES }, { deckSize: 40, maxCopiesPerPage: 4, minConfirmations: 1 });
|
||||
assert.equal(ownershipRules({ deckSize: 10, minConfirmations: undefined }).minConfirmations, 1);
|
||||
assert.throws(() => ownershipRules({ deckSize: 0 }), RangeError);
|
||||
assert.throws(() => ownershipRules({ maxCopiesPerPage: 1.5 }), RangeError);
|
||||
assert.throws(() => ownershipRules({ minConfirmations: 0 }), RangeError);
|
||||
});
|
||||
|
||||
test('verifyAccount maps token failures to DeckError(auth) and Dex outages to OwnershipUnavailable', async () => {
|
||||
const { deps } = fixture();
|
||||
assert.equal((await verifyAccount(deps, 'good.token.alice')).sub, 'alice');
|
||||
for (const t of [undefined, '', 42, 'x'.repeat(9000)]) await rejects(verifyAccount(deps, t), 'auth');
|
||||
await assert.rejects(verifyAccount(deps, 'bad'), (e: unknown) => e instanceof DeckError && e.code === 'auth' && e.status === 401 && e.message === 'Token expired');
|
||||
await assert.rejects(verifyAccount(deps, 'dex.is.down'), (e: unknown) => e instanceof OwnershipUnavailable && e.status === 503);
|
||||
});
|
||||
|
||||
test('resolveDeck accepts 40 owned cards across linked wallets and builds them from the chain, in order', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
const ids = [...mintMany(ledger, ALICE, 25, 1), ...mintMany(ledger, ALICE2, 15, 100)].reverse();
|
||||
const cards = await resolveDeck(deps, ALICE_ACCT, ids);
|
||||
assert.equal(cards.length, 40);
|
||||
assert.deepEqual(cards.map(c => c.tokenId), ids);
|
||||
const c = cards.find(x => x.pageId === 100)!;
|
||||
const chain = ledger.nft(c.tokenId)!.block;
|
||||
assert.equal(c.owner, ALICE2);
|
||||
assert.equal(c.title, 'Article 100');
|
||||
assert.equal(c.revisionId, 1100);
|
||||
assert.equal(c.article.title, 'Article 100');
|
||||
assert.equal(c.statsSnapshot.pageBytes, 5100);
|
||||
assert.equal(c.blockHash, chain.hash);
|
||||
assert.equal(c.powHash, chain.powHash);
|
||||
assert.equal(c.height, chain.height);
|
||||
});
|
||||
|
||||
test('resolveDeck takes token ids only: card data is never taken from the client', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
const ids = mintMany(ledger, ALICE, 40);
|
||||
const forged = ids.map(tokenId => ({ tokenId, article: { title: 'Barack Obama' }, statsSnapshot: { pageBytes: 9e9 } }));
|
||||
await rejects(resolveDeck(deps, ALICE_ACCT, forged), 'unknown-token');
|
||||
});
|
||||
|
||||
test('resolveDeck enforces the exact deck size from ruleset data', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
const ids = mintMany(ledger, ALICE, 41);
|
||||
for (const deck of [ids.slice(0, 39), ids, [], 'nope', null, Array(10_000).fill(ids[0])]) await rejects(resolveDeck(deps, ALICE_ACCT, deck), 'size');
|
||||
assert.equal((await resolveDeck(deps, ALICE_ACCT, ids.slice(0, 10), { deckSize: 10 })).length, 10, 'a testnet mode may lower deckSize');
|
||||
});
|
||||
|
||||
test('resolveDeck rejects malformed and duplicated token ids', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
const ids = mintMany(ledger, ALICE, 40);
|
||||
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids.slice(0, 39), 'ABC']), 'unknown-token', ['ABC']);
|
||||
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids.slice(0, 39), ids[0]]), 'duplicate-token', [ids[0]]);
|
||||
});
|
||||
|
||||
test('resolveDeck requires a linked wallet', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
const ids = mintMany(ledger, ALICE, 40);
|
||||
await assert.rejects(resolveDeck(deps, { sub: 'stranger' }, ids), (e: unknown) => e instanceof DeckError && e.code === 'not-owned' && e.status === 403 && /Link a wallet/.test(e.message));
|
||||
});
|
||||
|
||||
test('resolveDeck rejects unknown cards and cards owned by someone else, listing every one', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
const ids = mintMany(ledger, ALICE, 38);
|
||||
const bobs = mintMany(ledger, BOB, 2, 500);
|
||||
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids, ...bobs]), 'not-owned', bobs);
|
||||
await rejects(resolveDeck(deps, ALICE_ACCT, [...ids, hex('nope'), bobs[0]]), 'unknown-token', [hex('nope')]);
|
||||
// Bob cannot field Alice's cards either, even though they exist.
|
||||
await rejects(resolveDeck(deps, BOB_ACCT, [...ids, ...bobs]), 'not-owned', ids);
|
||||
});
|
||||
|
||||
test('ownership follows transfers: the current owner, not the miner, may play the card', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
const ids = mintMany(ledger, ALICE, 40);
|
||||
ledger.transfer(ids[7], BOB);
|
||||
await rejects(resolveDeck(deps, ALICE_ACCT, ids), 'not-owned', [ids[7]]);
|
||||
const cards = await resolveDeck(deps, BOB_ACCT, [ids[7], ...mintMany(ledger, BOB, 39, 300)]);
|
||||
assert.equal(cards[0].owner, BOB);
|
||||
});
|
||||
|
||||
test('resolveDeck requires minConfirmations (3 for rated play)', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
const ids = mintMany(ledger, ALICE, 40);
|
||||
// The last card has 1 confirmation, the one before it 2.
|
||||
await rejects(resolveDeck(deps, ALICE_ACCT, ids, { minConfirmations: 3 }), 'unconfirmed', ids.slice(38));
|
||||
ledger.mineEmpty(2);
|
||||
assert.equal((await resolveDeck(deps, ALICE_ACCT, ids, { minConfirmations: 3 })).length, 40);
|
||||
});
|
||||
|
||||
test('duplicates of an article count as separate cards, up to 4 copies per pageId', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
const base = mintMany(ledger, ALICE, 35, 1);
|
||||
const copies = Array.from({ length: 5 }, () => ledger.mint(ALICE, 777));
|
||||
await assert.rejects(resolveDeck(deps, ALICE_ACCT, [...base, ...copies]),
|
||||
(e: unknown) => e instanceof DeckError && e.code === 'copy-limit' && e.pageId === 777 && e.tokenIds.length === 5);
|
||||
const cards = await resolveDeck(deps, ALICE_ACCT, [...base, ...copies.slice(0, 4), ledger.mint(ALICE, 900)]);
|
||||
assert.equal(cards.filter(c => c.pageId === 777).length, 4);
|
||||
assert.equal((await resolveDeck(deps, ALICE_ACCT, [...base, ...copies], { maxCopiesPerPage: 5 })).length, 40, 'the copy limit is ruleset data');
|
||||
});
|
||||
|
||||
test('playableCount applies the copy limit', () => {
|
||||
const cards = [1, 1, 1, 1, 1, 1, 2, 3].map(pageId => ({ pageId }));
|
||||
assert.equal(playableCount(cards, 4), 6);
|
||||
assert.equal(playableCount(cards, 1), 3);
|
||||
});
|
||||
|
||||
test('collection lists every owned card across wallets with no 128-block cap', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
mintMany(ledger, ALICE, 150, 1);
|
||||
mintMany(ledger, BOB, 10, 1000);
|
||||
mintMany(ledger, ALICE2, 3, 2000);
|
||||
const cards = await collection(deps, ALICE_ACCT);
|
||||
assert.equal(cards.length, 153);
|
||||
assert.equal(new Set(cards.map(x => x.tokenId)).size, 153);
|
||||
assert.ok(cards.every(x => x.owner === ALICE || x.owner === ALICE2));
|
||||
const r = collectionResponse(deps, 'alice');
|
||||
assert.equal(r.owned, 153); assert.equal(r.playable, 153); assert.equal(r.needed, 0); assert.equal(r.eligible, true);
|
||||
assert.deepEqual(r.wallets, [ALICE, ALICE2]);
|
||||
assert.equal(r.tip, ledger.tip);
|
||||
assert.deepEqual(await collection(deps, { sub: 'stranger' }), []);
|
||||
});
|
||||
|
||||
test('collection shows progress toward 40 and applies the copy limit to eligibility', () => {
|
||||
const { ledger, deps } = fixture();
|
||||
mintMany(ledger, ALICE, 20, 1);
|
||||
for (let i = 0; i < 10; i++) ledger.mint(ALICE, 4242);
|
||||
const c = collectionResponse(deps, 'alice');
|
||||
assert.equal(c.owned, 30); assert.equal(c.playable, 24); assert.equal(c.needed, 16); assert.equal(c.eligible, false);
|
||||
assert.equal(c.deckSize, 40); assert.equal(c.copyLimit, 4); assert.equal(c.maxCopiesPerPage, 4);
|
||||
assert.equal(collectionResponse(deps, 'alice', { deckSize: 20 }).eligible, true);
|
||||
const none = collectionResponse(deps, 'stranger');
|
||||
assert.equal(none.owned, 0); assert.equal(none.needed, 40); assert.deepEqual(none.cards, []);
|
||||
});
|
||||
|
||||
test('collection only counts cards with enough confirmations', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
mintMany(ledger, ALICE, 5);
|
||||
assert.equal((await collection(deps, ALICE_ACCT, { minConfirmations: 3 })).length, 3);
|
||||
});
|
||||
|
||||
test('collection restarts when the tip moves mid-scan and gives up if it never settles', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
mintMany(ledger, ALICE, 60);
|
||||
let moves = 1;
|
||||
ledger.onDeck = () => { if (moves-- > 0) ledger.mint(ALICE, 9999); };
|
||||
const c = collectionResponse(deps, 'alice');
|
||||
assert.equal(c.owned, 61);
|
||||
assert.equal(c.tip, ledger.tip);
|
||||
ledger.onDeck = () => { ledger.mineEmpty(); };
|
||||
await assert.rejects(collection(deps, ALICE_ACCT), OwnershipUnavailable);
|
||||
});
|
||||
|
||||
async function serve(router: express.Router) {
|
||||
const app = express();
|
||||
app.use('/api/game/collection', router);
|
||||
const server = app.listen(0, '127.0.0.1');
|
||||
await new Promise(r => server.once('listening', r));
|
||||
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api/game/collection`;
|
||||
return { base, close: () => new Promise(r => server.close(r)) };
|
||||
}
|
||||
|
||||
test('GET /api/game/collection requires a verified eom.dev token (local loopback only, no upstream)', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
mintMany(ledger, ALICE, 23);
|
||||
const { base, close } = await serve(collectionRouter(deps));
|
||||
const as = (t: string) => ({ headers: { authorization: `Bearer ${t}` } });
|
||||
try {
|
||||
let res = await fetch(base);
|
||||
assert.equal(res.status, 401);
|
||||
res = await fetch(base, as('bad.token.x!'));
|
||||
assert.equal(res.status, 401);
|
||||
res = await fetch(base, as('expired.token.x'));
|
||||
assert.equal(res.status, 401);
|
||||
assert.equal((await res.json()).error, 'Token expired');
|
||||
res = await fetch(base, as('dex.is.down'));
|
||||
assert.equal(res.status, 503);
|
||||
res = await fetch(`${base}?minConfirmations=abc`, as('good.token.alice'));
|
||||
assert.equal(res.status, 400);
|
||||
res = await fetch(base, as('good.token.alice'));
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.headers.get('cache-control'), 'no-store');
|
||||
const body = await res.json();
|
||||
assert.equal(body.owned, 23); assert.equal(body.playable, 23); assert.equal(body.needed, 17);
|
||||
assert.equal(body.eligible, false); assert.equal(body.deckSize, 40); assert.equal(body.copyLimit, 4);
|
||||
assert.equal(body.cards.length, 23);
|
||||
assert.equal(body.cards[0].title, 'Article 1');
|
||||
assert.equal(body.cards[0].pageId, 1);
|
||||
res = await fetch(`${base}?minConfirmations=3`, as('good.token.alice'));
|
||||
assert.equal((await res.json()).owned, 21);
|
||||
res = await fetch(base, as('good.token.bob'));
|
||||
assert.equal((await res.json()).owned, 0);
|
||||
} finally { await close(); }
|
||||
});
|
||||
|
||||
test('GET /api/game/collection attaches the injected duel card when one is ready, and omits it otherwise', async () => {
|
||||
const { ledger, deps } = fixture();
|
||||
mintMany(ledger, ALICE, 3);
|
||||
const duelCard = (c: { pageId: number }) => {
|
||||
if (c.pageId === 2) return undefined; // profile pending
|
||||
if (c.pageId === 3) throw new Error('boom'); // never breaks the collection
|
||||
return { kind: 'Figure', pageId: c.pageId };
|
||||
};
|
||||
const { base, close } = await serve(collectionRouter({ ...deps, duelCard }));
|
||||
try {
|
||||
const body = await (await fetch(base, { headers: { authorization: 'Bearer good.token.alice' } })).json();
|
||||
assert.deepEqual(body.cards.map((c: { duel?: unknown }) => c.duel), [{ kind: 'Figure', pageId: 1 }, undefined, undefined]);
|
||||
assert.ok(!('duel' in body.cards[1]));
|
||||
} finally { await close(); }
|
||||
});
|
||||
@@ -38,9 +38,6 @@ 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']);
|
||||
@@ -49,14 +46,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, N);
|
||||
const r = winRate(normal, randomBot, 100);
|
||||
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, N);
|
||||
const e = winRate(easy, randomBot, 100), g = winRate(normal, easy, 100);
|
||||
console.log(`easy vs random ${e}, normal vs easy ${g}`); assert.ok(e > 0.5, `easy vs random ${e}`);
|
||||
assert.ok(g > 0.55, `normal vs easy ${g}`);
|
||||
assert.ok(g > 0.6, `normal vs easy ${g}`);
|
||||
});
|
||||
|
||||
test('bots never concede or un-queue, and end the turn when nothing fits', () => {
|
||||
|
||||
@@ -141,14 +141,3 @@ 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);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user