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>
119 lines
6.4 KiB
TypeScript
119 lines
6.4 KiB
TypeScript
/**
|
|
* Entry point for the game-modes API. server/testnet/http.ts mounts it with one line:
|
|
* app.use('/api/game', await (await import('../game/index.ts')).gameRouter({ dataDir, enrichment: wikipediaEnrichment }));
|
|
*/
|
|
import { join } from 'node:path';
|
|
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
import express from 'express';
|
|
import { loadModes, hostIdentity, gamePeers } from './config.ts';
|
|
import { ModeDiscovery } from './discovery.ts';
|
|
import { ModeHost } from './host.ts';
|
|
import { createGameRouter } from './router.ts';
|
|
import { MatchStore } from './store.ts';
|
|
import type { EnginePort, OwnershipPort } from './engine-port.ts';
|
|
import type { EngineId } from '../../shared/game/modes.ts';
|
|
import { TrendCache } from './trends.ts';
|
|
import { loadDuelEngine, toDuelCard } from './duel-binding.ts';
|
|
import { collectionRouter } from './collection.ts';
|
|
import { IdentityStore } from './identity.ts';
|
|
import { collection, resolveDeck, verifyAccount, type OwnershipDeps } from './ownership.ts';
|
|
|
|
type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> };
|
|
|
|
export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment;
|
|
/** The Edit War engine (default: the real binding). */
|
|
engine?: EnginePort<any, any, any, any>;
|
|
/** Extra engines by id, e.g. `{ duel }` (tests inject stubs). */
|
|
engines?: Partial<Record<EngineId, EnginePort<any, any, any, any>>>;
|
|
/** Account verification + server-side ownership, adapted from server/game/ownership.ts (#57). */
|
|
ownershipPort?: OwnershipPort;
|
|
/** Server-side ownership deps (#57): http.ts passes `{ledger, accounts, verifyIdToken}`; adapted to the port here. */
|
|
ownership?: OwnershipDeps;
|
|
env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise<express.Router> {
|
|
const env = options.env ?? process.env;
|
|
const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding;
|
|
const engines: Partial<Record<EngineId, EnginePort<any, any, any, any>>> = { editwar: engine, ...options.engines };
|
|
// Frozen card identities (testnet-ops #68) give duel cards their P31 typing. Opened once, here,
|
|
// and shared by the duel engine binding and the collection API's card faces.
|
|
const identity = options.dataDir ? new IdentityStore(join(options.dataDir, 'card-identity.sqlite')) : undefined;
|
|
if (!engines.duel) {
|
|
const duel = await loadDuelEngine({ identity });
|
|
if (duel) engines.duel = duel;
|
|
}
|
|
const modes = loadModes(env).filter(m => {
|
|
if (engines[m.engine]) return true;
|
|
console.warn(`Game modes: skipping "${m.id}": engine "${m.engine}" is not in this build`);
|
|
return false;
|
|
});
|
|
// Trends come from a slowly warmed, cache-only store: never a Wikipedia call per match.
|
|
let trends: TrendCache | undefined;
|
|
if (options.enrichment && modes.some(m => m.cards.preset === 'trending')) {
|
|
const enrichment = options.enrichment;
|
|
// Wikipedia egress is shared and rate-limited: default one page per 20 s (≥ 15 s enforced).
|
|
const interval = Number(env.WIKIDECK_GAME_TREND_INTERVAL_MS ?? 20_000);
|
|
if (!Number.isSafeInteger(interval) || interval < 15_000 || interval > 3_600_000) throw new Error('WIKIDECK_GAME_TREND_INTERVAL_MS must be 15000..3600000');
|
|
trends = new TrendCache(pageId => enrichment.get(pageId), { intervalMs: interval });
|
|
for (const card of engine.starterDeck(engine.defaultRuleset, 'trend-warmup')) {
|
|
const id = engine.cardPageId(card); if (id !== null) trends.enqueue(id);
|
|
}
|
|
for (const card of engine.previewPool(engine.defaultRuleset, 'trend-warmup', 64)) {
|
|
const id = engine.cardPageId(card); if (id !== null) trends.enqueue(id);
|
|
}
|
|
if (options.warmTrends !== false) trends.start();
|
|
}
|
|
const ownership = options.ownershipPort ?? (options.ownership ? ownershipPortFrom(options.ownership) : undefined);
|
|
const host = new ModeHost({ identity: hostIdentity(env), modes, engines, ownership,
|
|
store: new MatchStore(options.dataDir ? join(options.dataDir, 'game') : null),
|
|
liveData: trends ? async pageId => trends!.get(pageId) : undefined });
|
|
const discovery = new ModeDiscovery({ peers: gamePeers(env) });
|
|
if (options.dataDir) persistLive(host, join(options.dataDir, 'game'), options.handleSignals !== false);
|
|
const timer = setInterval(() => host.sweep(), 5_000);
|
|
timer.unref();
|
|
const game = createGameRouter(host, discovery);
|
|
if (!options.ownership) return game;
|
|
// GET /api/game/collection (#57), with each card's DuelCard face from the same toDuelCard the host uses.
|
|
const router = express.Router();
|
|
router.use('/collection', collectionRouter({ ...options.ownership, duelCard: c => toDuelCard(c, { identity }) }));
|
|
router.use(game);
|
|
return router;
|
|
}
|
|
|
|
/** The async port the host calls, over ownership.ts's pure functions (#57). */
|
|
export function ownershipPortFrom(deps: OwnershipDeps): OwnershipPort {
|
|
return {
|
|
verifyAccount: idToken => verifyAccount(deps, idToken),
|
|
resolveDeck: (account, tokenIds, opts) => resolveDeck(deps, account, tokenIds, opts),
|
|
collection: account => collection(deps, account),
|
|
};
|
|
}
|
|
|
|
const MAX_LIVE_BYTES = 32 * 1024 * 1024;
|
|
|
|
/**
|
|
* Keep live lobbies and matches across restarts: restore `live.json` on start, save it every
|
|
* 15 s and synchronously on SIGTERM/SIGINT. These listeners are registered when the router is
|
|
* mounted, before the node's own shutdown handler, so the save finishes before it exits.
|
|
*/
|
|
export function persistLive(host: ModeHost, directory: string, handleSignals: boolean): { save(): void } {
|
|
const file = join(directory, 'live.json');
|
|
if (existsSync(file)) {
|
|
try {
|
|
const text = readFileSync(file, 'utf8');
|
|
if (text.length <= MAX_LIVE_BYTES) console.log(`Game modes: restored ${host.restore(text)} live lobbies`);
|
|
} catch (e) { console.error(`Game modes: could not restore live lobbies: ${(e as Error).message.slice(0, 200)}`); }
|
|
// Keep the file we restored from for inspection; the next save writes a fresh one.
|
|
try { renameSync(file, `${file}.restored`); } catch { /* ignore */ }
|
|
}
|
|
const save = () => {
|
|
try {
|
|
const tmp = `${file}.tmp`;
|
|
writeFileSync(tmp, host.snapshot(), { mode: 0o600 });
|
|
renameSync(tmp, file);
|
|
} catch (e) { console.error(`Game modes: could not save live lobbies: ${(e as Error).message.slice(0, 200)}`); }
|
|
};
|
|
const timer = setInterval(save, 15_000);
|
|
timer.unref();
|
|
if (handleSignals) for (const signal of ['SIGTERM', 'SIGINT'] as const) process.once(signal, save);
|
|
return { save };
|
|
}
|