From 26ca8e2f2793a23fd88ed352897972d97d9d6897 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:43:32 -0500 Subject: [PATCH 1/4] shared/duel/story: deterministic match log and Battle of X recap, golden tests Co-Authored-By: Claude Opus 5.5 --- shared/duel/story/index.ts | 6 + shared/duel/story/log.ts | 189 +++++++++++++++++++ shared/duel/story/recap.ts | 274 ++++++++++++++++++++++++++++ shared/duel/story/templates.ts | 141 ++++++++++++++ shared/duel/story/types.ts | 86 +++++++++ tests/duel-design-story.golden.json | 50 +++++ tests/duel-design-story.test.ts | 212 +++++++++++++++++++++ 7 files changed, 958 insertions(+) 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-story.golden.json create mode 100644 tests/duel-design-story.test.ts 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..ca91392 --- /dev/null +++ b/shared/duel/story/log.ts @@ -0,0 +1,189 @@ +/** + * 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). */ + cite(id: string): number { + let n = this.refByCard.get(id); + if (n === undefined) { + const c = this.card(id); + 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); + 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 '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 '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': { + 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..aa6cf82 --- /dev/null +++ b/shared/duel/story/recap.ts @@ -0,0 +1,274 @@ +/** + * "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 { + winner: Seat; + 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') 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); + }); + return { winner: over.winner, loser: over.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; + 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; + 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 [portal, n] = [...counts.entries()].sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0]))[0]; + background.push(`${portal} was the largest Portal in the force of ${record.players[seat].name} (${numberWord(n)} of ${numberWord(mine.length)} ${mine.length === 1 ? 'card' : 'cards'} 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 = [ + `${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 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..f2de0cc --- /dev/null +++ b/shared/duel/story/templates.ts @@ -0,0 +1,141 @@ +/** + * 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}.", + ], + 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.', + ], + connected: [ + '{a} and {b} were Connected ({reason}).', + '{a} was Connected to {b} through {reason}.', + 'Records link {a} and {b} ({reason}).', + ], + rivalry: [ + '{a} and {b} had previously been associated through {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}.', + ], + 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..49bbf6c --- /dev/null +++ b/shared/duel/story/types.ts @@ -0,0 +1,86 @@ +/** + * 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). */ + revisionId: number; + /** 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 } + | { 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 } + | { kind: 'connected'; seat: Seat; a: string; b: string; reason: string } + | { kind: 'rivalry'; a: string; b: string; reason: string } + | { kind: 'gameOver'; winner: Seat; reason: GameOverReason; turn: number }; + +export interface StoryPlayer { + /** Display name of the seat (account display name or "Bot (Normal)"). */ + name: string; +} + +export interface MatchRecord { + matchId: string; + /** Match seed (the same one the engine used). Drives template variants. */ + 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-story.golden.json b/tests/duel-design-story.golden.json new file mode 100644 index 0000000..1fbc5aa --- /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 brought *Pallas's cat* (Species of small wild cat) into play.[7]", + "Turn 11. alice drew a card. *Tom Ewell* (American actor, 1909–1994) was deployed by alice.[8]", + "Turn 12. bob drew a card. *Tom Ewell* adopted *Heart rot* (Fungal disease of trees) and became a 2/2.[9] *Pallas's cat* (5/5) attacked. *Pallas's cat* dealt 5 damage to alice, leaving 15 Notability.", + "Turn 13. alice drew one card. *Tom Ewell* adopted *Monoid* (Algebraic structure with an associative operation and an identity element) and became a 5/5.[10] *Tom Ewell* (5/5) advanced on bob. bob lost 5 Notability (11 remaining).", + "Turn 14. bob drew one card. bob cited *2025 Tehreek-e-Labbaik Pakistan protests* (Gaza war protests in Pakistan).[11] *Tom Ewell* took 3 damage from *2025 Tehreek-e-Labbaik Pakistan protests*. *Tatsunoko Production* (Japanese animation studio) was deployed by bob.[12] *Pallas's cat* (5/5) attacked. alice's Notability fell to 10.", + "Turn 15. alice drew one card. *Tom Ewell* (5/5) advanced on bob. *Tom Ewell* dealt 5 damage to bob, leaving 6 Notability.", + "Turn 16. bob added a card to their hand. bob sent *Pallas's cat* (5/5) into combat. *Pallas's cat* dealt 5 damage to alice, leaving 5 Notability.", + "Turn 17. alice added a card to their hand. *Tom Ewell* (5/5) advanced on bob. *Tom Ewell* dealt 5 damage to bob, leaving 1 Notability.", + "Turn 18. bob drew one card. *Pallas's cat* (5/5) advanced on alice. alice lost 5 Notability (0 remaining). alice was nominated for deletion. The result was **delete**." + ], + "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": [ + "History was the largest Portal in the force of alice (two of five cards played).", + "Earth was the largest Portal in the force of bob (two 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 reduced to 0 Notability. bob won." + ] + }, + { + "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..6187319 --- /dev/null +++ b/tests/duel-design-story.test.ts @@ -0,0 +1,212 @@ +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, 'History', 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, 'History', 1), + card('b7', 'Tatsunoko Production', 'Institution', 6, 'Arts', 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: '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, 12); + // 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('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); +}); -- 2.54.0 From 0ca7704767b0a786d5e74815b090f5e6e549b7cf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 21:55:25 -0500 Subject: [PATCH 2/4] story: public discards, factual rivalry wording, Portal ties, fixture Portals per duel-cards #70 Co-Authored-By: Claude Opus 5.5 --- shared/duel/story/log.ts | 2 ++ shared/duel/story/recap.ts | 13 +++++++++++-- shared/duel/story/templates.ts | 7 ++++++- shared/duel/story/types.ts | 2 ++ tests/duel-design-story.golden.json | 24 ++++++++++++------------ tests/duel-design-story.test.ts | 14 ++++++++++---- 6 files changed, 43 insertions(+), 19 deletions(-) diff --git a/shared/duel/story/log.ts b/shared/duel/story/log.ts index ca91392..45d5c52 100644 --- a/shared/duel/story/log.ts +++ b/shared/duel/story/log.ts @@ -150,6 +150,8 @@ export function renderEvent(nar: Narrator, ev: StoryEvent, index: number, viewer 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': diff --git a/shared/duel/story/recap.ts b/shared/duel/story/recap.ts index aa6cf82..2a0b6f0 100644 --- a/shared/duel/story/recap.ts +++ b/shared/duel/story/recap.ts @@ -181,8 +181,13 @@ export function recap(record: MatchRecord): RecapDoc { 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 [portal, n] = [...counts.entries()].sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0]))[0]; - background.push(`${portal} was the largest Portal in the force of ${record.players[seat].name} (${numberWord(n)} of ${numberWord(mine.length)} ${mine.length === 1 ? 'card' : 'cards'} played).`); + 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. @@ -266,6 +271,10 @@ export function recap(record: MatchRecord): RecapDoc { }; } +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 { diff --git a/shared/duel/story/templates.ts b/shared/duel/story/templates.ts index f2de0cc..312ecca 100644 --- a/shared/duel/story/templates.ts +++ b/shared/duel/story/templates.ts @@ -71,13 +71,18 @@ export const LOG_TEMPLATES = { '{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} had previously been associated through {reason}.', + '{a} and {b} are both listed under {reason}.', '{a} and {b} share {reason}.', 'The two sides were linked through {reason}.', ], diff --git a/shared/duel/story/types.ts b/shared/duel/story/types.ts index 49bbf6c..7e5625c 100644 --- a/shared/duel/story/types.ts +++ b/shared/duel/story/types.ts @@ -43,6 +43,8 @@ export type StoryEvent = | { 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 } | { kind: 'gameOver'; winner: Seat; reason: GameOverReason; turn: number }; diff --git a/tests/duel-design-story.golden.json b/tests/duel-design-story.golden.json index 1fbc5aa..1df7fa1 100644 --- a/tests/duel-design-story.golden.json +++ b/tests/duel-design-story.golden.json @@ -9,23 +9,23 @@ "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 brought *Pallas's cat* (Species of small wild cat) into play.[7]", - "Turn 11. alice drew a card. *Tom Ewell* (American actor, 1909–1994) was deployed by alice.[8]", - "Turn 12. bob drew a card. *Tom Ewell* adopted *Heart rot* (Fungal disease of trees) and became a 2/2.[9] *Pallas's cat* (5/5) attacked. *Pallas's cat* dealt 5 damage to alice, leaving 15 Notability.", - "Turn 13. alice drew one card. *Tom Ewell* adopted *Monoid* (Algebraic structure with an associative operation and an identity element) and became a 5/5.[10] *Tom Ewell* (5/5) advanced on bob. bob lost 5 Notability (11 remaining).", - "Turn 14. bob drew one card. bob cited *2025 Tehreek-e-Labbaik Pakistan protests* (Gaza war protests in Pakistan).[11] *Tom Ewell* took 3 damage from *2025 Tehreek-e-Labbaik Pakistan protests*. *Tatsunoko Production* (Japanese animation studio) was deployed by bob.[12] *Pallas's cat* (5/5) attacked. alice's Notability fell to 10.", - "Turn 15. alice drew one card. *Tom Ewell* (5/5) advanced on bob. *Tom Ewell* dealt 5 damage to bob, leaving 6 Notability.", - "Turn 16. bob added a card to their hand. bob sent *Pallas's cat* (5/5) into combat. *Pallas's cat* dealt 5 damage to alice, leaving 5 Notability.", - "Turn 17. alice added a card to their hand. *Tom Ewell* (5/5) advanced on bob. *Tom Ewell* dealt 5 damage to bob, leaving 1 Notability.", - "Turn 18. bob drew one card. *Pallas's cat* (5/5) advanced on alice. alice lost 5 Notability (0 remaining). alice was nominated for deletion. The result was **delete**." + "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": [ - "History was the largest Portal in the force of alice (two of five cards played).", - "Earth was the largest Portal in the force of bob (two of seven cards played)." + "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)." ] }, { @@ -37,7 +37,7 @@ "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 reduced to 0 Notability. bob won." + "alice was nominated for deletion. The result was **delete**." ] }, { diff --git a/tests/duel-design-story.test.ts b/tests/duel-design-story.test.ts index 6187319..21dea81 100644 --- a/tests/duel-design-story.test.ts +++ b/tests/duel-design-story.test.ts @@ -19,7 +19,7 @@ function card(id: string, title: string, type: CardType, cost: number, portal: s } const cards: Record = Object.fromEntries([ card('a1', 'Dichromorpha viridis', 'Figure', 2, 'Earth', 0), - card('a2', 'Pathrail Mosque', 'Location', 2, 'History', 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), @@ -28,8 +28,9 @@ const cards: Record = Object.fromEntries([ 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, 'History', 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 }); @@ -49,7 +50,7 @@ const events: StoryEvent[] = [ 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: 'deploy', seat: 1, card: 'b4' }, + 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 }, @@ -124,7 +125,7 @@ test('log: golden lines for the omniscient view', () => { 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, 12); + 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 }); @@ -142,6 +143,11 @@ test('log: logFor hides the opponent\'s draws', () => { 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' }); -- 2.54.0 From 83a3afef1b027f65e98d635b21eef3634fa5621f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:04:39 -0500 Subject: [PATCH 3/4] story: tokens (never cited) and drawn matches, for duel-core's LogEvent shape Co-Authored-By: Claude Opus 5.5 --- shared/duel/story/log.ts | 5 ++++- shared/duel/story/recap.ts | 12 +++++++++--- shared/duel/story/templates.ts | 5 +++++ shared/duel/story/types.ts | 9 ++++++--- tests/duel-design-story.test.ts | 23 +++++++++++++++++++++++ 5 files changed, 47 insertions(+), 7 deletions(-) diff --git a/shared/duel/story/log.ts b/shared/duel/story/log.ts index 45d5c52..07e65f8 100644 --- a/shared/duel/story/log.ts +++ b/shared/duel/story/log.ts @@ -47,11 +47,12 @@ export class Narrator { player(seat: Seat): string { return this.record.players[seat].name; } - /** Assigns a reference number without mentioning the card (e.g. for the References list). */ + /** 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({ @@ -66,6 +67,7 @@ export class Narrator { /** 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}*`; @@ -157,6 +159,7 @@ export function renderEvent(nar: Narrator, ev: StoryEvent, index: number, viewer 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) }); } diff --git a/shared/duel/story/recap.ts b/shared/duel/story/recap.ts index 2a0b6f0..21ec228 100644 --- a/shared/duel/story/recap.ts +++ b/shared/duel/story/recap.ts @@ -50,7 +50,9 @@ export function longDate(iso: string): string { 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; @@ -72,7 +74,8 @@ function facts(record: MatchRecord): Facts { if (e.kind === 'adopt') played.push({ id: e.doctrine, seat: e.seat, order: i }); if (e.kind === 'destroyed') destroyed.push(e.card); }); - return { winner: over.winner, loser: over.winner === 0 ? 1 : 0, reason: over.reason, turns: over.turn, life, played, destroyed }; + 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. */ @@ -104,6 +107,7 @@ export function battleTitle(record: MatchRecord, f: Facts = facts(record)): stri 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`; @@ -138,6 +142,7 @@ function sub(t: string, v: Record): string { /** 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`; @@ -216,8 +221,9 @@ export function recap(record: MatchRecord): RecapDoc { if (end) course.push(end.text); // Aftermath. - const aftermath = [ - `${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]}.`, + 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}`); diff --git a/shared/duel/story/templates.ts b/shared/duel/story/templates.ts index 312ecca..657d29a 100644 --- a/shared/duel/story/templates.ts +++ b/shared/duel/story/templates.ts @@ -91,6 +91,11 @@ export const LOG_TEMPLATES = { '{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.', diff --git a/shared/duel/story/types.ts b/shared/duel/story/types.ts index 7e5625c..df8bab4 100644 --- a/shared/duel/story/types.ts +++ b/shared/duel/story/types.ts @@ -19,8 +19,10 @@ export interface StoryCard { cost: number; /** Portal (faction): Arts, Earth, History, Science, Society or Neutral. */ portal?: string; - /** The article revision the card was minted from (on-chain). */ - revisionId: number; + /** 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. */ @@ -47,7 +49,8 @@ export type StoryEvent = | { kind: 'discard'; seat: Seat; card: string } | { kind: 'connected'; seat: Seat; a: string; b: string; reason: string } | { kind: 'rivalry'; a: string; b: string; reason: string } - | { kind: 'gameOver'; winner: Seat; reason: GameOverReason; turn: number }; + /** winner null = draw (both players reached 0 at once). */ + | { kind: 'gameOver'; winner: Seat | null; reason: GameOverReason; turn: number }; export interface StoryPlayer { /** Display name of the seat (account display name or "Bot (Normal)"). */ diff --git a/tests/duel-design-story.test.ts b/tests/duel-design-story.test.ts index 21dea81..779683a 100644 --- a/tests/duel-design-story.test.ts +++ b/tests/duel-design-story.test.ts @@ -216,3 +216,26 @@ test('golden: full log and recap prose match tests/duel-design-story.golden.json 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)); +}); -- 2.54.0 From 39ffe409cbb031c05333c0ea7ccb653264cb557b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 22:16:56 -0500 Subject: [PATCH 4/4] story: lifeGain event, authoritative gameOver.life, document story seed (night-review #69 notes) Co-Authored-By: Claude Opus 5.5 --- shared/duel/story/log.ts | 2 ++ shared/duel/story/recap.ts | 3 ++- shared/duel/story/templates.ts | 5 +++++ shared/duel/story/types.ts | 11 +++++++++-- tests/duel-design-story.test.ts | 15 +++++++++++++++ 5 files changed, 33 insertions(+), 3 deletions(-) diff --git a/shared/duel/story/log.ts b/shared/duel/story/log.ts index 07e65f8..6b18022 100644 --- a/shared/duel/story/log.ts +++ b/shared/duel/story/log.ts @@ -137,6 +137,8 @@ export function renderEvent(nar: Narrator, ev: StoryEvent, index: number, viewer 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': diff --git a/shared/duel/story/recap.ts b/shared/duel/story/recap.ts index 21ec228..721db36 100644 --- a/shared/duel/story/recap.ts +++ b/shared/duel/story/recap.ts @@ -69,11 +69,12 @@ function facts(record: MatchRecord): Facts { const played: Played[] = []; const destroyed: string[] = []; record.events.forEach((e, i) => { - if (e.kind === 'playerDamage') life[e.seat] = Math.max(0, e.life); + 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 }; } diff --git a/shared/duel/story/templates.ts b/shared/duel/story/templates.ts index 657d29a..b63b98c 100644 --- a/shared/duel/story/templates.ts +++ b/shared/duel/story/templates.ts @@ -40,6 +40,11 @@ export const LOG_TEMPLATES = { '{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}.', diff --git a/shared/duel/story/types.ts b/shared/duel/story/types.ts index df8bab4..a740207 100644 --- a/shared/duel/story/types.ts +++ b/shared/duel/story/types.ts @@ -40,6 +40,8 @@ export type StoryEvent = | { 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 } @@ -50,7 +52,8 @@ export type StoryEvent = | { 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). */ - | { kind: 'gameOver'; winner: Seat | null; reason: GameOverReason; turn: number }; + /** `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)"). */ @@ -59,7 +62,11 @@ export interface StoryPlayer { export interface MatchRecord { matchId: string; - /** Match seed (the same one the engine used). Drives template variants. */ + /** + * 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; diff --git a/tests/duel-design-story.test.ts b/tests/duel-design-story.test.ts index 779683a..6d7cdb6 100644 --- a/tests/duel-design-story.test.ts +++ b/tests/duel-design-story.test.ts @@ -239,3 +239,18 @@ test('tokens are named plainly and never cited; draws are recorded as inconclusi 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'); +}); -- 2.54.0