From a2c2166bccd27c87ef24b8dd2126cb6133d7fd36 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:04:12 -0500 Subject: [PATCH] Modes: follow engine core f3b6097 (trend arrows, timeouts, deckSize) Live/trending presets freeze the engine's trend arrow from cached live data; the host turn timer uses the ruleset's turnSeconds and applies the engine's timeout action (logged, replayable AFK forfeits). Non-draft modes whose rules make starter decks illegal are rejected at startup. HOSTING.md updated. Co-Authored-By: Claude Opus 5.5 --- docs/game/HOSTING.md | 29 ++++++++-------- server/game/engine-binding.ts | 27 ++++++++++----- server/game/engine-port.ts | 8 +++++ server/game/host.ts | 63 ++++++++++++++++++++++++----------- server/game/modes/draft.json | 12 ++----- tests/modes-api.test.ts | 55 ++++++++++++++++++++++++++---- 6 files changed, 135 insertions(+), 59 deletions(-) diff --git a/docs/game/HOSTING.md b/docs/game/HOSTING.md index 38ce34d..1cbf3d6 100644 --- a/docs/game/HOSTING.md +++ b/docs/game/HOSTING.md @@ -24,7 +24,7 @@ A mode is a JSON document, at most 8 KiB: "name": "Trending", "description": "Live Wikipedia pageview trends power cards up or down.", "tags": ["live-data"], - "rules": { "maxTurns": 6, "energy": { "max": 7 } }, + "rules": { "trendUp": 15, "trendDown": -15 }, "cards": { "preset": "trending", "percentPerPoint": 25, "maxBonus": 3, "penalise": true }, "decks": { "kind": "starter" }, "limits": { "maxConcurrentMatches": 32, "turnSeconds": 90, "lobbyMinutes": 15 } @@ -35,10 +35,10 @@ A mode is a JSON document, at most 8 KiB: |---|---| | `id`, `version` | Lowercase slug and a version integer. Bump `version` whenever the rules change, so old match records and leaderboards stay attributable (`#@`). | | `name`, `description`, `tags` | Plain text only: no control characters or `<` `>`. | -| `rules` | **Overrides** on top of the engine's `DEFAULT_RULESET` (see `docs/game/ENGINE_API.md`). Objects merge one level deep; arrays and numbers replace. The merged result then goes through the engine's strict `parseRuleset`, so the engine alone decides what's legal (bounded turns, lanes, deck sizes, known keywords and lane modifiers only). | -| `cards` | A card-mapping **preset** from a fixed list: `standard` (the at-mint snapshot), `live` (current stats) or `trending` (standard power ± a bounded bonus from the live 6-month pageview trend). The mode only picks a preset and tunes its bounded numbers. | +| `rules` | **Overrides** on top of the engine's `DEFAULT_RULESET` (see `docs/game/ENGINE_API.md`). Objects merge one level deep; arrays and numbers replace. The merged result then goes through the engine's strict `parseRuleset`, so the engine alone decides what's legal (bounded turns, Topics, deck sizes, known keywords and portals only; see DESIGN.md §9 for the keys). | +| `cards` | A card-mapping **preset** from a fixed list. `standard` leaves cards as dealt. `live` freezes each card's live trend arrow (DESIGN §1.6, using the ruleset's `trendUp`/`trendDown`) at match start. `trending` does the same and also adds a bounded power bonus from the live pageview trend. The mode only picks a preset and tunes its bounded numbers. | | `decks` | `starter` (everyone gets a seeded starter deck), `draft` (snake draft from a host-seeded pool of preview cards) or `constructed` (bring your own; see "Not yet" below). | -| `limits` | Concurrency, turn timer and lobby expiry for this mode on this host. | +| `limits` | Concurrency and lobby expiry for this mode on this host. `turnSeconds` only applies to engines without their own turn timer; with tonight's engine, the ruleset's `turnSeconds` (plus 5 s network grace) is the timer. | The schema is strict: unknown fields are rejected, as are prototype keys (`__proto__`, `constructor`, `prototype`) anywhere in the document, nesting deeper than two @@ -81,9 +81,11 @@ WIKIDECK_MODES: classic,trending,draft,/app/data/modes/blitz.json Start from `server/game/modes/classic.json`, change `id`, `name` and `description`, then override rules. Some ideas within tonight's rules: -- **Blitz:** `"rules": { "maxTurns": 4, "energy": { "start": 3, "perTurn": 1, "max": 6 } }` -- **Wide board:** `"rules": { "lanes": 4, "laneModifiers": { "pool": ["plain","portal","narrow","plain"], "revealTurns": [1,2,3,4] } }` -- **Big decks:** `"rules": { "deck": { "min": 16, "max": 16, "maxCopiesPerPage": 2 } }` +- **Blitz:** `"rules": { "turns": 4, "energyByTurn": [3, 4, 5, 6] }` +- **On-topic:** `"rules": { "onTopicBonus": 4, "trendUp": 10, "trendDown": -10 }` +- **Slow play:** `"rules": { "turns": 6, "turnSeconds": 40 }` (the engine caps turns × turnSeconds at 240) +- **Big decks:** `"rules": { "deckSize": 16, "maxLoaners": 16 }` with `"decks": { "kind": "draft", "poolSize": 40 }`. + Starter decks are 12 cards, so a non-draft mode with another deck size is rejected at startup. Check that a mode parses with `npm test` (the built-in modes are tested), or load it on a local node: it fails at startup if the engine rejects it. @@ -138,7 +140,7 @@ for how they could become rewards without trusting the host's word. | Peer `/api/game/modes` response | 192 KiB, read with a streaming byte cap; 3 s timeout; no redirects; cached 30 s; at most one refresh in flight | | Peers | at most 16, operator-configured origins only (HTTPS, or HTTP with `WIKIDECK_ALLOW_PRIVATE_PEERS=1`) | | Lobbies + matches in memory | 512 per node; `maxConcurrentMatches` per mode; 3 per player | -| Match length | engine bounds (`maxTurns` ≤ 12) plus a hard 2,000-action cap | +| Match length | engine bounds (`turns` ≤ 12, turns × turnSeconds ≤ 240 s) plus a hard 2,000-action cap | | Rate limits per IP | 240/min reads and plays, 60/min lobby create/join/resign, 30/min peer-discovery routes (on top of the node-wide 300/min `/api` limit and the RPC admission budget) | | Request body | the node's 68 KB JSON limit | | Wikipedia lookups (`trending`) | background only: one page per 3 s, at most 256 queued, never per request | @@ -150,10 +152,12 @@ for how they could become rewards without trusting the host's word. don't hold, overspend energy or act after the match ends. - **Hidden information stays on the host.** Each seat only ever receives `viewFor(state, seat)`; the opponent's hand and staged plays never leave the server. Spectators see status only. -- **Seeds are the host's.** The match seed is 128 random bits chosen by the host when the lobby - opens, so players can't grind for a favourable shuffle. -- **Stalling** forfeits: whoever still owes an action after `turnSeconds` loses; if both do, the - match ends as a draw. A stalled draft pick is made automatically. +- **Seeds are the host's.** The host picks a random seed when the lobby opens, so players can't + grind for a favourable shuffle. The engine hashes it to 32 bits: fine against players, but + not a secret worth relying on against a host. +- **Stalling:** when a seat runs out of turn time, the host applies the engine's `timeout` + action (auto-commit). After `afkTurns` idle timeouts the engine forfeits that seat. Timeouts + are in the action log, so they replay. A stalled draft pick is made automatically. - **Sybils and win-trading:** anyone can make a new player id, and two ids controlled by the same person can feed each other wins. Tonight's leaderboards are for fun. Accounts (#7) or wallet-signed identities would raise the cost. @@ -216,7 +220,6 @@ be pinned in consensus. starter decks for it. Playing with your own cards needs a wallet-signed ownership proof for the lobby (and then the engine's `cardFromStats`). That's a follow-up once accounts and wallet linking (#7) settle. -- The `live` preset is accepted, but tonight it behaves like `standard`. - `trending` never calls Wikipedia when a match starts. The node warms a cache-only trend store in the background, one page every 3 s, through its existing enrichment cache (6 h TTL), starting with the preview-card pages. A card whose page isn't warm yet gets no bonus. This diff --git a/server/game/engine-binding.ts b/server/game/engine-binding.ts index f7437fb..6678317 100644 --- a/server/game/engine-binding.ts +++ b/server/game/engine-binding.ts @@ -1,18 +1,18 @@ /** Binds the mode host to the real engine through its public API (shared/game/index.ts). */ -import { DEFAULT_RULESET, parseRuleset, starterDeck, starterCard, STARTER_POOL, validateDeck, createMatch, +import { DEFAULT_RULESET, parseRuleset, starterDeck, loanerCard, STARTER_POOL, validateDeck, createMatch, legalActions, applyAction, isOver, result, viewFor, Rng, type Action, type GameCard, type MatchState, type Ruleset } from '../../shared/game/index.ts'; import type { EnginePort, Seat } from './engine-port.ts'; /** - * Deterministic pool of preview (non-NFT) cards for draft modes: seeded shuffles of the + * Deterministic pool of loaner (non-NFT) cards for draft modes: seeded shuffles of the * starter pool, one copy per round, never exceeding the ruleset's per-page copy limit. */ export function previewPool(rules: Ruleset, seed: string, size: number): GameCard[] { const rng = Rng.fromSeed(`draft-pool:${seed}`); const pool: GameCard[] = []; - for (let copy = 0; pool.length < size && copy < rules.deck.maxCopiesPerPage; copy++) { - for (const spec of rng.shuffle(STARTER_POOL)) { if (pool.length >= size) break; pool.push(starterCard(spec, copy)); } + for (let copy = 0; pool.length < size && copy < rules.maxCopiesPerPage; copy++) { + for (const spec of rng.shuffle(STARTER_POOL)) { if (pool.length >= size) break; pool.push(loanerCard(spec, copy)); } } return pool; } @@ -20,18 +20,18 @@ export function previewPool(rules: Ruleset, seed: string, size: number): GameCar export const engineBinding: EnginePort = { defaultRuleset: DEFAULT_RULESET, parseRuleset, - deckSize: rules => rules.deck.min, - starterDeck: (rules, seed) => starterDeck(seed, rules), + deckSize: rules => rules.deckSize, + starterDeck: (_rules, seed) => starterDeck(seed), previewPool, validateDeck: (rules, cards) => { const problems = validateDeck(rules, cards); if (problems.length) throw new Error(problems.slice(0, 3).join('; ')); }, cardPower: card => card.power, - withPower: (card, power) => ({ ...card, power }), + withPower: (card, power) => ({ ...card, power: Math.min(30, Math.max(0, power)) }), cardPageId: card => card.pageId, - cardSummary: card => ({ id: card.id, name: card.name, pageId: card.pageId, category: card.category, - cost: card.cost, power: card.power, keyword: card.keyword }), + cardSummary: card => ({ cardId: card.cardId, title: card.title, pageId: card.pageId, faction: card.faction, + cost: card.cost, power: card.power, home: card.home, trend: card.trend, keyword: card.keyword }), createMatch: (rules, decks, seed) => createMatch(rules, decks, seed), legalActions: (state, seat) => legalActions(state, seat), applyAction: (state, seat: Seat, action) => { @@ -39,6 +39,15 @@ export const engineBinding: EnginePort = return applyAction(state, action); }, concedeAction: seat => ({ type: 'concede', player: seat }), + timeoutAction: seat => ({ type: 'timeout', player: seat }), + turnSeconds: rules => rules.turnSeconds, + turnOf: state => state.turn, + // DESIGN §1.6: the live trend arrow, frozen at match start, using the ruleset's thresholds. + applyLive: (rules, card, live) => { + const t = live.trendPercent; + const trend = t === null || !Number.isFinite(t) ? 0 : t >= rules.trendUp ? 1 : t <= rules.trendDown ? -1 : 0; + return { ...card, trend }; + }, isOver, result: state => { const r = result(state); return { winner: r?.winner ?? null, reason: r?.reason ?? 'complete' }; }, viewFor: (state, seat) => viewFor(state, seat), diff --git a/server/game/engine-port.ts b/server/game/engine-port.ts index d936195..74b50b7 100644 --- a/server/game/engine-port.ts +++ b/server/game/engine-port.ts @@ -28,6 +28,14 @@ export interface EnginePort isDeepStrictEqual(a, action)); if (chosen === undefined) throw new GameError(400, 'Illegal action.'); - l.state = this.engine.applyAction(l.state, seat, chosen); - l.actions.push({ seat, action: chosen }); - l.lastMove = this.now(); + this.apply(l, seat, chosen); l.players[seat]!.seen = l.lastMove; - if (this.engine.isOver(l.state)) { - const r = this.engine.result(l.state); - this.finish(l, r.winner, r.reason ?? 'complete'); - } else if (l.actions.length >= 2000) this.finish(l, null, 'action-limit'); return this.view(lobbyId, token); } @@ -197,10 +196,8 @@ export class ModeHost { if (l.phase === 'waiting') { l.phase = 'expired'; return this.view(lobbyId, token); } if (l.phase !== 'playing' && l.phase !== 'drafting') throw new GameError(409, 'Nothing to resign.'); if (l.phase === 'playing' && l.state !== undefined && this.engine.concedeAction) { - const action = this.engine.concedeAction(seat); - l.state = this.engine.applyAction(l.state, seat, action); - l.actions.push({ seat, action }); - if (this.engine.isOver(l.state)) { const r = this.engine.result(l.state); this.finish(l, r.winner, 'resign'); return this.view(lobbyId, token); } + this.apply(l, seat, this.engine.concedeAction(seat), 'resign'); + if ((l.phase as Phase) === 'finished') return this.view(lobbyId, token); } this.finish(l, seat === 0 ? 1 : 0, 'resign'); return this.view(lobbyId, token); @@ -217,16 +214,18 @@ export class ModeHost { sweep(): void { const now = this.now(); for (const l of this.lobbies.values()) { - const turnMs = l.mode.limits.turnSeconds * 1000; if (l.phase === 'waiting' && now - l.createdAt > l.mode.limits.lobbyMinutes * 60_000) l.phase = 'expired'; else if (l.phase === 'drafting' && l.draft && now > l.draft.deadline) { // Auto-pick the first free card for whoever is stalling; synchronous, no live data. const idx = l.draft.taken.indexOf(null); if (idx >= 0) void this.takePick(l, l.draft.order[l.draft.turn]!, idx).catch(() => { l.phase = 'expired'; }); - } else if (l.phase === 'playing' && l.state !== undefined && now - l.lastMove > turnMs) { + } else if (l.phase === 'playing' && l.state !== undefined && now - (l.turnStartedAt ?? l.lastMove) > this.turnMs(l)) { const waiting = ([0, 1] as Seat[]).filter(s => this.engine.legalActions(l.state, s).length > 0); - // Whoever still owes an action forfeits. If both do, it's a draw (abandoned). - if (waiting.length === 1) this.finish(l, waiting[0] === 0 ? 1 : 0, 'timeout'); + if (this.engine.timeoutAction) { + // The engine decides what a timeout means (auto-commit, AFK forfeit); it is logged and replayable. + for (const s of waiting) if (l.phase === 'playing') this.apply(l, s, this.engine.timeoutAction(s)); + l.turnStartedAt = now; + } else if (waiting.length === 1) this.finish(l, waiting[0] === 0 ? 1 : 0, 'timeout'); else this.finish(l, null, 'abandoned'); } if ((l.phase === 'finished' || l.phase === 'expired') && now - l.lastMove > 10 * 60_000) this.lobbies.delete(l.id); @@ -268,7 +267,8 @@ export class ModeHost { l.decks = mapped; l.state = this.engine.createMatch(l.rules, mapped, l.seed); l.phase = 'playing'; - l.startedAt = l.lastMove = this.now(); + l.startedAt = l.lastMove = l.turnStartedAt = this.now(); + l.turn = this.engine.turnOf?.(l.state); delete l.draft; if (this.engine.isOver(l.state)) { const r = this.engine.result(l.state); this.finish(l, r.winner, r.reason ?? 'complete'); } } @@ -276,16 +276,39 @@ export class ModeHost { /** Apply the mode's card-mapping preset. Bonus data is looked up once, before the match. */ private async mapDeck(mode: ModeDocument, deck: unknown[]): Promise { const mapping = mode.cards; - if (mapping.preset !== 'trending' || !this.liveData) return deck; + if (mapping.preset === 'standard' || !this.liveData) return deck; return Promise.all(deck.map(async card => { const pageId = this.engine.cardPageId(card); if (pageId === null) return card; const live = await this.liveData!(pageId).catch(() => null); - const bonus = trendBonus(mapping, live?.trendPercent ?? null); - return bonus === 0 ? card : this.engine.withPower(card, clampPower(this.engine.cardPower(card) + bonus)); + if (!live) return card; + // `live` and `trending`: freeze the live trend arrow onto the card (engine rules decide its effect). + let mapped = this.engine.applyLive ? this.engine.applyLive(this.hosted.get(mode.id)!.rules, card, live) : card; + if (mapping.preset === 'trending') { + const bonus = trendBonus(mapping, live.trendPercent); + if (bonus !== 0) mapped = this.engine.withPower(mapped, clampPower(this.engine.cardPower(mapped) + bonus)); + } + return mapped; })); } + /** Apply an action already known to be legal (or host-issued), log it, and settle the match if over. */ + private apply(l: Lobby, seat: Seat, action: unknown, reason?: string) { + l.state = this.engine.applyAction(l.state, seat, action); + l.actions.push({ seat, action }); + l.lastMove = this.now(); + const turn = this.engine.turnOf?.(l.state); + if (turn !== l.turn) { l.turn = turn; l.turnStartedAt = l.lastMove; } + if (this.engine.isOver(l.state)) { const r = this.engine.result(l.state); this.finish(l, r.winner, reason ?? r.reason ?? 'complete'); } + else if (l.actions.length >= 2000) this.finish(l, null, 'action-limit'); + } + + /** Turn timer: the engine's own per-turn limit plus a little network grace, else the mode's limit. */ + private turnMs(l: Lobby): number { + const engineSeconds = this.engine.turnSeconds?.(l.rules); + return engineSeconds !== undefined ? (engineSeconds + 5) * 1000 : l.mode.limits.turnSeconds * 1000; + } + private finish(l: Lobby, winner: Seat | null, reason: string) { if (l.phase === 'finished' || l.phase === 'expired') return; l.phase = 'finished'; diff --git a/server/game/modes/draft.json b/server/game/modes/draft.json index 02482f8..9026074 100644 --- a/server/game/modes/draft.json +++ b/server/game/modes/draft.json @@ -9,16 +9,8 @@ "no-collection" ], "rules": { - "deck": { - "min": 10, - "max": 10, - "maxCopiesPerPage": 2 - }, - "hand": { - "start": 4, - "max": 7, - "drawPerTurn": 1 - } + "deckSize": 10, + "openingHand": 4 }, "cards": { "preset": "standard" diff --git a/tests/modes-api.test.ts b/tests/modes-api.test.ts index 9de5904..acb7490 100644 --- a/tests/modes-api.test.ts +++ b/tests/modes-api.test.ts @@ -35,7 +35,7 @@ async function playToEnd(base: string, lobby: string, tokens: string[]) { const v = (await call(base, `/api/game/lobbies/${lobby}`, undefined, t)).json; if (v.phase !== 'playing') return v; // Play the first card if possible, else end the turn. - const a = v.legalActions.find((x: any) => x.type === 'play') ?? v.legalActions.find((x: any) => x.type === 'endTurn'); + const a = v.legalActions.find((x: any) => x.type === 'play') ?? v.legalActions.find((x: any) => x.type === 'commit'); if (a) { const r = await call(base, `/api/game/lobbies/${lobby}/actions`, { action: a }, t); assert.equal(r.status, 200, JSON.stringify(r.json)); moved = true; } } if (!moved) break; @@ -133,18 +133,59 @@ test('modes api: draft preview pool is deterministic and deck-legal', () => { const p1 = previewPool(DEFAULT_RULESET, 'seed', 30), p2 = previewPool(DEFAULT_RULESET, 'seed', 30); assert.deepEqual(p1, p2); assert.equal(p1.length, 30); - assert.equal(new Set(p1.map(c => c.id)).size, 30); - assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, STARTER_POOL.length * DEFAULT_RULESET.deck.maxCopiesPerPage); + assert.equal(new Set(p1.map(c => c.cardId)).size, 30); + assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, STARTER_POOL.length * DEFAULT_RULESET.maxCopiesPerPage); }); test('modes api: the rule examples in HOSTING.md are valid modes', () => { for (const rules of [ - { maxTurns: 4, energy: { start: 3, perTurn: 1, max: 6 } }, - { lanes: 4, laneModifiers: { pool: ['plain', 'portal', 'narrow', 'plain'], revealTurns: [1, 2, 3, 4] } }, - { deck: { min: 16, max: 16, maxCopiesPerPage: 2 } }, - { maxTurns: 6, energy: { max: 7 } }, + { turns: 4, energyByTurn: [3, 4, 5, 6] }, + { onTopicBonus: 4, trendUp: 10, trendDown: -10 }, + { deckSize: 16, maxCopiesPerPage: 2, maxLoaners: 16 }, + { turns: 6, turnSeconds: 40 }, ]) { const m = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'doc-example', version: 1, name: 'x', description: 'x', rules }); assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, m.rules, parseRuleset), JSON.stringify(rules)); } }); + +test('modes api: mode rules that make starter decks illegal fail at startup; live trend arrows follow the ruleset', async () => { + const { ModeHost } = await import('../server/game/host.ts'); + const { MatchStore } = await import('../server/game/store.ts'); + const { engineBinding } = await import('../server/game/engine-binding.ts'); + const big = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'big', version: 1, name: 'Big', description: 'x', + decks: { kind: 'starter' }, rules: { deckSize: 16, maxLoaners: 16 } }); + assert.throws(() => new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [big], engine: engineBinding, + store: new MatchStore(null) }), /starter decks are illegal/); + const card = engineBinding.starterDeck(DEFAULT_RULESET, 's')[0]!; + assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: 30 }).trend, 1); + assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: -30 }).trend, -1); + assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: 5 }).trend, 0); + assert.equal(engineBinding.applyLive!(DEFAULT_RULESET, card, { trendPercent: null }).trend, 0); + assert.equal(engineBinding.withPower(card, 99).power, 30, 'power stays within engine bounds'); +}); + +test('modes api: turn timer applies the engine timeout action; AFK forfeits are replayable', async () => { + const { ModeHost } = await import('../server/game/host.ts'); + const { MatchStore } = await import('../server/game/store.ts'); + const { engineBinding } = await import('../server/game/engine-binding.ts'); + let now = 0; + const classic = parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } }); + const host = new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes: [classic], engine: engineBinding, + store: new MatchStore(null), now: () => now }); + const a = host.createLobby('classic', alice); + const b = await host.join(a.lobbyId, bob); + // Bob plays normally; Alice never acts. + for (let turn = 0; turn < 6; turn++) { + const v = host.view(a.lobbyId, b.token) as any; + if (v.phase !== 'playing') break; + await host.act(a.lobbyId, b.token, { type: 'commit', player: 1 }); + now += (DEFAULT_RULESET.turnSeconds + 6) * 1000; host.sweep(); + } + const end = host.view(a.lobbyId, a.token) as any; + assert.equal(end.phase, 'finished'); + assert.deepEqual(end.outcome, { winner: 1, reason: 'afk' }); + const rec = host.matchRecord(end.matchId); + assert.ok(rec.actions.some(x => (x.action as any).type === 'timeout')); + assert.equal(replay(rec.rules as any, rec.decks as any, rec.seed, rec.actions.map(x => x.action) as any).result?.winner, 1); +});