Preserve postcombat objective plans and fix city-scoped Tributes AI; release viewer 231 engine 163

This commit is contained in:
coyotte508 2026-11-20 22:24:01 +00:00
commit a6d65a0e4d
35 changed files with 668 additions and 28 deletions

View file

@ -1,7 +1,7 @@
name: Web viewer
on:
pull_request:
paths: ['web-client/**', 'server/**', 'scripts/status-phase-battle.test.cjs', 'Cargo.*', '.github/workflows/web-viewer.yml']
paths: ['web-client/**', 'server/**', 'scripts/status-phase-battle.test.cjs', 'scripts/postcombat-queue*.cjs', 'scripts/tributes.test.cjs', 'Cargo.*', '.github/workflows/web-viewer.yml']
push:
branches: [main, feat/3d-web-viewer]
jobs:

View file

@ -0,0 +1,66 @@
# Private planning during postcombat objective choices
The existing action queue can continue while another player chooses whether to
complete an objective after combat. The queue row uses “Choosing an objective”;
there is no separate panel. An existing plan keeps its key, actions and explicit
Wait preference across the settler-placement → objective-choice handoff.
Eligibility requires a single event during a normal round, an optional zero-or-one
objective-card request from the objective-selection ability, and serialized
`combat_turn_owner` provenance from a completed `CombatEnd`. Own pending choices,
unfinished combat, status-phase, mandatory and nested prompts remain excluded.
The optional provenance field defaults to absent and is omitted when absent.
Existing saved prompts without provenance remain unsupported (fail closed); no
legacy save repair, migration, historical backfill or live-game write is included.
Queue keys redact private objective identities and choices before hashing, so the
owner's stripped board agrees with the authoritative board without leaking an
opponent's cards. Plans remain private and queued actions are revalidated only
after every pending choice finishes. Projection does not claim an objective on
anyone's behalf; the owner must explicitly choose their own objective.
The native resistance regression covers combat win/draw/loss and objective
claim/skip, reload, privacy, invalid keys, exclusions and the eventual replay.
Twelve real-WASM regressions run through `web-client`'s `npm test` and Web viewer
CI, alongside the existing status-phase tests:
```sh
cd web-client
npm run build:bridge
npm test
npm run build
node scripts/postcombat-queue-smoke.mjs
```
The focused browser smoke uses the actual production controller, viewer and WASM
with a local platform transport. It checks the settler → objective transition,
private Wait submission and replay after the defender's explicit claim.
## Tributes release blocker
The AI selected its preferred collection modifier once for the entire player,
then applied it to every activatable city. With Acamapichtli in a small city,
that offered Tributes in other cities, which the authoritative executor correctly
rejected. The AI now uses the existing per-city availability filter before
choosing a variant. No leader eligibility, size limit, fee or action cost changes.
`server/tests/tributes_ai_tests.rs` constructs a small public fixture, exercises
both eligible and oversized leader cities, verifies the ordinary fallback in the
other city, and executes every offered collection (including its payment).
The regression fails against the previous generator. `scripts/tributes.test.cjs`
keeps both normal and queued WASM legality strict, rejecting wrong-city and
oversized-city Tributes while accepting the eligible city. It runs in `npm test`.
Release targets: viewer **0.1.231**, engine **0.4.163**. Use pinned Rust 1.94.1,
full workspace tests including random actions, all frontend/localization checks,
and main-commit Check and Web viewer CI before publishing. Preserve catalog
revision 8 (46 definitions), artwork revision 4, all 60 named assets, gallery,
Standard settings, preferences and unrelated metadata. No live-game actions,
rewinds, migrations, repairs or backfills.
The queue browser smoke supports `CLASH_MOBILE=1` and an optional
`CLASH_VIEWER_URL` for testing hosted viewer/WASM bytes with a synthetic local
transport; `CLASH_WASM` selects the downloaded engine. These never submit moves
to production games.
The achievement artwork input manifest's lockfile hash is refreshed only for the
viewer version bump; dependencies and every artwork source/output are unchanged.

View file

