Complete explicit withdrawal decisions and preserve replay boundaries; prepare viewer 0.1.238 and engine 0.4.169

This commit is contained in:
coyotte508 2026-11-23 08:36:37 +00:00
commit 34226c4ec9
25 changed files with 1187 additions and 85 deletions

View file

@ -1,7 +1,7 @@
name: Web viewer
on:
pull_request:
paths: ['web-client/**', 'server/**', 'scripts/status-phase-battle.test.cjs', 'scripts/postcombat-queue*.cjs', 'scripts/tributes.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', 'scripts/withdrawal.test.cjs', 'Cargo.*', '.github/workflows/web-viewer.yml']
push:
branches: [main, feat/3d-web-viewer]
jobs:
@ -28,7 +28,7 @@ jobs:
working-directory: web-client
- run: npm run test:boarding && node scripts/embark-smoke.mjs && node scripts/ship-landing-smoke.mjs
working-directory: web-client
- run: node scripts/horse-master-smoke.mjs && node scripts/carthage-recruit-smoke.mjs && node scripts/payment-defaults-smoke.mjs && node scripts/wonder-payment-perf.mjs
- run: node scripts/withdrawal-smoke.mjs && node scripts/horse-master-smoke.mjs && node scripts/carthage-recruit-smoke.mjs && node scripts/payment-defaults-smoke.mjs && node scripts/wonder-payment-perf.mjs
working-directory: web-client
- run: node scripts/map-guide-smoke.mjs && node scripts/trade-routes-smoke.mjs && node scripts/raiders-smoke.mjs
working-directory: web-client

102
docs/withdrawal-progress.md Normal file
View file

@ -0,0 +1,102 @@
# Explicit withdrawal and automatic decisions
This is an asynchronous-platform product policy, not a claim about printed
Clash rules. **Elapsed clock time is not withdrawal.** Only an explicit platform
`dropPlayer` notification (or a save already containing that platform flag)
authorizes dropped-seat automation. Cities and units remain on the board as that
player's pieces. They do not become barbarians, and no full-turn AI is installed.
## Policy
* Continue with two or more surviving human seats; retain seat indices. Skip
future normal turns of dropped seats. Complete an already-started transaction
before stopping movement/ending that seat's current turn.
* End immediately with one survivor; all-withdrawn games are terminal with tied
rankings. Draft withdrawal retains its existing deterministic offered-choice
handling and now also ends when only one survivor remains.
* At a persistent decision, use the actual responder, not the normal turn owner.
Stop at living-player input, including a living defender of a dropped attacker.
Existing saved living-player settings/queued choices remain separately honored.
* Decline optional payments, optional zero-card/unit/position selections, and
Boolean invitations. A dropped defender does not buy Steel Weapons or play
optional tactics. `false` on a retreat invitation means continue the battle.
* Mandatory choices are **not passes**. Use the first valid minimum-cardinality
selection in the request's stable order, respecting unit/card/structure
validators. Casualties still die; a defeated city owner still receives and
places an eligible mandatory settler. This is a deterministic default, not an
optimizing combat AI or a promise to preserve the strongest units.
* Single choices use the first offered value; mandatory resource rewards use
the validated engine default. Mandatory government replacement uses the first
eligible government and required advances. Exploration uses the revealed
block's base rotation, not a hard-coded global rotation.
* Mandatory payment groups are searched together: an optional payment is empty,
but flexible mandatory costs must leave enough for later mandatory costs. No
fabricated empty payment and no repayment of an already completed step.
* Existing rules deciding event participation remain unchanged. In particular,
ordinary status-phase participant lists exclude dropped seats. A decision
**already pending** when a seat withdraws is retained and completed for that
saved actor, even if the newly computed participant list excludes that actor.
## Persistence and boundaries
`board_history::settle` is shared by the authoritative ordinary-move boundary and
withdrawal. Each generated response/stop/end-turn uses the ordinary recorded
execution path, then the top of the event stack is inspected again. No blanket
clearing of combat or nested events. Dropped owners' private plans/choices are
removed; living queued plans use their existing revalidation path. Private
`QueueMoves` / `QueueChoice` updates remain non-resolving early returns: saving a
plan alone does not answer anyone's prompt. A subsequent explicit drop or ordinary
response settles the event and only then resumes a living owner's valid plan.
Automatic dropped-seat actions earn no clock increments. A quit transaction
preserves **all** clock counters, including when it resumes a living queued plan.
Undo/Redo does not run a fresh automatic cascade. Withdrawal seals prior undo.
New ordinary-play withdrawals save `(action cursor, seat)` bookkeeping in
`withdrawals`, so history reconstruction applies the drop at its original
boundary and replays the recorded responses without generating them again.
Old saves without these markers retain their historical replay limitations;
this is not a speculative reconstruction of when an old player left.
The selector does not advance RNG or consult a new private-information policy.
Executing a legal selected response may trigger ordinary rule-mandated randomness.
Search is bounded (100,000 selection/payment candidate steps); the automatic
cascade is bounded (512 actions), with a decision-state progress check. Invalid
requests, exhausted search budgets, or non-progressing continuations fail
explicitly rather than looping or inventing an illegal response. Typical real
WASM fixture cascades are tested below the host's ten-second deadline; these
bounds are not a proof that every corrupt/pathological save fits that deadline.
## Legacy and platform limitation
The existing narrow legacy Banking load repair is retained for compatibility,
but now records the mandatory reward instead of cancelling it, preserves clocks,
and starts the successor once. It still requires the same proof of the old shape.
At an authoritative settle boundary, the current player-turn log can also prove
that an old save advanced its normal seat pointer before a withdrawn owner's
suspended transaction completed; that pointer is restored without replacing the
saved event responder or clearing its stack. An unproven mismatched turn-start
continuation fails explicitly rather than guessing whether a successor already
started. This is not a blanket replay repair.
**A release/viewer reload does not repair platform responder metadata for an
already-blocked game.** BGS authorizes moves against its stored `currentPlayers`
before calling the engine and does not issue another quit notification for an
already-flagged participant. Such games require separately authorized,
lock-protected reconciliation of engine data, responders, and preserved clocks.
No production save repair, rewind, forced move, or clock edit is part of this
code release.
## Regression checks
* Native unit tests: Banking current/legacy shapes, first-seat/round handoff,
idempotence, survivor finish, invalid-handler nonmutation, payment-group
backtracking, valid minimum selection, and withdrawal replay boundaries.
* Exported JSON round trips: current/future dropped defender Steel/tactics,
compulsory casualties before living retreat, dropped attacker with living
defender, status actor attribution, paid government completion, captured-city
settler, private plans, legacy pointer evidence, last/zero survivors.
* Actual Node WASM tests: `scripts/withdrawal.test.cjs`; also run existing status
battle, postcombat queue, Tributes, combat preparation/finalization and native
replay regressions. The selector's match is exhaustive over all persistent
request variants; that is not a claim of a dedicated scenario fixture for
every civilization/incident combination.

185
scripts/withdrawal.test.cjs Normal file
View file

