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>
186 lines
11 KiB
TypeScript
186 lines
11 KiB
TypeScript
// host-pvp (#56) part 2: the duel binding, ChainCard → DuelCard, the ownership adapter and
|
|
// built-in duel modes. Uses docs/game/card-sample.json only: zero network calls.
|
|
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import { readFileSync } from 'node:fs';
|
|
import express from 'express';
|
|
import { derive } from '../shared/duel/derive.ts';
|
|
import { sampleInputs, type SampleCard } from '../shared/duel/sample.ts';
|
|
import * as duelApi from '../shared/duel/index.ts';
|
|
import { buildIdentity, toProfile } from '../server/game/identity.ts';
|
|
import { toDuelCard, duelBinding } from '../server/game/duel-binding.ts';
|
|
import { gameRouter, ownershipPortFrom } from '../server/game/index.ts';
|
|
import { ModeHost } from '../server/game/host.ts';
|
|
import { MatchStore } from '../server/game/store.ts';
|
|
import { parseMode, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts';
|
|
import { loadModes } from '../server/game/config.ts';
|
|
import type { ChainCard, EnginePort, OwnershipPort } from '../server/game/engine-port.ts';
|
|
|
|
const SAMPLE = (JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8')) as { cards: SampleCard[] }).cards;
|
|
|
|
/** A ChainCard as ownership.ts builds it from a block, here from a sample card. */
|
|
function chainCard(s: SampleCard, owner = 'wallet'): ChainCard {
|
|
const { chain } = sampleInputs(s);
|
|
return { tokenId: chain.tokenId, owner, confirmations: 5, pageId: s.pageId, title: s.title, revisionId: s.revisionId,
|
|
article: { ...chain.article, url: `https://en.wikipedia.org/?curid=${s.pageId}` },
|
|
statsSnapshot: { ...chain.statsSnapshot, revisionId: s.revisionId } };
|
|
}
|
|
|
|
test('host-pvp binding: toDuelCard uses the frozen identity, deterministically', () => {
|
|
const s = SAMPLE[0]!;
|
|
const card = chainCard(s);
|
|
const ident = buildIdentity({ tokenId: card.tokenId, pageId: s.pageId, title: s.title, revisionId: s.revisionId },
|
|
{ description: s.description, wikidataId: s.wikidataId, categories: s.categories, instanceOf: s.instanceOf } as any,
|
|
'cache', new Date('2026-11-17T00:00:00Z'));
|
|
const identity = { get: (t: string) => (t === card.tokenId ? ident : undefined) };
|
|
const a = toDuelCard(card, { identity });
|
|
assert.deepEqual(a, derive(sampleInputs(s).chain, toProfile(ident) as any), 'same as derive(chain, frozen profile)');
|
|
assert.deepEqual(toDuelCard(card, { identity }), a, 'deterministic');
|
|
// A miss falls back to what the chain carries: still a legal card, no fetch.
|
|
const fallback = toDuelCard(card, {});
|
|
assert.equal(fallback.pageId, s.pageId);
|
|
assert.ok(fallback.cost >= 1 && fallback.cost <= 6);
|
|
assert.throws(() => toDuelCard({ ...card, article: undefined }), /no on-chain article/);
|
|
});
|
|
|
|
test('host-pvp binding: the ownership adapter passes the account and options through', async () => {
|
|
const seen: unknown[] = [];
|
|
const deps = {
|
|
ledger: { nft: () => undefined, deck: () => ({ tip: 't', total: 0, next: null, nfts: [] }), summary: () => ({ tip: 't', height: 1 }) },
|
|
accounts: { wallets: (sub: string) => { seen.push(sub); return []; } },
|
|
verifyIdToken: async (t: string) => { if (t !== 'a.b.c') throw Object.assign(new Error('Token expired'), { status: 401 });
|
|
return { sub: 'alice', issuer: 'https://dex.test', name: 'Alice', username: 'alice' }; },
|
|
};
|
|
const port: OwnershipPort = ownershipPortFrom(deps as any);
|
|
const acct = await port.verifyAccount('a.b.c');
|
|
assert.equal(acct.sub, 'alice');
|
|
await assert.rejects(port.verifyAccount('x.y.z'), (e: any) => e.status === 401);
|
|
assert.deepEqual(await port.collection(acct), []);
|
|
await assert.rejects(port.resolveDeck(acct, ['a'.repeat(64)], { deckSize: 40, maxCopiesPerPage: 4, minConfirmations: 1 }),
|
|
(e: any) => e.status >= 400 && e.status < 500);
|
|
assert.ok(seen.includes('alice'));
|
|
});
|
|
|
|
test('host-pvp binding: built-in duel modes parse; Edit War ids moved to edit-war*', () => {
|
|
const modes = loadModes({});
|
|
assert.deepEqual(modes.map(m => [m.id, m.engine]), [['classic', 'duel'], ['draft', 'duel'], ['trending', 'duel'], ['edit-war', 'editwar']]);
|
|
const classic = modes[0]!;
|
|
assert.equal(classic.limits.rated, true);
|
|
assert.equal(classic.decks.kind, 'constructed');
|
|
const draft = modes[1]!;
|
|
assert.ok(draft.decks.kind === 'draft' && draft.decks.source === 'collections' && draft.decks.poolSize >= 80);
|
|
});
|
|
|
|
test('host-pvp binding: duel modes are skipped (not fatal) when the build has no duel engine', async () => {
|
|
const hasEngine = typeof (duelApi as Record<string, any>).duelEnginePort?.createMatch === 'function';
|
|
const app = express();
|
|
app.use('/api/game', await gameRouter({ dataDir: null, warmTrends: false, handleSignals: false,
|
|
env: { WIKIDECK_MODES: 'classic,edit-war', PUBLIC_ORIGIN: 'http://127.0.0.1:3101', WIKIDECK_GAME_PEERS: '' } }));
|
|
const server = app.listen(0);
|
|
try {
|
|
const list = await (await fetch(`http://127.0.0.1:${(server.address() as any).port}/api/game/modes`)).json();
|
|
assert.deepEqual(list.modes.map((m: any) => m.mode.id), hasEngine ? ['classic', 'edit-war'] : ['edit-war']);
|
|
} finally { server.close(); }
|
|
});
|
|
|
|
const realPort = (duelApi as Record<string, any>).duelEnginePort as EnginePort<any, any, any, any> | undefined;
|
|
|
|
test('host-pvp binding: two scripted players finish a hosted 40-card duel on the real engine', { skip: !realPort && 'duel engine alpha not merged yet' }, async () => {
|
|
const engine = duelBinding(realPort!);
|
|
const alice = SAMPLE.slice(0, 40).map(s => chainCard(s, 'wallet-alice'));
|
|
const bob = SAMPLE.slice(40, 80).map(s => chainCard(s, 'wallet-bob'));
|
|
const owned: Record<string, ChainCard[]> = { alice, bob };
|
|
const ownership: OwnershipPort = {
|
|
verifyAccount: async t => ({ sub: String(t), issuer: 'https://dex.test', name: String(t) }),
|
|
resolveDeck: async (a, ids) => (ids as string[]).map(id => { const c = owned[a.sub]!.find(x => x.tokenId === id);
|
|
if (!c) throw Object.assign(new Error('not yours'), { status: 403 }); return c; }),
|
|
collection: async a => owned[a.sub] ?? [],
|
|
};
|
|
const mode = parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'duel', id: 'classic', version: 1, name: 'Classic', description: 'x',
|
|
decks: { kind: 'constructed', minConfirmations: 1 }, limits: { rated: true } });
|
|
const host = new ModeHost({ identity: { origin: 'http://node.test', operator: 'T' }, modes: [mode], engines: { duel: engine },
|
|
ownership, store: new MatchStore(null) });
|
|
const a = await host.createLobby('classic', { idToken: 'alice', deck: alice.map(c => c.tokenId) });
|
|
const b = await host.join(a.lobbyId, { idToken: 'bob', deck: bob.map(c => c.tokenId) });
|
|
await assert.rejects(host.join(a.lobbyId, { idToken: 'bob', deck: bob.map(c => c.tokenId) }), /no longer open/);
|
|
const tokens = [a.token, b.token];
|
|
for (let i = 0; i < 4000; i++) {
|
|
const v = host.view(a.lobbyId, a.token) as any;
|
|
if (v.phase !== 'playing') break;
|
|
let moved = false;
|
|
for (const t of tokens) {
|
|
const sv = host.view(a.lobbyId, t) as any;
|
|
if (sv.legalActions?.length) { await host.act(a.lobbyId, t, sv.legalActions[i % sv.legalActions.length]); moved = true; break; }
|
|
}
|
|
assert.ok(moved, 'someone can always act');
|
|
}
|
|
const end = host.view(a.lobbyId, a.token) as any;
|
|
assert.equal(end.phase, 'finished');
|
|
const rec = host.matchRecord(end.matchId);
|
|
assert.equal(rec.decks[0]!.length, 40);
|
|
assert.equal(rec.engine, 'duel');
|
|
// Anyone can audit: replaying the record reproduces the result.
|
|
const api = duelApi as Record<string, any>;
|
|
if (typeof api.replay === 'function') {
|
|
const replayed = api.replay(rec.rules, rec.decks, rec.seed, rec.actions);
|
|
assert.equal(api.result(replayed)?.winner ?? null, rec.winner);
|
|
}
|
|
});
|
|
|
|
test('host-pvp binding: gameRouter mounts GET /collection when ownership deps are given', async () => {
|
|
const deps = {
|
|
ledger: { nft: () => undefined, deck: () => ({ tip: 't', total: 0, next: null, nfts: [] }), summary: () => ({ tip: 't', height: 1 }) },
|
|
accounts: { wallets: () => [] },
|
|
verifyIdToken: async (t: string) => { if (t !== 'a.b.c') throw Object.assign(new Error('Token expired'), { status: 401 });
|
|
return { sub: 'alice', issuer: 'https://dex.test', name: 'Alice', username: 'alice' }; },
|
|
};
|
|
const app = express();
|
|
app.use('/api/game', await gameRouter({ dataDir: null, warmTrends: false, handleSignals: false, ownership: deps as any,
|
|
env: { WIKIDECK_MODES: 'edit-war', PUBLIC_ORIGIN: 'http://127.0.0.1:3101', WIKIDECK_GAME_PEERS: '' } }));
|
|
const server = app.listen(0);
|
|
try {
|
|
const base = `http://127.0.0.1:${(server.address() as any).port}/api/game`;
|
|
assert.equal((await fetch(`${base}/collection`)).status, 401);
|
|
const ok = await fetch(`${base}/collection`, { headers: { authorization: 'Bearer a.b.c' } });
|
|
assert.equal(ok.status, 200);
|
|
assert.deepEqual((await ok.json()).cards, []);
|
|
assert.equal((await fetch(`${base}/modes`)).status, 200, 'the game routes still answer');
|
|
} finally { server.close(); }
|
|
});
|
|
|
|
/** server/wiki.ts's mint-time category(), reproduced for the sample (it is not exported). */
|
|
function mintCategory(title: string, categories: string[]): string {
|
|
const text = `${title} ${categories.join(' ')}`.toLowerCase();
|
|
if (/astronom|planet|space|galax|moon|star\b/.test(text)) return 'Space';
|
|
if (/animal|plant|species|ocean|biolog|mollusc/.test(text)) return 'Nature';
|
|
if (/births|deaths|people|scientist/.test(text)) return 'People';
|
|
if (/physic|chem|math|science|technolog/.test(text)) return 'Science';
|
|
if (/histor|ancient|archaeolog|empire/.test(text)) return 'History';
|
|
return 'Culture';
|
|
}
|
|
|
|
test('host-pvp binding: without a frozen identity, cards are typed from on-chain data, not all Doctrine (night-review P1)', () => {
|
|
const types: Record<string, number> = {};
|
|
for (const s of SAMPLE) {
|
|
const c = chainCard(s);
|
|
(c.article as any).category = mintCategory(s.title, s.categories);
|
|
const d = toDuelCard(c, {});
|
|
types[d.type] = (types[d.type] ?? 0) + 1;
|
|
assert.equal(d.typedBy, 'fallback');
|
|
assert.equal(d.description, undefined, 'no fabricated short description');
|
|
assert.ok(!d.connect.p31.includes(''), 'hints never become Connected keys');
|
|
}
|
|
assert.ok((types.Doctrine ?? 0) < SAMPLE.length / 2, JSON.stringify(types));
|
|
assert.ok((types.Figure ?? 0) >= 40, JSON.stringify(types));
|
|
// The extract's first sentence wins over the category hint.
|
|
const s = SAMPLE[0]!;
|
|
const battle = chainCard(s);
|
|
(battle.article as any).extract = 'The Battle of Somewhere was a battle fought in 1548. It was long.';
|
|
(battle.article as any).category = 'People';
|
|
assert.equal(toDuelCard(battle, {}).type, 'Event');
|
|
const pol = chainCard(s);
|
|
(pol.article as any).extract = 'Jane Doe is an American politician.';
|
|
(pol.article as any).category = 'Culture';
|
|
assert.equal(toDuelCard(pol, {}).type, 'Figure');
|
|
});
|