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

291 lines
12 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* "Battle of X (2026)" recap (DUEL_DESIGN.md §8.3). Pure and deterministic: input is the
* match record only. Output is structured data; ui-pvp renders it. All prose is templates
* filled with real card and match data. No LLM, no invented facts.
*/
import { Narrator, renderEvent, variantIndex } from './log.ts';
import { FOOTER, numberWord, ordinalWord } from './templates.ts';
import type { GameOverReason, MatchRecord, Reference, Seat, StoryCard, StoryEvent } from './types.ts';
export interface RecapInfobox {
date: string;
location: string;
result: string;
belligerents: [string, string];
commanders: [string, string];
strength: [string, string];
casualties: [string, string];
}
export interface RecapSection {
heading: string;
paragraphs: string[];
}
export interface RecapDoc {
matchId: string;
/** Path of the shareable page. */
url: string;
masthead: 'WikiDeck';
title: string;
/** Card the battle is named after, if any. */
nameCardId?: string;
infobox: RecapInfobox;
/** Lead paragraph, then Background, Course of the battle, Aftermath, See also. */
lead: string;
sections: RecapSection[];
references: Reference[];
footer: string;
}
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
/** "2026-11-17" → "17 November 2026". */
export function longDate(iso: string): string {
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso);
if (!m) throw new Error(`recap: date must be ISO YYYY-MM-DD, got ${iso}`);
return `${Number(m[3])} ${MONTHS[Number(m[2]) - 1]} ${m[1]}`;
}
interface Played { id: string; seat: Seat; order: number }
interface Facts {
/** For a draw: seat 0, with `draw` set. */
winner: Seat;
draw: boolean;
loser: Seat;
reason: GameOverReason;
turns: number;
life: [number, number];
played: Played[];
destroyed: string[];
}
function facts(record: MatchRecord): Facts {
const over = [...record.events].reverse().find((e): e is Extract<StoryEvent, { kind: 'gameOver' }> => e.kind === 'gameOver');
if (!over) throw new Error('recap: match has no gameOver event');
const start = record.startingLife ?? 20;
const life: [number, number] = [start, start];
const played: Played[] = [];
const destroyed: string[] = [];
record.events.forEach((e, i) => {
if (e.kind === 'playerDamage' || e.kind === 'lifeGain') life[e.seat] = Math.max(0, e.life);
if (e.kind === 'deploy' || e.kind === 'cast') played.push({ id: e.card, seat: e.seat, order: i });
if (e.kind === 'adopt') played.push({ id: e.doctrine, seat: e.seat, order: i });
if (e.kind === 'destroyed') destroyed.push(e.card);
});
if (over.life) { life[0] = Math.max(0, over.life[0]); life[1] = Math.max(0, over.life[1]); }
const winner: Seat = over.winner ?? 0;
return { winner, draw: over.winner === null, loser: winner === 0 ? 1 : 0, reason: over.reason, turns: over.turn, life, played, destroyed };
}
/** Highest cost wins; ties go to the card played first. */
function best(cands: Played[], cards: Record<string, StoryCard>): Played | undefined {
let top: Played | undefined;
for (const c of cands) if (!top || cards[c.id].cost > cards[top.id].cost) top = c;
return top;
}
/** DUEL_DESIGN §8.3 naming order. */
export function battleName(record: MatchRecord, f: Facts = facts(record)): StoryCard | undefined {
const C = record.cards;
const of = (seat: Seat | null, type?: StoryCard['type']) =>
f.played.filter(p => (seat === null || p.seat === seat) && (!type || C[p.id].type === type));
const pick = best(of(f.winner, 'Location'), C) ?? best(of(f.loser, 'Location'), C)
?? best(of(null, 'Event'), C) ?? best(of(f.winner), C) ?? best(of(f.loser), C);
return pick ? C[pick.id] : undefined;
}
export function battleTitle(record: MatchRecord, f: Facts = facts(record)): string {
const card = battleName(record, f);
const year = record.date.slice(0, 4);
if (!card) return `WikiDeck match of ${longDate(record.date)}`;
if (card.type === 'Figure') return `${card.title} campaign (${year})`;
const each = Math.ceil(f.turns / 2);
const prefix = each <= 6 ? 'Skirmish at' : each >= 13 ? 'Siege of' : 'Battle of';
return `${prefix} ${card.title} (${year})`;
}
function resultText(record: MatchRecord, f: Facts): string {
const w = record.players[f.winner].name;
if (f.draw) return 'Inconclusive';
switch (f.reason) {
case 'concede': case 'timeout': return `${w} victory by withdrawal`;
case 'library': return `${w} victory by attrition`;
case 'turnCap': return `${w} victory by decision`;
case 'life': {
if (f.life[f.winner] <= 3) return `Pyrrhic ${w} victory`;
if (f.life[f.winner] - f.life[f.loser] >= 10) return `Decisive ${w} victory`;
return `${w} victory`;
}
}
}
const LEAD_VARIANTS = [
'The {title} was a WikiDeck engagement fought on {date} between the forces of {a} and {b}. It lasted {turns} turns and ended in {result}.',
'The {title} was fought on {date} between {a} and {b}, and lasted {turns} turns. It ended in {result}.',
'The {title} took place on {date}. The forces of {a} and {b} engaged for {turns} turns; the engagement ended in {result}.',
];
const FIRST_DEPLOY_VARIANTS = [
'Contemporary accounts note the deployment of {card} in the {ordinal} turn.',
'Records list {card} as the first Figure deployed, in the {ordinal} turn.',
'The first Figure to enter play was {card}, in the {ordinal} turn.',
];
function pickVariant(record: MatchRecord, salt: string, list: readonly string[]): string {
return list[variantIndex(record.seed, `recap:${salt}`, 0, list.length)];
}
function sub(t: string, v: Record<string, string | number>): string {
return t.replace(/\{(\w+)\}/g, (_, k: string) => String(v[k]));
}
/** The result as a phrase for the lead: "a Pyrrhic victory for bob". */
function resultPhrase(record: MatchRecord, f: Facts): string {
const w = record.players[f.winner].name;
if (f.draw) return 'a draw';
switch (f.reason) {
case 'concede': case 'timeout': return `a victory for ${w} by withdrawal`;
case 'library': return `a victory for ${w} by attrition`;
case 'turnCap': return `a victory for ${w} by decision`;
case 'life': {
if (f.life[f.winner] <= 3) return `a Pyrrhic victory for ${w}`;
if (f.life[f.winner] - f.life[f.loser] >= 10) return `a decisive victory for ${w}`;
return `a victory for ${w}`;
}
}
}
export function recap(record: MatchRecord): RecapDoc {
const f = facts(record);
const C = record.cards;
const nar = new Narrator(record, 'recap');
const [a, b] = [record.players[0].name, record.players[1].name];
const nameCard = battleName(record, f);
const title = battleTitle(record, f);
const result = resultText(record, f);
// Lead: cite the name card first so it is reference [1].
const nameRef = nameCard ? `[${nar.cite(nameCard.id)}]` : '';
let lead = sub(pickVariant(record, 'lead', LEAD_VARIANTS), {
title: `**${title}**`, date: longDate(record.date), a, b, turns: numberWord(f.turns), result: resultPhrase(record, f),
}) + nameRef;
const firstFig = record.events.findIndex(e => e.kind === 'deploy' && C[e.card].type === 'Figure');
if (firstFig >= 0) {
const ev = record.events[firstFig] as Extract<StoryEvent, { kind: 'deploy' }>;
const turn = turnAt(record.events, firstFig);
const t = pickVariant(record, 'firstDeploy', FIRST_DEPLOY_VARIANTS);
const card = nar.mention(ev.card);
const refs = nar.flush();
lead += ' ' + sub(t, { card, ordinal: ordinalWord(turn) }) + refs.map(r => `[${r}]`).join('');
}
// Background: Portal mix of the cards each side played.
const background: string[] = [];
for (const seat of [0, 1] as Seat[]) {
const mine = f.played.filter(p => p.seat === seat);
if (!mine.length) { background.push(`${record.players[seat].name} played no cards.`); continue; }
const counts = new Map<string, number>();
for (const p of mine) { const k = C[p.id].portal ?? 'Neutral'; counts.set(k, (counts.get(k) ?? 0) + 1); }
const sorted = [...counts.entries()].sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0]));
const max = sorted[0][1];
const tops = sorted.filter(([, n]) => n === max).map(([k]) => k);
const name = record.players[seat].name;
const played = `${numberWord(mine.length)} ${mine.length === 1 ? 'card' : 'cards'} played`;
if (tops.length === 1) background.push(`${tops[0]} was the largest Portal in the force of ${name} (${numberWord(max)} of ${played}).`);
else background.push(`${listJoin(tops)} were equally represented in the force of ${name} (${numberWord(max)} ${max === 1 ? 'card' : 'cards'} each, of ${played}).`);
}
// Course of the battle: the largest Notability swings and destroyed cards of cost ≥ 4.
const swings = record.events
.map((e, i) => ({ e, i }))
.filter(x => x.e.kind === 'playerDamage')
.sort((x, y) => (y.e as { amount: number }).amount - (x.e as { amount: number }).amount || x.i - y.i)
.slice(0, 5).map(x => x.i);
const big = record.events.map((e, i) => ({ e, i }))
.filter(x => x.e.kind === 'destroyed' && C[(x.e as { card: string }).card].cost >= 4).map(x => x.i);
const chosen = [...new Set([...swings, ...big])].sort((x, y) => x - y);
const course: string[] = [];
let curTurn = -1;
let para: string[] = [];
for (const i of chosen) {
const t = turnAt(record.events, i);
if (t !== curTurn && para.length) { course.push(para.join(' ')); para = []; }
if (t !== curTurn) para.push(`In the ${ordinalWord(t)} turn,`);
curTurn = t;
const out = renderEvent(nar, record.events[i], i, null, { preferSource: true });
if (out) para.push(out.text);
}
if (para.length) course.push(para.join(' '));
const over = record.events.findIndex(e => e.kind === 'gameOver');
const end = renderEvent(nar, record.events[over], over, null);
if (end) course.push(end.text);
// Aftermath.
const aftermath = [f.draw
? `Both ${a} and ${b} ended the engagement with ${f.life[0]} Notability.`
: `${record.players[f.winner].name} ended the engagement with ${f.life[f.winner]} Notability; ${record.players[f.loser].name} ended with ${f.life[f.loser]}.`,
];
if (record.ratingChange) {
const fmt = (n: number) => (n >= 0 ? `+${n}` : `${n}`);
aftermath.push(`Ratings changed by ${fmt(record.ratingChange[0])} for ${a} and ${fmt(record.ratingChange[1])} for ${b}.`);
}
// See also: Connected pairs and rivalries.
const seeAlso: string[] = [];
for (const e of record.events) {
if (e.kind === 'connected' || e.kind === 'rivalry') seeAlso.push(`*${C[e.a].title}* – *${C[e.b].title}* (${e.reason})`);
}
// References: every card played, in first-mention order.
for (const p of f.played) nar.cite(p.id);
const perSeat = (fn: (s: Seat) => string): [string, string] => [fn(0), fn(1)];
const infobox: RecapInfobox = {
date: longDate(record.date),
location: nameCard?.type === 'Location' ? nameCard.title : `WikiDeck host ${record.hostName ?? 'unknown'}`,
result,
belligerents: [a, b],
commanders: perSeat(s => {
const c = best(f.played.filter(p => p.seat === s && C[p.id].type === 'Figure'), C);
return c ? C[c.id].title : 'None recorded';
}),
strength: perSeat(s => cards(f.played.filter(p => p.seat === s).length)),
casualties: perSeat(s => {
const lost = f.destroyed.filter(id => C[id].owner === s).map(id => C[id].title);
return lost.length ? `${cards(lost.length)} destroyed: ${lost.join(', ')}` : 'None';
}),
};
const sections: RecapSection[] = [
{ heading: 'Background', paragraphs: background },
{ heading: 'Course of the battle', paragraphs: course },
{ heading: 'Aftermath', paragraphs: aftermath },
];
if (seeAlso.length) sections.push({ heading: 'See also', paragraphs: seeAlso });
return {
matchId: record.matchId,
url: `/recap/${encodeURIComponent(record.matchId)}`,
masthead: 'WikiDeck',
title,
nameCardId: nameCard?.id,
infobox,
lead,
sections,
references: nar.references,
footer: FOOTER,
};
}
function listJoin(xs: string[]): string {
return xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`;
}
function cards(n: number): string { return `${n} ${n === 1 ? 'card' : 'cards'}`; }
function turnAt(events: StoryEvent[], index: number): number {
for (let i = index; i >= 0; i--) { const e = events[i]; if (e.kind === 'turnStart') return e.turn; }
return 0;
}