Files
wikideck/tests/ui-pvp-recap.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

106 lines
6.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { renderToStaticMarkup } from 'react-dom/server';
import { createElement } from 'react';
import { RecapArticle, loadRecap, matchIdFromPath } from '../src/game/recap/BattleRecap.tsx';
import { fallbackRecap, parseMatchRecord, runs } from '../src/game/recap/model.ts';
// Real cards from the sample pool (no network).
const sample = JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8'));
const pool: { pageId: number; title: string; revisionId?: number }[] = (Array.isArray(sample) ? sample : sample.cards ?? []).map((c: Record<string, unknown>) => {
const a = (c.article ?? c) as Record<string, unknown>;
return { pageId: a.pageId as number, title: a.title as string, revisionId: a.revisionId as number | undefined };
}).filter((c: { pageId: unknown; title: unknown }) => typeof c.pageId === 'number' && typeof c.title === 'string');
const record = {
matchId: 'm_7f3a', modeName: 'Classic', players: [{ name: 'alice' }, { name: 'bob' }],
startedAt: Date.UTC(2026, 10, 17, 23, 40), endedAt: Date.UTC(2026, 10, 18, 0, 2), turns: 9,
result: { winner: 0, reason: 'notability' }, strength: [40, 40],
played: [pool.slice(0, 4).map(c => ({ ...c, type: 'Figure' })).concat([{ ...pool[4], type: 'Doctrine' }]), pool.slice(5, 8).map(c => ({ ...c, type: 'Figure' }))],
lost: [[pool[1]], [pool[5], pool[6]]],
};
test('recap: deterministic, named after the winner’s decisive non-Figure card, with an infobox', () => {
assert.ok(pool.length >= 8, 'card-sample.json has cards');
const a = fallbackRecap(parseMatchRecord(record));
const b = fallbackRecap(parseMatchRecord(structuredClone(record)));
assert.deepEqual(a, b);
assert.equal(a.title, `Battle of ${pool[4].title} (2026)`);
assert.equal(a.infobox.date, '18 November 2026');
assert.deepEqual(a.infobox.belligerents, ['alice', 'bob']);
assert.deepEqual(a.infobox.casualties, [`1 card destroyed: ${pool[1].title}`, `2 cards destroyed: ${pool[5].title}, ${pool[6].title}`]);
assert.deepEqual(a.infobox.commanders, [pool[0].title, pool[5].title]);
assert.equal(a.masthead, 'WikiDeck');
assert.match(a.footer, /game events/);
assert.equal(a.infobox.result, 'Victory for alice');
assert.equal(a.url, '/recap/m_7f3a');
});
test('recap: References cite every card played, once each, with revision ids', () => {
const doc = fallbackRecap(parseMatchRecord(record));
const played = [...record.played[0], ...record.played[1]];
assert.equal(doc.references.length, new Set(played.map(c => `${c.pageId}:${c.revisionId ?? ''}`)).size);
for (const c of played) assert.ok(doc.references.some(r => r.title === c.title));
const html = renderToStaticMarkup(createElement(RecapArticle, { doc }));
assert.match(html, /WikiDeck/);
assert.match(html, /Casualties/);
assert.match(html, /Course of the battle/);
assert.doesNotMatch(html, /\*\*/, 'markup is rendered, not shown');
assert.match(html, /href="#ref-1"/);
if (pool[0].revisionId) assert.match(html, new RegExp(`oldid=${pool[0].revisionId}`));
});
test('recap text: fixed templates only, no adjectives about the outcome or winks', () => {
const doc = fallbackRecap(parseMatchRecord(record));
const text = [doc.lead, ...doc.sections.flatMap(s => s.paragraphs)].join(' ');
assert.doesNotMatch(text, /!|lol|brutal|humiliat|heroic|surprising|twist|killed|decisive|pyrrhic/i);
assert.match(text, /\*\*Battle of [^*]+\*\* was a WikiDeck engagement fought on 18 November 2026 between the forces of alice and bob/);
assert.match(text, /nine turns/);
assert.match(text, /bob was reduced to zero Notability\./);
});
test('recap falls back to "Match of <date>" when nothing was played, and tolerates junk', () => {
const doc = fallbackRecap(parseMatchRecord({ matchId: 'x', endedAt: Date.UTC(2026, 10, 17), players: ['a', 'b'], result: { winner: null } }));
assert.equal(doc.title, 'Match of 17 November 2026');
assert.equal(doc.infobox.result, 'Draw');
const junk = fallbackRecap(parseMatchRecord({ players: 7, played: [[{ title: 3 }], 'x'], url: 'javascript:1' }));
assert.equal(junk.references.length, 0);
});
test('only https Wikipedia links reach the References', () => {
const doc = fallbackRecap(parseMatchRecord({ ...record, played: [[{ pageId: 1, title: 'A', url: 'https://evil.example/a' }], []] }));
assert.match(doc.references[0].url, /^https:\/\/en\.wikipedia\.org\/wiki\/A$/);
});
test('/battle/<id> routing and loading from GET /api/game/matches/:id (stubbed fetch)', async () => {
assert.equal(matchIdFromPath('/battle/m_7f3a'), 'm_7f3a');
assert.equal(matchIdFromPath('/battle/../x'), '');
assert.equal(matchIdFromPath('/recap/m_7f3a'), 'm_7f3a');
let asked = '';
const fake = (async (url: string) => { asked = url; return new Response(JSON.stringify(record), { headers: { 'content-type': 'application/json' } }); }) as typeof fetch;
const doc = await loadRecap('m_7f3a', fake);
assert.equal(asked, '/api/game/matches/m_7f3a');
assert.match(doc.title, /^Battle of /);
const missing = (async () => new Response('{}', { status: 404 })) as unknown as typeof fetch;
await assert.rejects(loadRecap('nope', missing), /No battle/);
});
test('story markup becomes text runs; card titles cannot inject markup', () => {
assert.deepEqual(runs('The **Battle of X** saw *Moon*[2].'), [{ text: 'The ' }, { text: 'Battle of X', bold: true }, { text: ' saw ' },
{ text: 'Moon', italic: true }, { text: '[2]', cite: 2 }, { text: '.' }]);
const doc = fallbackRecap(parseMatchRecord({ matchId: 'z', players: ['a', 'b'], result: { winner: 0 }, played: [[{ pageId: 1, title: '**Evil** [9]', type: 'Event' }], []] }));
assert.equal(doc.title, 'Battle of Evil 9');
const seen = [doc.lead, ...doc.sections.flatMap(s => s.paragraphs)].flatMap(runs);
assert.ok(!seen.some(r => r.cite === 9));
});
test('a host-pvp match record (winner/reason at top level, decks, no replay yet) still yields a plain recap', () => {
const doc = fallbackRecap(parseMatchRecord({ matchId: 'a'.repeat(32), modeId: 'classic', seed: 's', rules: {}, players: [{ id: 'x', name: 'alice' }, { id: 'y', name: 'bob' }],
winner: 1, reason: 'concede', startedAt: Date.UTC(2026, 10, 18, 1), endedAt: Date.UTC(2026, 10, 18, 1, 20), decks: [new Array(40).fill({}), new Array(40).fill({})], actions: [] }));
assert.equal(doc.title, 'Match of 18 November 2026');
assert.equal(doc.infobox.result, 'Victory for bob');
assert.deepEqual(doc.infobox.strength, ['40 cards', '40 cards']);
assert.match(doc.sections.flatMap(s => s.paragraphs).join(' '), /alice withdrew from the engagement\./);
});