Files
wikideck/tests/ui-duel-adapter.test.ts
claudeanderic dbb89ce9c5 Night 2: 40-card Magic-style duel, PvP with owned decks, polite Wikimedia client, Android mining (#23)
Night 2 (2026-11-17), from the `claude/wikideck` fork's `night/2026-11-17` branch. It follows Night 1 (#22).

## What's in it
- **Duel engine** (fork #72, #80): 40-card decks of cards you own, Notability/Citations, keywords, effects T1–T12, Connected, a hidden-information-safe `viewFor`/`logFor`, and replay. Balance v1 tuning (#84) gives the first player about 51%.
- **Card profiles** (#70, #82): Figure, Location, Event, Institution or Doctrine, plus stats, keywords and rules text, all derived from real article data. Templates only.
- **Design and story** (#66, #69, #83): DUEL_DESIGN.md, plus the match log and the encyclopedic "Battle of X (2026)" recap.
- **PvP** (#74, #77, #81, #76, #85):
  - The server checks ownership, and 40-card eligibility is enforced.
  - Modes: Classic (ranked), Draft and Trending.
  - Invites, quick match, Elo, a ladder and recap pages. Online matches render on the duel board.
- **Duel board UI** (#79): MTG-style card faces and combat declaration, built for 360 px first.
- **Polite Wikimedia client** (#73, #75): throttled, cached and identified requests, the mint-path fix, and a prefetch pool.
- **Android mining** (#78): native RandomX, as a sideload build. The emulator mined a testnet block.
- **Testnet ops** (#67, #68).

PR numbers refer to `claude/wikideck`.

## Status
- **Tests:** 423, of which 422 pass, 0 fail and 1 is skipped. The build is OK (`node:24-alpine`, `--network none`).
- **Testnet:** running this commit (036489c) on r350.
- **Untouched:** no changes to `server/testnet/consensus.ts`, `randomx.ts`, `native/` or the mainnet compose.
- **Review:** night-review reviewed fork #66–#79. #80–#85 came from the agents' unfinished branches and were not reviewed.
- **Known gaps:**
  - The PvP end-to-end test hasn't been run (it needs two eom.dev accounts).
  - Bot matches aren't reachable from Play.
  - Card identity pre-bake hasn't been done.
  - The RandomX verifier latch (`server/testnet/randomx.ts:140`) is still open.

This PR is for Eric to merge.

🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: WikiDeck/wikideck#23

Co-authored-by: Claude <claude@eom.dev>
2026-11-18 18:12:24 +00:00

125 lines
7.7 KiB
TypeScript

import test from 'node:test';
import assert from 'node:assert/strict';
import type { DuelAction, DuelCard, LogEvent, PermanentView, PlayerView, SideView } from '../src/game/duel/contract.ts';
import { boardFromView, expand, legalFromActions, plainLog } from '../src/game/duel/adapter.ts';
const card = (id: string, extra: Partial<DuelCard> = {}): DuelCard => ({
cardId: id, pageId: 1, revisionId: 100, title: id, type: 'Figure', portal: 'Society', cost: 2, power: 2, toughness: 2,
keywords: [], effects: [], rulesText: '', flavor: 'A thing. More.', ...extra,
});
const perm = (uid: string, controller: 0 | 1, c: DuelCard, extra: Partial<PermanentView> = {}): PermanentView => ({
uid, owner: controller, controller, card: c, tapped: false, sick: false, damage: 0, counters: 0,
power: c.power ?? 0, toughness: c.toughness ?? 0, keywords: c.keywords, ...extra,
});
const side = (seat: 0 | 1, extra: Partial<SideView> = {}): SideView => ({
seat, life: 20, citations: 3, maxCitations: 4, handSize: 2, librarySize: 30, graveyard: [], bankSeconds: 300, ready: true, mulligansTaken: 0, ...extra,
});
function view(): PlayerView {
const fig = card('fig', { keywords: ['Legacy'] });
return {
engine: 'duel', seat: 1, turn: 5, active: 0, phase: 'block', toAct: 1,
you: { ...side(1), hand: [{ uid: '1:7', owner: 1, card: card('ev', { type: 'Event', power: null, toughness: null }) }] },
opponent: side(0, { life: 12 }),
battlefield: [
perm('0:1', 0, fig, { tapped: true, power: 4, toughness: 3 }),
perm('0:2', 0, card('loc', { type: 'Location', power: 0, toughness: 0 })),
perm('1:3', 1, card('mine'), { sick: true, connected: { with: '1:4', tier: 'Compatriot', via: 'Portugal', bonus: 1 } }),
perm('1:4', 1, card('gar', { type: 'Location', power: 0, toughness: 3 })),
perm('1:5', 1, card('doc', { type: 'Doctrine', power: null, toughness: null }), { attachedTo: '1:3' }),
],
combat: { attackers: ['0:1'], blocks: {} }, result: null, version: 9, rules: {},
};
}
test('PlayerView → board: sides from my seat, current stats, Garrison only when T > 0, attachments, Connected', () => {
const b = boardFromView(view(), ['alice', 'bob'], ['Turn 5.']);
assert.equal(b.me.name, 'bob');
assert.equal(b.opponent.name, 'alice');
assert.equal(b.opponent.notability, 12);
assert.deepEqual(b.combat, [{ attackerId: '0:1', blockerId: undefined }]);
const att = b.opponent.battlefield.find(c => c.id === '0:1')!;
assert.equal(att.power, 4); assert.equal(att.basePower, 2); assert.equal(att.tapped, true);
assert.equal(b.opponent.battlefield.find(c => c.id === '0:2')!.power, undefined);
assert.equal(b.me.battlefield.find(c => c.id === '1:4')!.toughness, 3);
const mine = b.me.battlefield.find(c => c.id === '1:3')!;
assert.deepEqual(mine.attachments, ['1:5']);
assert.ok(mine.keywords.includes('Connected'));
assert.equal(mine.pending, true);
assert.equal(mine.connectedNote, 'Compatriot (Portugal): +1/+1');
assert.equal(b.hand[0].id, '1:7');
assert.equal(b.hand[0].flavour, 'A thing.');
});
test('legal actions → board legality, and board intents → atomic action sequences', () => {
const legal: DuelAction[] = [
{ type: 'block', blocker: '1:3', attacker: '0:1' }, { type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' },
];
const l = legalFromActions(legal);
assert.deepEqual(l.blockers, { '1:3': ['0:1'], '1:4': ['0:1'] });
assert.deepEqual(expand({ type: 'block', blocks: [{ blockerId: '1:4', attackerId: '0:1' }] }, legal),
[{ type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' }]);
const main: DuelAction[] = [
{ type: 'play', uid: 'h1' },
{ type: 'play', uid: 'h2', targets: [{ kind: 'card', uid: 'a' }, { kind: 'card', uid: 'x' }] },
{ type: 'play', uid: 'h3', targets: [{ kind: 'player', seat: 0 }] },
{ type: 'endPhase' },
];
const m = legalFromActions(main);
assert.deepEqual(m.plays, { h1: [[]], h2: [['a', 'x']], h3: [['player:0']] });
assert.equal(m.canGoToCombat, true);
// The exact legal element comes back, so the host's deep-equal check passes (no `targets: []`).
assert.strictEqual(expand({ type: 'play', cardId: 'h1', targetIds: [] }, main)[0], main[0]);
assert.strictEqual(expand({ type: 'play', cardId: 'h3', targetIds: ['player:0'] }, main)[0], main[2]);
assert.deepEqual(expand({ type: 'endTurn' }, main), [{ type: 'endPhase' }, { type: 'confirmAttack' }]);
assert.deepEqual(expand({ type: 'attack', attackerIds: ['a', 'b'] }, [{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]),
[{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]);
assert.deepEqual(expand({ type: 'mulligan', keep: true }, [{ type: 'keep' }, { type: 'mulligan' }]), [{ type: 'keep' }]);
assert.equal(legalFromActions([]).canEndTurn, false);
});
test('fallback log: real names and titles only, no adjectives', () => {
const ref = (title: string) => ({ uid: title, cardId: title, title, pageId: 1, type: 'Figure' as const, power: 3, toughness: 2 });
const events: LogEvent[] = [
{ seq: 1, turn: 3, kind: 'turnStart', seat: 0, citations: 3, life: [20, 20] },
{ seq: 2, turn: 3, kind: 'deploy', seat: 0, card: ref('Cho Yang-ho') },
{ seq: 3, turn: 3, kind: 'attack', seat: 0, attackers: [ref('Cho Yang-ho')] },
{ seq: 4, turn: 3, kind: 'playerDamage', source: ref('Cho Yang-ho'), seat: 1, amount: 3, life: 17, combat: true },
{ seq: 5, turn: 3, kind: 'destroyed', card: ref('Dichromorpha viridis'), owner: 1 },
{ seq: 6, turn: 9, kind: 'gameOver', winner: 0, reason: 'life', life: [12, 0] },
];
assert.deepEqual(plainLog(events, ['Eric', 'Bot (Normal)']), [
'Turn 3.', 'Eric deployed Cho Yang-ho.', 'Cho Yang-ho (3/2) attacked.', 'Bot (Normal) lost 3 Notability (17 remaining).',
'Dichromorpha viridis was moved to Deleted.', 'Bot (Normal) was nominated for deletion. The result was delete.',
]);
});
test('bot match decks: exactly deckSize owned, profiled cards; the bot deck is its own and deterministic', async () => {
const { botDeck, playerDeck } = await import('../src/game/duel/decks.ts');
const cards = Array.from({ length: 41 }, (_, i) => ({ tokenId: `t${i}`, title: `Card ${i}`, duel: card(`d${i}`, { pageId: i }) }));
const ids = cards.slice(0, 40).map(c => c.tokenId);
const ok = playerDeck(ids, cards, 40);
assert.equal(ok.cards.length, 40);
assert.equal(ok.cards[0].cardId, 't0'); // the NFT tokenId, not the profile id
assert.equal(playerDeck(ids.slice(0, 39), cards, 40).cards.length, 0); // no partial decks, no filler
assert.deepEqual(playerDeck([...ids.slice(0, 39), 'nope'], cards, 40).missing, ['nope']);
const noProfile = cards.map((c, i) => (i === 3 ? { tokenId: c.tokenId, title: c.title } : c));
assert.deepEqual(playerDeck(ids, noProfile, 40).pending, ['Card 3']);
const pool = Array.from({ length: 236 }, (_, i) => card(`s${i}`, { pageId: i }));
const a = botDeck(pool, 40, 'seed'), b = botDeck(pool, 40, 'seed');
assert.deepEqual(a, b);
assert.equal(new Set(a.map(c => c.cardId)).size, 40);
assert.ok(a.every(c => c.cardId.startsWith('bot:')));
assert.notDeepEqual(botDeck(pool, 40, 'other').map(c => c.cardId), a.map(c => c.cardId));
});
test('bot match: untyped profiles from the wire are shape-checked', async () => {
const { playerDeck, isDuelCard } = await import('../src/game/duel/decks.ts');
assert.equal(isDuelCard(card('x')), true);
assert.equal(isDuelCard({ title: 'x' }), false);
assert.equal(isDuelCard(null), false);
const cards = Array.from({ length: 40 }, (_, i) => ({ tokenId: `t${i}`, title: `C${i}`, duel: i === 5 ? { junk: true } : card(`d${i}`) }));
assert.deepEqual(playerDeck(cards.map(c => c.tokenId), cards, 40).pending, ['C5']);
});