From c4636530ef78a709ea04748f3e390015f5bddc14 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:55:58 -0500 Subject: [PATCH] Play: bots see only viewFor output (MatchView.engine = { view, seat }) Per night-lead's rule on #5 the adapter no longer exposes MatchState to bots; a test checks no RNG state, seed or deck order leaks. Co-Authored-By: Claude Opus 5.5 --- src/game/OnlinePlay.tsx | 2 +- src/game/adapter.ts | 3 +- src/game/types.ts | 6 +- tests/ui-play.test.ts | 225 +++++++++++++++++++++------------------- 4 files changed, 123 insertions(+), 113 deletions(-) diff --git a/src/game/OnlinePlay.tsx b/src/game/OnlinePlay.tsx index ae8f527..1db4caa 100644 --- a/src/game/OnlinePlay.tsx +++ b/src/game/OnlinePlay.tsx @@ -98,7 +98,7 @@ export function OnlinePlay({ mode, playerName, onExit, onFinish }: { const phase = status?.phase; // ----- match ----- if ((phase === 'playing' || phase === 'finished') && status?.state) { - const view = viewFromPlayerView(status.state); + const view = { ...viewFromPlayerView(status.state), engine: { view: status.state, seat: seat.seat } }; const legal = uiActions(status.legalActions ?? []); const opp = status.players.find((_, i) => i !== seat.seat)?.name ?? 'Opponent'; const act = (a: UIAction) => { diff --git a/src/game/adapter.ts b/src/game/adapter.ts index 5aaa7fc..7da75f2 100644 --- a/src/game/adapter.ts +++ b/src/game/adapter.ts @@ -68,7 +68,8 @@ export const engine = { for (const l of state.lanes) for (const side of l.cards) for (const c of side) titles.set(c.card.cardId, c.card.title); const log = state.log.filter(e => e.t !== 'draw') .map(e => logLine(e, me, id => titles.get(id) ?? 'a card')).filter((x): x is string => !!x).slice(-30); - return { ...viewFromPlayerView(viewFor(state, me), { log, capacity: i => laneCapacity(state, i) }), engine: { state, seat: me } }; + const pv = viewFor(state, me); + return { ...viewFromPlayerView(pv, { log, capacity: i => laneCapacity(state, i) }), engine: { view: pv, seat: me } }; }, isOver: (s: MatchState) => isOver(s), result(state: MatchState, me: PlayerId): ResultView { diff --git a/src/game/types.ts b/src/game/types.ts index 69612ce..0eb1122 100644 --- a/src/game/types.ts +++ b/src/game/types.ts @@ -1,6 +1,6 @@ // UI-side view models for the Play section. Screens consume only these; adapter.ts maps the // shared/game engine (docs/game/ENGINE_API.md) onto them. -import type { Action, GameCard, MatchResult, MatchState, PlayerId, Ruleset, Stat } from '../../shared/game/index.ts'; +import type { Action, GameCard, MatchResult, PlayerId, PlayerView, Ruleset, Stat } from '../../shared/game/index.ts'; export type PlayerIndex = PlayerId; export type { Stat }; @@ -56,8 +56,8 @@ export type MatchView = { log: string[]; // newest last, this seat's events only waitingForOpponent: boolean; over: boolean; - /** For bots that reuse shared/bots (ui-b): the full state and this seat. Never render it. */ - engine?: { state: MatchState; seat: PlayerId }; + /** For engine-level bots (ui-b): this seat's hidden-information view only (night-lead: never the full MatchState). */ + engine?: { view: PlayerView; seat: PlayerId }; }; export type UIAction = ( diff --git a/tests/ui-play.test.ts b/tests/ui-play.test.ts index bb9a90a..f2ce68d 100644 --- a/tests/ui-play.test.ts +++ b/tests/ui-play.test.ts @@ -1,108 +1,117 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import { DEFAULT_RULESET } from '../shared/game/index.ts'; -import { engine } from '../src/game/adapter.ts'; -import { randomBot } from '../src/game/bots.ts'; -import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts'; -import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx'; -import { parseModeList } from '../src/game/useModes.ts'; -import type { PlayerIndex } from '../src/game/types.ts'; -import type { TestnetBlock } from '../shared/testnet.ts'; - -function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); } - -/** Both seats driven by the UI bot through the UI adapter, exactly as the match screen does. */ -function playOut(seed: string) { - let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed); - const r = rand(seed.length * 7919 + 1); - for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) { - for (const p of [0, 1] as PlayerIndex[]) { - const legal = engine.legal(s, p).filter(a => a.type !== 'concede'); - if (!legal.length) continue; - s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r)); - } - } - return s; -} - -test('the starter deck is a legal Standard deck and the bot gets a legal deck too', () => { - assert.equal(deckProblem(starterDeck(), DEFAULT_RULESET), ''); - assert.equal(deckProblem(opponentDeck('x'), DEFAULT_RULESET), ''); - assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/); -}); - -test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => { - const pool = loanerPool(); - const heavy = pool.filter(c => c.cost >= 3).slice(0, 12); - assert.match(deckWarning(heavy), /cost 2 or less/); - assert.equal(deckWarning(starterDeck()), ''); -}); - -test('UI-driven random play always finishes within the turn cap and is deterministic', () => { - for (let i = 0; i < 40; i++) { - const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`); - assert.ok(engine.isOver(a), `match ${i} finished`); - const ra = engine.result(a, 0); - assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`); - assert.deepEqual(ra, engine.result(b, 0)); - const rb = engine.result(a, 1); - assert.equal(rb.winner, ra.winner === null ? null : 1 - ra.winner, 'each side sees the other side of the same result'); - assert.deepEqual(rb.totalPower, [ra.totalPower[1], ra.totalPower[0]]); - } -}); - -test('my view never shows the opponent’s queued cards', () => { - // Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand). - let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0'); - for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++) - s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`); - const play = engine.legal(s, 1).find(a => a.type === 'play'); - assert.ok(play, 'some seed gives the opponent a turn-1 play'); - s = engine.apply(s, 1, play!); - const mine = engine.view(s, 0); - assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0); - assert.equal(mine.oppQueued, 1); - const theirs = engine.view(s, 1); - assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1); - assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand'); -}); - -test('unstage refunds energy, and illegal plays are explained', () => { - let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy'); - const v = engine.view(s, 0); - const expensive = v.hand.find(c => c.cost > v.energy); - if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 })); - const play = engine.legal(s, 0).find(a => a.type === 'play'); - if (play?.type === 'play') { - s = engine.apply(s, 0, play); - assert.ok(engine.view(s, 0).energy < v.energy); - s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId }); - assert.equal(engine.view(s, 0).energy, v.energy); - } -}); - -test('an owned NFT maps to a sidegrade card that the engine accepts', () => { - const block = { tokenId: 'ab'.repeat(32), powHash: '00'.repeat(32), article: { pageId: 42, title: 'Test', category: 'Space', image: undefined }, - statsSnapshot: { stats: { attention: 100, depth: 100, reach: 100 } } } as unknown as TestnetBlock; - const card = cardFromBlock(block); - assert.equal(card.source, 'nft'); - assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped'); - assert.equal(card.basePower, DEFAULT_RULESET.powerByCost[card.cost]); - const deck = [card, ...starterDeck().slice(1)]; - assert.equal(deckProblem(deck, DEFAULT_RULESET), ''); -}); - -test('peer mode lists are parsed defensively', () => { - const modes = parseModeList({ host: { origin: 'http://192.168.1.32:3102', operator: 'node-b' }, modes: [ - { mode: { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), rules: { turns: 5 } }, stats: { playersOnline: 3, matchesPlayed: 9 } }, - { mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } }, - { mode: { name: 'no id' } }, 'junk', null, - ] }, { self: false, origin: 'http://192.168.1.32:3102' }); - assert.equal(modes.length, 1); - const [m] = modes; - assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b'); - assert.equal(m.ruleset.turns, 5); - assert.ok(m.description.length <= 280); - assert.equal(m.players, 3); - assert.deepEqual(parseModeList('nope', { self: true, origin: '' }), []); -}); +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { DEFAULT_RULESET } from '../shared/game/index.ts'; +import { engine } from '../src/game/adapter.ts'; +import { randomBot } from '../src/game/bots.ts'; +import { cardFromBlock, loanerPool, opponentDeck, starterDeck } from '../src/game/cards.ts'; +import { deckProblem, deckWarning } from '../src/game/DeckBuilder.tsx'; +import { parseModeList } from '../src/game/useModes.ts'; +import type { PlayerIndex } from '../src/game/types.ts'; +import type { TestnetBlock } from '../shared/testnet.ts'; + +function rand(seed: number) { return () => ((seed = (seed * 1103515245 + 12345) >>> 0) / 4294967296); } + +/** Both seats driven by the UI bot through the UI adapter, exactly as the match screen does. */ +function playOut(seed: string) { + let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(seed)], seed); + const r = rand(seed.length * 7919 + 1); + for (let steps = 0; steps < 2000 && !engine.isOver(s); steps++) { + for (const p of [0, 1] as PlayerIndex[]) { + const legal = engine.legal(s, p).filter(a => a.type !== 'concede'); + if (!legal.length) continue; + s = engine.apply(s, p, randomBot.choose(engine.view(s, p), legal, r)); + } + } + return s; +} + +test('the starter deck is a legal Standard deck and the bot gets a legal deck too', () => { + assert.equal(deckProblem(starterDeck(), DEFAULT_RULESET), ''); + assert.equal(deckProblem(opponentDeck('x'), DEFAULT_RULESET), ''); + assert.match(deckProblem(starterDeck().slice(1), DEFAULT_RULESET), /exactly 12/); +}); + +test('the deck curve warning is soft advice for fewer than 4 cards of cost 2 or less', () => { + const pool = loanerPool(); + const heavy = pool.filter(c => c.cost >= 3).slice(0, 12); + assert.match(deckWarning(heavy), /cost 2 or less/); + assert.equal(deckWarning(starterDeck()), ''); +}); + +test('UI-driven random play always finishes within the turn cap and is deterministic', () => { + for (let i = 0; i < 40; i++) { + const a = playOut(`seed-${i}`), b = playOut(`seed-${i}`); + assert.ok(engine.isOver(a), `match ${i} finished`); + const ra = engine.result(a, 0); + assert.ok(ra.turns <= DEFAULT_RULESET.turns, `match ${i}: ${JSON.stringify(ra)}`); + assert.deepEqual(ra, engine.result(b, 0)); + const rb = engine.result(a, 1); + assert.equal(rb.winner, ra.winner === null ? null : 1 - ra.winner, 'each side sees the other side of the same result'); + assert.deepEqual(rb.totalPower, [ra.totalPower[1], ra.totalPower[0]]); + } +}); + +test('my view never shows the opponent’s queued cards', () => { + // Find a seed where the opponent has a turn-1 play (cost 1 in the opening hand). + let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('h0')], 'hidden-0'); + for (let i = 1; i < 50 && !engine.legal(s, 1).some(a => a.type === 'play'); i++) + s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck(`h${i}`)], `hidden-${i}`); + const play = engine.legal(s, 1).find(a => a.type === 'play'); + assert.ok(play, 'some seed gives the opponent a turn-1 play'); + s = engine.apply(s, 1, play!); + const mine = engine.view(s, 0); + assert.equal(mine.lanes.flatMap(l => [...l.theirs, ...l.staged]).length, 0); + assert.equal(mine.oppQueued, 1); + const theirs = engine.view(s, 1); + assert.equal(theirs.lanes.flatMap(l => l.staged).length, 1); + assert.ok(!theirs.hand.some(c => play!.type === 'play' && c.id === play!.cardId), 'a queued card leaves the visible hand'); +}); + +test('unstage refunds energy, and illegal plays are explained', () => { + let s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('e')], 'energy'); + const v = engine.view(s, 0); + const expensive = v.hand.find(c => c.cost > v.energy); + if (expensive) assert.ok(engine.problem(s, 0, { type: 'play', cardId: expensive.id, lane: 0 })); + const play = engine.legal(s, 0).find(a => a.type === 'play'); + if (play?.type === 'play') { + s = engine.apply(s, 0, play); + assert.ok(engine.view(s, 0).energy < v.energy); + s = engine.apply(s, 0, { type: 'unstage', cardId: play.cardId }); + assert.equal(engine.view(s, 0).energy, v.energy); + } +}); + +test('an owned NFT maps to a sidegrade card that the engine accepts', () => { + const block = { tokenId: 'ab'.repeat(32), powHash: '00'.repeat(32), article: { pageId: 42, title: 'Test', category: 'Space', image: undefined }, + statsSnapshot: { stats: { attention: 100, depth: 100, reach: 100 } } } as unknown as TestnetBlock; + const card = cardFromBlock(block); + assert.equal(card.source, 'nft'); + assert.ok(card.cost <= DEFAULT_RULESET.uncheckedCostCap, 'forged max stats are capped'); + assert.equal(card.basePower, DEFAULT_RULESET.powerByCost[card.cost]); + const deck = [card, ...starterDeck().slice(1)]; + assert.equal(deckProblem(deck, DEFAULT_RULESET), ''); +}); + +test('peer mode lists are parsed defensively', () => { + const modes = parseModeList({ host: { origin: 'http://192.168.1.32:3102', operator: 'node-b' }, modes: [ + { mode: { id: 'trending', name: 'Trending', description: 'x'.repeat(1000), rules: { turns: 5 } }, stats: { playersOnline: 3, matchesPlayed: 9 } }, + { mode: { id: 'bad', name: 'Bad rules', rules: { turns: 999 } } }, + { mode: { name: 'no id' } }, 'junk', null, + ] }, { self: false, origin: 'http://192.168.1.32:3102' }); + assert.equal(modes.length, 1); + const [m] = modes; + assert.equal(m.host.kind === 'peer' && m.host.name, 'node-b'); + assert.equal(m.ruleset.turns, 5); + assert.ok(m.description.length <= 280); + assert.equal(m.players, 3); + assert.deepEqual(parseModeList('nope', { self: true, origin: '' }), []); +}); + +test('bots get only the hidden-information view, never the full match state', () => { + const s = engine.createMatch(DEFAULT_RULESET, [starterDeck(), opponentDeck('v')], 'view-only'); + const v = engine.view(s, 1); + assert.ok(v.engine?.view); + const json = JSON.stringify(v); + assert.ok(!json.includes('"rng"') && !json.includes('"seed"'), 'no RNG state or seed'); + assert.ok(!('deck' in (v.engine!.view as object)), 'no deck order'); +});