@ -0,0 +1,185 @@
// Actual production JSON/WASM boundaries. No wall-clock expiration is simulated:
// only the platform's explicit dropPlayer notification authorizes automation.
const assert = require('node:assert/strict');
const { test } = require('node:test');
const { readFileSync } = require('node:fs');
const { resolve } = require('node:path');
const engine = require(process.env.CLASH_WASM || '../server/pkg/server.js');
function fixture(name) {
const g = JSON.parse(readFileSync(resolve(__dirname, '../server/tests/test_games/', name + '.json')));
const third = structuredClone(g.players[0]);
Object.assign(third, {id:2,civilization:'Persia',units:[],cities:[{position:'B2',mood_state:'Happy'}],action_cards:[],objective_cards:[]});
g.players.splice(2,0,third);
g.players.forEach((p,i)=>p.id=i);
return g;
}
const move = (g,a,p) => JSON.parse(engine.move(JSON.stringify(g), JSON.stringify(a), p));
const drop = async (g,p) => JSON.parse(await engine.dropPlayer(JSON.stringify(g),p));
const active = g => engine.currentPlayer(JSON.stringify(g));
const clocks = g => engine.timeIncrements(JSON.stringify(g));
function battle() {
const g = fixture('tactics_cards/peltasts');
for (const p of [0,1]) g.players[p].advances.push('SteelWeapons');
g.players[0].action_cards=[3,6,11];g.players[1].action_cards=[4,7,23];
return move(g,{Movement:{Move:{units:[0,1,2],destination:'C1',payment:{}}}},0);
}
function defender(g) {
return move(move(g,{Response:{Payment:[{}]}},0),{Response:{SelectHandCards:[]}},0);
}
test('drop notification drains optional defender prompts, preserves clocks, saves ordinary actions',async()=>{
let g=defender(battle());
const clock=clocks(g), ore=g.players[1].resources.ore, cards=g.players[1].action_cards;
const start=performance.now();
g=await drop(g,1);
assert.ok(performance.now()-start<5000,'well within the host 10-second deadline');
assert.notEqual(active(g),1);
assert.equal(g.players[1].resources.ore,ore);
assert.deepEqual(g.players[1].action_cards,cards);
assert.deepEqual(clocks(g),clock);
assert.deepEqual(await drop(g,1),g);
});
test('future dropped defender drains at ordinary move boundary, never answering living attacker',async()=>{
let g=battle();const before=g.events;
g=await drop(g,1);assert.deepEqual(g.events,before);assert.equal(active(g),0);
g=defender(g);assert.notEqual(active(g),1);assert.equal(clocks(g)[1],0);
});
test('mandatory casualties resolve, living retreat remains open',async()=>{
let g=fixture('combat/retreat');
g.players[0].units=g.players[0].units.filter(u=>u.id<4).map(u=>({...u,unit_type:'Infantry'}));
g.players[1].units=Array.from({length:4},(_,id)=>({id,position:'C1',unit_type:id===3?'Infantry':'Cavalry'}));
g.dice_roll_outcomes=Array(8).fill(4);
g=move(g,{Movement:{Move:{units:[0,1,2,3],destination:'C1',payment:{}}}},0);
assert.equal(active(g),1);
g=await drop(g,1);
assert.equal(g.players[1].units.length,2);assert.equal(g.players[0].units.length,2);
assert.equal(active(g),0);
assert.ok(g.events.at(-1).handler.request.BoolRequest);
});
test('withdrawn attacker does not steal living defender choice or change suspended owner',async()=>{
let g=defender(battle());const events=g.events;
g=await drop(g,0);assert.equal(g.current_player_index,0);assert.equal(active(g),1);assert.deepEqual(g.events,events);
g=move(g,{Response:{Payment:[{}]}},1);
g=move(g,{Response:{SelectHandCards:[]}},1);
assert.notEqual(active(g),0);
});
test('zero surviving seats produce terminal tied rankings',async()=>{
let g=await drop(battle(),0);g=await drop(g,1);
assert.equal(g.state,'Finished');assert.equal(engine.rankings(JSON.stringify(g))[2],1);
g=await drop(g,2);assert.deepEqual(engine.rankings(JSON.stringify(g)),[1,1,1]);
});
test('pending status advance is completed for its saved actor, not the successor',async()=>{
let g=move(fixture('status_phase/free_advance'),{Playing:'EndTurn'},0);
assert.equal(active(g),1);const advances=g.players[0].advances;
g=await drop(g,1);assert.deepEqual(g.players[0].advances,advances);assert.notEqual(active(g),1);
});
test('captured city still gives dropped loser a mandatory settler',async()=>{
let g=fixture('combat/capture_and_raze_city');
g.players[1].cities.push({position:'B1',mood_state:'Happy'});
g=move(g,{Movement:{Move:{units:[0,1,2,3],destination:'C1',payment:{}}}},0);
assert.equal(active(g),1);
const settlers=(g.players[1].units||[]).filter(u=>u.unit_type==='Settler').length;
g=await drop(g,1);
assert.equal((g.players[1].units||[]).filter(u=>u.unit_type==='Settler').length,settlers+1);
assert.notEqual(active(g),1);
});
test('government already paid for completes without a second token payment',async()=>{
let g=move(fixture('status_phase/change_government'),{Response:{SelectPositions:[]}},1);
if(active(g)===2) g=move(g,{Response:{SelectPositions:[]}},2);
g=move(g,{Response:{Payment:[{culture_tokens:1,mood_tokens:1}]}},0);
const resources=g.players[0].resources;
g=await drop(g,0);
assert.equal(g.players[0].resources.mood_tokens,resources.mood_tokens);
assert.equal(g.players[0].resources.culture_tokens,resources.culture_tokens);
assert.notEqual(active(g),0);
});
test('multiple inactive seats skip ordinary turns across round boundaries',async()=>{
let g=JSON.parse(await engine.init(4,[],{},'withdrawal-four-seats',{}));
// init uses the default simultaneous civilization draft; use its offers.
if(g.civilization_draft) {
for(let p=0;p<4;p++) g=move(g,{ChooseCivilization:g.civilization_draft.offers[p][0]},p);
}
const first=g.current_player_index;
const dead=[(first+1)%4,(first+2)%4];
g=await drop(g,dead[0]);g=await drop(g,dead[1]);
for(let i=0;i<4;i++) {
assert.ok(!dead.includes(active(g)));
assert.ok(!(g.events||[]).length,'ordinary starting turns for this fixed seed');
g=move(g,{Playing:'EndTurn'},active(g));
}
assert.equal(g.round,3);
assert.ok(!dead.includes(active(g)));
for(const p of dead) assert.equal(clocks(g)[p],0);
});
test('draft withdrawal locks only departed offers and ends at one survivor',async()=>{
let g=JSON.parse(await engine.init(4,[],{civilization:'DraftThree'},'withdrawal-draft',{}));
assert.ok(g.civilization_draft);
const offers=structuredClone(g.civilization_draft.offers);
g=await drop(g,0);
assert.equal(g.civilization_draft.ready[0],true);
assert.equal(g.civilization_draft.choices[0],offers[0][0]);
assert.deepEqual(active(g),[1,2,3]);
g=await drop(g,1);assert.deepEqual(active(g),[2,3]);
g=await drop(g,2);assert.equal(g.state,'Finished');
assert.equal(engine.rankings(JSON.stringify(g))[3],1);
});
for (const legacy of [false, true]) test(`withdrawn Horse Master defender declines pending modifier (${legacy ? 'legacy' : 'finalized'})`, async () => {
let g=fixture('combat/retreat');
g.players[0].civilization='India';g.players[1].civilization='Huns';
for(const p of [0,1]) {
g.players[p].advances=['Farming','Mining','Tactics'];
g.players[p].units=[{id:0,position:p===0?'C2':'C1',unit_type:p===0?'Infantry':{Leader:'Attila'}},{id:1,position:p===0?'C2':'C1',unit_type:p===0?'Infantry':'Cavalry'}];
g.players[p].next_unit_id=2;
}
g.players[1].advances.push('SteelWeapons');
g.players[0].action_cards=[31];g.players[1].action_cards=[9];
g.dice_roll_outcomes=[10,2,9,3,9];
if(legacy)g.finalized_combat_from=10000;
g=move(g,{Movement:{Move:{units:[0,1],destination:'C1',payment:{}}}},0);
for(const r of [{SelectHandCards:[{ActionCard:31}]},{Payment:[{ore:1}]},{SelectHandCards:[{ActionCard:9}]}]) g=move(g,{Response:r},active(g));
assert.match(g.events.at(-1).handler.request.BoolRequest,/Horse Master/);
const expected=move(structuredClone(g),{Response:{Bool:false}},1);
const before=clocks(g);g=await drop(g,1);
assert.deepEqual(clocks(g),before);
assert.deepEqual(g.players[0].units,expected.players[0].units);
assert.deepEqual(g.players[1].units,expected.players[1].units);
assert.notEqual(active(g),1);
});
test('private early QueueMoves update waits, then withdrawal resolves saved actor and resumes only living owner plan', async () => {
const q=require('./postcombat-queue-fixture.cjs');
let g=q.battle('win',false,g=>{
const third=structuredClone(g.players[0]);
Object.assign(third,{id:2,civilization:'Persia',units:[],cities:[{position:'B2',mood_state:'Happy'}],action_cards:[],objective_cards:[]});
g.players.splice(2,0,third);g.players.forEach((p,i)=>p.id=i);
});
const info=q.planning(g);assert.ok(info);
const events=structuredClone(g.events), before=clocks(g);
g=move(g,{QueueMoves:{key:info.key,actions:[{Movement:'Stop'}],waiting:true}},0);
assert.deepEqual(g.events,events);assert.deepEqual(clocks(g),before);
assert.equal(q.stripped(g,1).action_plan,undefined);
g=await drop(g,1);
assert.equal(g.current_player_index,0);assert.equal(active(g),0);
assert.equal(g.state,'Playing');assert.equal(g.action_plan,undefined);
assert.deepEqual(clocks(g),before);
});
test('JSON full and partial replay retain the exact drop boundary and seal undo', async () => {
let g=JSON.parse(await engine.init(4,[],{},'withdrawal-json-replay',{}));
g=move(g,{Playing:'EndTurn'},active(g));
const cursor=engine.logLength(JSON.stringify(g));
const seat=(active(g)+1)%4;
g=await drop(g,seat);
const boundary=structuredClone(g.withdrawals);
assert.throws(()=>move(g,'Undo',active(g)),'withdrawal seals earlier history');
for(let n=0;n<2;n++)g=move(g,{Playing:'EndTurn'},active(g));
const raw=JSON.stringify(g);
const full=JSON.parse(engine.replay(raw,{}));
assert.deepEqual(full.withdrawals,boundary);assert.deepEqual(full.dropped_players,[seat]);
assert.equal(full.current_player_index,g.current_player_index);assert.equal(full.round,g.round);
const before=JSON.parse(engine.replay(raw,{to:cursor-1}));
assert.ok(!(before.dropped_players||[]).includes(seat));assert.equal(before.withdrawals,undefined);
const at=JSON.parse(engine.replay(raw,{to:cursor}));
assert.deepEqual(at.withdrawals,boundary);assert.deepEqual(at.dropped_players,[seat]);
assert.deepEqual(clocks(at),clocks(g));
});