@ -0,0 +1,31 @@
const { readFileSync } = require('node:fs');
const { resolve } = require('node:path');
const engine = require(process.env.CLASH_WASM || '../web-client/.engine/server.js');
const move = (game, action, player) => JSON.parse(engine.tryMove(JSON.stringify(game), JSON.stringify(action), player));
const stripped = (game, player) => JSON.parse(engine.stripSecret(JSON.stringify(game), player));
const planning = (game, player = 0) => JSON.parse(engine.webPlanning(JSON.stringify(stripped(game, player)), player));
function battle(result = 'win', extraObjectives = false, configure = () => {}) {
const game = JSON.parse(readFileSync(resolve(__dirname, '../server/tests/test_games/tactics_cards/heavy_resistance.json')));
for (const p of game.players) {
p.objective_cards = [];
p.action_cards = [];
p.advances = ['Farming', 'Mining', 'Tactics'];
}
game.players[1].objective_cards = extraObjectives ? [27, 28, 5, 6] : [27, 28];
const count = result === 'win' || extraObjectives ? 3 : 2;
game.players[0].units = Array.from({ length: count }, (_, id) => ({ id, position: 'C2', unit_type: 'Infantry' }));
game.players[0].units.push({ id: 30, position: 'C2', unit_type: 'Settler' });
game.players[0].next_unit_id = 31;
if (result === 'loss' || extraObjectives) game.players[1].units.push({ id: 20, position: 'C1', unit_type: 'Infantry' });
for (const position of ['B1', 'B3']) game.players[1].cities.push({ position, mood_state: 'Neutral' });
game.dice_roll_outcomes = Array(10).fill(11);
configure(game);
return move(game, { Movement: { Move: { units: Array.from({ length: count }, (_, id) => id), destination: 'C1', payment: {} } } }, 0);
}
function objectives(game) {
if (game.events[0]?.event_type.CombatEnd) return move(game, { Response: { SelectPositions: ['B1'] } }, 1);
return game;
}
module.exports = { battle, objectives, engine, move, planning, stripped };

View file

@ -0,0 +1,115 @@
// Build web-client/.engine with scripts/build-bridge.sh before running.
const assert = require('node:assert/strict');
const { test } = require('node:test');
const { battle, objectives, engine, move, planning, stripped } = require('./postcombat-queue-fixture.cjs');
const stop = { Movement: 'Stop' };
const response = cards => ({ Response: { SelectHandCards: cards.map(ObjectiveCard => ({ ObjectiveCard })) } });
for (const result of ['win', 'draw', 'loss']) for (const claim of [false, true]) {
test(`${result}: private queue survives objective ${claim ? 'claim' : 'skip'} and serialized handoff`, () => {
let game = battle(result);
const info = planning(game);
assert.ok(info);
game = move(game, { QueueMoves: { key: info.key, actions: [stop], waiting: true } }, 0);
game = objectives(game);
const next = planning(game);
assert.equal(next.label, 'Choosing an objective');
assert.equal(next.key, info.key);
assert.equal(next.waiting, true);
assert.deepEqual(next.actions, [stop]);
assert.equal(game.state.Movement.movement_actions_left, 2);
assert.equal(stripped(game, 1).action_plan, undefined);
assert.equal(planning(game, 1), null);
const owner = stripped(game, 0);
assert.deepEqual(owner.events[0].handler.request.SelectHandCards.choices, []);
assert.equal(owner.events[0].event_type.SelectObjectives.shown_objective, null);
assert.throws(() => move(game, { QueueMoves: { key: 'stale', actions: [], waiting: false } }, 0));
game = move(game, response(claim ? [27] : []), 1);
assert.equal(game.state, 'Playing');
assert.equal(game.action_plan, undefined);
assert.equal((game.events || []).length, 0);
assert.equal((game.players[1].completed_objectives || []).length, Number(claim));
});
}
test('fresh objective queue has identical public and authoritative key; no opponent reveal', () => {
let game = objectives(battle());
const info = planning(game);
assert.ok(info);
assert.equal(info.key, JSON.parse(engine.webPlanning(JSON.stringify(game), 0)).key);
const before = JSON.stringify(game);
const projected = JSON.parse(info.projected);
assert.equal(projected.state.Movement.movement_actions_left, 2);
assert.equal(JSON.stringify(game), before);
assert.equal(projected.players[1].objective_cards.every(card => card === 0), true);
game = move(game, { QueueMoves: { key: info.key, actions: [], waiting: true } }, 0);
game = move(game, response([]), 1);
assert.equal(game.state.Movement.movement_actions_left, 2);
assert.equal(game.action_plan, undefined);
});
test('all repeated objective opportunities finish before queue execution', () => {
let game = objectives(battle('draw', true));
const info = planning(game);
game = move(game, { QueueMoves: { key: info.key, actions: [stop], waiting: true } }, 0);
let prompts = 0;
while ((game.events || []).length) {
assert.equal(game.state.Movement.movement_actions_left, 2);
assert.equal(planning(game).key, info.key);
assert.equal(planning(game).waiting, true);
game = move(game, response([]), 1);
assert.ok(++prompts < 10);
}
assert.ok(prompts >= 3);
assert.equal(game.state, 'Playing');
assert.equal(game.action_plan, undefined);
});
test('replay revalidates and keeps only the failed private suffix', () => {
let game = objectives(battle());
const info = planning(game);
const collect = { Playing: { Collect: { city_position: 'A1', collections: [{ position: 'A1', pile: { food: 1 }, times: 1 }], action_type: 'Collect' } } };
const end = { Playing: 'EndTurn' };
game = move(game, { QueueMoves: { key: info.key, actions: [stop, collect, end], waiting: false } }, 0);
// Authoritative changes are revalidated, never trusted from a projection.
game.actions_left = 0;
game = move(game, response([]), 1);
assert.equal(game.state, 'Playing');
assert.equal(game.current_player_index, 0);
assert.deepEqual(game.action_plan.actions, [collect, end]);
assert.ok(game.action_plan.error);
assert.equal(stripped(game, 1).action_plan, undefined);
});
test('legacy/unproven, status-phase, mandatory and nested objective prompts fail closed', () => {
const game = objectives(battle());
for (const change of [
g => { delete g.events[0].event_type.SelectObjectives.combat_turn_owner; },
g => { g.round = 4; },
g => { g.events[0].handler.request.SelectHandCards.needed.start = 1; },
g => { g.events.push(structuredClone(g.events[0])); },
]) {
const changed = structuredClone(game);
change(changed);
assert.equal(planning(changed), null);
}
});
test('own postcombat objectives require an actual choice, never an inferred claim', () => {
let game = battle('draw', true, g => { g.players[0].objective_cards = [6]; });
assert.equal(game.events[0].player, 0);
assert.equal(planning(game), null);
assert.equal((game.players[0].completed_objectives || []).length, 0);
game = move(game, response([6]), 0);
assert.equal(game.players[0].completed_objectives[0].card, 6);
assert.ok(planning(game));
assert.equal((game.players[1].completed_objectives || []).length, 0);
});
test('unfinished combat tactics do not offer a continuation queue', () => {
const game = battle('win', false, g => { g.players[1].action_cards = [7]; });
assert.equal(planning(game), null);
assert.ok(game.events.some(e => e.event_type.CombatRoundStart));
});

