Files
wikideck/server/game/index.ts
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

78 lines
4.1 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 type 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 } from './engine-port.ts';
import { TrendCache } from './trends.ts';
type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> };
export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment;
engine?: EnginePort<any, any, any, any>; 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 modes = loadModes(env);
// 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 host = new ModeHost({ identity: hostIdentity(env), modes, engine,
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();
return createGameRouter(host, discovery);
}
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 };
}