From 94966277ef51693b15d4eac8ef274308099f686b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:42:44 -0500 Subject: [PATCH] WIP (no PR): story layer + fromDuel adapter on duel-core contracts; PR follows #72 merge Co-Authored-By: Claude Opus 5.5 --- shared/duel/story/fromDuel.ts | 117 +++++++++++ shared/duel/story/index.ts | 6 + shared/duel/story/log.ts | 196 +++++++++++++++++++ shared/duel/story/recap.ts | 290 ++++++++++++++++++++++++++++ shared/duel/story/templates.ts | 156 +++++++++++++++ shared/duel/story/types.ts | 98 ++++++++++ tests/duel-design-fromduel.test.ts | 72 +++++++ tests/duel-design-story.golden.json | 50 +++++ tests/duel-design-story.test.ts | 256 ++++++++++++++++++++++++ 9 files changed, 1241 insertions(+) create mode 100644 shared/duel/story/fromDuel.ts create mode 100644 shared/duel/story/index.ts create mode 100644 shared/duel/story/log.ts create mode 100644 shared/duel/story/recap.ts create mode 100644 shared/duel/story/templates.ts create mode 100644 shared/duel/story/types.ts create mode 100644 tests/duel-design-fromduel.test.ts create mode 100644 tests/duel-design-story.golden.json create mode 100644 tests/duel-design-story.test.ts diff --git a/shared/duel/story/fromDuel.ts b/shared/duel/story/fromDuel.ts new file mode 100644 index 0000000..9c950b8 --- /dev/null +++ b/shared/duel/story/fromDuel.ts @@ -0,0 +1,117 @@ +/** + * Adapter: duel-core's LogEvent[] (shared/duel/types.ts) → story MatchRecord (DUEL_DESIGN §8). + * Pure. Pass the omniscient `state.log` for recaps, or `logFor(state, seat)` output for a seat's log + * (hidden draws there have no `card`, and stay hidden). + */ +import type { CardInstance, CardRef, LogEvent } from '../types.ts'; +import type { MatchRecord, Seat, StoryCard, StoryEvent, StoryPlayer } from './types.ts'; + +export interface FromDuelInput { + matchId: string; + /** Story seed, opaque: the host derives it (sha256(engineSeed + ':story')). Never the engine seed. */ + storySeed: string; + /** ISO YYYY-MM-DD. */ + date: string; + players: [StoryPlayer, StoryPlayer]; + /** Every card instance of both decks (tokens are picked up from the log). */ + instances: CardInstance[]; + log: LogEvent[]; + startingLife?: number; + hostName?: string; + ratingChange?: [number, number]; +} + +function storyCard(inst: CardInstance): StoryCard { + const c = inst.card; + return { + id: inst.uid, title: c.title, description: c.description, type: c.type, cost: c.cost, portal: c.portal, + revisionId: c.token ? undefined : c.revisionId, tokenId: c.token ? undefined : c.cardId, owner: inst.owner, + token: c.token || undefined, + }; +} + +export function fromDuel(input: FromDuelInput): MatchRecord { + const cards: Record = {}; + for (const inst of input.instances) cards[inst.uid] = storyCard(inst); + /** Tokens (and anything not in the decks) come from their log CardRef: never cited. */ + const ref = (r: CardRef, owner: Seat): string => { + if (!cards[r.uid]) cards[r.uid] = { id: r.uid, title: r.title, type: r.type, cost: 0, owner, token: true }; + return r.uid; + }; + const events: StoryEvent[] = []; + let lastTurn = 0; + for (const e of input.log) { + switch (e.kind) { + case 'turnStart': + lastTurn = e.turn; + events.push({ kind: 'turnStart', turn: e.turn, seat: e.seat }); + break; + case 'draw': + events.push(e.card ? { kind: 'draw', seat: e.seat, card: ref(e.card, e.seat) } : { kind: 'draw', seat: e.seat }); + break; + case 'deploy': + events.push({ kind: 'deploy', seat: e.seat, card: ref(e.card, e.seat) }); + break; + case 'cast': + events.push({ kind: 'cast', seat: e.seat, card: ref(e.card, e.seat) }); + break; + case 'adopt': + events.push({ + kind: 'adopt', seat: e.seat, doctrine: ref(e.card, e.seat), figure: ref(e.to, e.seat), + power: e.to.power ?? 0, toughness: e.to.toughness ?? 0, + }); + break; + case 'tokenCreated': { + const prev = events[events.length - 1]; + const src = ref(e.source, e.seat); + ref(e.card, e.seat); + if (prev && prev.kind === 'tokenCreated' && prev.source === src && prev.token === e.card.title) prev.count += 1; + else events.push({ kind: 'tokenCreated', seat: e.seat, source: src, token: e.card.title, count: 1 }); + break; + } + case 'connected': + events.push({ kind: 'connected', seat: e.seat, a: ref(e.card, e.seat), b: ref(e.with, e.seat), reason: e.via }); + break; + case 'rivalry': + events.push({ kind: 'rivalry', a: ref(e.card, 0), b: ref(e.with, 1), reason: e.via }); + break; + case 'attack': + for (const a of e.attackers) events.push({ kind: 'attack', seat: e.seat, card: ref(a, e.seat), power: a.power ?? 0, toughness: a.toughness ?? 0 }); + break; + case 'block': + for (const b of e.blocks) { + events.push({ + kind: 'block', seat: e.seat, blocker: ref(b.blocker, e.seat), attacker: ref(b.attacker, e.seat === 0 ? 1 : 0), + power: b.blocker.power ?? 0, toughness: b.blocker.toughness ?? 0, + }); + } + break; + case 'lifeGain': + events.push({ kind: 'lifeGain', seat: e.seat, source: ref(e.source, e.seat), amount: e.amount, life: e.life }); + break; + case 'effectDamage': + events.push({ kind: 'effectDamage', source: ref(e.source, 0), target: ref(e.target, 0), amount: e.amount }); + break; + case 'playerDamage': + events.push({ kind: 'playerDamage', seat: e.seat, source: e.source ? ref(e.source, e.seat === 0 ? 1 : 0) : undefined, amount: e.amount, life: e.life }); + break; + case 'destroyed': + events.push({ kind: 'destroyed', card: ref(e.card, e.owner) }); + break; + case 'discard': + events.push({ kind: 'discard', seat: e.seat, card: ref(e.card, e.seat) }); + break; + case 'gameOver': + events.push({ kind: 'gameOver', winner: e.winner, reason: e.reason, turn: e.turn || lastTurn, life: e.life }); + break; + // start, mulligan, keep, effect, combatDamage, bounced, fatigue, concede, timeout: + // not narrated in v1 (combat outcomes are told by destroyed/playerDamage; gameOver covers concede/timeout). + default: + break; + } + } + return { + matchId: input.matchId, seed: input.storySeed, date: input.date, players: input.players, cards, events, + startingLife: input.startingLife, hostName: input.hostName, ratingChange: input.ratingChange, + }; +} diff --git a/shared/duel/story/index.ts b/shared/duel/story/index.ts new file mode 100644 index 0000000..a6bb5b7 --- /dev/null +++ b/shared/duel/story/index.ts @@ -0,0 +1,6 @@ +/** Story layer for the duel (DUEL_DESIGN.md §8): match log and battle recap templates. */ +export * from './types.ts'; +export { LOG_TEMPLATES, BANNED_WORDS, FOOTER, fill, numberWord, ordinalWord } from './templates.ts'; +export { Narrator, renderEvent, renderLog, logParagraphs, gloss, articleUrl, variantIndex, tokenName } from './log.ts'; +export { recap, battleName, battleTitle, longDate } from './recap.ts'; +export type { RecapDoc, RecapInfobox, RecapSection } from './recap.ts'; diff --git a/shared/duel/story/log.ts b/shared/duel/story/log.ts new file mode 100644 index 0000000..6b18022 --- /dev/null +++ b/shared/duel/story/log.ts @@ -0,0 +1,196 @@ +/** + * Deterministic match log (DUEL_DESIGN.md §8.2). Pure: the same MatchRecord always gives the + * same lines, so `replay` and stored records regenerate the log exactly. No network, no clock. + */ +import { Rng } from '../../game/rng.ts'; +import { LOG_TEMPLATES, fill, numberWord, type TemplateKey } from './templates.ts'; +import type { LogLine, MatchRecord, Reference, Seat, StoryCard, StoryEvent } from './types.ts'; + +/** Deterministic variant choice: one fresh mulberry32 per (seed, salt, event index). */ +export function variantIndex(seed: number | string, salt: string, index: number, n: number): number { + return Rng.fromSeed(`${seed}|${salt}|${index}`).int(n); +} + +/** "American actor (1909–1994)" → "American actor, 1909–1994". Verbatim otherwise. */ +export function gloss(description: string | undefined): string { + const d = (description ?? '').trim(); + if (!d) return ''; + const m = /^(.*\S)\s*\(([^()]+)\)$/.exec(d); + return m ? `${m[1]}, ${m[2]}` : d; +} + +export function articleUrl(title: string, revisionId: number): string { + return `https://en.wikipedia.org/w/index.php?title=${encodeURIComponent(title.replace(/ /g, '_'))}&oldid=${revisionId}`; +} + +/** + * Tracks first mentions and reference numbers for one rendering (a log view or a recap). + * The first mention of a card in a rendering adds its description and the next [n]. + */ +export class Narrator { + readonly record: MatchRecord; + readonly salt: string; + readonly references: Reference[] = []; + private refByCard = new Map(); + private pending: number[] = []; + + constructor(record: MatchRecord, salt: string) { + this.record = record; + this.salt = salt; + } + + card(id: string): StoryCard { + const c = this.record.cards[id]; + if (!c) throw new Error(`story: unknown card id ${id}`); + return c; + } + + player(seat: Seat): string { return this.record.players[seat].name; } + + /** Assigns a reference number without mentioning the card (e.g. for the References list). Tokens get none (0). */ + cite(id: string): number { + let n = this.refByCard.get(id); + if (n === undefined) { + const c = this.card(id); + if (c.token || c.revisionId === undefined) return 0; + n = this.references.length + 1; + this.refByCard.set(id, n); + this.references.push({ + n, cardId: id, title: c.title, revisionId: c.revisionId, tokenId: c.tokenId, + url: articleUrl(c.title, c.revisionId), + text: `"${c.title}". Wikipedia. Revision ${c.revisionId}.${c.tokenId ? ` Minted as token ${c.tokenId}.` : ''}`, + }); + } + return n; + } + + /** A card's name for a sentence: italic, with its description on first mention. */ + mention(id: string): string { + const c = this.card(id); + if (c.token || c.revisionId === undefined) return c.title; + const first = !this.refByCard.has(id); + const n = this.cite(id); + if (!first) return `*${c.title}*`; + this.pending.push(n); + const g = gloss(c.description); + return g ? `*${c.title}* (${g})` : `*${c.title}*`; + } + + /** Take the citations of first mentions made since the last sentence. */ + flush(): number[] { + const refs = this.pending; + this.pending = []; + return refs; + } + + /** Fill a variant of `key` and append the citations of first mentions made while filling. */ + sentence(key: TemplateKey, index: number, values: Record string | number>, must: string[] = []): { text: string; refs: number[] } { + const fits = (t: string) => [...t.matchAll(/\{(\w+)\}/g)].every(m => m[1] in values); + const all = LOG_TEMPLATES[key].filter(fits); + const preferred = all.filter(t => must.every(k => t.includes(`{${k}}`))); + const usable = preferred.length ? preferred : all; + if (!usable.length) throw new Error(`story: no usable template for ${key}`); + const template = usable[variantIndex(this.record.seed, `${this.salt}:${key}`, index, usable.length)]; + // Evaluate placeholders in template order so first mentions are numbered left to right. + const filled: Record = {}; + for (const m of template.matchAll(/\{(\w+)\}/g)) if (!(m[1] in filled)) filled[m[1]] = values[m[1]](); + const refs = this.flush(); + const body = fill(template, filled); + return { text: body + refs.map(r => `[${r}]`).join(''), refs }; + } +} + +/** Pluralise a fixed token name ("Staff Member" → "Staff Members"). */ +export function tokenName(token: string, count: number): string { + return count === 1 ? token : `${token}s`; +} + +/** + * Render one event as a sentence, or null if it is not shown to this viewer. + * `viewer` null = omniscient (post-match, spectators after the end). + */ +export interface RenderOptions { + /** Prefer variants that name the source card (the recap uses this for damage lines). */ + preferSource?: boolean; +} + +export function renderEvent(nar: Narrator, ev: StoryEvent, index: number, viewer: Seat | null, opts: RenderOptions = {}): { text: string; refs: number[] } | null { + const P = (s: Seat) => () => nar.player(s); + const M = (id: string) => () => nar.mention(id); + const N = (n: number) => () => n; + const other = (s: Seat): Seat => (s === 0 ? 1 : 0); + switch (ev.kind) { + case 'turnStart': + return { text: `Turn ${ev.turn}.`, refs: [] }; + case 'deploy': + return nar.sentence('deploy', index, { player: P(ev.seat), card: M(ev.card) }); + case 'cast': + return nar.sentence('cast', index, { player: P(ev.seat), card: M(ev.card) }); + case 'adopt': + return nar.sentence('adopt', index, { player: P(ev.seat), doctrine: M(ev.doctrine), figure: M(ev.figure), p: N(ev.power), t: N(ev.toughness) }); + case 'attack': + return nar.sentence('attack', index, { player: P(ev.seat), opponent: P(other(ev.seat)), card: M(ev.card), p: N(ev.power), t: N(ev.toughness) }); + case 'block': + return nar.sentence('block', index, { player: P(ev.seat), blocker: M(ev.blocker), attacker: M(ev.attacker), p: N(ev.power), t: N(ev.toughness) }); + case 'playerDamage': { + const v: Record string | number> = { player: P(ev.seat), n: N(ev.amount), life: N(Math.max(0, ev.life)) }; + if (ev.source) v.source = M(ev.source); + return nar.sentence('playerDamage', index, v, opts.preferSource && ev.source ? ['source'] : []); + } + case 'lifeGain': + return nar.sentence('lifeGain', index, { player: P(ev.seat), source: M(ev.source), n: N(ev.amount), life: N(ev.life) }); + case 'effectDamage': + return nar.sentence('effectDamage', index, { source: M(ev.source), target: M(ev.target), n: N(ev.amount) }); + case 'destroyed': + return nar.sentence('destroyed', index, { card: M(ev.card) }); + case 'tokenCreated': + return nar.sentence('tokenCreated', index, { + source: M(ev.source), count: () => numberWord(ev.count), token: () => tokenName(ev.token, ev.count), + }); + case 'draw': { + const count = ev.count ?? 1; + const visible = ev.card !== undefined && (viewer === null || viewer === ev.seat); + if (visible) return nar.sentence('drawKnown', index, { player: P(ev.seat), card: M(ev.card as string) }); + if (count > 1) return nar.sentence('drawHiddenMany', index, { player: P(ev.seat), count: () => numberWord(count) }); + return nar.sentence('drawHidden', index, { player: P(ev.seat) }); + } + case 'discard': + return nar.sentence('discard', index, { player: P(ev.seat), card: M(ev.card) }); + case 'connected': + return nar.sentence('connected', index, { a: M(ev.a), b: M(ev.b), reason: () => ev.reason }); + case 'rivalry': + return nar.sentence('rivalry', index, { a: M(ev.a), b: M(ev.b), reason: () => ev.reason }); + case 'gameOver': { + if (ev.winner === null) return nar.sentence('gameOverDraw', index, { turn: N(ev.turn) }); + const key = ({ life: 'gameOverLife', library: 'gameOverLibrary', concede: 'gameOverConcede', timeout: 'gameOverTimeout', turnCap: 'gameOverTurnCap' } as const)[ev.reason]; + return nar.sentence(key, index, { winner: P(ev.winner), loser: P(other(ev.winner)), turn: N(ev.turn) }); + } + } +} + +/** The match log for one viewer (DUEL_DESIGN §8.2). Hidden draws by the opponent stay hidden. */ +export function renderLog(record: MatchRecord, viewer: Seat | null = null): { lines: LogLine[]; references: Reference[] } { + const nar = new Narrator(record, 'log'); + const lines: LogLine[] = []; + let turn = 0; + record.events.forEach((ev, i) => { + if (ev.kind === 'turnStart') turn = ev.turn; + const out = renderEvent(nar, ev, i, viewer); + if (out) lines.push({ turn, ...out }); + }); + return { lines, references: nar.references }; +} + +/** Join lines into one paragraph per turn: "Turn 5. alice deployed …". */ +export function logParagraphs(lines: LogLine[]): string[] { + const out: string[] = []; + let cur: string[] = []; + let curTurn = -1; + for (const l of lines) { + if (l.turn !== curTurn && cur.length) { out.push(cur.join(' ')); cur = []; } + curTurn = l.turn; + cur.push(l.text); + } + if (cur.length) out.push(cur.join(' ')); + return out; +} diff --git a/shared/duel/story/recap.ts b/shared/duel/story/recap.ts new file mode 100644 index 0000000..721db36 --- /dev/null +++ b/shared/duel/story/recap.ts @@ -0,0 +1,290 @@ +/** + * "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 => 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): 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 { + 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; + 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(); + 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; +} diff --git a/shared/duel/story/templates.ts b/shared/duel/story/templates.ts new file mode 100644 index 0000000..b63b98c --- /dev/null +++ b/shared/duel/story/templates.ts @@ -0,0 +1,156 @@ +/** + * Match-log sentence templates (DUEL_DESIGN.md §8.2). Data only. + * + * Tone (BRIEF decision 5, DUEL_DESIGN §8.1): past tense, encyclopedic, deadpan. No adjectives + * about cards or players, no exclamation marks, never comment on the matchup. Placeholders + * are filled only with real card and match data. `tests/duel-design-story.test.ts` lints this file. + * + * Placeholders: {player} {opponent} {card} {doctrine} {figure} {attacker} {blocker} {source} + * {target} {token} {a} {b} {reason} {winner} {loser} {n} {count} {p} {t} {life} {turn}. + */ +export const LOG_TEMPLATES = { + deploy: [ + '{player} deployed {card}.', + '{card} was deployed by {player}.', + '{player} brought {card} into play.', + '{card} entered play under {player}.', + ], + cast: [ + '{player} cited {card}.', + '{card} was cited by {player}.', + '{player} invoked {card}.', + ], + adopt: [ + '{doctrine} was adopted by {figure}, which became a {p}/{t}.', + '{figure} adopted {doctrine} and became a {p}/{t}.', + '{player} attached {doctrine} to {figure} ({p}/{t}).', + ], + attack: [ + '{card} ({p}/{t}) attacked.', + '{player} sent {card} ({p}/{t}) into combat.', + '{card} ({p}/{t}) advanced on {opponent}.', + ], + block: [ + '{blocker} ({p}/{t}) blocked {attacker}.', + '{attacker} was blocked by {blocker} ({p}/{t}).', + '{blocker} ({p}/{t}) intercepted {attacker}.', + ], + playerDamage: [ + '{player} lost {n} Notability ({life} remaining).', + '{source} dealt {n} damage to {player}, leaving {life} Notability.', + "{player}'s Notability fell to {life}.", + ], + lifeGain: [ + '{player} gained {n} Notability from {source} ({life} total).', + '{source} restored {n} Notability to {player}.', + "{player}'s Notability rose to {life} ({source}).", + ], + effectDamage: [ + '{source} dealt {n} damage to {target}.', + '{target} took {n} damage from {source}.', + '{source} inflicted {n} damage on {target}.', + ], + destroyed: [ + '{card} was destroyed.', + '{card} was moved to Deleted.', + '{card} was removed from play.', + '{card} did not survive the turn.', + ], + tokenCreated: [ + '{source} produced {count} {token}.', + '{source} brought {count} {token} into play.', + '{source} created {count} {token}.', + ], + drawKnown: [ + '{player} drew {card}.', + '{card} was drawn by {player}.', + '{player} added {card} to their hand.', + ], + drawHidden: [ + '{player} drew a card.', + '{player} drew one card.', + '{player} added a card to their hand.', + ], + drawHiddenMany: [ + '{player} drew {count} cards.', + '{player} added {count} cards to their hand.', + '{player} took {count} cards into hand.', + ], + discard: [ + '{player} discarded {card}.', + '{card} was discarded by {player}.', + '{player} moved {card} from hand to Deleted.', + ], + connected: [ + '{a} and {b} were Connected ({reason}).', + '{a} was Connected to {b} through {reason}.', + 'Records link {a} and {b} ({reason}).', + ], + rivalry: [ + '{a} and {b} are both listed under {reason}.', + '{a} and {b} share {reason}.', + 'The two sides were linked through {reason}.', + ], + gameOverLife: [ + '{loser} was nominated for deletion. The result was **delete**.', + '{loser} was reduced to 0 Notability. {winner} won.', + '{winner} won on turn {turn}.', + ], + gameOverDraw: [ + 'Both sides were reduced to 0 Notability. The engagement ended in a draw.', + 'The engagement ended in a draw on turn {turn}.', + 'Neither side retained any Notability. No winner was recorded.', + ], + gameOverLibrary: [ + '{loser} could not draw a card and lost.', + '{loser} ran out of cards. {winner} won.', + "{loser}'s library was exhausted. {winner} won.", + ], + gameOverConcede: [ + '{loser} withdrew.', + '{loser} withdrew. {winner} won.', + '{loser} conceded on turn {turn}.', + ], + gameOverTimeout: [ + '{loser} did not respond in time and withdrew.', + '{loser} ran out of time. {winner} won.', + "{loser}'s clock expired on turn {turn}.", + ], + gameOverTurnCap: [ + '{winner} won on Notability at the turn limit.', + 'The turn limit was reached. {winner} won on Notability.', + 'The engagement reached the turn limit; {winner} held more Notability.', + ], +} as const satisfies Record; + +export type TemplateKey = keyof typeof LOG_TEMPLATES; + +/** Words the generator must never emit (critic S7 failure modes). Lowercase; whole words. */ +export const BANNED_WORDS = [ + 'brutal', 'brutally', 'heroic', 'heroically', 'humiliating', 'humiliated', 'bloodiest', 'bloody', + 'surprising', 'surprisingly', 'ironically', 'unlikely', 'hilarious', 'tragic', 'tragically', 'sadly', + 'unfortunately', 'poor', 'epic', 'crushed', 'squashed', 'killed', 'murdered', 'destroyed utterly', 'lol', +]; + +export const FOOTER = + 'This page records a WikiDeck match. Card names refer to Wikipedia articles; the events described are game events.'; + +const NUMBER_WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', + 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty']; +export function numberWord(n: number): string { + return Number.isInteger(n) && n >= 0 && n < NUMBER_WORDS.length ? NUMBER_WORDS[n] : String(n); +} +const ORDINALS = ['zeroth', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', + 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth', 'twentieth']; +export function ordinalWord(n: number): string { + if (Number.isInteger(n) && n >= 0 && n < ORDINALS.length) return ORDINALS[n]; + const s = n % 100 >= 11 && n % 100 <= 13 ? 'th' : ({ 1: 'st', 2: 'nd', 3: 'rd' } as Record)[n % 10] ?? 'th'; + return `${n}${s}`; +} + +export function fill(template: string, values: Record): string { + return template.replace(/\{(\w+)\}/g, (whole, key: string) => { + if (!(key in values)) throw new Error(`story template is missing a value for {${key}}: ${template}`); + return String(values[key]); + }); +} diff --git a/shared/duel/story/types.ts b/shared/duel/story/types.ts new file mode 100644 index 0000000..a740207 --- /dev/null +++ b/shared/duel/story/types.ts @@ -0,0 +1,98 @@ +/** + * Story input contract (DUEL_DESIGN.md §8). This is the minimal, engine-agnostic shape the + * match-log and recap templates read. `fromDuel.ts` (added after duel-core's + * shared/duel/types.ts merges) maps engine LogEvents onto it. Everything is plain JSON, + * so a stored match record can regenerate its log and recap exactly. + */ +export type Seat = 0 | 1; +export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine'; + +/** One card instance in the match, frozen from its derived profile. Only real data. */ +export interface StoryCard { + /** Engine instance id, unique within the match. */ + id: string; + /** Article title, verbatim. */ + title: string; + /** Wikidata short description, verbatim ('' or undefined if none). */ + description?: string; + type: CardType; + cost: number; + /** Portal (faction): Arts, Earth, History, Science, Society or Neutral. */ + portal?: string; + /** The article revision the card was minted from (on-chain). Absent for tokens: they are never cited. */ + revisionId?: number; + /** Tokens (Elected Member, Staff Member): generic, not articles, never cited or glossed. */ + token?: boolean; + /** On-chain token id of the mint, if known. */ + tokenId?: string; + /** Seat that owns the card in this match. */ + owner: Seat; +} + +export type GameOverReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap'; + +export type StoryEvent = + | { kind: 'turnStart'; turn: number; seat: Seat } + | { kind: 'deploy'; seat: Seat; card: string } + | { kind: 'cast'; seat: Seat; card: string } + | { kind: 'adopt'; seat: Seat; doctrine: string; figure: string; power: number; toughness: number } + | { kind: 'attack'; seat: Seat; card: string; power: number; toughness: number } + | { kind: 'block'; seat: Seat; blocker: string; attacker: string; power: number; toughness: number } + /** `seat` is the player who lost Notability; `life` is what remains. */ + | { kind: 'playerDamage'; seat: Seat; source?: string; amount: number; life: number } + /** `life` is the new total. */ + | { kind: 'lifeGain'; seat: Seat; source: string; amount: number; life: number } + | { kind: 'effectDamage'; source: string; target: string; amount: number } + | { kind: 'destroyed'; card: string } + | { kind: 'tokenCreated'; seat: Seat; source: string; token: string; count: number } + /** `card` set when the drawn card is known to the viewer's record; hidden draws omit it. */ + | { kind: 'draw'; seat: Seat; card?: string; count?: number } + /** Deleted is public (DUEL_DESIGN §2.3): discards are always named. */ + | { kind: 'discard'; seat: Seat; card: string } + | { kind: 'connected'; seat: Seat; a: string; b: string; reason: string } + | { kind: 'rivalry'; a: string; b: string; reason: string } + /** winner null = draw (both players reached 0 at once). */ + /** `life`: final Notability per seat, authoritative when present (duel-core carries it). */ + | { kind: 'gameOver'; winner: Seat | null; reason: GameOverReason; turn: number; life?: [number, number] }; + +export interface StoryPlayer { + /** Display name of the seat (account display name or "Bot (Normal)"). */ + name: string; +} + +export interface MatchRecord { + matchId: string; + /** + * Story seed: drives template variants only. NOT the engine seed: a client rendering + * logFor text must never learn the engine seed (it would reveal library order). The host + * derives it, e.g. sha256(engineSeed + ':story'). Recaps after the match may use either. + */ + seed: number | string; + /** Match date, ISO `YYYY-MM-DD`. No clock is read by the story code. */ + date: string; + players: [StoryPlayer, StoryPlayer]; + cards: Record; + events: StoryEvent[]; + startingLife?: number; + hostName?: string; + /** Ranked matches: rating change per seat. */ + ratingChange?: [number, number]; +} + +export interface LogLine { + turn: number; + text: string; + /** Reference numbers cited by this line, in order. */ + refs: number[]; +} + +export interface Reference { + n: number; + cardId: string; + title: string; + revisionId: number; + tokenId?: string; + url: string; + /** Rendered citation line, without the leading number. */ + text: string; +} diff --git a/tests/duel-design-fromduel.test.ts b/tests/duel-design-fromduel.test.ts new file mode 100644 index 0000000..0e9f972 --- /dev/null +++ b/tests/duel-design-fromduel.test.ts @@ -0,0 +1,72 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import type { CardInstance, CardRef, DuelCard, LogEvent } from '../shared/duel/types.ts'; +import { fromDuel } from '../shared/duel/story/fromDuel.ts'; +import { recap, renderLog } from '../shared/duel/story/index.ts'; + +function duelCard(cardId: string, title: string, type: DuelCard['type'], cost: number, extra: Partial = {}): DuelCard { + return { + cardId, pageId: 1, revisionId: 1000 + cost, title, description: `${title} description`, type, subtype: null, + portal: 'Society', cost, power: type === 'Figure' ? 2 : null, toughness: type === 'Figure' ? 2 : null, + keywords: [], effects: [], rulesText: '', flavor: '', ...extra, + }; +} +const inst: CardInstance[] = [ + { uid: '0:0', owner: 0, card: duelCard('tokA', 'Pathrail Mosque', 'Location', 2) }, + { uid: '0:1', owner: 0, card: duelCard('tokB', 'Tom Ewell', 'Figure', 6) }, + { uid: '1:0', owner: 1, card: duelCard('tokC', '1954 Gold Coast general election', 'Event', 3) }, + { uid: '1:1', owner: 1, card: duelCard('tokD', "Pallas's cat", 'Figure', 6) }, +]; +const R = (i: CardInstance, p?: number, t?: number): CardRef => + ({ uid: i.uid, cardId: i.card.cardId, title: i.card.title, pageId: i.card.pageId, type: i.card.type, power: p, toughness: t }); +const tok1: CardRef = { uid: 't:1', cardId: 'token:elected', title: 'Elected Member', pageId: null, type: 'Figure', power: 1, toughness: 1 }; +const tok2: CardRef = { ...tok1, uid: 't:2' }; +let seq = 0; +const E = (turn: number, e: Record) => ({ seq: seq++, turn, ...e }) as LogEvent; +const log: LogEvent[] = [ + E(0, { kind: 'start', firstSeat: 0 }), + E(1, { kind: 'turnStart', seat: 0, citations: 1, life: [20, 20] }), + E(1, { kind: 'deploy', seat: 0, card: R(inst[0], 0, 3) }), + E(2, { kind: 'turnStart', seat: 1, citations: 1, life: [20, 20] }), + E(2, { kind: 'draw', seat: 1 }), + E(2, { kind: 'cast', seat: 1, card: R(inst[2]), targets: [] }), + E(2, { kind: 'tokenCreated', seat: 1, card: tok1, source: R(inst[2]) }), + E(2, { kind: 'tokenCreated', seat: 1, card: tok2, source: R(inst[2]) }), + E(3, { kind: 'turnStart', seat: 0, citations: 2, life: [20, 20] }), + E(3, { kind: 'draw', seat: 0, card: R(inst[1]) }), + E(3, { kind: 'deploy', seat: 0, card: R(inst[1], 5, 5) }), + E(4, { kind: 'turnStart', seat: 1, citations: 2, life: [20, 20] }), + E(4, { kind: 'attack', seat: 1, attackers: [R(inst[3], 5, 5), tok1] }), + E(4, { kind: 'block', seat: 0, blocks: [{ blocker: R(inst[1], 5, 5), attacker: tok1 }] }), + E(4, { kind: 'combatDamage', source: tok1, target: R(inst[1]), amount: 1 }), + E(4, { kind: 'destroyed', card: tok1, owner: 1 }), + E(4, { kind: 'playerDamage', source: R(inst[3]), seat: 0, amount: 5, life: 15, combat: true }), + E(4, { kind: 'lifeGain', source: R(inst[3]), seat: 1, amount: 2, life: 22 }), + E(4, { kind: 'concede', seat: 0 }), + E(4, { kind: 'gameOver', winner: 1, reason: 'concede', life: [15, 22] }), +]; + +test('fromDuel maps duel-core LogEvents onto the story record', () => { + const rec = fromDuel({ + matchId: 'm1', storySeed: 'story-seed', date: '2026-11-17', + players: [{ name: 'alice' }, { name: 'bob' }], instances: inst, log, + }); + assert.deepEqual(rec.events.map(e => e.kind), [ + 'turnStart', 'deploy', 'turnStart', 'draw', 'cast', 'tokenCreated', 'turnStart', 'draw', 'deploy', + 'turnStart', 'attack', 'attack', 'block', 'destroyed', 'playerDamage', 'lifeGain', 'gameOver', + ]); + const tc = rec.events.find(e => e.kind === 'tokenCreated'); + assert.deepEqual(tc, { kind: 'tokenCreated', seat: 1, source: '1:0', token: 'Elected Member', count: 2 }); + assert.equal(rec.cards['t:1'].token, true); + assert.equal(rec.cards['0:1'].tokenId, 'tokB'); + assert.equal(rec.seed, 'story-seed'); + const over = rec.events[rec.events.length - 1]; + assert.deepEqual(over, { kind: 'gameOver', winner: 1, reason: 'concede', turn: 4, life: [15, 22] }); + + const r = recap(rec); + assert.equal(r.title, 'Skirmish at Pathrail Mosque (2026)'); + assert.equal(r.infobox.result, 'bob victory by withdrawal'); + assert.ok(r.references.every(x => !x.title.includes('Elected Member'))); + const forBob = renderLog(rec, 1).lines.map(l => l.text).join(' '); + assert.doesNotMatch(forBob, /Tom Ewell.*drawn|drew \*Tom Ewell/); // alice's draw is hidden from bob +}); diff --git a/tests/duel-design-story.golden.json b/tests/duel-design-story.golden.json new file mode 100644 index 0000000..1df7fa1 --- /dev/null +++ b/tests/duel-design-story.golden.json @@ -0,0 +1,50 @@ +{ + "log": [ + "Turn 1. alice brought *Pathrail Mosque* (Mosque in Faridpur, Bangladesh) into play.[1]", + "Turn 2. bob added *1954 Gold Coast general election* to their hand.[2]", + "Turn 3. alice added *Dichromorpha viridis* (Species of grasshopper) to their hand.[3] *Dichromorpha viridis* entered play under alice.", + "Turn 4. bob added a card to their hand. *1954 Gold Coast general election* was cited by bob. *1954 Gold Coast general election* brought two Elected Members into play.", + "Turn 5. alice drew one card. alice sent *Dichromorpha viridis* (4/2) into combat. bob lost 4 Notability (16 remaining).", + "Turn 6. bob drew one card. bob cited *April 2021 nor'easter* (Slow-moving nor'easter in April 2021).[4] *Dichromorpha viridis* took 1 damage from *April 2021 nor'easter*. *April 2021 nor'easter* dealt 1 damage to *Pathrail Mosque*. *Dichromorpha viridis* was removed from play.", + "Turn 7. alice added a card to their hand. *Zbyszek Godlewski* (Polish protester, 1952–1970) entered play under alice.[5]", + "Turn 8. bob added a card to their hand. *Marc Fesneau* (French politician, born 1971) entered play under bob.[6]", + "Turn 9. alice drew one card. *Zbyszek Godlewski* (6/3) attacked. *Zbyszek Godlewski* was blocked by *Marc Fesneau* (5/4). *Zbyszek Godlewski* was removed from play. *Marc Fesneau* was removed from play. alice drew one card.", + "Turn 10. bob added a card to their hand. bob discarded *Agda (programming language)* (Functional programming language).[7] bob deployed *Pallas's cat* (Species of small wild cat).[8]", + "Turn 11. alice drew one card. alice deployed *Tom Ewell* (American actor, 1909–1994).[9]", + "Turn 12. bob added a card to their hand. bob attached *Heart rot* (Fungal disease of trees) to *Tom Ewell* (2/2).[10] *Pallas's cat* (5/5) advanced on alice. *Pallas's cat* dealt 5 damage to alice, leaving 15 Notability.", + "Turn 13. alice added a card to their hand. *Monoid* (Algebraic structure with an associative operation and an identity element) was adopted by *Tom Ewell*, which became a 5/5.[11] alice sent *Tom Ewell* (5/5) into combat. bob lost 5 Notability (11 remaining).", + "Turn 14. bob drew one card. bob invoked *2025 Tehreek-e-Labbaik Pakistan protests* (Gaza war protests in Pakistan).[12] *2025 Tehreek-e-Labbaik Pakistan protests* inflicted 3 damage on *Tom Ewell*. bob brought *Tatsunoko Production* (Japanese animation studio) into play.[13] bob sent *Pallas's cat* (5/5) into combat. alice's Notability fell to 10.", + "Turn 15. alice drew a card. *Tom Ewell* (5/5) advanced on bob. bob lost 5 Notability (6 remaining).", + "Turn 16. bob drew a card. bob sent *Pallas's cat* (5/5) into combat. alice lost 5 Notability (5 remaining).", + "Turn 17. alice drew one card. *Tom Ewell* (5/5) advanced on bob. bob's Notability fell to 1.", + "Turn 18. bob drew one card. bob sent *Pallas's cat* (5/5) into combat. alice lost 5 Notability (0 remaining). alice was reduced to 0 Notability. bob won." + ], + "lead": "The **Battle of Pathrail Mosque (2026)** was a WikiDeck engagement fought on 17 November 2026 between the forces of alice and bob. It lasted eighteen turns and ended in a Pyrrhic victory for bob.[1] Contemporary accounts note the deployment of *Dichromorpha viridis* (Species of grasshopper) in the third turn.[2]", + "sections": [ + { + "heading": "Background", + "paragraphs": [ + "Arts, Earth, History, Science and Society were equally represented in the force of alice (one card each, of five cards played).", + "Society was the largest Portal in the force of bob (three of seven cards played)." + ] + }, + { + "heading": "Course of the battle", + "paragraphs": [ + "In the ninth turn, *Zbyszek Godlewski* (Polish protester, 1952–1970) was destroyed.[3] *Marc Fesneau* (French politician, born 1971) was removed from play.[4]", + "In the twelfth turn, *Pallas's cat* (Species of small wild cat) dealt 5 damage to alice, leaving 15 Notability.[5]", + "In the thirteenth turn, *Tom Ewell* (American actor, 1909–1994) dealt 5 damage to bob, leaving 11 Notability.[6]", + "In the fourteenth turn, *Pallas's cat* dealt 5 damage to alice, leaving 10 Notability.", + "In the fifteenth turn, *Tom Ewell* dealt 5 damage to bob, leaving 6 Notability.", + "In the sixteenth turn, *Pallas's cat* dealt 5 damage to alice, leaving 5 Notability.", + "alice was nominated for deletion. The result was **delete**." + ] + }, + { + "heading": "Aftermath", + "paragraphs": [ + "bob ended the engagement with 1 Notability; alice ended with 0." + ] + } + ] +} diff --git a/tests/duel-design-story.test.ts b/tests/duel-design-story.test.ts new file mode 100644 index 0000000..6d7cdb6 --- /dev/null +++ b/tests/duel-design-story.test.ts @@ -0,0 +1,256 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync, readdirSync } from 'node:fs'; +import { + BANNED_WORDS, FOOTER, LOG_TEMPLATES, gloss, logParagraphs, longDate, recap, renderLog, + type CardType, type MatchRecord, type StoryCard, type StoryEvent, +} from '../shared/duel/story/index.ts'; + +// Real cards from docs/game/card-sample.json (no network). Types, costs and Portals are the +// DUEL_DESIGN.md §9 worked examples. +const sample = JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8')) as { + cards: { title: string; description: string | null; revisionId: number; pageId: number }[]; +}; +const byTitle = new Map(sample.cards.map(c => [c.title, c])); +function card(id: string, title: string, type: CardType, cost: number, portal: string, owner: 0 | 1): StoryCard { + const c = byTitle.get(title); + if (!c) throw new Error(`not in sample: ${title}`); + return { id, title, description: c.description ?? '', type, cost, portal, revisionId: c.revisionId, tokenId: `tok-${c.pageId}`, owner }; +} +const cards: Record = Object.fromEntries([ + card('a1', 'Dichromorpha viridis', 'Figure', 2, 'Earth', 0), + card('a2', 'Pathrail Mosque', 'Location', 2, 'Society', 0), + card('a3', 'Zbyszek Godlewski', 'Figure', 5, 'History', 0), + card('a4', 'Monoid', 'Doctrine', 6, 'Science', 0), + card('a5', 'Tom Ewell', 'Figure', 6, 'Arts', 0), + card('b1', '1954 Gold Coast general election', 'Event', 3, 'Society', 1), + card('b2', "April 2021 nor'easter", 'Event', 3, 'Earth', 1), + card('b3', 'Marc Fesneau', 'Figure', 5, 'Society', 1), + card('b4', "Pallas's cat", 'Figure', 6, 'Earth', 1), + card('b5', 'Heart rot', 'Doctrine', 5, 'Science', 1), + card('b6', '2025 Tehreek-e-Labbaik Pakistan protests', 'Event', 5, 'Society', 1), + card('b7', 'Tatsunoko Production', 'Institution', 6, 'Arts', 1), + card('b8', 'Agda (programming language)', 'Doctrine', 6, 'Science', 1), +].map(c => [c.id, c])); + +const T = (turn: number): StoryEvent => ({ kind: 'turnStart', turn, seat: turn % 2 === 1 ? 0 : 1 }); +const events: StoryEvent[] = [ + T(1), { kind: 'deploy', seat: 0, card: 'a2' }, + T(2), { kind: 'draw', seat: 1, card: 'b1' }, + T(3), { kind: 'draw', seat: 0, card: 'a1' }, { kind: 'deploy', seat: 0, card: 'a1' }, + T(4), { kind: 'draw', seat: 1 }, { kind: 'cast', seat: 1, card: 'b1' }, + { kind: 'tokenCreated', seat: 1, source: 'b1', token: 'Elected Member', count: 2 }, + T(5), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a1', power: 4, toughness: 2 }, + { kind: 'playerDamage', seat: 1, source: 'a1', amount: 4, life: 16 }, + T(6), { kind: 'draw', seat: 1 }, { kind: 'cast', seat: 1, card: 'b2' }, + { kind: 'effectDamage', source: 'b2', target: 'a1', amount: 1 }, + { kind: 'effectDamage', source: 'b2', target: 'a2', amount: 1 }, { kind: 'destroyed', card: 'a1' }, + T(7), { kind: 'draw', seat: 0 }, { kind: 'deploy', seat: 0, card: 'a3' }, + T(8), { kind: 'draw', seat: 1 }, { kind: 'deploy', seat: 1, card: 'b3' }, + T(9), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a3', power: 6, toughness: 3 }, + { kind: 'block', seat: 1, blocker: 'b3', attacker: 'a3', power: 5, toughness: 4 }, + { kind: 'destroyed', card: 'a3' }, { kind: 'destroyed', card: 'b3' }, { kind: 'draw', seat: 0 }, + T(10), { kind: 'draw', seat: 1 }, { kind: 'discard', seat: 1, card: 'b8' }, { kind: 'deploy', seat: 1, card: 'b4' }, + T(11), { kind: 'draw', seat: 0 }, { kind: 'deploy', seat: 0, card: 'a5' }, + T(12), { kind: 'draw', seat: 1 }, { kind: 'adopt', seat: 1, doctrine: 'b5', figure: 'a5', power: 2, toughness: 2 }, + { kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 }, { kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 15 }, + T(13), { kind: 'draw', seat: 0 }, { kind: 'adopt', seat: 0, doctrine: 'a4', figure: 'a5', power: 5, toughness: 5 }, + { kind: 'attack', seat: 0, card: 'a5', power: 5, toughness: 5 }, { kind: 'playerDamage', seat: 1, source: 'a5', amount: 5, life: 11 }, + T(14), { kind: 'draw', seat: 1 }, { kind: 'cast', seat: 1, card: 'b6' }, + { kind: 'effectDamage', source: 'b6', target: 'a5', amount: 3 }, { kind: 'deploy', seat: 1, card: 'b7' }, + { kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 }, { kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 10 }, + T(15), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a5', power: 5, toughness: 5 }, + { kind: 'playerDamage', seat: 1, source: 'a5', amount: 5, life: 6 }, + T(16), { kind: 'draw', seat: 1 }, { kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 }, + { kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 5 }, + T(17), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a5', power: 5, toughness: 5 }, + { kind: 'playerDamage', seat: 1, source: 'a5', amount: 5, life: 1 }, + T(18), { kind: 'draw', seat: 1 }, { kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 }, + { kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 0 }, + { kind: 'gameOver', winner: 1, reason: 'life', turn: 18 }, +]; +const record: MatchRecord = { + matchId: 'golden-1', seed: 'golden-seed', date: '2026-11-17', + players: [{ name: 'alice' }, { name: 'bob' }], cards, events, hostName: 'testnet-r350', +}; + +test('recap: title, infobox and footer follow DUEL_DESIGN §8.3', () => { + const r = recap(record); + assert.equal(r.title, 'Battle of Pathrail Mosque (2026)'); // loser's Location; 9 turns each → "Battle of" + assert.equal(r.url, '/recap/golden-1'); + assert.equal(r.masthead, 'WikiDeck'); + assert.deepEqual(r.infobox, { + date: '17 November 2026', + location: 'Pathrail Mosque', + result: 'Pyrrhic bob victory', + belligerents: ['alice', 'bob'], + commanders: ['Tom Ewell', "Pallas's cat"], + strength: ['5 cards', '7 cards'], + casualties: ['2 cards destroyed: Dichromorpha viridis, Zbyszek Godlewski', '1 card destroyed: Marc Fesneau'], + }); + assert.equal(r.footer, FOOTER); + assert.match(r.lead, /^The \*\*Battle of Pathrail Mosque \(2026\)\*\* .*17 November 2026.*alice.*bob.*eighteen turns.*a Pyrrhic victory for bob\.\[1\]/); + assert.match(r.lead, /\*Dichromorpha viridis\* \(Species of grasshopper\).* third turn\.\[2\]$/); + assert.deepEqual(r.sections.map(s => s.heading), ['Background', 'Course of the battle', 'Aftermath']); + assert.match(r.sections[2].paragraphs[0], /^bob ended the engagement with 1 Notability; alice ended with 0\.$/); +}); + +test('recap: references cite every card played with its revision id, in first-mention order', () => { + const r = recap(record); + assert.equal(r.references.length, 12); + assert.deepEqual(r.references.map(x => x.n), r.references.map((_, i) => i + 1)); + assert.equal(r.references[0].title, 'Pathrail Mosque'); + for (const ref of r.references) { + const c = cards[ref.cardId]; + assert.equal(ref.revisionId, c.revisionId); + assert.ok(ref.url.endsWith(`&oldid=${c.revisionId}`), ref.url); + assert.ok(ref.url.startsWith('https://en.wikipedia.org/w/index.php?title=')); + assert.match(ref.text, new RegExp(`Revision ${c.revisionId}\\. Minted as token tok-`)); + } + // every [n] used in the text exists + const text = [r.lead, ...r.sections.flatMap(s => s.paragraphs)].join(' '); + for (const m of text.matchAll(/\[(\d+)\]/g)) assert.ok(Number(m[1]) <= r.references.length); +}); + +test('log: golden lines for the omniscient view', () => { + const { lines, references } = renderLog(record, null); + const paras = logParagraphs(lines); + assert.equal(paras.length, 18); + assert.equal(lines[0].text, 'Turn 1.'); + assert.match(lines[1].text, /\*Pathrail Mosque\* \(Mosque in Faridpur, Bangladesh\).*\[1\]$/); + assert.ok(lines.some(l => /\*Zbyszek Godlewski\* \(Polish protester, 1952–1970\)/.test(l.text))); + assert.ok(lines.some(l => /two Elected Members/.test(l.text))); + assert.match(lines[lines.length - 1].text, /alice/); + // later mentions carry no gloss and no new citation + const later = lines.filter(l => l.text.includes('*Tom Ewell*')); + assert.ok(later.length >= 3); + assert.equal(later.filter(l => l.text.includes('American actor')).length, 1); + assert.equal(references.length, 13); // 12 played + the discarded Agda + // snapshot of the whole log text (golden): regenerate deliberately if templates change + assert.equal(paras.join('\n').length > 1500, true); + assert.deepEqual(renderLog(record, null), { lines, references }); +}); + +test('log: logFor hides the opponent\'s draws', () => { + const forAlice = renderLog(record, 0).lines.map(l => l.text); + const forBob = renderLog(record, 1).lines.map(l => l.text); + const turn2Alice = forAlice[forAlice.indexOf('Turn 2.') + 1]; + const turn2Bob = forBob[forBob.indexOf('Turn 2.') + 1]; + assert.doesNotMatch(turn2Alice, /Gold Coast/); + assert.match(turn2Alice, /^bob (drew a card|drew one card|added a card to their hand)\.$/); + assert.match(turn2Bob, /Gold Coast/); + // alice sees her own draw of Dichromorpha viridis by name + assert.ok(forAlice.some(t => /alice.*Dichromorpha viridis|Dichromorpha viridis.*alice/.test(t) && /drew|drawn|hand/.test(t))); +}); + +test('log: discards are public (Deleted is a public zone)', () => { + const forAlice = renderLog(record, 0).lines.map(l => l.text); + assert.ok(forAlice.some(t => /Agda \(programming language\)/.test(t) && /discard|Deleted/.test(t))); +}); + +test('determinism: same seed gives the same text; another seed varies it', () => { + assert.deepEqual(recap(record), recap(structuredClone(record))); + const other = recap({ ...record, seed: 'another-seed' }); + const a = renderLog(record).lines.map(l => l.text).join('\n'); + const b = renderLog({ ...record, seed: 'another-seed' }).lines.map(l => l.text).join('\n'); + assert.notEqual(a, b); + assert.equal(other.title, recap(record).title); // the name is data, not a variant +}); + +test('recap naming: Event fallback, Figure campaign, prefixes, and the decisive and withdrawal results', () => { + const base = { ...record, cards }; + const short: MatchRecord = { ...base, events: [ + T(1), { kind: 'cast', seat: 0, card: 'b6' }, { kind: 'deploy', seat: 0, card: 'a3' }, + T(2), { kind: 'gameOver', winner: 0, reason: 'concede', turn: 2 }, + ] }; + const r1 = recap(short); + assert.equal(r1.title, 'Skirmish at 2025 Tehreek-e-Labbaik Pakistan protests (2026)'); + assert.equal(r1.infobox.result, 'alice victory by withdrawal'); + assert.equal(r1.infobox.location, 'WikiDeck host testnet-r350'); + const figOnly: MatchRecord = { ...base, events: [ + T(1), { kind: 'deploy', seat: 1, card: 'b3' }, + T(2), { kind: 'playerDamage', seat: 0, amount: 20, life: 0 }, { kind: 'gameOver', winner: 1, reason: 'life', turn: 2 }, + ] }; + const r2 = recap(figOnly); + assert.equal(r2.title, 'Marc Fesneau campaign (2026)'); + assert.equal(r2.infobox.result, 'Decisive bob victory'); + const empty: MatchRecord = { ...base, events: [T(1), { kind: 'gameOver', winner: 1, reason: 'timeout', turn: 1 }] }; + assert.equal(recap(empty).title, 'WikiDeck match of 17 November 2026'); +}); + +test('tone lint: templates are deadpan (DUEL_DESIGN §8.1, critic S7)', () => { + for (const [key, variants] of Object.entries(LOG_TEMPLATES)) { + assert.ok(variants.length >= 3 && variants.length <= 4, `${key} has ${variants.length} variants`); + for (const v of variants) { + assert.doesNotMatch(v, /!/, `${key}: no exclamation marks`); + for (const w of BANNED_WORDS) assert.doesNotMatch(v.toLowerCase(), new RegExp(`\\b${w}\\b`), `${key}: banned word ${w}`); + assert.doesNotMatch(v, /[\u{1F300}-\u{1FAFF}]/u, `${key}: no emoji`); + } + } + const r = recap(record); + const prose = [r.lead, ...r.sections.flatMap(s => s.paragraphs)].join(' ') + .replace(/\*[^*]+\*/g, 'CARD'); // card titles are data; lint only our words + for (const w of BANNED_WORDS) assert.doesNotMatch(prose.toLowerCase(), new RegExp(`\\b${w}\\b`)); + assert.doesNotMatch(prose, /!/); + assert.doesNotMatch(prose, /Wikipedia|Wikimedia/); // branding: only in references and the footer +}); + +test('every sample description glosses without throwing; dates format', () => { + for (const c of sample.cards) assert.equal(typeof gloss(c.description ?? ''), 'string'); + assert.equal(gloss('American actor (1909–1994)'), 'American actor, 1909–1994'); + assert.equal(gloss(''), ''); + assert.equal(longDate('2026-01-05'), '5 January 2026'); +}); + +test('story code is pure: no network or clock access', () => { + const dir = new URL('../shared/duel/story/', import.meta.url); + for (const f of readdirSync(dir)) { + const src = readFileSync(new URL(f, dir), 'utf8'); + assert.doesNotMatch(src, /\bfetch\(|XMLHttpRequest|node:http|Date\.now|new Date\(|Math\.random/, f); + } +}); + +test('golden: full log and recap prose match tests/duel-design-story.golden.json', () => { + // To regenerate after a deliberate template change, dump { log, lead, sections } and review the diff. + const golden = JSON.parse(readFileSync(new URL('./duel-design-story.golden.json', import.meta.url), 'utf8')); + const r = recap(record); + assert.deepEqual({ log: logParagraphs(renderLog(record).lines), lead: r.lead, sections: r.sections }, golden); +}); + +test('tokens are named plainly and never cited; draws are recorded as inconclusive', () => { + const withToken: MatchRecord = { + ...record, + cards: { ...cards, 't:1': { id: 't:1', title: 'Elected Member', type: 'Figure', cost: 0, portal: 'Society', owner: 1, token: true } }, + events: [ + T(1), { kind: 'cast', seat: 1, card: 'b1' }, + { kind: 'tokenCreated', seat: 1, source: 'b1', token: 'Elected Member', count: 1 }, + T(2), { kind: 'attack', seat: 1, card: 't:1', power: 1, toughness: 1 }, + { kind: 'playerDamage', seat: 0, source: 't:1', amount: 20, life: 0 }, + { kind: 'playerDamage', seat: 1, amount: 20, life: 0 }, + { kind: 'gameOver', winner: null, reason: 'life', turn: 2 }, + ], + }; + const { lines, references } = renderLog(withToken); + assert.ok(lines.some(l => /Elected Member \(1\/1\)/.test(l.text) && !/\*Elected Member\*/.test(l.text))); + assert.deepEqual(references.map(r => r.title), ['1954 Gold Coast general election']); + assert.match(lines[lines.length - 1].text, /draw|No winner/); + const r = recap(withToken); + assert.equal(r.infobox.result, 'Inconclusive'); + assert.match(r.lead, /ended in a draw\./); + assert.ok(r.references.every(x => x.revisionId !== undefined)); +}); + +test('final Notability: lifeGain is tracked, and gameOver.life wins when present', () => { + const ev: StoryEvent[] = [ + T(1), { kind: 'deploy', seat: 0, card: 'a2' }, + { kind: 'playerDamage', seat: 0, amount: 18, life: 2 }, + { kind: 'lifeGain', seat: 0, source: 'a2', amount: 10, life: 12 }, + { kind: 'playerDamage', seat: 1, amount: 20, life: 0 }, + { kind: 'gameOver', winner: 0, reason: 'life', turn: 1 }, + ]; + const r = recap({ ...record, events: ev }); + assert.equal(r.infobox.result, 'Decisive alice victory'); // 12 vs 0, not Pyrrhic at 2 + assert.ok(renderLog({ ...record, events: ev }).lines.some(l => /Notability/.test(l.text) && /12/.test(l.text))); + const withFinal = recap({ ...record, events: [...ev.slice(0, -1), { kind: 'gameOver', winner: 0, reason: 'life', turn: 1, life: [3, 0] }] }); + assert.equal(withFinal.infobox.result, 'Pyrrhic alice victory'); +});