Files
wikideck/tests/modes-api.test.ts
T
claudeanderic 4f7a8a7c74 Night 1: Edit War card game, eom.dev accounts, peer-hosted modes, Android and iOS apps (#22)
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: WikiDeck/wikideck#22

Co-authored-by: Claude <claude@eom.dev>
2026-11-17 17:40:58 +00:00

269 lines
17 KiB
TypeScript

// End to end over HTTP with the real engine: publish, discover, host all three example modes.
import test from 'node:test';
import assert from 'node:assert/strict';
import express from 'express';
import type { AddressInfo } from 'node:net';
import { gameRouter } from '../server/game/index.ts';
import { previewPool } from '../server/game/engine-binding.ts';
import { DEFAULT_RULESET, replay, parseRuleset, previewPool as engineLoaners } from '../shared/game/index.ts';
import { parseMode, resolveRuleset, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
import { ModeListSchema } from '../shared/game/modes.ts';
async function serve(env: NodeJS.ProcessEnv, enrichment?: any) {
const app = express();
app.use(express.json({ limit: '68kb' }));
app.use('/api/game', await gameRouter({ dataDir: null, env, enrichment }));
app.use((err: Error, _q: express.Request, res: express.Response, _n: express.NextFunction) => res.status(400).json({ error: err.message }));
const server = app.listen(0, '127.0.0.1');
await new Promise(r => server.once('listening', r));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
return { base, close: () => new Promise(r => server.close(r)) };
}
const call = async (base: string, path: string, body?: unknown, token?: string) => {
const res = await fetch(base + path, { method: body === undefined ? 'GET' : 'POST',
headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
body: body === undefined ? undefined : JSON.stringify(body) });
return { status: res.status, json: await res.json() as any };
};
const alice = { name: 'Alice', secret: 'alice-secret-0123456789abcdef' };
const bob = { name: 'Bob', secret: 'bob-secret-0123456789abcdefgh' };
async function playToEnd(base: string, lobby: string, tokens: string[]) {
for (let i = 0; i < 400; i++) {
let moved = false;
for (const t of tokens) {
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 === '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;
}
return (await call(base, `/api/game/lobbies/${lobby}`, undefined, tokens[0])).json;
}
test('modes api: three example modes over HTTP with the real engine', { timeout: 60_000 }, async () => {
const node = await serve({ WIKIDECK_MODES: 'classic,trending,draft', PUBLIC_ORIGIN: 'http://127.0.0.1:3101',
WIKIDECK_GAME_OPERATOR: 'Node A', WIKIDECK_GAME_PEERS: '' },
{ get: async (pageId: number) => ({ pageviews: { trendPercent: pageId % 3 === 0 ? 80 : -30 } }) });
try {
const list = (await call(node.base, '/api/game/modes')).json;
ModeListSchema.parse(list);
assert.deepEqual(list.modes.map((m: any) => m.mode.id), ['classic', 'trending', 'draft']);
assert.equal(list.host.operator, 'Node A');
for (const id of ['classic', 'trending']) {
const a = await call(node.base, `/api/game/modes/${id}/lobbies`, alice);
assert.equal(a.status, 201);
const b = await call(node.base, `/api/game/lobbies/${a.json.lobbyId}/join`, bob);
assert.equal(b.status, 200, JSON.stringify(b.json));
const peek = (await call(node.base, `/api/game/lobbies/${a.json.lobbyId}`)).json;
assert.equal(peek.state, undefined);
const wrongSeat = (await call(node.base, `/api/game/lobbies/${a.json.lobbyId}`, undefined, a.json.token)).json.legalActions[0];
const cheat = await call(node.base, `/api/game/lobbies/${a.json.lobbyId}/actions`, { action: { ...wrongSeat, player: 1 } }, a.json.token);
assert.equal(cheat.status, 400, 'cannot act for the other seat');
const end = await playToEnd(node.base, a.json.lobbyId, [a.json.token, b.json.token]);
assert.equal(end.phase, 'finished', JSON.stringify(end).slice(0, 300));
const rec = (await call(node.base, `/api/game/matches/${end.matchId}`)).json;
assert.equal(rec.modeId, id);
assert.equal(rec.decks[0].length, 12);
}
// Draft: 20 snake picks, 10-card decks.
const a = (await call(node.base, '/api/game/modes/draft/lobbies', alice)).json;
const b = (await call(node.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json;
const tokens = [a.token, b.token];
let picks = 0;
for (;;) {
const v = (await call(node.base, `/api/game/lobbies/${a.lobbyId}`, undefined, a.token)).json;
if (v.phase !== 'drafting') { assert.equal(v.phase, 'playing'); break; }
const free = v.draft.pool.find((c: any) => c.takenBy === null);
const r = await call(node.base, `/api/game/lobbies/${a.lobbyId}/pick`, { index: free.index }, tokens[v.draft.toPick]);
assert.equal(r.status, 200, JSON.stringify(r.json));
picks++;
}
assert.equal(picks, 20);
const end = await playToEnd(node.base, a.lobbyId, tokens);
assert.equal(end.phase, 'finished');
const record = (await call(node.base, `/api/game/matches/${end.matchId}`)).json;
assert.equal(record.decks[1].length, 10);
// Anyone can audit a match: replaying the published record reproduces the result.
const replayed = replay(record.rules, record.decks, record.seed, record.actions.map((a: any) => a.action));
assert.equal(replayed.phase, 'over');
assert.equal(replayed.result?.winner ?? null, record.winner);
const after = (await call(node.base, '/api/game/modes')).json;
assert.equal(after.matchesHosted, 3);
const board = (await call(node.base, '/api/game/modes/draft/leaderboard')).json;
assert.equal(board.entries.length, 2);
assert.equal((await call(node.base, '/api/game/modes/nope/leaderboard')).status, 404);
assert.equal((await call(node.base, '/api/game/lobbies/zzz')).status, 404);
} finally { await node.close(); }
});
test('modes api: a node lists its peers\' modes and ranks hosts by matches hosted', { timeout: 30_000 }, async () => {
const peerB = await serve({ WIKIDECK_MODES: 'draft,classic', PUBLIC_ORIGIN: 'http://b.invalid', WIKIDECK_GAME_OPERATOR: 'Node B' });
const nodeA = await serve({ WIKIDECK_MODES: 'classic', PUBLIC_ORIGIN: 'http://a.invalid', WIKIDECK_GAME_OPERATOR: 'Node A',
WIKIDECK_GAME_PEERS: `${peerB.base},http://127.0.0.1:1`, WIKIDECK_ALLOW_PRIVATE_PEERS: '1' });
try {
// One match on B so it leads the host leaderboard.
const a = (await call(peerB.base, '/api/game/modes/draft/lobbies', alice)).json;
const b = (await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json;
await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/resign`, {}, b.token); // during the draft: not a match
const c = (await call(peerB.base, '/api/game/modes/classic/lobbies', alice)).json;
const d = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/join`, bob)).json;
assert.equal((await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/resign`, {}, d.token)).json.outcome.winner, 0);
const resigned = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}`, undefined, c.token)).json;
const rec = (await call(peerB.base, `/api/game/matches/${resigned.matchId}`)).json;
assert.equal(replay(rec.rules, rec.decks, rec.seed, rec.actions.map((x: any) => x.action)).result?.winner, 0, 'resign replays as concede');
const net = (await call(nodeA.base, '/api/game/network/modes')).json;
assert.equal(net.self.host.operator, 'Node A');
assert.equal(net.peers.length, 2);
assert.equal(net.peers[0].ok, true);
assert.equal(net.peers[0].list.host.origin, peerB.base, 'origin pinned to the fetched peer');
assert.equal(net.peers[0].list.modes[0].mode.id, 'draft');
assert.equal(net.peers[1].ok, false);
const hosts = (await call(nodeA.base, '/api/game/hosts/leaderboard')).json.hosts;
assert.deepEqual(hosts.map((h: any) => [h.operator, h.matchesHosted]), [['Node B', 1], ['Node A', 0]]);
} finally { await nodeA.close(); await peerB.close(); }
});
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.cardId)).size, 30);
assert.equal(previewPool(DEFAULT_RULESET, 'x', 100).length, engineLoaners(DEFAULT_RULESET).length * DEFAULT_RULESET.maxCopiesPerPage);
assert.ok(p1.every(c => c.check === 'loaner' && c.source === 'loaner'), 'only engine loaner data');
});
test('modes api: the rule examples in HOSTING.md are valid modes', () => {
for (const rules of [
{ turns: 4, energyByTurn: [3, 4, 5, 6] },
{ onTopicBonus: [0, 2, 2, 3, 3, 4, 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: DEFAULT_RULESET.trendDown - 1 }).trend, -1);
assert.equal(engineBinding.applyLive!({ ...DEFAULT_RULESET, trendDown: -25 }, 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);
});
test('modes api: mode rules are checked beyond the engine schema and rejected, not passed on', async () => {
const { parseModeRuleset } = await import('../server/game/engine-binding.ts');
const bad = [
{ turns: 2, energyByTurn: [1, 2] }, // portalReveal has a turn > 2
{ distinctStats: true, topicCount: 2, portalReveal: [1, 2] },
{ turns: 12, turnSeconds: 25, energyByTurn: Array(12).fill(3), portalReveal: [1, 2, 3] },
{ powerByCost: [0, 1, 2] },
{ mulligan: true },
{ keywordParams: { notAKeyword: { amount: 1 } } },
{ keywordsEnabled: [...DEFAULT_RULESET.keywordsEnabled, 'obscure'] },
];
for (const rules of bad) assert.throws(() => resolveRuleset(DEFAULT_RULESET, rules as any, parseModeRuleset), JSON.stringify(rules));
assert.throws(() => resolveRuleset(DEFAULT_RULESET, { keywordsEnabled: ['viral', 'obscure'] }, parseModeRuleset), /not hostable/);
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, { keywordsEnabled: ['viral', 'edition', 'wildcard'] }, parseModeRuleset));
assert.doesNotThrow(() => resolveRuleset(DEFAULT_RULESET, {}, parseModeRuleset));
});
test('modes api: live matches survive a node restart (snapshot on shutdown, restore on start)', 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 { persistLive } = await import('../server/game/index.ts');
const { mkdtempSync, rmSync, existsSync } = await import('node:fs');
const { tmpdir } = await import('node:os');
const { join } = await import('node:path');
const dir = mkdtempSync(join(tmpdir(), 'modes-live-'));
try {
const modes = [parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' } }),
parseMode({ schema: MODE_SCHEMA_VERSION, id: 'draft', version: 1, name: 'D', description: 'x', decks: { kind: 'draft', poolSize: 30 }, rules: { deckSize: 10, openingHand: 4 } })];
const make = () => new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, modes, engine: engineBinding, store: new MatchStore(dir) });
const first = make();
persistLive(first, dir, false);
const a = first.createLobby('classic', alice);
const b = await first.join(a.lobbyId, bob);
// Random seed: the opening hand may have nothing playable on turn 1, so fall back to commit.
const legal = (first.view(a.lobbyId, a.token) as any).legalActions;
await first.act(a.lobbyId, a.token, legal.find((x: any) => x.type === 'play') ?? legal.find((x: any) => x.type === 'commit'));
const d = first.createLobby('draft', alice);
const e = await first.join(d.lobbyId, bob);
const pick = (first.view(d.lobbyId, d.token) as any).draft;
await first.pick(d.lobbyId, [d.token, e.token][pick.toPick]!, 0);
const waiting = first.createLobby('classic', { name: 'Cy', secret: 'cy-secret-0123456789abcdefghij' });
const before = first.view(a.lobbyId, b.token) as any;
persistLive(first, dir, false).save();
// "Restart": a fresh host restores the snapshot. Same tokens keep working.
const second = make();
persistLive(second, dir, false);
assert.ok(existsSync(join(dir, 'live.json.restored')));
const after = second.view(a.lobbyId, b.token) as any;
assert.equal(after.phase, 'playing');
assert.deepEqual(after.state, before.state, 'match state restored exactly');
assert.equal((second.view(d.lobbyId, d.token) as any).phase, 'drafting');
assert.equal((second.view(waiting.lobbyId) as any).phase, 'waiting');
// Finish the restored match: the record replays.
for (let i = 0; i < 200; i++) {
const v = second.view(a.lobbyId, a.token) as any;
if (v.phase !== 'playing') break;
for (const t of [a.token, b.token]) {
const w = second.view(a.lobbyId, t) as any;
const c = w.legalActions?.find((x: any) => x.type === 'commit');
if (c) await second.act(a.lobbyId, t, c);
}
}
const end = second.view(a.lobbyId, a.token) as any;
assert.equal(end.phase, 'finished');
const rec = second.matchRecord(end.matchId);
assert.equal(replay(rec.rules as any, rec.decks as any, rec.seed, rec.actions.map(x => x.action) as any).result?.winner ?? null, rec.winner);
// Rules changed under a mode → its lobbies are dropped, not run under different rules.
const changed = new ModeHost({ identity: { origin: 'http://x.test', operator: 'X' }, engine: engineBinding, store: new MatchStore(null),
modes: [parseMode({ schema: MODE_SCHEMA_VERSION, id: 'classic', version: 1, name: 'C', description: 'x', decks: { kind: 'starter' }, rules: { turns: 5 } })] });
assert.equal(changed.restore(second.snapshot()), 0);
} finally { rmSync(dir, { recursive: true, force: true }); }
});