49
scripts/tributes.test.cjs Normal file
View file

@ -0,0 +1,49 @@
// City-scoped Tributes legality through ordinary and private queue WASM APIs.
const assert = require('node:assert/strict');
const { test } = require('node:test');
const { readFileSync } = require('node:fs');
const { resolve } = require('node:path');
const { battle, objectives, engine, move, planning } = require('./postcombat-queue-fixture.cjs');
function fixture(queued, large = false) {
const game = JSON.parse(readFileSync(resolve(__dirname, '../server/tests/test_games/advances/collect_free_economy.json')));
game.players.push({ id: 2, civilization: 'Barbarians', next_unit_id: 0 },
{ id: 3, civilization: 'Pirates', next_unit_id: 0 });
const p = game.players[0];
p.civilization = 'Aztecs';
p.advances = ['Farming', 'Mining'];
p.resources = { food: 1, wood: 1, mood_tokens: 6 };
p.resource_limit.food = 7;
p.units = [{ id: 0, position: 'A1', unit_type: { Leader: 'Acamapichtli' } }];
p.next_unit_id = 1;
p.recruited_leaders = ['Acamapichtli'];
if (large) p.cities[0].city_pieces = { temple: 0, academy: 0, fortress: 0 };
if (queued) game.events = objectives(battle()).events;
return game;
}
const collect = city => ({ Playing: { Collect: {
city_position: city,
collections: [{ position: city === 'A1' ? 'A2' : 'B2', pile: { food: 1 }, times: 1 }],
action_type: { Special: { Modifier: 'Tributes' } },
} } });
for (const queued of [false, true]) test(`Tributes keeps city eligibility ${queued ? 'in queue projection' : 'in ordinary execution'}`, () => {
const game = fixture(queued);
function play(state, action) {
if (!queued) return move(state, action, 0);
const info = planning(state);
assert.ok(info);
return move(state, { QueueMoves: { key: info.key, actions: [action], waiting: false } }, 0);
}
// A non-leader city must not acquire the modifier just because A1 qualifies.
assert.throws(() => play(game, collect('C2')), error => /Tributes requires Acamapichtli/.test(String(error)));
assert.throws(() => play(fixture(queued, true), collect('A1')), error => /Tributes requires Acamapichtli/.test(String(error)));
// Use the engine's actual choices instead of assuming a terrain resource.
const view = JSON.parse(engine.webView(JSON.stringify(game), 0));
// The queued view is projected by webPlanning, so build choices on the plain fixture.
const ordinary = JSON.parse(engine.webView(JSON.stringify(fixture(false)), 0));
const city = ordinary.cities.find(c => c.position === 'A1');
const choice = city.choices[0];
const action = collect('A1');
action.Playing.Collect.collections = [{ position: choice.position, pile: choice.pile, times: 1 }];
assert.ok(view);
assert.doesNotThrow(() => play(game, action));
});

View file

