Normalize adjacent resource journal prose echoes; release viewer 232

This commit is contained in:
coyotte508 2026-11-21 13:20:06 +00:00
commit 579db2215f
11 changed files with 253 additions and 26 deletions

View file

@ -22,6 +22,10 @@ jobs:
working-directory: web-client
- run: npm run build:bridge && npm run check && npm test && npm run build
working-directory: web-client
- run: npx playwright install --with-deps chromium
working-directory: web-client
- run: node scripts/resource-journal-smoke.mjs && node scripts/famine-journal-smoke.mjs
working-directory: web-client
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
with:
name: clash-viewer

View file

@ -1694,3 +1694,18 @@ Require green main-commit Check and Web viewer CI before BGS publication.
Preserve revision-8 catalog (46 definitions), revision-4 artwork, 60 named assets,
gallery, Standard settings/preferences and all unrelated metadata. No production
moves, rewinds, backfill, migration or history changes.
# Viewer 0.1.232 — resource journal prose echoes (engine unchanged)
Normalize only a trailing resource prose echo beside its structured transaction in
one action, with the same player, nonempty origin and complete normalized pile.
Pay/Lose compatibility is limited to the audited Pandemics (49) and Viking Raids
listeners. Structured transactions are never merged: two real equal payments
still show twice. Preserve legacy text-only history, collection bundles, objective
context and explanatory notes; recognize Paid/Gained and captive badges.
This is display-only: no resource charges, balances, rules or saved history change.
Publish viewer only, retaining engine 0.4.163, achievement catalog revision 8 (46
entries), artwork revision 4 and all 60 named assets. The Web viewer CI runs both
the resource-echo and Famine offline built-viewer regressions on desktop/mobile,
in addition to the complete frontend suite and WASM regressions.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.231",
"version": "0.1.232",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.231",
"version": "0.1.232",
"dependencies": {
"@boardgamers/protocol": "0.11.0",
"lucide-svelte": "^0.577.0",

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.231",
"version": "0.1.232",
"private": true,
"type": "module",
"scripts": {

View file

@ -13,7 +13,7 @@
"web-client/src/civilization-emblems.ts": "01b0cbf3fa77a8466532ccd73d63c1a3ddc9bbc79fc06ce7224b425322a9c9f0",
"web-client/src/civilization-flags.ts": "cd176076bfe05b3059093b80c88596b7ae46b77898695c6c7406cbe1a3a0f78b",
"server/src/content/civilizations.rs": "73602f3db506f3dc2dbc6de43d01179440fd3bb034c997ff209336faaef2a332",
"web-client/package-lock.json": "89d73e7e9983f2a16cc38e593a7c3ac19494485aed54daca78dcb8da00a6564f",
"web-client/package-lock.json": "ed2e0095ae00090b1f60cf1d362678ec7a93202b570cb17e543cf2a1e380ee1c",
"web-client/node_modules/lucide-svelte/dist/Icon.svelte": "f7b49ab842c143fa680fa8bd9a54a9efdc48c2e2d49fa574bd5ccf8f6cfca5be",
"web-client/node_modules/lucide-svelte/dist/defaultAttributes.js": "5b8981c6e3434ae6538716af9e0403554e7708c4087f18d060950a7bef00d96a",
"web-client/node_modules/lucide-svelte/LICENSE": "668dcc52803480e0a026b31140a4cae668772663cd764e5991d252eef03f98db"

View file

@ -0,0 +1,62 @@
// Offline real built-viewer regression. Uses only checked-in engine fixtures;
// no production requests, private games or mutations of resource balances.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { chromium } from 'playwright';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const raw = JSON.parse(await readFile(new URL('../../server/tests/test_games/incidents/pandemics/pandemics.outcome3.json', import.meta.url), 'utf8'));
const balances = raw.players.map(p => p.resources);
const browser = await chromium.launch({ headless: true, args: ['--use-gl=angle', '--use-angle=swiftshader'] });
try {
for (const [width, height] of [[1400, 900], [390, 740]]) {
for (const repeated of [false, true]) {
const state = structuredClone(raw);
const actions = state.log[0].rounds[0].turns[0].actions;
const payment = actions.at(-1);
assert.equal(payment.items[0].Resources.balance, 'Pay');
assert.equal(payment.items[1].Text, 'Lose 1 culture token');
// Minimal redacted reproduction of the reported wood/ore payment echoes.
// The surrounding board is a public repository fixture, not the private game.
payment.items = ['wood', 'ore'].flatMap((resource, player) => [
{ player, origin: { Incident: 49 }, Resources: { balance: 'Pay', resources: { [resource]: 1 } } },
{ player, origin: { Incident: 49 }, Text: `Lose 1 ${resource}` },
]);
if (repeated) payment.items.push(...structuredClone(payment.items));
const publicState = engine.stripSecret(JSON.stringify(state), 0);
assert.deepEqual(JSON.parse(publicState).players.map(p => p.resources), balances);
const page = await browser.newPage({ viewport: { width, height } });
const errors = [];
page.on('pageerror', e => errors.push(e.message));
await page.route('**/*', async route => {
const path = new URL(route.request().url()).pathname;
if (path === '/') return route.fulfill({ contentType: 'text/html', body: '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><div id="app"></div><script src="/viewer.js"></script>' });
if (!['/viewer.js', '/server_bg.wasm'].includes(path)) return route.abort();
return route.fulfill({ contentType: path.endsWith('.wasm') ? 'application/wasm' : 'text/javascript', body: await readFile(new URL('../dist' + path, import.meta.url)) });
});
await page.goto('http://clash.test');
await page.evaluate(state => {
window.host = clash3d.launch('#app');
host.emit('player', { index: 0 });
host.emit('theme', { dark: true });
host.emit('preferences', { sound: false });
host.emit('state', state);
}, publicState);
await page.getByRole('button', { name: 'Open journal', exact: true }).click();
const event = page.locator('.journal-event').filter({ hasText: /Pandemic/ });
await event.waitFor();
const badges = event.locator('.journal-delta[aria-label*="wood"], .journal-delta[aria-label*="ore"]');
for (const resource of ['wood', 'ore']) assert.equal(await event.locator(`.journal-delta[aria-label*="${resource}"]`).count(), repeated ? 2 : 1);
for (const badge of await badges.all()) assert.match(await badge.innerText(), /−1/);
await event.locator('.event-rules summary').click();
assert.match(await event.locator('.event-rules').innerText(), /Every player loses/);
assert.deepEqual(JSON.parse(publicState).players.map(p => p.resources), balances);
await page.screenshot({ path: `/tmp/resource-journal-${width}${repeated ? '-repeated' : ''}.png` });
assert.deepEqual(errors, []);
console.log(`${width}px ${repeated ? 'two real payments' : 'one payment plus prose'}: ${await badges.count()} wood/ore badge(s), balances unchanged`);
await page.close();
}
}
} finally {
await browser.close();
}

View file

@ -499,7 +499,7 @@ test('food explanations are suppressed only beside their matching incident resou
assert.equal(count([{ items: [loss, { ...text, Text: 'Lost 2 food' }] }]), 2);
assert.equal(count([{ items: [loss, { ...text, Text: 'A separate effect' }, text] }]), 2);
assert.equal(count([{ items: [text, loss] }]), 2, 'prose before a loss is not its trailing explanation');
assert.equal(count([{ items: [{ ...loss, origin: { Advance: 'Storage' } }, { ...text, origin: { Advance: 'Storage' } }] }]), 2);
assert.equal(count([{ items: [{ ...loss, origin: { Advance: 'Storage' } }, { ...text, origin: { Advance: 'Storage' } }] }]), 1);
assert.equal(count([{ items: [{ ...loss, Resources: { balance: 'Gain', resources: { food: 1 } } }, text] }]), 2);
assert.equal(count([{ items: [{ ...loss, Resources: { balance: 'Loss', resources: { food: 1, wood: 1 } } }, text] }]), 2);
for (const origin of [undefined, { Incident: 52 }]) {

View file

@ -12,6 +12,8 @@ const resourceIcons: Record<string, Resource | 'action'> = {
idea: 'ideas',
ideas: 'ideas',
gold: 'gold',
captive: 'captives',
captives: 'captives',
'mood token': 'mood_tokens',
'mood tokens': 'mood_tokens',
'culture token': 'culture_tokens',
@ -142,20 +144,20 @@ function confirmPayments(action: LoggedAction, payments: PaymentLog[], entries:
}
function addClause(entry: JournalEntry, clause: string, payments: PaymentLog[]): void {
let match = clause.match(/^(Pay|Gain|Added|Lose|Lost) (.+?)(?: with (.+))?$/);
let match = clause.match(/^(Pay|Paid|Gain|Gained|Added|Lose|Lost) (.+?)(?: with (.+))?$/);
if (match) {
const sign = match[1] === 'Gain' || match[1] === 'Added' ? 1 : -1;
const sign = match[1] === 'Gain' || match[1] === 'Gained' || match[1] === 'Added' ? 1 : -1;
const quantities = match[2]
.split(/,\s*(?:and\s+)?|\s+and\s+|\s*\+\s*/)
.map((part) =>
part.match(/^(\d+(?:\.\d+)?) (food|wood|ore|ideas?|gold|mood tokens?|culture tokens?|actions?)$/),
part.match(/^(\d+(?:\.\d+)?) (food|wood|ore|ideas?|gold|captives?|mood tokens?|culture tokens?|actions?)$/),
);
if (quantities.every((q) => q)) {
const tokens = quantities.map((q) => delta(sign * Number(q![1]), q![2], resourceIcons[q![2]], true));
entry.tokens.push(...tokens);
const note = match[3] ? `With ${match[3]}` : undefined;
if (note) entry.notes.push(note);
if (match[1] === 'Pay' && tokens.every((token) => token.icon !== 'action')) {
if (['Pay', 'Paid'].includes(match[1]) && tokens.every((token) => token.icon !== 'action')) {
const pile: Pile = {};
for (const q of quantities) {
const resource = resourceIcons[q![2]] as Resource;

View file

@ -0,0 +1,102 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { resourceExplanation } from './resource-log.ts';
import { readableHistory } from './structured-log.ts';
import { journal } from './journal.ts';
import type { Game, LoggedAction, Pile } from './types.ts';
type Item = NonNullable<LoggedAction['items']>[number];
const origin = { Incident: 49 };
const record = (resources: Pile, balance: 'Pay' | 'Loss' | 'Gain' = 'Pay'): Item => ({ player: 0, origin, Resources: { resources, balance } });
const prose = (Text: string): Item => ({ player: 0, origin, Text });
const history = (actions: LoggedAction[]): Game => ({
state: 'Playing', map: { tiles: [] }, current_player_index: 0,
age: 2, round: 1, actions_left: 1, log_index: actions.length,
players: [{ id: 0, name: 'Player1', civilization: 'Rome' }],
log: [{ age: 2, rounds: [{ round: 1, turns: [{ turn_type: { Player: 0 }, actions }] }] }],
});
const lines = (actions: LoggedAction[]) => readableHistory(history(actions)).log![0].rounds[0].turns[0].actions!.flatMap(a => a.log!);
for (const [resource, label] of Object.entries({ food: 'food', wood: 'wood', ore: 'ore', gold: 'gold', ideas: 'idea', mood_tokens: 'mood token', culture_tokens: 'culture token', captives: 'captive' })) {
for (const [balance, verb] of [['Pay', 'Pay'], ['Pay', 'Paid'], ['Pay', 'Lose'], ['Pay', 'Lost'], ['Loss', 'Lose'], ['Loss', 'Lost'], ['Gain', 'Gain'], ['Gain', 'Gained']] as const) {
test(`${balance}/${verb}: ${resource} is rendered once, legacy and repeated transactions survive`, () => {
const structured = record({ [resource]: 1 }, balance), text = prose(`${verb} 1 ${label}`);
const game = history([{ items: [structured, text] }]), before = JSON.stringify(game);
const tokens = journal(game).flatMap(e => e.event ? e.event.outcomes.flatMap(o => o.tokens) : e.tokens);
assert.equal(tokens.filter(t => t.icon === resource).length, 1);
assert.equal(JSON.stringify(game), before);
assert.equal(lines([{ items: [structured, text] }]).length, 1);
assert.equal(lines([{ items: [structured, structured] }]).length, 2);
assert.equal(lines([{ items: [structured, text, structured, text] }]).length, 2);
assert.equal(lines([{ items: [text] }]).length, 1);
const tokenCount = (actions: LoggedAction[]) => journal(history(actions)).flatMap(e => e.event ? e.event.outcomes.flatMap(o => o.tokens) : e.tokens).filter(t => t.icon === resource).length;
assert.equal(tokenCount([{ items: [structured, structured] }]), 2);
assert.equal(tokenCount([{ items: [text] }]), 1);
assert.equal(tokenCount([{ log: [`Player1: Pandemics: ${text.Text}`] }]), 1);
assert.equal(lines([{ log: [`Player1: Pandemics: ${text.Text}`] }]).length, 1);
assert.equal(lines([{ items: [structured] }, { items: [text] }]).length, 2);
});
}
}
test('reported Pandemics and Viking Raids payment-loss echoes use exact scoped piles', () => {
for (const source of [origin, { Ability: 'Viking Raids' }]) {
assert.equal(resourceExplanation({ ...prose('Lose 1 gold'), origin: source }, { ...record({ gold: 1 }), origin: source }), undefined);
}
assert.equal(resourceExplanation(prose('Lose 1 gold'), record({ gold: 1 })), undefined);
assert.equal(resourceExplanation({ ...prose('Lose 1 gold'), origin: { Incident: 50 } }, { ...record({ gold: 1 }), origin: { Incident: 50 } }), 'Lose 1 gold');
assert.equal(resourceExplanation(prose('Pay 1 gold'), record({ gold: 1 }, 'Loss')), 'Pay 1 gold');
});
test('mixed piles are compared in full with aliases, zero fields, order and retained explanations', () => {
const actual = record({ ideas: 1, mood_tokens: 2, food: 0, captives: 1 });
assert.equal(resourceExplanation(prose('Paid 1 captive, 2 mood tokens and 1 idea with a discount'), actual), 'With a discount');
assert.equal(resourceExplanation(prose('Pay 1 idea + 1 mood token + 1 mood token and 1 captive'), actual), undefined);
for (const Text of ['Pay 1 idea', 'Pay 1 idea and 2 mood tokens', 'Pay 2 ideas and 2 mood tokens and 1 captive', 'Pay 1 resource', 'Pay 1 idea if possible', 'Added 1 idea', 'Gain 1 victory point']) {
assert.equal(resourceExplanation(prose(Text), actual), Text);
}
});
test('correlation does not cross origin, player, item, action or transaction semantics', () => {
const actual = record({ gold: 1 }), text = prose('Pay 1 gold');
for (const changed of [{ ...text, player: 1 }, { ...text, origin: { Incident: 50 } }, { ...text, origin: undefined }]) {
assert.equal(resourceExplanation(changed, actual), text.Text);
}
assert.equal(resourceExplanation({ ...text, origin: {} }, { ...actual, origin: {} }), text.Text);
assert.equal(resourceExplanation({ ...text, origin: undefined }, { ...actual, origin: undefined }), text.Text);
assert.equal(resourceExplanation(text, record({ gold: 1 }, 'Gain')), text.Text);
assert.equal(lines([{ items: [text, actual] }]).length, 2);
assert.equal(lines([{ items: [actual, prose('A separate effect'), text] }]).length, 3);
assert.equal(lines([{ items: [actual, record({ wood: 1 }), text] }]).length, 3);
assert.equal(lines([{ items: [actual, text, text] }]).length, 2);
assert.equal(lines([{ log: ['Player1: Event: Pay 1 gold', 'Player1: Event: Pay 1 gold'] }]).length, 2);
assert.equal(resourceExplanation(prose('Added 1 gold'), record({ gold: 1 }, 'Gain')), 'Added 1 gold');
});
test('real checked-in Pandemics and Raids logs normalize without changing state or structured records', () => {
for (const name of ['incidents/pandemics/pandemics.outcome3', 'civilizations/vikings/raids.outcome2']) {
const game: Game = JSON.parse(readFileSync(new URL(`../../server/tests/test_games/${name}.json`, import.meta.url), 'utf8'));
const before = JSON.stringify(game);
let echoes = 0;
for (const age of game.log!) for (const round of age.rounds) for (const turn of round.turns) for (const action of turn.actions ?? []) {
for (const [i, item] of (action.items ?? []).entries()) if (item.Text && resourceExplanation(item, action.items?.[i - 1]) !== item.Text) echoes++;
}
assert.ok(echoes > 0, name);
readableHistory(game);
assert.equal(JSON.stringify(game), before);
}
});
test('descriptive objectives, reward-route prose, collection modifiers and waste are retained', () => {
const objective = { Objective: 'Stockpile' };
const objectiveText = { ...prose('Pay 1 gold for Stockpile'), origin: objective };
assert.equal(resourceExplanation(objectiveText, { ...record({ gold: 1 }), origin: objective }), objectiveText.Text);
// Reward callbacks run BEFORE the gain; the only custom callback emits trade
// route descriptions, not duplicate resource amounts. Do not infer backwards.
assert.equal(lines([{ items: [prose('Settler at A1 traded with city B2'), record({ gold: 1 }, 'Gain')] }]).length, 2);
assert.equal(lines([{ items: [prose('Gain 1 gold'), record({ gold: 1 }, 'Gain')] }]).length, 2);
assert.equal(lines([{ items: [record({ gold: 1 }, 'Gain'), { ...record({ gold: 1 }, 'Loss'), origin: { Ability: 'Waste' } }] }]).length, 2);
assert.equal(resourceExplanation({ ...prose('Gain 1 idea'), origin: { Advance: 'PublicEducation' } }, record({ ideas: 1 }, 'Gain')), 'Gain 1 idea');
});

View file

@ -0,0 +1,52 @@
import type { LoggedAction, Pile, Resource } from './types.ts';
type Item = NonNullable<LoggedAction['items']>[number];
const resources: Record<string, Resource> = {
food: 'food', wood: 'wood', ore: 'ore', idea: 'ideas', ideas: 'ideas', gold: 'gold',
'mood token': 'mood_tokens', 'mood tokens': 'mood_tokens',
'culture token': 'culture_tokens', 'culture tokens': 'culture_tokens',
captive: 'captives', captives: 'captives',
};
// Parse completed resource transactions, not offers, rules, conversions, or
// "Added" collection modifiers (which intentionally describe included effects).
function transaction(text: string): { balance: 'Pay' | 'Loss' | 'Gain'; pile: Pile; reason?: string } | undefined {
const match = /^(Pay|Paid|Lose|Lost|Gain|Gained) (.+?)(?: with (.+))?$/.exec(text);
if (!match) return;
const pile: Pile = {};
for (const part of match[2].split(/,\s*(?:and\s+)?|\s+and\s+|\s*\+\s*/)) {
const quantity = /^(\d+) (.+)$/.exec(part);
const resource = quantity && resources[quantity[2]];
if (!quantity || !resource) return;
pile[resource] = (pile[resource] ?? 0) + Number(quantity[1]);
}
return {
balance: /^Pa/.test(match[1]) ? 'Pay' : /^Lo/.test(match[1]) ? 'Loss' : 'Gain',
pile,
reason: match[3] ? `With ${match[3]}` : undefined,
};
}
/** Normalize only a trailing prose echo of the immediately preceding resource
* record. Never merge resource records, search across intervening items/actions,
* or guess from amounts alone. Legacy prose without its record remains intact.
*/
export function resourceExplanation(item: Item, previous?: Item): string | undefined {
const text = item.Text;
if (text === undefined || !previous?.Resources || !item.origin || !previous.origin ||
item.player !== previous.player) return text;
const origin = Object.entries(item.origin);
if (!origin.length || origin.length !== Object.keys(previous.origin).length ||
!origin.every(([key, value]) => previous.origin?.[key] === value)) return text;
const parsed = transaction(text);
if (!parsed) return text;
const actual = previous.Resources;
// These two audited payment listeners explicitly call the payment a loss.
// Do not equate Pay and Loss for unrelated origins/transactions.
const paymentLoss = actual.balance === 'Pay' && parsed.balance === 'Loss' &&
(item.origin.Incident === 49 || item.origin.Ability === 'Viking Raids');
if (actual.balance !== parsed.balance && !paymentLoss) return text;
const keys = new Set([...Object.keys(actual.resources), ...Object.keys(parsed.pile)]);
if (![...keys].every(key => (actual.resources[key as Resource] ?? 0) === (parsed.pile[key as Resource] ?? 0))) return text;
return parsed.reason;
}

View file

@ -1,4 +1,5 @@
import type { Game, LoggedAction, Pile, View } from './types.ts';
import { resourceExplanation } from './resource-log.ts';
import { officialWonderText } from './wonder-names.ts';
type Units = Record<string, number | string>;
@ -76,25 +77,14 @@ function lines(game: Game, action: LoggedAction, context?: Context): string[] {
? source({ ...item, origin: { CivilCard: played } }, context)
: source(item, context);
const write = (text: string) => add(item.player, origin, text);
// Famine's listener logs the loss, then repeats it as "Lost N food".
// Only suppress that adjacent explanation for the same incident and player;
// never deduplicate resource records (equal losses can be separate effects).
const previous = items[index - 1];
const foodLoss = item.Text?.match(/^Lost (\d+) food$/);
const repeatedFoodLoss = foodLoss &&
item.origin?.Incident !== undefined &&
previous?.origin?.Incident === item.origin.Incident &&
previous.player === item.player &&
previous.Resources?.balance === 'Loss' &&
previous.Resources.resources.food === Number(foodLoss[1]) &&
Object.entries(previous.Resources.resources).every(([resource, amount]) => resource === 'food' || !amount);
if (item.Text !== undefined && !offeredDiscount(item.Text) && !repeatedFoodLoss) {
const event = item.Text.match(/^triggers the event (.+)$/);
const text = resourceExplanation(item, items[index - 1]);
if (text !== undefined && !offeredDiscount(text)) {
const event = text.match(/^triggers the event (.+)$/);
if (event) result.push(`A new game event has been triggered: ${event[1]}`);
else if (item.Text === 'wins the battle')
else if (text === 'wins the battle')
result.push(item.player === attacker ? 'Attacker wins' : 'Defender wins');
else if (item.Text === 'ends the battle in a draw') result.push('Battle ends in a draw');
else write(item.Text);
else if (text === 'ends the battle in a draw') result.push('Battle ends in a draw');
else write(text);
}
if (item.Resources && (item.Resources.balance !== 'Pay' || Object.values(item.Resources.resources).some(Boolean)))
write(