Files
claudeanderic dbb89ce9c5 Night 2: 40-card Magic-style duel, PvP with owned decks, polite Wikimedia client, Android mining (#23)
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>
2026-11-18 18:12:24 +00:00

118 lines
5.6 KiB
TypeScript

/**
* Off-chain match records for this node: an append-only JSON-lines file plus in-memory
* aggregates (leaderboards, host totals). Nothing here touches the ledger.
*/
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { z } from 'zod';
export const MatchRecordSchema = z.object({
matchId: z.string().regex(/^[a-f0-9]{32}$/),
modeId: z.string().max(40),
modeVersion: z.number().int(),
/** Engine the match ran on (absent in Night 1 records: `editwar`). */
engine: z.enum(['editwar', 'duel']).optional(),
/** Counted for Elo: the mode was rated and both seats were eom.dev accounts. */
rated: z.boolean().optional(),
/** Host-chosen seed. Together with decks and actions it lets anyone replay the match. */
seed: z.string().max(128),
/** The resolved ruleset the match ran under (mode overrides already applied). */
rules: z.unknown(),
players: z.array(z.object({ id: z.string().regex(/^[a-f0-9]{64}$/), name: z.string().max(24),
account: z.boolean().optional() }).strict()).length(2),
winner: z.union([z.literal(0), z.literal(1), z.null()]),
reason: z.string().max(40),
startedAt: z.number().int(),
endedAt: z.number().int(),
decks: z.array(z.array(z.unknown()).max(64)).length(2),
actions: z.array(z.object({ seat: z.union([z.literal(0), z.literal(1)]), action: z.unknown() }).strict()).max(2000),
/** Constructed modes: the NFT token ids each seat played, in deck order (recap references). */
tokens: z.array(z.array(z.string().max(128)).max(64)).length(2).optional(),
}).strict();
export type MatchRecord = z.infer<typeof MatchRecordSchema>;
export type LeaderboardEntry = { playerId: string; name: string; wins: number; losses: number; draws: number; played: number;
/** Elo (start 1200, K 24) from rated matches; null if the player has none in this mode. */
rating: number | null; ratedPlayed: number };
/** Elo constants (engineer review §3). Ratings are recomputed by replaying records in order. */
export const ELO_START = 1200;
export const ELO_K = 24;
/** New ratings for [seat0, seat1] after one game; winner null is a draw. */
export function eloUpdate(r0: number, r1: number, winner: 0 | 1 | null): [number, number] {
const e0 = 1 / (1 + 10 ** ((r1 - r0) / 400));
const s0 = winner === null ? 0.5 : winner === 0 ? 1 : 0;
const d = ELO_K * (s0 - e0);
return [r0 + d, r1 - d];
}
type ModeAgg = { matches: number; players: Map<string, LeaderboardEntry> };
const KEEP_RECENT = 500;
export class MatchStore {
private readonly file: string | null;
private readonly modes = new Map<string, ModeAgg>();
private readonly recent = new Map<string, MatchRecord>();
private readonly allPlayers = new Set<string>();
total = 0;
/** `directory` null keeps records in memory only (tests). */
constructor(directory: string | null) {
this.file = directory ? join(directory, 'matches.jsonl') : null;
if (!directory || !this.file) return;
mkdirSync(directory, { recursive: true, mode: 0o700 });
if (!existsSync(this.file)) return;
for (const line of readFileSync(this.file, 'utf8').split('\n')) {
if (!line.trim()) continue;
const parsed = MatchRecordSchema.safeParse(safeJson(line));
if (parsed.success) this.index(parsed.data); // A torn last line after a crash is skipped.
}
}
add(record: MatchRecord): void {
const valid = MatchRecordSchema.parse(record);
if (this.file) appendFileSync(this.file, JSON.stringify(valid) + '\n', { mode: 0o600 });
this.index(valid);
}
get(matchId: string): MatchRecord | undefined { return this.recent.get(matchId); }
modeMatches(modeId: string): number { return this.modes.get(modeId)?.matches ?? 0; }
modePlayers(modeId: string): number { return this.modes.get(modeId)?.players.size ?? 0; }
distinctPlayers(): number { return this.allPlayers.size; }
leaderboard(modeId: string, limit = 20): LeaderboardEntry[] {
const players = [...(this.modes.get(modeId)?.players.values() ?? [])];
// Rated players first, by Elo; then everyone else by W/L (the cut-order fallback).
return players.sort((a, b) => (b.rating ?? -Infinity) - (a.rating ?? -Infinity) || b.wins - a.wins || a.losses - b.losses ||
b.played - a.played || a.playerId.localeCompare(b.playerId)).slice(0, limit)
.map(p => ({ ...p, rating: p.rating === null ? null : Math.round(p.rating) }));
}
private index(r: MatchRecord): void {
this.total++;
const agg = this.modes.get(r.modeId) ?? { matches: 0, players: new Map() };
this.modes.set(r.modeId, agg);
agg.matches++;
const entries = r.players.map((p, seat) => {
this.allPlayers.add(p.id);
const e = agg.players.get(p.id) ?? { playerId: p.id, name: p.name, wins: 0, losses: 0, draws: 0, played: 0, rating: null, ratedPlayed: 0 };
e.name = p.name; e.played++;
if (r.winner === null) e.draws++; else if (r.winner === seat) e.wins++; else e.losses++;
agg.players.set(p.id, e);
return e;
});
// Elo only for rated matches between two account seats that actually played (no aborted 0-action games).
if (r.rated && r.players.every(p => p.account) && r.actions.length > 0 && r.reason !== 'abandoned') {
const [a, b] = entries as [LeaderboardEntry, LeaderboardEntry];
[a.rating, b.rating] = eloUpdate(a.rating ?? ELO_START, b.rating ?? ELO_START, r.winner);
a.ratedPlayed++; b.ratedPlayed++;
}
this.recent.set(r.matchId, r);
if (this.recent.size > KEEP_RECENT) this.recent.delete(this.recent.keys().next().value!);
}
}
function safeJson(line: string): unknown { try { return JSON.parse(line); } catch { return null; } }