@ -31,6 +31,20 @@ pub fn offer(game: &Game, player: usize) -> Option<(String, String)> {
let event = game.events.last()?;
let handler = event.player.handler.as_ref()?;
let label = match (&event.event_type, &handler.origin, &handler.request) {
(
PersistentEventType::SelectObjectives(info),
EventOrigin::Ability(name),
PersistentEventRequest::SelectHandCards(request),
) if name == "Select Objective Cards to Complete"
&& info.combat_turn_owner == Some(player)
&& request.needed == (0..=1)
&& request
.choices
.iter()
.all(|card| matches!(card, crate::card::HandCard::ObjectiveCard(_))) =>
{
"Choosing an objective"
}
(
PersistentEventType::CombatEnd(_),
EventOrigin::Ability(name),
@ -117,6 +131,21 @@ pub fn offer(game: &Game, player: usize) -> Option<(String, String)> {
{
return Some((plan.key.clone(), label.into()));
}
// Objective identities and card choices are private. Hash the same public
// event shape on authoritative and stripped boards, not the opponent's hand.
let mut key_events = game.events.clone();
for event in &mut key_events {
if let PersistentEventType::SelectObjectives(info) = &mut event.event_type {
info.strip_secret();
if let Some(handler) = &mut event.player.handler {
if let PersistentEventRequest::SelectHandCards(request) = &mut handler.request {
request.choices.clear();
request.description.clear();
}
handler.response = None;
}
}
}
let key = format!(
"{:x}",
Sha256::digest(
@ -124,7 +153,7 @@ pub fn offer(game: &Game, player: usize) -> Option<(String, String)> {
game.age,
game.round,
crate::game_api::log_length(game),
&game.events
&key_events
))
.ok()?
)

View file

@ -3,7 +3,7 @@ use crate::advance::AdvanceAction;
use crate::ai_collect::{possible_collections, total_collect};
use crate::card::validate_card_selection;
use crate::city::{City, MoodState};
use crate::collect::{Collect, available_collect_actions, possible_resource_collections};
use crate::collect::{Collect, available_collect_actions_for_city, possible_resource_collections};
use crate::construct::{Construct, available_buildings, new_building_positions};
use crate::content::custom_actions::{CustomAction, CustomActionType, SpecialAction};
use crate::content::persistent_events::{
@ -325,16 +325,16 @@ fn advances(ai_actions: &mut AiActions, p: &Player, game: &Game) -> Vec<Action>
}
fn collect_actions(p: &Player, game: &Game) -> Vec<Action> {
let collect = available_collect_actions(game, p.index);
if collect.is_empty() {
return vec![];
}
let action_type = prefer_custom_action(&collect);
p.cities
.iter()
.filter(|city| city.can_activate())
.flat_map(|city| {
// A modifier may be legal in only one city (for example Tributes).
// Choose the preferred variant per city, not once for the player.
let collect = available_collect_actions_for_city(game, p.index, city.position);
if collect.is_empty() {
return vec![];
}
let action_type = prefer_custom_action(&collect);
let info = possible_resource_collections(
game,
city.position,

View file

@ -388,3 +388,151 @@ fn defiance_can_be_claimed_after_a_real_defender_loss_or_draw_and_save_reload()
}
}
}
#[test]
fn postcombat_queue_survives_settler_objective_reload_and_claim_or_skip() {
use crate::{action_queue, board_history};
for result in [
CombatResult::AttackerWins,
CombatResult::Draw,
CombatResult::DefenderWins,
] {
for claim in [false, true] {
let mut game = test_game(1, &CARDS, false);
let attackers = if result == CombatResult::AttackerWins {
3
} else {
2
};
game.players[0].units = (0..attackers)
.map(|id| Unit::new(0, Position::from_offset("C2"), UnitType::Infantry, id))
.collect();
game.players[0].units.push(Unit::new(
0,
Position::from_offset("C2"),
UnitType::Settler,
30,
));
game.players[0].next_unit_id = 31;
if result == CombatResult::DefenderWins {
game.players[1].units.push(Unit::new(
1,
Position::from_offset("C1"),
UnitType::Infantry,
20,
));
}
for position in ["B1", "B3"] {
game.players[1]
.cities
.push(City::new(1, Position::from_offset(position)));
}
game.dice_roll_outcomes = vec![11; 8];
let mut game = board_history::execute(
game,
Action::Movement(MovementAction::Move(MoveUnits::new(
(0..attackers).collect(),
Position::from_offset("C1"),
None,
ResourcePile::empty(),
))),
0,
)
.unwrap();
let (key, _) = action_queue::offer(&game, 0).expect("postcombat off-turn choice");
let actions = vec![Action::Movement(MovementAction::Stop)];
let before_log = crate::game_api::log_length(&game);
game = board_history::execute(
game,
Action::QueueMoves {
key: key.clone(),
actions: actions.clone(),
waiting: true,
},
0,
)
.unwrap();
assert_eq!(crate::game_api::log_length(&game), before_log);
if result == CombatResult::AttackerWins {
game = board_history::execute(
game,
Action::Response(EventResponse::SelectPositions(vec![Position::from_offset(
"B1",
)])),
1,
)
.unwrap();
}
assert!(has_defiance_prompt(&game));
let mut fresh = game.clone();
fresh.action_plan = None;
let stripped = game_api::strip_secret(fresh.clone(), Some(0));
assert_eq!(
action_queue::offer(&fresh, 0),
action_queue::offer(&stripped, 0)
);
assert!(action_queue::project(&stripped, 0, &actions).is_ok());
assert_eq!(action_queue::offer(&game, 0).unwrap().0, key);
assert_eq!(
action_queue::offer(&game, 0).unwrap().1,
"Choosing an objective"
);
assert!(action_queue::offer(&game, 1).is_none());
assert!(action_queue::save(&mut game, 0, "stale", vec![], false).is_err());
assert!(action_queue::save(&mut game, 1, &key, vec![], false).is_err());
let data =
serde_json::from_str(&serde_json::to_string(&game.cloned_data()).unwrap()).unwrap();
game = Game::from_data(data, game.cache.clone(), GameContext::Play);
assert_eq!(action_queue::offer(&game, 0).unwrap().0, key);
assert!(game.action_plan.as_ref().unwrap().waiting);
assert_eq!(game.action_plan.as_ref().unwrap().actions, actions);
for viewer in [None, Some(1)] {
assert!(
game_api::strip_secret(game.clone(), viewer)
.action_plan
.is_none()
);
}
assert!(
matches!(&game.state, crate::game::GameState::Movement(m) if m.movement_actions_left == 2)
);
let projected = action_queue::project(&game, 0, &[]).unwrap();
assert_eq!(projected.state, game.state);
assert!(game.players[1].completed_objectives.is_empty());
for variant in 0..4 {
let mut blocked = game.clone();
match variant {
0 => blocked.round = 4,
1 => {
if let PersistentEventType::SelectObjectives(i) =
&mut blocked.events[0].event_type
{
i.combat_turn_owner = None;
}
}
2 => blocked.events.push(blocked.events[0].clone()),
_ => blocked.events[0].player.index = 0,
}
assert!(action_queue::offer(&blocked, 0).is_none());
}
game = board_history::execute(
game,
Action::Response(EventResponse::SelectHandCards(if claim {
vec![HandCard::ObjectiveCard(27)]
} else {
vec![]
})),
1,
)
.unwrap();
assert!(game.events.is_empty());
assert!(game.action_plan.is_none());
assert_eq!(game.state, crate::game::GameState::Playing);
assert_eq!(game.current_player_index, 0);
assert_eq!(
game.players[1].completed_objectives.len(),
usize::from(claim)
);
}
}
}

View file

@ -453,9 +453,16 @@ where
}
}
crate::early_choices::expire_current_event(game);
game.events.pop();
let completed = game.events.pop().expect("completed event");
let combat_turn_owner = match completed.event_type {
PersistentEventType::CombatEnd(stats) if stats.result.is_some() => {
Some(stats.attacker.player)
}
PersistentEventType::SelectObjectives(info) => info.combat_turn_owner,
_ => None,
};
present_instant_objective_cards(game);
present_instant_objective_cards(game, combat_turn_owner);
Some(value)
}

View file

@ -224,6 +224,10 @@ impl AbilityInitializerSetup for ObjectiveBuilder {
pub struct SelectObjectivesInfo {
pub(crate) objective_opportunities: Vec<String>,
pub(crate) shown_objective: Option<String>,
// Provenance survives reload and successive players' objective prompts.
// Only a completed CombatEnd event sets this; old saves fail closed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) combat_turn_owner: Option<usize>,
}
impl SelectObjectivesInfo {
@ -232,6 +236,7 @@ impl SelectObjectivesInfo {
Self {
objective_opportunities,
shown_objective: None,
combat_turn_owner: None,
}
}
@ -254,7 +259,7 @@ pub(crate) fn objective_is_ready(player: &mut Player, name: &str) {
o.dedup(); // can't fulfill 2 objectives with the same name at once
}
pub(crate) fn present_instant_objective_cards(game: &mut Game) {
pub(crate) fn present_instant_objective_cards(game: &mut Game, combat_turn_owner: Option<usize>) {
let Some(player) = game
.players
.iter()
@ -265,20 +270,23 @@ pub(crate) fn present_instant_objective_cards(game: &mut Game) {
let opportunities = std::mem::take(&mut game.player_mut(player).objective_opportunities);
present_objective_cards(game, player, opportunities);
let mut info = sorted_objective_info(game, opportunities);
info.combat_turn_owner = combat_turn_owner;
on_objective_cards(game, player, info);
}
pub(crate) fn present_objective_cards(
game: &mut Game,
player: usize,
mut opportunities: Vec<String>,
) {
pub(crate) fn present_objective_cards(game: &mut Game, player: usize, opportunities: Vec<String>) {
let info = sorted_objective_info(game, opportunities);
on_objective_cards(game, player, info);
}
fn sorted_objective_info(game: &Game, mut opportunities: Vec<String>) -> SelectObjectivesInfo {
opportunities.sort_by_cached_key(|name| {
let o = game.cache.get_objective(name);
(-o.priority(), o.name.clone())
});
opportunities.dedup(); // can't use 2 objectives with the same name at once
on_objective_cards(game, player, SelectObjectivesInfo::new(opportunities));
SelectObjectivesInfo::new(opportunities)
}
pub(crate) fn on_objective_cards(game: &mut Game, player_index: usize, info: SelectObjectivesInfo) {

View file

@ -17,7 +17,8 @@
"event_type": {
"SelectObjectives": {
"objective_opportunities": [],
"shown_objective": "General"
"shown_objective": "General",
"combat_turn_owner": 0
}
},
"player": 0,
@ -998,4 +999,4 @@
9,
14
]
}
}

View file

@ -0,0 +1,83 @@
//! Tributes is city-scoped; a legal variant in one city must not leak to another.
use serde_json::{Value, json};
use server::{
action::{Action, try_execute_action},
ai_actions::AiActions,
cache::Cache,
game::{Game, GameContext},
game_data::GameData,
playing_actions::{PlayingAction, PlayingActionType},
};
fn fixture(large: bool) -> Game {
let mut data: Value = serde_json::from_str(include_str!(
"test_games/advances/collect_free_economy.json"
))
.unwrap();
let fresh = server::game_api::init(2, "tributes-regression".into(), Default::default());
let npcs = serde_json::to_value(fresh.cloned_data()).unwrap();
data["players"]
.as_array_mut()
.unwrap()
.extend(npcs["players"].as_array().unwrap().iter().skip(2).cloned());
let p = &mut data["players"][0];
p["civilization"] = json!("Aztecs");
p["advances"] = json!(["Farming", "Mining"]);
p["resources"] = json!({"food":1,"wood":1,"mood_tokens":6});
p["resource_limit"]["food"] = json!(7);
p["units"] = json!([{"id":0,"position":"A1","unit_type":{"Leader":"Acamapichtli"}}]);
p["next_unit_id"] = json!(1);
p["recruited_leaders"] = json!(["Acamapichtli"]);
if large {
p["cities"][0]["city_pieces"] = json!({"temple":0,"academy":0,"fortress":0});
}
let data: GameData = serde_json::from_value(data).unwrap();
let cache = Cache::new(&data.options);
Game::from_data(data, cache, GameContext::AI)
}
#[test]
fn tributes_ai_selects_variant_per_city_and_every_offer_executes() {
for large in [false, true] {
let game = fixture(large);
let offers = AiActions::new().get_available_actions(&game);
let collections: Vec<_> = offers
.iter()
.flat_map(|(_, actions)| actions)
.filter_map(|action| {
if let Action::Playing(PlayingAction::Collect(collect)) = action {
Some((action, collect))
} else {
None
}
})
.collect();
assert!(
collections
.iter()
.any(|(_, c)| c.city_position.to_string() == "A1")
);
assert!(
collections
.iter()
.any(|(_, c)| c.city_position.to_string() == "C2")
);
for (action, collect) in collections {
let ordinary = large || collect.city_position.to_string() != "A1";
assert_eq!(collect.action_type == PlayingActionType::Collect, ordinary);
let before = game.player(0).resources.mood_tokens;
let mut result = try_execute_action(game.clone(), action.clone(), 0).unwrap();
if !ordinary && result.current_event_handler().is_some() {
let payment =
serde_json::from_value(json!({"Response":{"Payment":[{"mood_tokens":2}]}}))
.unwrap();
result = try_execute_action(result, payment, 0).unwrap();
}
assert_eq!(
result.player(0).resources.mood_tokens,
before - if ordinary { 0 } else { 2 }
);
assert_eq!(result.actions_left, game.actions_left - u32::from(ordinary));
}
}
}

View file

@ -1676,3 +1676,21 @@ matching viewer/engine; independently byte-verify all hosted files and engine.
Preserve revision-7 catalog (46 definitions), all 58 named assets, gallery and
unrelated metadata. No production moves, save migration, history repair, backfill
or Fossil refresh. The exact user game was not provided or verified.
# Viewer 0.1.231 / engine 0.4.163 — postcombat objective planning
Private action plans now survive the settler → optional postcombat objective
handoff, with stable redacted keys, explicit Wait and serialized combat-turn
provenance. Unsupported legacy prompts remain fail-closed; no saved-game repair.
The queue label is translated in all 17 locales. See
[postcombat objective queue](../../docs/postcombat-objective-queue.md).
Also fixes the release-blocking AI Tributes bug: choose a collection modifier per
eligible city instead of applying the player's preferred modifier to all cities.
The authoritative Acamapichtli/size/fee rules are unchanged. Deterministic native
and normal/queue WASM regressions accompany the fix; random testing is not skipped.
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.

View file

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

View file

@ -1,13 +1,13 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.230",
"version": "0.1.231",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1 --port 8643",
"build": "vite build",
"check": "svelte-check --tsconfig ./tsconfig.json",
"test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs && npm run test:achievement-assets && npm run test:locales && node scripts/exhausted-movement-check.mjs && CLASH_WASM=\"$PWD/.engine/server.js\" node --test ../scripts/status-phase-battle.test.cjs",
"test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs && npm run test:achievement-assets && npm run test:locales && node scripts/exhausted-movement-check.mjs && CLASH_WASM=\"$PWD/.engine/server.js\" node --test ../scripts/status-phase-battle.test.cjs ../scripts/postcombat-queue.test.cjs ../scripts/tributes.test.cjs",
"test:home-orientation": "npm run build && node scripts/home-orientation-smoke.mjs",
"build:achievement-assets": "node scripts/build-achievement-assets.mjs",
"test:achievement-assets": "node --test scripts/achievement-assets.test.mjs scripts/publish-achievement-assets.test.mjs scripts/publish-achievement-backups.test.mjs",

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": "6d78d2f12bbd8bda1d1ad2854ae359a2bd07d4a95efadd0287759c707ba5af47",
"web-client/package-lock.json": "89d73e7e9983f2a16cc38e593a7c3ac19494485aed54daca78dcb8da00a6564f",
"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

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-server",
"version": "0.4.162",
"version": "0.4.163",
"description": "Clash of Cultures: Monumental edition engine for Boardgamers Space",
"license": "MIT",
"type": "commonjs",

View file

@ -0,0 +1,68 @@
// Real production controller, viewer and WASM; only the platform transport is local.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import { chromium } from 'playwright';
const { battle, objectives, engine, move, planning } = createRequire(import.meta.url)('../../scripts/postcombat-queue-fixture.cjs');
const browser = await chromium.launch({ headless: true, args: ['--use-gl=angle', '--use-angle=swiftshader'] });
try {
const mobile = process.env.CLASH_MOBILE === '1';
const page = await browser.newPage({ viewport: mobile ? { width: 390, height: 844 } : { width: 1400, height: 900 }, isMobile: mobile, hasTouch: mobile });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
let state = battle('win', false, game => {
// The combat unit fixture omits NPCs; the full viewer expects both seats.
game.players.push({ id: 2, civilization: 'Barbarians', next_unit_id: 0 },
{ id: 3, civilization: 'Pirates', next_unit_id: 0 });
});
const key = planning(state).key;
state = move(state, { QueueMoves: { key, actions: [{ Movement: 'Stop' }], waiting: false } }, 0);
const sent = [];
const emit = () => page.evaluate(raw => host.emit('state', raw), engine.stripSecret(JSON.stringify(state), 0));
await page.exposeFunction('applyMove', async action => {
sent.push(JSON.parse(action));
state = JSON.parse(engine.tryMove(JSON.stringify(state), action, 0));
await emit();
});
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"><div id="app"></div><script src="/viewer.js"></script>' });
if (!['/viewer.js', '/server_bg.wasm'].includes(path)) return route.abort();
const hosted = process.env.CLASH_VIEWER_URL;
const body = hosted
? Buffer.from(await (await fetch(new URL(path.slice(1), hosted))).arrayBuffer())
: await readFile(new URL('../dist' + path, import.meta.url));
return route.fulfill({ contentType: path.endsWith('.wasm') ? 'application/wasm' : 'text/javascript', body });
});
await page.goto('http://clash.test/');
assert.deepEqual(errors, []);
await page.evaluate(() => {
window.host = clash3d.launch('#app');
host.on('move', action => window.applyMove(action));
host.emit('player', { index: 0 });
host.emit('theme', { dark: true });
host.emit('preferences', { sound: false, reducedMotion: true });
});
await emit();
await page.getByText('Placing a settler', { exact: true }).waitFor();
assert.match(await page.locator('.concurrent-choice-row').innerText(), /1 queued/);
state = objectives(state);
await emit();
await page.getByText('Choosing an objective', { exact: true }).waitFor();
assert.match(await page.locator('.concurrent-choice-row').innerText(), /1 queued/);
assert.equal(planning(state).key, key);
await page.getByRole('button', { name: 'Wait for choice', exact: true }).click();
await page.waitForFunction(() => !document.querySelector('.concurrent-choice-row'));
assert.equal(sent.length, 1);
assert.deepEqual(sent[0], { QueueMoves: { key, actions: [{ Movement: 'Stop' }], waiting: true } });
assert.equal(state.state.Movement.movement_actions_left, 2);
state = move(state, { Response: { SelectHandCards: [{ ObjectiveCard: 27 }] } }, 1);
await emit();
assert.equal(state.state, 'Playing');
assert.equal(state.action_plan, undefined);
await page.screenshot({ path: '/tmp/clash-postcombat-queue.png' });
assert.deepEqual(errors, []);
console.log('Real queue UI: settler → objective retains key/action; Wait submits private plan; defender claim then replays Stop.');
} finally {
await browser.close();
}

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Afvent valg",
"{p0} queued": "{p0} i kø",
"End turn queued": "Turafslutning i kø",
"Choosing an objective": "Vælger et mål",
"Choosing an advance": "Vælger et fremskridt",
"Placing a settler": "Placerer en nybygger",
"Discard queue": "Ryd kø",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Auswahl abwarten",
"{p0} queued": "{p0} vorgemerkt",
"End turn queued": "Zugende vorgemerkt",
"Choosing an objective": "Wählt ein Ziel",
"Choosing an advance": "Wählt einen Fortschritt",
"Placing a settler": "Platziert einen Siedler",
"Discard queue": "Plan verwerfen",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Αναμονή επιλογής",
"{p0} queued": "{p0} στην ουρά",
"End turn queued": "Τέλος γύρου στην ουρά",
"Choosing an objective": "Επιλέγει έναν στόχο",
"Choosing an advance": "Επιλέγει πρόοδο",
"Placing a settler": "Τοποθετεί άποικο",
"Discard queue": "Εκκαθάριση ουράς",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Wait for choice",
"{p0} queued": "{p0} queued",
"End turn queued": "End turn queued",
"Choosing an objective": "Choosing an objective",
"Choosing an advance": "Choosing an advance",
"Placing a settler": "Placing a settler",
"Discard queue": "Discard queue",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "انتظار برای انتخاب",
"{p0} queued": "{p0} در صف",
"End turn queued": "پایان نوبت در صف",
"Choosing an objective": "در حال انتخاب یک هدف",
"Choosing an advance": "در حال انتخاب پیشرفت",
"Placing a settler": "در حال قرار دادن مهاجر",
"Discard queue": "پاک کردن صف",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Attendre le choix",
"{p0} queued": "{p0} en attente",
"End turn queued": "Fin de tour en attente",
"Choosing an objective": "Choisit un objectif",
"Choosing an advance": "Choisit une avancée",
"Placing a settler": "Place un colon",
"Discard queue": "Vider la file",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "चयन की प्रतीक्षा",
"{p0} queued": "कतार में {p0}",
"End turn queued": "बारी समाप्ति कतार में",
"Choosing an objective": "उद्देश्य चुन रहा है",
"Choosing an advance": "उन्नति चुन रहा है",
"Placing a settler": "बसने वाला रख रहा है",
"Discard queue": "कतार साफ़ करें",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Attendi la scelta",
"{p0} queued": "{p0} in coda",
"End turn queued": "Fine turno in coda",
"Choosing an objective": "Sceglie un obiettivo",
"Choosing an advance": "Sceglie un progresso",
"Placing a settler": "Posiziona un colono",
"Discard queue": "Svuota coda",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "선택 기다리기",
"{p0} queued": "{p0}개 대기 중",
"End turn queued": "턴 종료 대기 중",
"Choosing an objective": "목표 선택 중",
"Choosing an advance": "발전 선택 중",
"Placing a settler": "개척자 배치 중",
"Discard queue": "대기열 비우기",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Wacht op keuze",
"{p0} queued": "{p0} in wachtrij",
"End turn queued": "Beurteinde in wachtrij",
"Choosing an objective": "Kiest een doel",
"Choosing an advance": "Kiest een ontwikkeling",
"Placing a settler": "Plaatst een kolonist",
"Discard queue": "Wachtrij wissen",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Czekaj na wybór",
"{p0} queued": "{p0} w kolejce",
"End turn queued": "Koniec tury w kolejce",
"Choosing an objective": "Wybiera cel",
"Choosing an advance": "Wybiera postęp",
"Placing a settler": "Umieszcza osadnika",
"Discard queue": "Wyczyść kolejkę",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Aguardar escolha",
"{p0} queued": "{p0} na fila",
"End turn queued": "Fim do turno na fila",
"Choosing an objective": "Escolhendo um objetivo",
"Choosing an advance": "Escolhendo um avanço",
"Placing a settler": "Posicionando um colono",
"Discard queue": "Limpar fila",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Așteaptă alegerea",
"{p0} queued": "{p0} în așteptare",
"End turn queued": "Sfârșit de tură în așteptare",
"Choosing an objective": "Alege un obiectiv",
"Choosing an advance": "Alege un progres",
"Placing a settler": "Plasează un colonist",
"Discard queue": "Golește coada",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Ждать выбора",
"{p0} queued": "В очереди: {p0}",
"End turn queued": "Конец хода в очереди",
"Choosing an objective": "Выбирает цель",
"Choosing an advance": "Выбирает достижение",
"Placing a settler": "Размещает поселенца",
"Discard queue": "Очистить очередь",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "Chờ lựa chọn",
"{p0} queued": "{p0} đang chờ",
"End turn queued": "Kết thúc lượt đang chờ",
"Choosing an objective": "Đang chọn mục tiêu",
"Choosing an advance": "Đang chọn tiến bộ",
"Placing a settler": "Đang đặt người định cư",
"Discard queue": "Xóa hàng đợi",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "等待选择",
"{p0} queued": "{p0} 项待执行",
"End turn queued": "结束回合待执行",
"Choosing an objective": "正在选择目标",
"Choosing an advance": "正在选择进步",
"Placing a settler": "正在放置移民",
"Discard queue": "清空队列",

View file

@ -4768,6 +4768,7 @@
"Wait for choice": "等待選擇",
"{p0} queued": "{p0} 項待執行",
"End turn queued": "結束回合待執行",
"Choosing an objective": "正在選擇目標",
"Choosing an advance": "正在選擇進步",
"Placing a settler": "正在放置移民",
"Discard queue": "清空佇列",