View file

@ -20,7 +20,8 @@ pub struct Plan {
}
pub fn offer(game: &Game, player: usize) -> Option<(String, String)> {
if player != game.current_player_index
if game.dropped_players.contains(&player)
|| player != game.current_player_index
|| player == game.active_player()
|| game.round > 3
|| game.events.len() != 1
@ -283,6 +284,9 @@ pub fn resume(mut game: Game) -> Game {
let Some(mut plan) = game.action_plan.take() else {
return game;
};
if game.dropped_players.contains(&plan.player) {
return game;
}
if plan.error.is_some() || !game.events.is_empty() || game.active_player() != plan.player {
game.action_plan = Some(plan);
return game;

View file

@ -99,6 +99,7 @@ pub fn create(mut game: Game, seat: Option<usize>, seed: &str) -> Result<Game, S
game.dice_roll_outcomes.clear();
game.dice_roll_log.clear();
game.dropped_players.clear();
game.withdrawals.clear();
game.custom_ui_elements.clear();
let known = known_hands(&game, seat);

View file

@ -281,9 +281,68 @@ pub fn execute(mut game: Game, action: Action, player: usize) -> Result<Game, St
if history_navigation {
return Ok(game);
}
settle(game)
}
/// Shared authoritative boundary for ordinary moves and platform withdrawal.
/// Queries do not call this: generated actions must be saved with responder metadata.
pub(crate) fn settle(mut game: Game) -> Result<Game, String> {
crate::withdrawal::discard_plans(&mut game);
// Old withdrawal code advanced the pointer before resolving the suspended
// turn. A still-current player turn log proves its owner; do not infer this
// from the responder (who can be a defender or another living participant).
if !game.events.is_empty()
&& !game.log.is_empty()
&& let crate::log::TurnType::Player(owner) = crate::log::current_turn_log(&game).turn_type
&& game.dropped_players.contains(&owner)
&& game.current_player_index != owner
{
game.current_player_index = owner;
}
if let Some(event) = game.events.first()
&& matches!(
event.event_type,
crate::content::persistent_events::PersistentEventType::TurnStart
)
&& game.dropped_players.contains(&event.player.index)
&& game.current_player_index != event.player.index
{
return Err(crate::withdrawal::AMBIGUOUS_OWNER.into());
}
// Save automatic responses as ordinary actions. Replay then reproduces them
// without needing past settings; undo never immediately replays a skipped choice.
let mut steps = 0;
while game.context == crate::game::GameContext::Play {
if matches!(game.state, crate::game::GameState::Finished) || game.finish_after_drop() {
break;
}
steps += 1;
if steps > 512 {
return Err(crate::withdrawal::CASCADE_LIMIT.into());
}
if let Some(action) = crate::withdrawal::next_action(&game)? {
let player = game.active_player();
let before = (
game.events.clone(),
game.state.clone(),
game.current_player_index,
game.age,
game.round,
);
game = execute_one(game, action, player)?;
let after = (
game.events.clone(),
game.state.clone(),
game.current_player_index,
game.age,
game.round,
);
if before == after {
return Err(crate::withdrawal::NO_PROGRESS.into());
}
crate::early_choices::prune_objectives(&mut game);
continue;
}
if let Some(response) = crate::early_choices::take_ready(&mut game) {
let player = game.active_player();
game = execute_one(game, Action::Response(response), player)?;
@ -313,7 +372,11 @@ pub fn execute(mut game: Game, action: Action, player: usize) -> Result<Game, St
player,
)?;
}
let mut game = crate::action_queue::resume(game);
let mut game = if matches!(game.state, crate::game::GameState::Finished) {
game
} else {
crate::action_queue::resume(game)
};
crate::calendar_knowledge::disclose(&mut game);
Ok(game)
}

View file

@ -394,11 +394,18 @@ fn remaining_persistent_event_players(
players: &[usize],
state: &PersistentEventState,
) -> Vec<usize> {
players
let mut remaining = players
.iter()
.filter(|p| !state.players_used.contains(p))
.copied()
.collect_vec()
.collect_vec();
// A withdrawal may change the participant list while an event is paused.
// Its outstanding response still belongs to the saved actor, never the next
// survivor. Finish that transaction before advancing to the remaining list.
if state.player.handler.is_some() && !remaining.contains(&state.player.index) {
remaining.insert(0, state.player.index);
}
remaining
}
#[must_use]
@ -479,13 +486,20 @@ pub(crate) fn trigger_persistent_event_with_listener<V>(
where
V: Clone + PartialEq,
{
for p in players {
let mut initialized = players.to_vec();
if let Some(state) = game.events.last()
&& state.player.handler.is_some()
&& !initialized.contains(&state.player.index)
{
initialized.push(state.player.index);
}
for p in &initialized {
listeners.init(game, *p);
}
let result = trigger_persistent_event_ext(game, players, event, event_type, store_type, params);
for p in players {
for p in &initialized {
listeners.deinit(game, *p);
}
result

View file

@ -199,6 +199,7 @@ pub struct Game {
pub dice_roll_outcomes: Vec<u8>, // for testing
pub dice_roll_log: Vec<u8>,
pub dropped_players: Vec<usize>,
pub withdrawals: Vec<(usize, usize)>,
pub wonders_left: Vec<Wonder>,
/// Public history of wonders removed permanently from this game.
pub destroyed_wonders: Vec<Wonder>,
@ -532,10 +533,7 @@ impl Game {
#[must_use]
pub fn human_players_sorted(&self, first: usize) -> Vec<usize> {
let mut all = self.human_player_ids();
let i = all
.iter()
.position(|&p| p == first)
.expect("player should exist");
let i = all.iter().position(|&p| p >= first).unwrap_or(0);
all.rotate_left(i);
all
}
@ -563,9 +561,14 @@ impl Game {
i.undo.clear();
}
check_for_waste(self);
let withdrawing_first = self.current_player_index == self.starting_player_index
&& self.dropped_players.contains(&self.current_player_index);
self.increment_player_index();
self.skip_dropped_players();
if self.current_player_index == self.starting_player_index {
if withdrawing_first {
self.starting_player_index = self.current_player_index;
self.start_turn();
} else if self.current_player_index == self.starting_player_index {
self.next_round();
} else {
self.start_turn();
@ -675,9 +678,8 @@ impl Game {
true
}
/// Cancel only an unsubmitted, standalone Banking reward. Other turn-start
/// handlers include mandatory payments and shared effects; they are not safe
/// to discard generically, nor are nested persistent-event continuations.
/// Recognize only the legacy standalone Banking shape. Other turn-start
/// handlers and nested continuations do not qualify for load-time repair.
fn dropped_banking_player(&self) -> Option<usize> {
use crate::content::persistent_events::PersistentEventRequest;
use crate::special_advance::SpecialAdvance;
@ -699,8 +701,8 @@ impl Game {
/// Repair the old withdrawal shape: the seat pointer advanced, but Banking
/// still belongs to the departed seat and the successor has not started.
/// Removing the event before starting the successor makes repeated load/clone
/// idempotent and avoids resuming `TurnStart` with the wrong seat pointer.
/// Restore the proven owner before completing the mandatory reward through
/// the recorded boundary. Equal owner pointers do not re-enter this repair.
pub(crate) fn reconcile_dropped_banking(&mut self) {
let Some(player) = self.dropped_banking_player() else {
return;
@ -721,17 +723,11 @@ impl Game {
{
return;
}
self.events.clear();
self.cleanup_withdrawn_turn(player);
self.start_turn();
}
fn cleanup_withdrawn_turn(&mut self, player: usize) {
end_turn(self, player);
for action in &mut current_turn_log_mut(self).actions {
action.undo.clear();
}
check_for_waste(self);
self.current_player_index = player;
let clocks = self.time_increments.clone();
*self = crate::board_history::settle(self.clone())
.expect("could not complete legacy withdrawn Banking reward");
self.time_increments = clocks;
}
/// Remove a player while keeping surviving seat indices and round order stable.
@ -741,42 +737,60 @@ impl Game {
pub fn drop_player(&mut self, player_index: usize) {
if self.civilization_draft.is_some() {
crate::game_setup::drop_draft_player(self, player_index);
crate::withdrawal::discard_plans(self);
if self.human_players_count() <= 1 {
self.civilization_draft = None;
self.finish_after_drop();
}
return;
}
if self.dropped_players.contains(&player_index) {
self.reconcile_dropped_banking();
self.finish_after_drop();
return;
assert!(
self.players.get(player_index).is_some_and(Player::is_human),
"Invalid dropped seat"
);
if !self.dropped_players.contains(&player_index) {
self.withdrawals
.push((crate::game_api::log_length(self), player_index));
}
self.dropped_players.push(player_index);
self.apply_withdrawal(player_index);
if self.finish_after_drop() {
return;
}
self.add_message(&format!(
"{} has left the game",
self.player_name(player_index)
));
let dropped_first = self.starting_player_index == player_index;
if dropped_first {
// Do not move the turn pointer past a suspended action. Its continuation
// may still need the turn owner even when the responder is another seat.
let clocks = self.time_increments.clone();
*self =
crate::board_history::settle(self.clone()).expect("could not settle withdrawn player");
// The platform quit transaction preserves all existing deadlines. Even
// a living queued plan resumed here must not award quit-time credits.
self.time_increments = clocks;
}
/// Apply recorded platform bookkeeping without generating any responses.
/// Replay calls this at the saved action boundary before playing the recorded
/// automatic responses, so skipped future turns reconstruct identically.
pub(crate) fn apply_withdrawal(&mut self, player_index: usize) {
if !self.dropped_players.contains(&player_index) {
self.dropped_players.push(player_index);
self.add_message(&format!(
"{} has left the game",
self.player_name(player_index)
));
if !self.log.is_empty() {
self.lock_undo();
}
}
crate::withdrawal::discard_plans(self);
if self.human_players_count() > 0
&& self.dropped_players.contains(&self.starting_player_index)
&& self.current_player_index != self.starting_player_index
{
let seats = self.players.iter().filter(|p| p.is_human()).count();
self.starting_player_index = (1..seats)
.map(|offset| (player_index + offset) % seats)
.map(|offset| (self.starting_player_index + offset) % seats)
.find(|p| !self.dropped_players.contains(p))
.expect("an active player remains");
}
if self.current_player_index != player_index {
return;
}
if self.dropped_banking_player() == Some(player_index) {
self.events.clear();
self.cleanup_withdrawn_turn(player_index);
}
self.skip_dropped_players();
if !dropped_first && self.current_player_index == self.starting_player_index {
self.next_round();
} else if self.events.is_empty() {
self.start_turn();
}
}
#[must_use]

View file

@ -113,6 +113,14 @@ pub fn set_player_name(mut game: Game, player_index: usize, name: String) -> Gam
#[must_use]
pub fn rankings(game: &Game) -> Vec<u32> {
if game.human_players_count() == 0 {
return game
.players
.iter()
.filter(|p| p.is_human())
.map(|_| 1)
.collect();
}
let mut rankings = Vec::new();
for player in &game.players {
if !player.is_human() {

View file

@ -105,6 +105,8 @@ pub struct GameData {
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
dropped_players: Vec<usize>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
withdrawals: Vec<(usize, usize)>,
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
wonders_left: Vec<Wonder>,
@ -183,6 +185,7 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
dice_roll_outcomes: data.dice_roll_outcomes,
dice_roll_log: data.dice_roll_log,
dropped_players: data.dropped_players,
withdrawals: data.withdrawals,
wonders_left: data.wonders_left,
destroyed_wonders: data.destroyed_wonders,
action_cards_left: data.action_cards_left,
@ -251,6 +254,7 @@ pub fn data(game: Game) -> GameData {
dice_roll_outcomes: game.dice_roll_outcomes,
dice_roll_log: game.dice_roll_log,
dropped_players: game.dropped_players,
withdrawals: game.withdrawals,
wonders_left: game.wonders_left,
destroyed_wonders: game.destroyed_wonders,
action_cards_left: game.action_cards_left,
@ -300,6 +304,7 @@ pub fn cloned_data(game: &Game) -> GameData {
dice_roll_outcomes: game.dice_roll_outcomes.clone(),
dice_roll_log: game.dice_roll_log.clone(),
dropped_players: game.dropped_players.clone(),
withdrawals: game.withdrawals.clone(),
wonders_left: game.wonders_left.clone(),
destroyed_wonders: game.destroyed_wonders.clone(),
action_cards_left: game.action_cards_left.clone(),

View file

@ -241,6 +241,7 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game {
dice_roll_outcomes: Vec::new(),
dice_roll_log: Vec::new(),
dropped_players: Vec::new(),
withdrawals: Vec::new(),
wonders_left,
destroyed_wonders: Vec::new(),
action_cards_left,

View file

@ -90,3 +90,5 @@ mod game_length_tests;
#[cfg(test)]
mod withdrawal_tests;
mod withdrawal;

View file

@ -28,6 +28,8 @@ pub struct ReplayGameData {
players: Vec<ReplayPlayerData>,
#[serde(default)]
dropped_players: Vec<usize>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
withdrawals: Vec<(usize, usize)>,
#[serde(
default,
skip_serializing_if = "Vec::is_empty",
@ -143,6 +145,11 @@ pub fn replay(data: ReplayGameData, to: Option<usize>) -> Result<Game, String> {
}
}
for (i, item) in actions.into_iter().take(to).enumerate() {
for &(cursor, player) in &data.withdrawals {
if cursor == i {
game.apply_withdrawal(player);
}
}
if item.action == Action::StartTurn {
continue;
}
@ -180,7 +187,20 @@ pub fn replay(data: ReplayGameData, to: Option<usize>) -> Result<Game, String> {
for player in data.players {
game.players[player.id].settings = player.settings;
}
game.dropped_players = data.dropped_players;
for &(cursor, player) in &data.withdrawals {
if cursor == to {
game.apply_withdrawal(player);
}
}
let has_withdrawal_history = !data.withdrawals.is_empty();
game.withdrawals = data
.withdrawals
.into_iter()
.filter(|(cursor, _)| *cursor <= to)
.collect();
if full_replay || !has_withdrawal_history {
game.dropped_players = data.dropped_players;
}
// Clock totals belong to the live session, not the historical position.
// Reconstructing any cursor must neither earn nor revoke existing credits.
game.time_increments = data.time_increments;

View file

@ -59,6 +59,7 @@ pub(crate) fn execute(mut game: Game, action: Action, actor: usize) -> Result<Ga
revealed || next.active_player() != before_player || next.state == GameState::Finished
});
if eligible
&& !next.dropped_players.contains(&actor)
&& boundary
&& next
.players

300
server/src/withdrawal.rs Normal file
View file

@ -0,0 +1,300 @@
//! Withdrawal is a platform policy, not a civilization conversion or a full-turn AI.
//! Only explicit dropped seats are automated. Optional commitments are declined;
//! mandatory choices use stable request order and the ordinary legality constraints.
use crate::action::Action;
use crate::content::persistent_events::{
EventResponse, MultiRequest, PaymentRequest, PersistentEventRequest, PersistentEventType,
is_selected_structures_valid,
};
use crate::game::{Game, GameState};
use crate::resource::ResourceType::*;
use crate::resource_pile::ResourcePile;
use itertools::Itertools;
use std::collections::HashSet;
const SEARCH_LIMIT: usize = 100_000;
pub(crate) const AMBIGUOUS_OWNER: &str =
"Cannot prove the owner of the legacy withdrawn turn-start continuation";
pub(crate) const CASCADE_LIMIT: &str = "Automatic decision cascade exceeded 512 steps";
pub(crate) const NO_PROGRESS: &str = "Withdrawal response made no progress";
fn first_selection<T: Clone>(
request: &MultiRequest<T>,
valid: impl Fn(&[T]) -> bool,
) -> Result<Vec<T>, String> {
let mut budget = SEARCH_LIMIT;
for count in *request.needed.start()..=*request.needed.end() {
for selected in request
.choices
.iter()
.cloned()
.combinations(usize::from(count))
{
if budget == 0 {
return Err("Withdrawal selection search limit exceeded".into());
}
budget -= 1;
if valid(&selected) {
return Ok(selected);
}
}
}
Err("No legal withdrawal selection".into())
}
// Search whole payment groups, not greedily: a flexible first cost must not use
// the only resource that can satisfy a later fixed cost. Branch by reducing one
// component of a rejected recommendation. Any useful alternative must conserve
// at least one component; spending more of every component cannot help the suffix.
fn payments(
requests: &[PaymentRequest],
available: &ResourcePile,
) -> Result<Vec<ResourcePile>, String> {
fn search(
requests: &[PaymentRequest],
available: &ResourcePile,
budget: &mut usize,
) -> Option<Vec<ResourcePile>> {
let Some((request, rest)) = requests.split_first() else {
return Some(vec![]);
};
if request.optional {
let mut suffix = search(rest, available, budget)?;
suffix.insert(0, ResourcePile::empty());
return Some(suffix);
}
let mut caps = vec![available.clone()];
let mut visited = HashSet::new();
while let Some(cap) = caps.pop() {
if !visited.insert(cap.clone()) {
continue;
}
if *budget == 0 {
return None;
}
*budget -= 1;
let Some(payment) = request.cost.first_valid_payment(&cap) else {
continue;
};
let mut remaining = available.clone();
remaining -= payment.clone();
if let Some(mut suffix) = search(rest, &remaining, budget) {
suffix.insert(0, payment);
return Some(suffix);
}
for resource in [
Captives,
CultureTokens,
MoodTokens,
Gold,
Ideas,
Ore,
Wood,
Food,
] {
let amount = payment.get(&resource);
if amount > 0 {
let mut next = cap.clone();
*next.get_mut(&resource) = amount - 1;
caps.push(next);
}
}
}
None
}
let mut budget = SEARCH_LIMIT;
search(requests, available, &mut budget)
.ok_or_else(|| "No legal withdrawal payment within search budget".into())
}
pub(crate) fn response(game: &Game) -> Result<EventResponse, String> {
let event = game.events.last().ok_or("No withdrawal event")?;
let handler = event
.player
.handler
.as_ref()
.ok_or("Withdrawal event has no handler")?;
let player = game.player(event.player.index);
let missing = || "Withdrawal request has no legal choice".to_string();
Ok(match &handler.request {
PersistentEventRequest::Payment(requests) => {
EventResponse::Payment(payments(requests, &player.resources)?)
}
PersistentEventRequest::ResourceReward(request) => {
let options = &request.reward.payment_options;
let reward = options.default.clone();
if !options.is_valid_payment(&reward) {
return Err("Invalid default withdrawal reward".into());
}
EventResponse::ResourceReward(reward)
}
PersistentEventRequest::SelectAdvance(r) => {
EventResponse::SelectAdvance(*r.choices.first().ok_or_else(missing)?)
}
PersistentEventRequest::SelectPlayer(r) => {
EventResponse::SelectPlayer(*r.choices.first().ok_or_else(missing)?)
}
PersistentEventRequest::SelectUnitType(r) => {
EventResponse::SelectUnitType(*r.choices.first().ok_or_else(missing)?)
}
PersistentEventRequest::SelectPositions(r) => {
EventResponse::SelectPositions(first_selection(r, |_| true)?)
}
PersistentEventRequest::SelectCaptives(r) => {
EventResponse::SelectCaptives(first_selection(r, |_| true)?)
}
PersistentEventRequest::SelectUnits(r) => {
EventResponse::SelectUnits(first_selection(&r.request, |s| {
crate::unit::validate_units_selection(s, game, game.player(r.player)).is_ok()
})?)
}
PersistentEventRequest::SelectHandCards(r) => {
EventResponse::SelectHandCards(first_selection(r, |s| {
crate::card::validate_card_selection(s, game).is_ok()
})?)
}
PersistentEventRequest::SelectStructures(r) => {
let mut selected = first_selection(r, |s| {
let mut sorted = s.to_vec();
sorted.sort();
is_selected_structures_valid(game, &sorted)
})?;
selected.sort();
EventResponse::SelectStructures(selected)
}
PersistentEventRequest::BoolRequest(_) => EventResponse::Bool(false),
PersistentEventRequest::ChangeGovernment => {
let count = crate::status_phase::government_advances(player, game)
.len()
.saturating_sub(1);
let government = game
.cache
.get_governments()
.iter()
.find(|g| {
player.can_advance_ignore_contradicting(g.advances[0].advance, game)
&& g.advances.len() > count
})
.ok_or_else(missing)?;
EventResponse::ChangeGovernmentType(crate::status_phase::ChangeGovernment::new(
government.name.clone(),
government
.advances
.iter()
.skip(1)
.take(count)
.map(|a| a.advance)
.collect(),
))
}
PersistentEventRequest::ExploreResolution => {
let PersistentEventType::ExploreResolution(explore) = &event.event_type else {
return Err("Invalid withdrawal exploration event".into());
};
EventResponse::ExploreResolution(explore.block.position.rotation)
}
})
}
pub(crate) fn discard_plans(game: &mut Game) {
game.early_choices
.retain(|choice| !game.dropped_players.contains(&choice.player));
if game
.action_plan
.as_ref()
.is_some_and(|plan| game.dropped_players.contains(&plan.player))
{
game.action_plan = None;
}
}
/// One legal step only. The shared live boundary records and drains these steps.
/// Never skip an unresolved event, including events owned by a living opponent.
pub(crate) fn next_action(game: &Game) -> Result<Option<Action>, String> {
if matches!(game.state, GameState::Finished)
|| game.civilization_draft.is_some()
|| !game.dropped_players.contains(&game.active_player())
{
return Ok(None);
}
if !game.events.is_empty() {
return response(game).map(|response| Some(Action::Response(response)));
}
Ok(match game.state {
GameState::Playing => Some(Action::Playing(
crate::playing_actions::PlayingAction::EndTurn,
)),
GameState::Movement(_) => Some(Action::Movement(crate::movement::MovementAction::Stop)),
GameState::ChooseCivilization => Some(Action::ChooseCivilization(
crate::game_setup::civilization_choices(game, game.active_player())
.first()
.ok_or("No civilization available for withdrawn seat")?
.name
.clone(),
)),
GameState::Finished => None,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::events::EventOrigin;
use crate::payment::{PaymentConversion, PaymentOptions};
#[test]
fn payment_groups_backtrack_and_decline_optional_without_rng() {
let origin = EventOrigin::Ability("withdrawal test".into());
let flexible = PaymentOptions::new(
ResourcePile::food(1),
vec![PaymentConversion::unlimited(
ResourcePile::food(1),
ResourcePile::wood(1),
)],
vec![],
origin.clone(),
);
let fixed = PaymentOptions::new(ResourcePile::food(1), vec![], vec![], origin);
let requests = vec![
PaymentRequest::optional(fixed.clone(), "decline"),
PaymentRequest::mandatory(flexible, "flexible"),
PaymentRequest::mandatory(fixed, "fixed"),
];
let available = ResourcePile::food(1) + ResourcePile::wood(1);
assert_eq!(
payments(&requests, &available).unwrap(),
vec![
ResourcePile::empty(),
ResourcePile::wood(1),
ResourcePile::food(1)
]
);
assert!(payments(&requests, &ResourcePile::food(1)).is_err());
}
#[test]
fn pathological_selection_exhausts_budget_explicitly() {
let request = MultiRequest::new((0..24).collect::<Vec<_>>(), 12..=12, "mandatory");
assert_eq!(
first_selection(&request, |_| false).unwrap_err(),
"Withdrawal selection search limit exceeded"
);
let empty = MultiRequest::<u8>::new(vec![], 1..=1, "mandatory");
assert_eq!(
first_selection(&empty, |_| true).unwrap_err(),
"No legal withdrawal selection"
);
}
#[test]
fn selection_prefers_minimum_but_searches_past_invalid_prefix() {
let request = MultiRequest::new(vec![1, 2, 3], 2..=3, "mandatory");
assert_eq!(
first_selection(&request, |s| !s.contains(&1)).unwrap(),
vec![2, 3]
);
let optional = MultiRequest::new(vec![1, 2, 3], 0..=3, "optional");
assert!(first_selection(&optional, |_| true).unwrap().is_empty());
}
}

View file

@ -1,5 +1,4 @@
use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::{PersistentEventState, PersistentEventType};
use crate::game::{Game, GameContext, GameState};
use crate::game_setup::{GameSetupBuilder, setup_game};
use crate::resource_pile::ResourcePile;
@ -56,7 +55,7 @@ fn withdrawal_banking_starts_successor_once_and_preserves_seats() {
.insert("personal".into(), "stale".into());
let resources = game.player(2).resources.clone();
game.drop_player(2);
assert_eq!(game.player(2).resources, resources);
assert_eq!(game.player(2).resources, resources + ResourcePile::gold(1));
assert!(game.player(2).event_info.is_empty());
assert!(game.events.is_empty());
assert_eq!(game.current_player_index, 3);
@ -82,7 +81,7 @@ fn withdrawal_banking_legacy_advanced_pointer_recovers_once() {
assert_eq!(game.current_player_index, 3);
assert!(game.events.is_empty());
assert_eq!(game.actions_left, 2);
assert_eq!(game.player(2).resources, ResourcePile::gold(1));
assert_eq!(game.player(2).resources, ResourcePile::gold(2));
let saved = snapshot(&game);
assert_eq!(snapshot(&reload(&game)), saved);
game.drop_player(2);
@ -115,25 +114,12 @@ fn withdrawal_banking_round_boundary_and_first_seat() {
}
#[test]
fn withdrawal_does_not_discard_nested_or_other_handlers() {
fn withdrawal_invalid_handler_fails_without_discarding_state() {
let mut game = banking();
game.events.push(PersistentEventState::new(
2,
PersistentEventType::ChooseActionCard,
None,
));
let events = game.events.clone();
game.drop_player(2);
assert_eq!(game.events, events);
assert_eq!(reload(&game).events, events);
let mut game = banking();
game.events[0].player.handler.as_mut().unwrap().origin =
crate::events::EventOrigin::Ability("Not Banking".into());
let events = game.events.clone();
game.drop_player(2);
assert_eq!(game.events, events);
assert_eq!(reload(&game).events, events);
game.events.last_mut().unwrap().player.handler = None;
let before = snapshot(&game);
assert!(crate::withdrawal::response(&game).is_err());
assert_eq!(snapshot(&game), before);
}
#[test]
@ -157,3 +143,46 @@ fn withdrawal_legacy_does_not_restart_an_already_started_successor() {
assert_eq!(restored.events, old.events);
assert_eq!(snapshot(&restored), snapshot(&old));
}
#[test]
fn withdrawal_replay_records_drop_boundary_and_skipped_future_turns() {
for offset in [0, 1] {
replay_withdrawal(offset);
}
}
fn replay_withdrawal(offset: usize) {
let mut game = setup_game(
&GameSetupBuilder::new(4)
.seed("withdraw-replay".into())
.assigned_civilizations(vec![
"Greece".into(),
"China".into(),
"Persia".into(),
"Rome".into(),
])
.build(),
);
let dropped = (game.current_player_index + offset) % 4;
game.drop_player(dropped);
for _ in 0..25 {
let actor = game.active_player();
let action = if game.events.is_empty() {
crate::action::Action::Playing(crate::playing_actions::PlayingAction::EndTurn)
} else {
crate::action::Action::Response(crate::withdrawal::response(&game).unwrap())
};
game = crate::board_history::execute(game, action, actor).unwrap();
}
let replay_data =
serde_json::from_value(serde_json::to_value(game.cloned_data()).unwrap()).unwrap();
let replayed = crate::replay::replay(replay_data, None).unwrap();
assert_eq!(replayed.current_player_index, game.current_player_index);
assert_eq!(replayed.starting_player_index, game.starting_player_index);
assert_eq!(replayed.round, game.round);
assert_eq!(replayed.age, game.age);
assert_eq!(replayed.events, game.events);
assert_eq!(replayed.dropped_players, game.dropped_players);
assert_eq!(replayed.withdrawals, game.withdrawals);
assert_eq!(replayed.rng.seed, game.rng.seed);
}

View file

@ -0,0 +1,266 @@
//! Fixed synthetic fixtures; no production saves or time-expiration inference.
use serde_json::{Value, json};
use server::{
cache::Cache,
game::{Game, GameContext},
game_api_wrapper,
game_data::GameData,
};
fn load(v: Value) -> Game {
let d: GameData = serde_json::from_value(v).unwrap();
let cache = Cache::new(&d.options);
Game::from_data(d, cache, GameContext::Play)
}
fn data(g: &Game) -> Value {
serde_json::to_value(g.cloned_data()).unwrap()
}
fn play(g: Game, p: usize, a: Value) -> Game {
load(
serde_json::from_str(&game_api_wrapper::execute_move(
data(&g).to_string(),
a.to_string(),
p,
))
.unwrap(),
)
}
fn drop(g: Game, p: usize) -> Game {
load(
serde_json::from_str(&async_std::task::block_on(game_api_wrapper::drop_player(
data(&g).to_string(),
p,
)))
.unwrap(),
)
}
fn fixture(raw: &str) -> Value {
let mut v: Value = serde_json::from_str(raw).unwrap();
let mut third = v["players"][0].clone();
third["id"] = json!(2);
third["civilization"] = json!("Persia");
third["units"] = json!([]);
third["cities"] = json!([{"position":"B2","mood_state":"Happy"}]);
third["objective_cards"] = json!([]);
third["action_cards"] = json!([]);
let players = v["players"].as_array_mut().unwrap();
players.insert(2, third);
for (index, player) in players.iter_mut().enumerate() {
player["id"] = json!(index);
}
v
}
fn battle() -> Game {
let mut v = fixture(include_str!("test_games/tactics_cards/peltasts.json"));
for p in 0..2 {
v["players"][p]["advances"]
.as_array_mut()
.unwrap()
.push(json!("SteelWeapons"));
}
v["players"][0]["action_cards"] = json!([3, 6, 11]);
v["players"][1]["action_cards"] = json!([4, 7, 23]);
play(
load(v),
0,
json!({"Movement":{"Move":{"units":[0,1,2],"destination":"C1","payment":{}}}}),
)
}
fn defender(g: Game) -> Game {
let g = play(g, 0, json!({"Response":{"Payment":[{}]}}));
play(g, 0, json!({"Response":{"SelectHandCards":[]}}))
}
#[test]
fn dropped_defender_declines_steel_and_tactics_but_keeps_passive_board() {
let g = defender(battle());
assert_eq!(g.active_player(), 1);
let ore = g.player(1).resources.ore;
let cards = g.player(1).action_cards.clone();
let clocks = server::timing::time_increments(&g);
let g = drop(g, 1);
assert_eq!(g.player(1).resources.ore, ore);
assert_eq!(g.player(1).action_cards, cards);
assert!(!g.player(1).cities.is_empty());
assert_eq!(server::timing::time_increments(&g), clocks);
assert_ne!(g.active_player(), 1);
assert_ne!(g.state, server::game::GameState::Finished);
let saved = data(&g);
assert_eq!(data(&drop(g, 1)), saved);
}
#[test]
fn future_dropped_defender_settles_at_ordinary_exported_move_boundary() {
let g = battle();
let before = g.events.clone();
let g = drop(g, 1);
assert_eq!(g.events, before); // never submit the living attacker's choices
let g = defender(g);
assert_ne!(g.active_player(), 1);
assert_eq!(server::timing::time_increments(&g)[1], 0);
}
#[test]
fn mandatory_dropped_casualties_are_removed_before_living_retreat() {
let mut v = fixture(include_str!("test_games/combat/retreat.json"));
v["players"][0]["units"]
.as_array_mut()
.unwrap()
.retain(|u| u["id"].as_u64().unwrap() < 4);
for unit in v["players"][0]["units"].as_array_mut().unwrap() {
unit["unit_type"] = json!("Infantry");
}
v["players"][1]["units"] = json!([
{"id":0,"position":"C1","unit_type":"Cavalry"},
{"id":1,"position":"C1","unit_type":"Cavalry"},
{"id":2,"position":"C1","unit_type":"Cavalry"},
{"id":3,"position":"C1","unit_type":"Infantry"}
]);
let mut g = load(v);
g.dice_roll_outcomes = vec![4; 8];
let g = play(
g,
0,
json!({"Movement":{"Move":{"units":[0,1,2,3],"destination":"C1","payment":{}}}}),
);
assert_eq!(g.active_player(), 1);
assert!(matches!(
g.current_event_handler().unwrap().request,
server::content::persistent_events::PersistentEventRequest::SelectUnits(_)
));
let g = drop(g, 1);
assert_eq!(g.player(1).units.len(), 2);
assert_eq!(g.player(0).units.len(), 2);
assert_eq!(g.active_player(), 0);
assert!(matches!(
g.current_event_handler().unwrap().request,
server::content::persistent_events::PersistentEventRequest::BoolRequest(_)
));
let saved = data(&g);
assert_eq!(data(&load(saved.clone())), saved);
}
#[test]
fn pending_status_advance_stays_attributed_to_departed_seat() {
let mut g = load(fixture(include_str!(
"test_games/status_phase/free_advance.json"
)));
g = play(g, 0, json!({"Playing":"EndTurn"}));
assert_eq!(g.active_player(), 1);
let before = g.player(0).advances.clone();
let g = drop(g, 1);
assert_eq!(g.player(0).advances, before);
assert_ne!(g.active_player(), 1);
assert!(!g.events.is_empty());
}
#[test]
fn withdrawal_after_government_payment_completes_without_paying_twice() {
let g = load(fixture(include_str!(
"test_games/status_phase/change_government.json"
)));
let g = play(g, 1, json!({"Response":{"SelectPositions":[]}}));
let g = if g.active_player() == 2 {
play(g, 2, json!({"Response":{"SelectPositions":[]}}))
} else {
g
};
let g = play(
g,
0,
json!({"Response":{"Payment":[{"culture_tokens":1,"mood_tokens":1}]}}),
);
assert!(matches!(
g.current_event_handler().unwrap().request,
server::content::persistent_events::PersistentEventRequest::ChangeGovernment
));
let resources = g.player(0).resources.clone();
let g = drop(g, 0);
assert_eq!(g.player(0).resources.mood_tokens, resources.mood_tokens);
assert_eq!(
g.player(0).resources.culture_tokens,
resources.culture_tokens
);
assert_ne!(g.active_player(), 0);
}
#[test]
fn withdrawal_during_living_defender_choice_preserves_suspended_turn_owner() {
let g = defender(battle());
let events = g.events.clone();
let g = drop(g, 0);
assert_eq!(g.current_player_index, 0);
assert_eq!(g.active_player(), 1);
assert_eq!(g.events, events);
let g = play(g, 1, json!({"Response":{"Payment":[{}]}}));
let g = play(g, 1, json!({"Response":{"SelectHandCards":[]}}));
assert_ne!(g.active_player(), 0);
assert!(!g.dropped_players.contains(&g.active_player()));
}
#[test]
fn withdrawal_last_survivor_and_no_survivors_have_terminal_rankings() {
let g = drop(battle(), 0);
let g = drop(g, 1);
assert_eq!(g.state, server::game::GameState::Finished);
assert!(g.events.is_empty());
assert_eq!(server::game_api::rankings(&g)[2], 1);
let g = drop(g, 2);
assert_eq!(server::game_api::rankings(&g), vec![1, 1, 1]);
}
#[test]
fn captured_city_still_grants_dropped_loser_mandatory_settler() {
let mut v = fixture(include_str!("test_games/combat/capture_and_raze_city.json"));
v["players"][1]["cities"]
.as_array_mut()
.unwrap()
.push(json!({"position":"B1","mood_state":"Happy"}));
let g = play(
load(v),
0,
json!({"Movement":{"Move":{"units":[0,1,2,3],"destination":"C1","payment":{}}}}),
);
assert_eq!(g.active_player(), 1);
assert!(matches!(
g.current_event_handler().unwrap().request,
server::content::persistent_events::PersistentEventRequest::SelectPositions(_)
));
let before = g
.player(1)
.units
.iter()
.filter(|u| u.unit_type == server::unit::UnitType::Settler)
.count();
let g = drop(g, 1);
assert_eq!(
g.player(1)
.units
.iter()
.filter(|u| u.unit_type == server::unit::UnitType::Settler)
.count(),
before + 1
);
assert_ne!(g.active_player(), 1);
}
#[test]
fn legacy_advanced_pointer_is_repaired_only_on_authoritative_reconciliation() {
let g = defender(battle());
let mut v = data(&g);
v["dropped_players"] = json!([0]);
v["current_player_index"] = json!(1);
let g = load(v);
assert_eq!(g.current_player_index, 1); // a query/load does not commit a repair
let events = g.events.clone();
let g = drop(g, 0); // explicit authorized engine reconciliation, not a viewer read
assert_eq!(g.current_player_index, 0);
assert_eq!(g.active_player(), 1);
assert_eq!(g.events, events);
}
#[test]
fn withdrawal_discards_only_departed_private_plans() {
let mut v = data(&defender(battle()));
v["action_plan"] =
json!({"player":0,"key":"private","actions":[{"Playing":"EndTurn"}],"waiting":true});
v["early_choices"] = json!([
{"player":0,"key":"status/private","response":{"Bool":true}},
{"player":2,"key":"status/live","response":{"Bool":true}}
]);
let g = drop(load(v), 0);
assert!(g.action_plan.is_none());
assert_eq!(g.early_choices.len(), 1);
assert_eq!(g.early_choices[0].player, 2);
assert_eq!(g.active_player(), 1);
}

View file

@ -1799,3 +1799,21 @@ participant action row or seat mutation. All 17 locales include the label.
See [Raiders verification](raiders-trade-guide.md). Publish the matching viewer and
engine together; achievement catalog 8 (46 entries), art 4, all 60 named assets,
gallery, Standard variant and existing settings/preferences/options remain intact.
# Viewer 0.1.238 / engine 0.4.169 — explicit withdrawal progress
Only explicit platform withdrawal authorizes deterministic completion of pending
mandatory decisions and declining optional commitments for that seat. Living
responders keep control; normal dropped turns are skipped, not played by an AI.
Responses are recorded with their actual actor, clock increments are preserved,
and new withdrawal boundaries reconstruct in replay. See
[withdrawal policy and limits](../../docs/withdrawal-progress.md) for bounded
search, old-save limitations and fixture coverage (not universal scenario coverage).
Push matching source and require exact-commit Check and Web viewer CI green
before publishing the frozen viewer and engine together. Catalog 8 / 46 entries,
artwork 4, all 60 named assets, gallery, Standard options, settings and preferences
remain unchanged. The artwork lockfile pin changes only for the viewer version.
This code release cannot repair BGS responder metadata on already-blocked games;
no production save reconciliation, batch replay, forced moves or clock edits are
authorized or performed.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.237",
"version": "0.1.238",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.237",
"version": "0.1.238",
"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.237",
"version": "0.1.238",
"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 scripts/boarding.test.mjs scripts/raiders.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": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs scripts/boarding.test.mjs scripts/raiders.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 ../scripts/withdrawal.test.cjs",
"test:boarding": "npm run build:bridge && npm run build && node --test scripts/boarding.test.mjs && node scripts/boarding-smoke.mjs",
"test:home-orientation": "npm run build && node scripts/home-orientation-smoke.mjs",
"build:achievement-assets": "node scripts/build-achievement-assets.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": "2c2de2c40d022c6eef85578ee7949cc0dc0de9f5fc64f860d1b7581dcb1796fc",
"web-client/package-lock.json": "18e8eb271d15adbf54933db2dee15ce50e6ffc3f60bdec0dee7c1373243424d3",
"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.168",
"version": "0.4.169",
"description": "Clash of Cultures: Monumental edition engine for Boardgamers Space",
"license": "MIT",
"type": "commonjs",

View file

@ -53,9 +53,10 @@ function rust(directory) {
const file = path.join(directory, item.name);
// BGS consumes this catalog as platform metadata, not viewer-localized prose.
// It has its own revisioned names/descriptions and is never rendered by this viewer.
// Timing/withdrawal modules below contain internal diagnostics, not localized rules.
if (item.name === 'achievements.rs') continue;
if (item.isDirectory()) rust(file);
else if (item.name.endsWith('.rs') && !/(?:^|_)tests?\.rs$/.test(item.name) && item.name !== 'timing.rs') {
else if (item.name.endsWith('.rs') && !/(?:^|_)tests?\.rs$/.test(item.name) && !['timing.rs', 'withdrawal.rs'].includes(item.name)) {
const content = fs.readFileSync(file, 'utf8');
for (const { value, start } of rustStrings(content)) {
// Ignore test modules and diagnostics: these are not player-facing rules.

View file

@ -0,0 +1,66 @@
// Synthetic fixed dice only: never read or mutate a production game.
// CLASH_WASM and CLASH_VIEWER_DIR can point at downloaded release artifacts.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from 'playwright';
const root = fileURLToPath(new URL('..', import.meta.url));
const engine = createRequire(import.meta.url)(process.env.CLASH_WASM || '../.engine/server.js');
const viewer = process.env.CLASH_VIEWER_DIR || path.join(root, 'dist');
let game = JSON.parse(await readFile(new URL('../../server/tests/test_games/combat/retreat.json', import.meta.url)));
const third = structuredClone(game.players[0]);
Object.assign(third, { id: 2, civilization: 'Persia', units: [], cities: [{ position: 'B2', mood_state: 'Happy' }], action_cards: [], objective_cards: [] });
game.players.splice(2, 0, third);
game.players.forEach((p, i) => p.id = i);
game.players[0].units = game.players[0].units.filter(u => u.id < 4).map(u => ({ ...u, unit_type: 'Infantry' }));
game.players[1].units = Array.from({ length: 4 }, (_, id) => ({ id, position: 'C1', unit_type: id === 3 ? 'Infantry' : 'Cavalry' }));
game.dice_roll_outcomes = Array(8).fill(4);
let raw = engine.move(JSON.stringify(game), JSON.stringify({ Movement: { Move: { units: [0, 1, 2, 3], destination: 'C1', payment: {} } } }), 0);
assert.equal(engine.currentPlayer(raw), 1);
const clocks = engine.timeIncrements(raw);
raw = await engine.dropPlayer(raw, 1);
game = JSON.parse(raw);
assert.equal(game.players[1].units.length, 2);
assert.equal(engine.currentPlayer(raw), 0);
assert.equal(game.events.at(-1).handler.request.BoolRequest, 'Do you want to retreat?');
assert.deepEqual(engine.timeIncrements(raw), clocks);
const browser = await chromium.launch({ headless: true, args: ['--use-gl=angle', '--use-angle=swiftshader'] });
try {
for (const width of [1400, 390]) {
const page = await browser.newPage({ viewport: { width, height: 900 } });
const errors = [], sent = [];
page.on('pageerror', e => errors.push(e.message));
await page.exposeFunction('recordMove', action => sent.push(action));
await page.route('**/*', async route => {
const name = new URL(route.request().url()).pathname;
if (name === '/') 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(name)) return route.abort();
return route.fulfill({ contentType: name.endsWith('.wasm') ? 'application/wasm' : 'text/javascript', body: await readFile(path.join(viewer, name)) });
});
await page.goto('http://clash.test/');
await page.waitForFunction(() => typeof window.clash3d !== 'undefined');
await page.evaluate(state => {
window.host = clash3d.launch('#app');
host.on('move', action => window.recordMove(action));
host.emit('player', { index: 0 });
host.emit('preferences', { sound: false, reducedMotion: true });
host.emit('state', state);
}, engine.stripSecret(raw, 0));
const skip = page.getByRole('button', { name: 'Skip', exact: true });
await skip.waitFor();
await skip.click();
await page.getByText('Do you want to retreat?', { exact: true }).waitFor();
await page.getByRole('button', { name: /^Retreat$/i }).waitFor();
await page.getByRole('button', { name: /^Continue battle$/i }).waitFor();
await page.waitForTimeout(300);
assert.deepEqual(sent, [], 'viewer must not invent any living-player action');
assert.deepEqual(errors, []);
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
await page.close();
console.log(`${width}px: dropped defender mandatory casualties resolved; living retreat visible, zero viewer moves.`);
}
} finally {
await browser.close();
}

View file

@ -21,7 +21,7 @@ async function bankingFixture() {
return pending;
}
test('four-seat Banking withdrawal skips the reward and starts Rome exactly once', async () => {
test('four-seat Banking withdrawal resolves the mandatory reward and starts Rome exactly once', async () => {
const g = await bankingFixture();
const raw = await engine.dropPlayer(JSON.stringify(g), 2);
const result = JSON.parse(raw);
@ -29,7 +29,7 @@ test('four-seat Banking withdrawal skips the reward and starts Rome exactly once
assert.equal(result.actions_left, 2);
assert.equal(result.round, 2);
assert.equal(result.events?.length ?? 0, 0);
assert.deepEqual(result.players[2].resources, { gold: 1 });
assert.deepEqual(result.players[2].resources, { gold: 2 });
assert.equal(result.players.length, 6);
assert.equal(await engine.dropPlayer(raw, 2), raw);
const next = JSON.parse(engine.tryMove(raw, JSON.stringify({ Playing: 'EndTurn' }), 3));
@ -46,6 +46,8 @@ test('legacy advanced-pointer Banking save normalizes consistently at every engi
assert.equal(engine.currentPlayer(raw), 3);
const normalized = await engine.dropPlayer(raw, 2);
assert.equal(JSON.parse(normalized).actions_left, 2);
assert.deepEqual(JSON.parse(normalized).players[2].resources, { gold: 2 });
assert.deepEqual(engine.timeIncrements(normalized), engine.timeIncrements(raw));
assert.equal(await engine.dropPlayer(normalized, 2), normalized);
const move = JSON.stringify({ Playing: 'EndTurn' });
assert.equal(engine.tryMove(raw, move, 3), engine.tryMove(normalized, move, 3));