Overnight build by 17 Claude agents (2026-11-16 22:45 → 01:30 EST), coordinated in [claude/wikideck milestone 63](https://gitea.eom.dev/claude/wikideck/milestone/63). **For Eric's review. Do not merge without it.** The full write-up is in `docs/night/REPORT.md`. **What's in it** (38 reviewed PRs, squash-merged into `night/2026-11-16`): - **Edit War:** - a 3-lane, 6-turn card game built on what WikiDeck cards actually hold - a pure, deterministic, off-chain rules engine (`shared/game/`, with the API in `docs/game/ENGINE_API.md`); rules are data and v1.1 is the default - a mobile-first Play UI with a lobby, deck builder, four loaner starter decks, a match against the AI, results and a tutorial - a landing page (fixes #3) - **Design and balance:** `docs/game/DESIGN.md`, `CARD_DATA.md` (236 sampled articles) and `BALANCE.md` (bot simulations). Starter pairings went from 23–77% on v1 to roughly even on v1.1. - **eom.dev accounts:** Dex OIDC with PKCE, plus off-chain wallet linking, where the client builds the message it signs (`server/account/`, `src/auth/`). - **Peer-hosted game modes:** modes are JSON data, never code. Node API at `/api/game/*`, with host credit and leaderboards. Three example modes (`shared/game/modes.ts`, `server/game/`, `docs/game/HOSTING.md`). - **Mobile:** Capacitor 7 Android app (a debug APK played a full match against the AI in the emulator), and an iOS project waiting on Xcode (`docs/night/ANDROID.md`, `docs/night/IOS.md`). - **Testnet tooling:** `deploy/night/` (LAN-only, 3 nodes) and an optional `WIKIDECK_USER_AGENT` (the default is unchanged). **Not touched:** consensus and protocol (`server/chain.ts`, `shared/protocol.ts`, `server/testnet/{consensus,ledger,…}.ts`, `native/`), the live deployment and mainnet. Matches run off-chain and never move or burn NFTs. **Checks:** the final integration gate passed in `node:24-alpine`: `npm test` 241/242 with 0 fail (1 skipped), and `npm run build` passes. The repo needs Node 24, because Node 20 fails 12 tests falsely. **Decisions for Eric** (see REPORT.md, Known issues and Next steps): 1. whether the live node should set `WIKIDECK_USER_AGENT` 2. the Xcode licence, which you should accept yourself 3. #49 in the fork, a bot change held after the freeze 4. on-chain host rewards (proposal only, in HOSTING.md) 🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: #22 Co-authored-by: Claude <claude@eom.dev>
17 KiB
WikiDeck game engine API (v1)
Owner: engine-a (core and API) and engine-b (keywords, card derivation, tests). Issue: claude/wikideck#3.
Rules: docs/game/DESIGN.md v1 ("Edit War", as frozen in PR #17 @ cf2fceb). Where this file and DESIGN.md disagree, raise it on #3.
Stability: UI, simulation and modes build against this file. Any change to a name or shape below is
announced on #3 before it merges.
The engine is a pure TypeScript library in shared/game/:
- It does no I/O and has no clocks: no
Date.now(), noMath.random(). - It imports nothing from
server/orsrc/. - It runs entirely off-chain. A match never reads, moves, locks or burns an NFT.
- It is deterministic: the same
(ruleset, decks, seed, actions)always gives the same state, byte for byte.
Import only from shared/game/index.ts.
import { createMatch, legalActions, applyAction, isOver, result, viewFor,
serialize, deserialize, replay, DEFAULT_RULESET, parseRuleset, validateDeck,
starterDeck, previewPool, type MatchState, type Action, type GameCard } from '../shared/game/index.ts';
1. Lifecycle
let state = createMatch(DEFAULT_RULESET, [deck0, deck1], seed); // turn 1, planning
while (!isOver(state)) {
// Each seat (in any order, any interleaving) queues plays, then commits.
const actions = legalActions(state, seat); // play / undo / commit
state = applyAction(state, chosen); // returns a NEW state
// When both seats have committed, the turn resolves inside applyAction.
}
const r = result(state); // { winner: 0 | 1 | null, reason, topicsLed, lanePower, totalPower, turns }
| Function | Description |
|---|---|
createMatch(ruleset, [deck0, deck1], seed: number | string): MatchState |
Validates the ruleset (parseRuleset) and both decks (validateDeck), then performs DESIGN §4 setup and turn-1 start. A seed is a uint32. A string is hashed with FNV-1a (seedFromString). Throws ZodError for a bad ruleset and IllegalActionError for a bad deck. |
legalActions(state, seat): Action[] |
Lists every play (each card × each lane it can legally go into), every undo, and commit. Returns [] once the seat has committed or the match is over. It never lists concede (always legal while the match is running) or timeout (host only). |
applyAction(state, action): MatchState |
Pure: the input is never mutated. Throws IllegalActionError if the action is illegal. |
actionProblem(state, action): string | null |
Explains why an action is illegal, without throwing. Use it for UI hints and for validating client input on a host. |
isOver(state) / result(state) |
result is null while the match is running. |
viewFor(state, seat): PlayerView |
The hidden-information view. Send only this to clients and AIs, never MatchState, because a MatchState contains both deck orders and the RNG state. |
serialize(state): string / deserialize(json): MatchState |
Lossless JSON. MatchState is plain data. |
replay(ruleset, decks, seed, actions): MatchState |
Rebuilds a match from its inputs. state.actions records every action applied, so a host can store (ruleset, decks, seed, actions) and verify a result later. |
validateDeck(ruleset, cards): string[] |
Returns the list of problems; empty means the deck is legal. |
cardPower(state, cardInPlay), lanePower(state, lane), laneLeader(state, lane), topicsLed(state) |
Power queries (DESIGN §6). laneLeader and topicsLed apply the consensus tie-break. |
scoringPower(state, lane) |
Lane power plus revealed "at scoring" Portals (§7). result().lanePower uses this. |
laneCapacity(state, lane) |
Per-seat capacity of a lane. A Portal such as Stub may override it. |
isOnTopic(state, cardInPlay) |
§1.4/§6 on-topic test, including Disambiguation. |
STARTER_DECKS, starterDeckById(id, rules?) |
The 4 DESIGN §2.1 starter decks (stargazers, field-guide, headliners, pioneers), derived through deriveCard with the given rules (a Ruleset works). Use these for new players. |
starterDeck(seed) |
Older placeholder loaner deck (seeded, 2 per cost from STARTER_POOL). Kept for tests and tools; not a §2.1 starter deck. |
previewPool(rules?) |
The 20 frozen docs/game/starter-cards.json loaners (council-data), derived via §1 against the card-sample-2026-11-16 percentile table. For loaner slots and draft modes. |
deriveCard(input, table, rules?), deriveDeck(inputs, table, rules?) |
DESIGN §1 + §10.1: CardInput → GameCard. Hosts only: run on host-frozen, plausibility-checked inputs, never on client JSON. A Ruleset can be passed as rules. |
placeCard(state, seat, lane, card), revealPortal(state, lane) |
Test helpers for building boards by hand. |
2. Actions
type Action =
| { type: 'play'; player: 0 | 1; cardId: string; lane: number } // queue a card from hand (hidden)
| { type: 'undo'; player: 0 | 1; cardId: string } // un-queue it (refunds energy)
| { type: 'commit'; player: 0 | 1 } // lock in this turn (empty = pass)
| { type: 'timeout'; player: 0 | 1 } // HOST ONLY: turn timer expired
| { type: 'concede'; player: 0 | 1 };
Queuing a play
playreserves the card's cost from this turn's energy. It checks the energy, the lane's room (cards already in the lane plus queued plays must stay underlaneCapacity(state, lane)), and, once the Portal is revealed, whether it accepts the card (canPlay).- Your plays reveal in your queue order, interleaved with the opponent's (see below).
undoand new plays are allowed until the seat sendscommit.
Resolving a turn
- When both seats have committed,
applyActionresolves the turn (DESIGN §5.4–5.5):- Carry is set: min(
energyCarryMax, energy not reserved by queued plays). Energy spent on a play that later fizzles is still spent. - Interleaved reveal: the initiative seat's 1st play, then the other seat's 1st, then the initiative seat's 2nd, and so on. When one seat runs out, the other's remaining plays reveal in order. Each card gets the next global
seqnumber, and its on-reveal effects (keyword, then Portal) run at once. - End-of-turn effects run: the initiative seat's cards first, then lanes left→right, then
seqorder. - On the last turn, scoring follows (§7). Otherwise the next turn starts:
- initiative alternates
- any Portal scheduled by
portalRevealis revealed - energy =
energyByTurn[t-1]+ carry +bonusEnergy - each seat draws
- the underdog bonus applies (only if
underdogis on)
- Carry is set: min(
- A play that is illegal at reveal (the lane filled up, or a Portal rejects the card) fizzles. The card stays in hand and its energy is lost. A
fizzlelog event records it.
Timeouts. timeout is how a host enforces turnSeconds. It commits whatever is queued. A timeout with an empty queue counts toward afkTurns. When that count is reached, the seat concedes and the result has reason: 'afk'. An ordinary commit resets the count.
Seat ownership. The engine does not authenticate anyone. The host must check that the seat in action.player is the caller's.
3. Cards
interface GameCard {
cardId: string; // unique within a deck: the NFT card hash, or `loaner:<pageId>:<n>`
pageId: number | null; // at most maxCopiesPerPage cards share a pageId; null (unpinned loaners) → counted per cardId
title: string;
faction: 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture';
rarity: 'Common' | 'Rare' | 'Epic' | 'Legendary'; // cosmetic in v1
cost: number; // 0–6 (uncheckedCostCap already applied by derivation)
power: number; // 0–30, base power
home: 'attention' | 'depth' | 'reach';
trend: -1 | 0 | 1; // frozen at match start
keyword: string | null; // an id in KEYWORDS
source: 'owned' | 'loaner';
check?: 'verified' | 'unverified' | 'unchecked' | 'loaner'; // host plausibility result (§1.10), for logs
}
- The engine takes already-derived cards and never reads raw stats. The council asked for this, because snapshot stats are self-reported (#1, critic brief A.1).
- Derivation (DESIGN §1 and §10.1: percentile → fame → cost → power, home, trend, keyword and vanillaBonus) lives in
shared/game/derive.ts, which engine-b owns. Hosts run it on host-frozen, plausibility-checked inputs before callingcreateMatch. CardInput = { cardId, pageId | null, title, category, rarity, snapshot: { stats }, live: { trendPercent, dailyAverage }, check, pinned? }.pinned: { cost, home, faction }replaces §1.1–1.5 only whencheck === 'loaner'.check === 'unchecked'caps cost atuncheckedCostCap(home and fame are kept).- Never build
GameCards from client JSON.validateDeckonly checks shapes and ranges; a client could send cost 1 / power 30. Constructed modes must re-derive on the host. - Both seats can hold the same loaner
cardId. The engine keys per seat, so UIs should key cards byowner + cardId. - Modes may adjust
GameCardfields such aspowerbeforecreateMatch. The engine does not re-derive them. checkandpinnedare host decisions, not player input. Build loaner inputs only from shipped data (STARTER_DECKS,previewPool(),LOANER_SNAPSHOTS), and setcheckfor owned cards from the host's own §1.10 check. Otherwise a client could sendcheck: 'loaner', pinned: {cost: 1, …}for any card.obscureleaks in v1.viewFordoes not mask Obscure cards yet. Modes must not putobscureinkeywordsEnableduntil it does.- A keyword that isn't in
ruleset.keywordsEnablednever runs. Derivation is responsible for not giving that cardvanillaBonus. - Lane power =
power+bonus+trend+onTopicBonus[cost]if on-topic + ongoing keyword and Portal effects, floored at 0.
4. Ruleset
Ruleset holds the DESIGN §9 keys, flat (nothing deeper than one level, apart from topicPool entries and the param tables).
parseRuleset(unknown)is a strict zod parse: unknown keys are rejected and every number is bounded, so any ruleset that passes terminates withinturnsturns.- Modes merge overrides onto
DEFAULT_RULESETand then callparseRuleset.
Notes on the §9 keys:
topicPoolis inlineTopicDef[] = { id, name, stat, portal: PortalId | null }[].DEFAULT_TOPIC_POOLis the 9 Topics of §10.3. A Portal id is one ofPORTAL_IDS(main-page, trending, featured-article, stub, interwiki, disambiguation).keywordParams[keywordId]holds keyword numbers; keys must be inKEYWORD_IDS.portalParams[topicId]holds Portal numbers, and falls back toportalParams[portalId], so a mode can add a Topic that reuses a Portal kind with new numbers.keywordsEnabled⊆KEYWORD_IDS(the 6 v1 ids plusedition,obscureandwildcard).mulliganmust befalse. Mulligans are not implemented in v1.percentiles,starterDecks,trendUp/Down,trendMinDaily,uncheckedCostCap,vanillaBonus,costThresholds,powerByCost,verifyStatsandfactionSynergyCapare for derivation and the host. The core loop doesn't read them.
Validation also enforces:
turns × turnSeconds ≤ 240energyByTurn.length ≥ turnsportalReveal.length = topicCountopeningHand ≤ handLimitcostThresholdsin ascending order- with
distinctStats,topicCount == 3and the pool has all 3 stats - the ranges in DESIGN §11 are stricter and are enforced by modes (
shared/game/modes.ts). The engine's bounds only guarantee safety and termination.
5. Determinism and the RNG
- The RNG is mulberry32(seed: uint32), as in DESIGN §4. Its state is a single uint32 in
state.rng. - Draw order:
- p0's deck is shuffled.
- p1's deck is shuffled.
- The Topics are drawn. With
distinctStats: for each stat in the orderattention, depth, reach, takegroup[floor(next() × group.length)], wheregroupis that stat's Topics intopicPoolorder. Then the picks are shuffled, and that is the lane order. WithoutdistinctStats: the whole pool is shuffled and the firsttopicCountare taken. - The initiative coin is flipped: p0 has initiative on turn 1 (and every odd turn) if
next() < 0.5; otherwise p1 does. After that, initiative strictly alternates. - Keyword and Portal hooks draw in resolution order.
- Shuffles are Fisher–Yates with
ifrom n−1 down to 1 andj = floor(next() × (i+1)). ongoingpower hooks get a throwaway RNG copy, so computing power never changes the match RNG.
6. State and views
The full MatchState (plain JSON) is for the host only:
interface MatchState {
schema: 'wikideck-match/1'; engineVersion: number; ruleset: Ruleset; seed: number; rng: number;
turn: number /* 1-based */; phase: 'planning' | 'over'; initiative: 0 | 1;
players: [PlayerState, PlayerState]; // deck, hand, energy, queue, committed, afk
lanes: { topic: TopicDef; portalRevealed: boolean; cards: [CardInPlay[], CardInPlay[]] }[];
revealSeq: number; log: LogEvent[]; actions: Action[]; result: MatchResult | null;
}
interface PlayerState { deck; hand; energy; queue: { cardId; lane }[]; committed; afk; carry }
interface CardInPlay { card: GameCard; owner: 0 | 1; lane: number; turn: number; seq: number; bonus: number }
PlayerView, returned by viewFor(state, seat), is what a seat may see. In it, "you" is always index 0 and the opponent is index 1:
interface PlayerView {
you: 0 | 1; ruleset; turn; phase; initiative;
energy: number; energyLeft: number; hand: GameCard[]; queue: { cardId; lane }[]; committed; deckCount;
opponent: { handCount; deckCount; committed }; // §5.3: nothing about their queue (cards, count or energy) until reveal
lanes: { topic: TopicDef /* stat always; id/name/portal masked until portalRevealed */, portalRevealed, cards: [mine, theirs],
cardPower: [number[], number[]], power: [mine, theirs], leader: 'you' | 'opponent' | null }[];
result: MatchResult | null;
}
state.log is an append-only event list for animation and replays. Event types: turnStart, portalRevealed, underdog, draw, reveal, fizzle, effect, concede and matchOver. It contains both seats' draws, so a host must filter it per seat before sending it.
7. Results
interface MatchResult {
winner: 0 | 1 | null; // null = draw
reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk';
topicsLed: [number, number]; lanePower: [number, number][]; totalPower: [number, number]; turns: number;
}
Scoring runs after the last turn's End phase. Lane powers include revealed "at scoring" Portals, and each lane's leader uses the consensus tie-break (§6). Winner, per DESIGN §7:
- The seat that leads more Topics.
- If tied on Topics, the seat with more total power.
- If that is also tied, a draw.
8. Keywords and Portals (extension contract)
KEYWORDS and PORTALS in shared/game/keywords.ts (engine-b) are registries of hook objects. v1 keywords (V1_KEYWORDS, one per faction via FACTION_KEYWORD): viral, rising, local, encyclopedic, nostalgic, translated; optional (OPTIONAL_KEYWORDS, off by default): edition, obscure, wildcard. Portals: the 6 kinds of §10.3. The header of that file is normative. Every hook gets ctx = { state, rng, params, lane, log, power(card) }.
Keywords
onReveal(ctx, self)andendOfTurn(ctx, self)may changebonuson cards inctx.state.ongoing(ctx, self, target) → numbermust be pure, and must not callctx.power.- Keyword hooks run only if the keyword is in
keywordsEnabled.
Portals have the same hooks, plus:
onPortalReveal(ctx)canPlay(ctx, card, seat) → boolean, checked when a play is queued and again at revealcapacity(ctx) → numberallOnTopic: trueatScoring(ctx) → [delta0, delta1]
Portal hooks act only once the Portal is revealed.
Rules for all hooks
- Hooks must not move or remove cards (DESIGN §10).
- Any randomness must come from
ctx.rng. No v1 keyword uses it.
9. Testing
tests/game-core.test.ts(engine-a) covers the core loop:- the RNG reference value, ruleset bounds and setup
- hidden information and hidden Portals
- energy carry, interleaved reveal and alternating initiative
- on-topic power, the consensus tie-break, and Portal capacity, fizzle and at-scoring hooks
- disabled keywords, AFK and concede, and draws
- the random-play property: matches terminate, replay exactly, and serialise after every action
tests/game-keywords,game-derive,game-starter,game-property,game-golden(engine-b): every keyword and Portal, derivation, starter decks, properties (termination, determinism, round-trip, no input mutation, legality, power ≥ 0, capacity, no hand leak) and the DESIGN §12 golden match (19–15 / 15–19 / 13–10, p0 wins).