forked from WikiDeck/wikideck
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>
370 lines
22 KiB
TypeScript
370 lines
22 KiB
TypeScript
// host-pvp (#56): multi-engine host, account seats, constructed owned decks, invites, quick
|
|
// match, Elo and `?v=` polling. Stub engine + fake ownership port: zero network calls.
|
|
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { mkdtempSync, rmSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import express from 'express';
|
|
import { parseMode, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
|
|
import { ModeHost, GameError, seededShuffle } from '../server/game/host.ts';
|
|
import { MatchStore, eloUpdate, ELO_START } from '../server/game/store.ts';
|
|
import { ModeDiscovery } from '../server/game/discovery.ts';
|
|
import { createGameRouter } from '../server/game/router.ts';
|
|
import type { ChainCard, EnginePort, OwnershipPort, SeatAccount } from '../server/game/engine-port.ts';
|
|
import { stubEngine, type StubCard } from './modes-stub-engine.ts';
|
|
|
|
const DECK = 6; // stand-in for the duel's 40, to keep the stub small
|
|
const identity = { origin: 'http://node-a.test', operator: 'Alice' };
|
|
|
|
/** The stub engine, registered as `duel`, that can build cards from owned NFTs. */
|
|
const duelStub: EnginePort<any, StubCard, any, any> = {
|
|
...stubEngine,
|
|
defaultRuleset: { deckSize: DECK, turns: 3, scoring: { tieBreak: 'first' } },
|
|
fromChain: (_rules, c: ChainCard) => ({ id: c.tokenId, pageId: c.pageId, power: (c.pageId % 9) + 1 }),
|
|
copyLimit: () => 4,
|
|
};
|
|
|
|
const duelMode = (over: object = {}) => parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'duel', id: 'duel-classic', version: 1,
|
|
name: 'Duel', description: 'Constructed duel.', decks: { kind: 'constructed', minConfirmations: 1 },
|
|
limits: { rated: true }, ...over });
|
|
|
|
class OwnershipError extends Error { readonly status: number; constructor(status: number, m: string) { super(m); this.status = status; } }
|
|
|
|
/** In-memory accounts + ledger: tokens `<who>-<n>` belong to `<who>`. */
|
|
function fakeOwnership() {
|
|
const accounts: Record<string, SeatAccount> = {
|
|
'id-alice': { sub: 'alice', issuer: 'https://dex.test', name: 'Alice Example' },
|
|
'id-bob': { sub: 'bob', issuer: 'https://dex.test', name: 'Bob <b>' },
|
|
'id-carol': { sub: 'carol', issuer: 'https://dex.test', name: 'Carol' },
|
|
};
|
|
const ledger = new Map<string, { sub: string; confirmations: number; pageId: number }>();
|
|
const mint = (sub: string, n: number, confirmations = 5) => {
|
|
for (let i = 0; i < n; i++) ledger.set(`${sub}-${i}`, { sub, confirmations, pageId: 100 + ledger.size });
|
|
};
|
|
mint('alice', 10); mint('bob', 10); mint('carol', 3);
|
|
const card = (tokenId: string): ChainCard => {
|
|
const e = ledger.get(tokenId)!;
|
|
return { tokenId, owner: `wallet-${e.sub}`, confirmations: e.confirmations, pageId: e.pageId, title: `Page ${e.pageId}` };
|
|
};
|
|
const calls = { verify: 0, resolve: 0, collection: 0 };
|
|
const port: OwnershipPort = {
|
|
async verifyAccount(idToken) {
|
|
calls.verify++;
|
|
const a = typeof idToken === 'string' ? accounts[idToken] : undefined;
|
|
if (!a) throw new OwnershipError(401, 'Invalid eom.dev login');
|
|
return a;
|
|
},
|
|
async resolveDeck(account, tokenIds, opts) {
|
|
calls.resolve++;
|
|
const ids = tokenIds as string[];
|
|
if (ids.length !== opts.deckSize) throw new OwnershipError(400, 'wrong size');
|
|
if (new Set(ids).size !== ids.length) throw new OwnershipError(400, 'duplicate token');
|
|
for (const t of ids) {
|
|
const e = ledger.get(t);
|
|
if (!e) throw new OwnershipError(400, `unknown token ${t}`);
|
|
if (e.sub !== account.sub) throw new OwnershipError(403, `not yours: ${t}`);
|
|
if (e.confirmations < opts.minConfirmations) throw new OwnershipError(400, `unconfirmed: ${t}`);
|
|
}
|
|
return ids.map(card);
|
|
},
|
|
async collection(account) {
|
|
calls.collection++;
|
|
return [...ledger.entries()].filter(([, e]) => e.sub === account.sub).map(([t]) => card(t));
|
|
},
|
|
};
|
|
return { port, ledger, calls, mint };
|
|
}
|
|
|
|
const deckOf = (who: string, n = DECK) => Array.from({ length: n }, (_, i) => `${who}-${i}`);
|
|
|
|
function playOut(host: ModeHost, lobbyId: string, tokens: string[]) {
|
|
for (let guard = 0; guard < 50; guard++) {
|
|
const v0 = host.view(lobbyId, tokens[0]) as any;
|
|
if (v0.phase !== 'playing') return v0;
|
|
for (const t of tokens) {
|
|
const v = host.view(lobbyId, t) as any;
|
|
if (v.legalActions?.length) void host.act(lobbyId, t, v.legalActions[0]);
|
|
}
|
|
}
|
|
throw new Error('did not finish');
|
|
}
|
|
|
|
function newHost(modes = [duelMode()], store = new MatchStore(null), own = fakeOwnership()) {
|
|
return { host: new ModeHost({ identity, modes, engines: { duel: duelStub, editwar: stubEngine }, ownership: own.port, store }), own, store };
|
|
}
|
|
|
|
test('host-pvp: two account players finish a hosted constructed duel; rated, Elo moves, record has tokens', async () => {
|
|
const { host, store } = newHost();
|
|
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
const b = await host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
|
const v = host.view(a.lobbyId, a.token) as any;
|
|
assert.equal(v.phase, 'playing');
|
|
assert.equal(v.rated, true);
|
|
assert.equal(v.mode.engine, 'duel');
|
|
assert.deepEqual(v.players.map((p: any) => [p.name, p.account]), [['Alice Example', true], ['Bob b', true]]);
|
|
assert.deepEqual(v.state.hand.map((c: any) => c.id), deckOf('alice'), 'cards are built from the chain, in deck order');
|
|
const end = playOut(host, a.lobbyId, [a.token, b.token]);
|
|
assert.equal(end.phase, 'finished');
|
|
assert.match(end.matchId, /^[a-f0-9]{32}$/);
|
|
const rec = host.matchRecord(end.matchId);
|
|
assert.equal(rec.engine, 'duel');
|
|
assert.equal(rec.rated, true);
|
|
assert.deepEqual(rec.tokens, [deckOf('alice'), deckOf('bob')]);
|
|
assert.ok(!JSON.stringify(rec).includes('id-alice'), 'ID tokens are never stored');
|
|
const board = host.leaderboard('duel-classic').entries;
|
|
assert.equal(board.length, 2);
|
|
const [hi, lo] = eloUpdate(ELO_START, ELO_START, 0);
|
|
const ratings = board.map(e => e.rating).sort();
|
|
assert.deepEqual(ratings, [Math.round(lo), Math.round(hi)].sort());
|
|
assert.ok(board.every(e => e.ratedPlayed === 1));
|
|
assert.equal(store.total, 1);
|
|
});
|
|
|
|
test('host-pvp: forged, unowned, short and unconfirmed decks are rejected; guests need an account', async () => {
|
|
const { host, own } = newHost();
|
|
const status = async (p: Promise<unknown>) => { try { await p; return 0; } catch (e) { assert.ok(e instanceof GameError, String(e)); return e.status; } };
|
|
// Guest (secret) seat in an owned-cards mode.
|
|
assert.equal(await status(host.createLobby('duel-classic', { name: 'Al', secret: 'alice-secret-0123456789abcdef', deck: deckOf('alice') })), 401);
|
|
// Bad login.
|
|
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-mallory', deck: deckOf('alice') })), 401);
|
|
// Short deck, long deck, non-array, non-strings: rejected before ownership is asked.
|
|
const before = own.calls.resolve;
|
|
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice', DECK - 1) })), 400);
|
|
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice', DECK + 1) })), 400);
|
|
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: 'alice-0' })), 400);
|
|
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: [1, 2, 3, 4, 5, 6] })), 400);
|
|
assert.equal(own.calls.resolve, before);
|
|
// Forged token id (not on the chain), someone else's card, duplicate card.
|
|
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: [...deckOf('alice', DECK - 1), 'forged-1'] })), 400);
|
|
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: [...deckOf('alice', DECK - 1), 'bob-0'] })), 403);
|
|
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: [...deckOf('alice', DECK - 1), 'alice-0'] })), 400);
|
|
// Unconfirmed: a fresh mint below the mode's minConfirmations.
|
|
own.ledger.set('alice-new', { sub: 'alice', confirmations: 0, pageId: 999 });
|
|
assert.equal(await status(host.createLobby('duel-classic', { idToken: 'id-alice', deck: [...deckOf('alice', DECK - 1), 'alice-new'] })), 400);
|
|
// Joiner with a bad deck does not kill the creator's lobby.
|
|
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
assert.equal(await status(host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('alice') })), 403);
|
|
assert.equal((host.view(a.lobbyId) as any).phase, 'waiting');
|
|
// Same account on both seats.
|
|
assert.equal(await status(host.join(a.lobbyId, { idToken: 'id-alice', deck: deckOf('alice') })), 409);
|
|
});
|
|
|
|
test('host-pvp: cross-seat and cross-lobby tokens are rejected', async () => {
|
|
const { host } = newHost();
|
|
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
const b = await host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
|
const c = await host.createLobby('duel-classic', { idToken: 'id-carol2', deck: [] }).catch(() => null);
|
|
assert.equal(c, null);
|
|
const other = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
// Bob's token acts as Bob only: legal actions are per seat, so Alice's action from Bob's token is illegal.
|
|
const aliceAction = (host.view(a.lobbyId, a.token) as any).legalActions[0];
|
|
const bobView = host.view(a.lobbyId, b.token) as any;
|
|
assert.equal(bobView.seat, 1);
|
|
// A token from another lobby is not a seat here, and a spectator sees no private state.
|
|
await assert.rejects(host.act(a.lobbyId, other.token, aliceAction), (e: GameError) => e.status === 403);
|
|
assert.equal((host.view(a.lobbyId, other.token) as any).state, undefined);
|
|
assert.equal((host.view(a.lobbyId, other.token) as any).seat, null);
|
|
assert.throws(() => host.resign(a.lobbyId, 'x'.repeat(32)), (e: GameError) => e.status === 403);
|
|
// Seat ids are account-derived, never the token.
|
|
const ids = bobView.players.map((p: any) => p.id);
|
|
assert.ok(ids.every((id: string) => /^[a-f0-9]{64}$/.test(id)));
|
|
assert.ok(!ids.includes(a.token) && !ids.includes(b.token));
|
|
});
|
|
|
|
test('host-pvp: creator cards that moved before the join expire the lobby', async () => {
|
|
const { host, own } = newHost();
|
|
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
own.ledger.set('alice-3', { ...own.ledger.get('alice-3')!, sub: 'carol' }); // transferred away
|
|
await assert.rejects(host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') }), /no longer valid/);
|
|
assert.equal((host.view(a.lobbyId) as any).phase, 'expired');
|
|
assert.equal((host.view(a.lobbyId) as any).players.length, 1, 'a stale lobby never lists the joiner');
|
|
});
|
|
|
|
test('host-pvp: quick match skips a stale lobby and pairs the next one', async () => {
|
|
const { host, own } = newHost();
|
|
own.mint('dave', 0);
|
|
const stale = await host.quickMatch('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
const fresh = await host.quickMatch('duel-classic', { idToken: 'id-carol', deck: [] }).catch(() => null);
|
|
assert.equal(fresh, null, 'carol cannot build a deck');
|
|
own.ledger.set('alice-0', { ...own.ledger.get('alice-0')!, sub: 'carol' });
|
|
// Bob quick-matches: alice's lobby is stale (expired, skipped), so bob opens a new one.
|
|
const bob = await host.quickMatch('duel-classic', { idToken: 'id-bob', deck: deckOf('bob') });
|
|
assert.equal(bob.matched, false);
|
|
assert.notEqual(bob.lobbyId, stale.lobbyId);
|
|
assert.equal((host.view(stale.lobbyId) as any).phase, 'expired');
|
|
});
|
|
|
|
test('host-pvp: private lobbies are hidden and joined by invite code', async () => {
|
|
const { host } = newHost();
|
|
const pub = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
const priv = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice'), private: true });
|
|
assert.match(priv.invite!, /^[A-Za-z0-9_-]{12}$/);
|
|
assert.deepEqual(host.openLobbies('duel-classic').map(l => l.lobbyId), [pub.lobbyId]);
|
|
const inv = host.invite(priv.invite!);
|
|
assert.equal(inv.lobbyId, priv.lobbyId);
|
|
assert.equal(inv.open, true);
|
|
assert.equal(inv.accountRequired, true);
|
|
assert.equal(inv.createdBy, 'Alice Example');
|
|
assert.throws(() => host.invite('nope'), (e: GameError) => e.status === 404);
|
|
// Quick match never lands in a private lobby.
|
|
const q = await host.quickMatch('duel-classic', { idToken: 'id-bob', deck: deckOf('bob') });
|
|
assert.equal(q.matched, true);
|
|
assert.equal(q.lobbyId, pub.lobbyId);
|
|
await host.join(inv.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
|
assert.equal(host.invite(priv.invite!).open, false);
|
|
// Only the creator's view carries the invite code.
|
|
assert.equal((host.view(priv.lobbyId, priv.token) as any).invite, priv.invite);
|
|
assert.equal((host.view(priv.lobbyId) as any).invite, undefined);
|
|
});
|
|
|
|
test('host-pvp: quick match pairs the oldest open lobby, never yourself', async () => {
|
|
const { host } = newHost();
|
|
const first = await host.quickMatch('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
assert.equal(first.matched, false);
|
|
assert.equal(first.seat, 0);
|
|
const again = await host.quickMatch('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
assert.equal(again.matched, false, 'does not match your own lobby');
|
|
assert.notEqual(again.lobbyId, first.lobbyId);
|
|
const bob = await host.quickMatch('duel-classic', { idToken: 'id-bob', deck: deckOf('bob') });
|
|
assert.equal(bob.matched, true);
|
|
assert.equal(bob.lobbyId, first.lobbyId, 'oldest first');
|
|
assert.equal(bob.seat, 1);
|
|
assert.equal((host.view(first.lobbyId, first.token) as any).phase, 'playing');
|
|
});
|
|
|
|
test('host-pvp: state version; unchanged polls return null (204 over HTTP)', async () => {
|
|
const { host } = newHost();
|
|
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
const v1 = (host.view(a.lobbyId, a.token) as any).version;
|
|
assert.equal(host.view(a.lobbyId, a.token, v1), null);
|
|
const b = await host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
|
const v2 = (host.view(a.lobbyId, a.token, v1) as any).version;
|
|
assert.ok(v2 > v1);
|
|
assert.equal(host.view(a.lobbyId, b.token, v2), null);
|
|
await host.act(a.lobbyId, a.token, (host.view(a.lobbyId, a.token) as any).legalActions[0]);
|
|
assert.ok((host.view(a.lobbyId, b.token, v2) as any).version > v2);
|
|
|
|
// Over HTTP: 204 with no body, 200 with a newer version; Dex token accepted as a JWT bearer.
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use('/api/game', createGameRouter(host, new ModeDiscovery({ peers: [] })));
|
|
const server = app.listen(0);
|
|
try {
|
|
const base = `http://127.0.0.1:${(server.address() as any).port}/api/game`;
|
|
const cur = (await (await fetch(`${base}/lobbies/${a.lobbyId}`, { headers: { authorization: `Bearer ${a.token}` } })).json()).version;
|
|
const same = await fetch(`${base}/lobbies/${a.lobbyId}?v=${cur}`, { headers: { authorization: `Bearer ${a.token}` } });
|
|
assert.equal(same.status, 204);
|
|
const stale = await fetch(`${base}/lobbies/${a.lobbyId}?v=${cur - 1}`);
|
|
assert.equal(stale.status, 200);
|
|
const ladder = await (await fetch(`${base}/modes/duel-classic/ladder`)).json();
|
|
assert.ok(Array.isArray(ladder.entries));
|
|
// JWT-shaped bearer on a seat-creating route reaches verifyAccount (rejected here: unknown login).
|
|
const jwt = await fetch(`${base}/modes/duel-classic/quick`, { method: 'POST', headers: { 'content-type': 'application/json',
|
|
authorization: 'Bearer aaa.bbb.ccc' }, body: JSON.stringify({ deck: deckOf('alice') }) });
|
|
assert.equal(jwt.status, 401);
|
|
const inv = await fetch(`${base}/invites/${a.invite}`);
|
|
assert.equal(inv.status, 200);
|
|
assert.equal((await inv.json()).open, false);
|
|
} finally { server.close(); }
|
|
});
|
|
|
|
test('host-pvp: collections draft pools both players cards; short collections are rejected', async () => {
|
|
const mode = duelMode({ id: 'duel-draft', decks: { kind: 'draft', source: 'collections', poolSize: 2 * DECK, pickSeconds: 30 } });
|
|
const { host } = newHost([mode]);
|
|
const a = await host.createLobby('duel-draft', { idToken: 'id-alice' });
|
|
await host.join(a.lobbyId, { idToken: 'id-bob' });
|
|
const v = host.view(a.lobbyId, a.token) as any;
|
|
assert.equal(v.phase, 'drafting');
|
|
assert.equal((host.view(a.lobbyId) as any).draft, undefined, 'spectators see no draft pool');
|
|
assert.equal(v.draft.pool.length, 2 * DECK);
|
|
const owners = new Set(v.draft.pool.map((p: any) => String(p.card.id).split('-')[0]));
|
|
assert.ok(owners.size >= 1 && [...owners].every(o => o === 'alice' || o === 'bob'));
|
|
// Carol owns 3 < 6 cards: not eligible.
|
|
const c = await host.createLobby('duel-draft', { idToken: 'id-carol' });
|
|
await assert.rejects(host.join(c.lobbyId, { idToken: 'id-bob' }), /3 \/ 6 cards/);
|
|
assert.equal((host.view(c.lobbyId) as any).phase, 'expired');
|
|
});
|
|
|
|
test('host-pvp: duel modes reject loaner policies; Night 1 mode files are rejected cleanly', () => {
|
|
const store = new MatchStore(null);
|
|
assert.throws(() => new ModeHost({ identity, store, engines: { duel: duelStub }, modes: [duelMode({ decks: { kind: 'starter' } })] }), /owned cards only/);
|
|
assert.throws(() => new ModeHost({ identity, store, engines: { duel: duelStub },
|
|
modes: [duelMode({ decks: { kind: 'draft', source: 'preview', poolSize: 12 } })] }), /owned cards only/);
|
|
assert.throws(() => new ModeHost({ identity, store, engines: { editwar: stubEngine }, modes: [duelMode()] }), /engine "duel" is not available/);
|
|
assert.throws(() => parseMode({ schema: 'wikideck.mode/1', id: 'old', version: 1, name: 'Old', description: 'x' }), /Night 1.*wikideck\.mode\/2/);
|
|
assert.throws(() => parseMode({ schema: MODE_SCHEMA_VERSION, id: 'no-engine', version: 1, name: 'x', description: 'x' }));
|
|
});
|
|
|
|
test('host-pvp: Edit War guests still play, unrated, beside duel modes', async () => {
|
|
const war = parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'editwar', id: 'war', version: 1, name: 'War', description: 'x',
|
|
decks: { kind: 'starter' }, limits: { rated: true } });
|
|
const { host } = newHost([duelMode(), war]);
|
|
const a = await host.createLobby('war', { name: 'Al', secret: 'alice-secret-0123456789abcdef' });
|
|
const b = await host.join(a.lobbyId, { name: 'Bo', secret: 'bob-secret-0123456789abcdefgh' });
|
|
const end = playOut(host, a.lobbyId, [a.token, b.token]);
|
|
const rec = host.matchRecord(end.matchId);
|
|
assert.equal(rec.rated, false, 'guests are never rated');
|
|
assert.ok(host.leaderboard('war').entries.every(e => e.rating === null));
|
|
});
|
|
|
|
test('host-pvp: Elo is recomputed identically from matches.jsonl on restart', async () => {
|
|
const dir = mkdtempSync(join(tmpdir(), 'host-pvp-'));
|
|
try {
|
|
const { host } = newHost([duelMode()], new MatchStore(dir));
|
|
for (let i = 0; i < 3; i++) {
|
|
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
const b = await host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
|
playOut(host, a.lobbyId, [a.token, b.token]);
|
|
}
|
|
const before = host.leaderboard('duel-classic').entries;
|
|
const reloaded = new MatchStore(dir);
|
|
assert.deepEqual(reloaded.leaderboard('duel-classic'), before);
|
|
assert.ok(before.every(e => e.ratedPlayed === 3));
|
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
|
});
|
|
|
|
test('host-pvp: live lobbies with account seats survive a snapshot/restore', async () => {
|
|
const { host, own } = newHost();
|
|
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
const snap = host.snapshot();
|
|
assert.ok(!snap.includes(a.token) && !snap.includes('id-alice'));
|
|
const next = new ModeHost({ identity, modes: [duelMode()], engines: { duel: duelStub }, ownership: own.port, store: new MatchStore(null) });
|
|
assert.equal(next.restore(snap), 1);
|
|
const b = await next.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
|
assert.equal((next.view(a.lobbyId, b.token) as any).phase, 'playing');
|
|
assert.equal((next.view(a.lobbyId, a.token) as any).seat, 0);
|
|
});
|
|
|
|
test('host-pvp: seeded shuffle is deterministic and a permutation', () => {
|
|
const xs = Array.from({ length: 50 }, (_, i) => i);
|
|
assert.deepEqual(seededShuffle(xs, 's'), seededShuffle(xs, 's'));
|
|
assert.notDeepEqual(seededShuffle(xs, 's'), seededShuffle(xs, 't'));
|
|
assert.deepEqual([...seededShuffle(xs, 's')].sort((a, b) => a - b), xs);
|
|
});
|
|
|
|
test('host-pvp: a slow seat spends its time bank before it times out', async () => {
|
|
let now = 1_000_000;
|
|
// Stub turns are simultaneous; a 10 s turn plus a 30 s bank, timeouts from the engine.
|
|
const timed: EnginePort<any, StubCard, any, any> = { ...duelStub, turnSeconds: () => 10, bankSeconds: () => 30, turnOf: (s: any) => s.turn,
|
|
timeoutAction: () => ({ type: 'play', card: 0 }) };
|
|
const own = fakeOwnership();
|
|
const host = new ModeHost({ identity, modes: [duelMode()], engines: { duel: timed }, ownership: own.port,
|
|
store: new MatchStore(null), now: () => now });
|
|
const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') });
|
|
const b = await host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') });
|
|
await host.act(a.lobbyId, a.token, (host.view(a.lobbyId, a.token) as any).legalActions[0]); // alice moves, bob stalls
|
|
const clock = (host.view(a.lobbyId, b.token) as any).clock;
|
|
assert.deepEqual(clock.bankMs, [30_000, 30_000]);
|
|
assert.equal(clock.turnMs, 15_000, 'turn timer includes 5 s network grace');
|
|
now += 15_000 + 20_000; // past the turn timer, inside bob's bank
|
|
host.sweep();
|
|
assert.equal((host.view(a.lobbyId, b.token) as any).state.turn, 0, 'bob is still on his bank');
|
|
now += 11_000; // bank exhausted
|
|
host.sweep();
|
|
const v = host.view(a.lobbyId, b.token) as any;
|
|
assert.equal(v.state.turn, 1, 'timeout applied');
|
|
assert.equal(v.clock.bankMs[1], 0);
|
|
assert.equal(v.clock.bankMs[0], 30_000);
|
|
});
|