From 89c3ef17ec74f7f3134efd8d7650e4daca485067 Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Thu, 5 Nov 2026 00:37:10 +0000 Subject: [PATCH] Cache private Calendar knowledge and isolate Voting and Sparta fees --- client/src/log_ui.rs | 2 + docs/calendar-known-top.md | 48 +++ server/src/action.rs | 11 +- server/src/board_history.rs | 43 ++- server/src/calendar_knowledge.rs | 97 ++++++ server/src/content/civilizations/greece.rs | 21 ++ server/src/content/civilizations/maya.rs | 7 +- server/src/game.rs | 4 + server/src/game_api.rs | 1 + server/src/game_data.rs | 10 + server/src/game_setup.rs | 2 + server/src/happiness.rs | 26 +- server/src/incident.rs | 9 +- server/src/lib.rs | 1 + server/src/log.rs | 3 +- server/src/move_summary.rs | 1 + server/src/payment.rs | 56 ++++ server/src/replay.rs | 9 + server/src/undo.rs | 5 +- server/tests/advances_tests.rs | 2 +- server/tests/calendar_incident_undo_tests.rs | 43 ++- server/tests/calendar_preview_tests.rs | 180 ++++++++++- server/tests/sparta_leader_payment_tests.rs | 152 ++++++++++ ...ease_happiness_voting_rituals.outcome.json | 8 +- server/tests/voting_rituals_tests.rs | 279 ++++++++++++++++++ web-client/docs/viewer-publishing.md | 6 + web-client/package-lock.json | 4 +- web-client/package.json | 2 +- web-client/scripts/calendar-preview-smoke.mjs | 11 + web-client/src/calendar-incident-undo.test.ts | 4 +- web-client/src/controller.ts | 51 +++- web-client/src/prediction.test.ts | 96 +++++- web-client/src/prediction.ts | 19 +- web-client/src/types.ts | 2 + 34 files changed, 1175 insertions(+), 40 deletions(-) create mode 100644 docs/calendar-known-top.md create mode 100644 server/src/calendar_knowledge.rs create mode 100644 server/tests/sparta_leader_payment_tests.rs create mode 100644 server/tests/voting_rituals_tests.rs diff --git a/client/src/log_ui.rs b/client/src/log_ui.rs index a7a4bdda..c7c91775 100644 --- a/client/src/log_ui.rs +++ b/client/src/log_ui.rs @@ -377,6 +377,8 @@ fn draw_action(drawer: &mut RichTextDrawer, body: &ActionLogBody) { } }, Action::Response(r) => draw_response_action(drawer, r), + // The live command expands into ordinary Calendar start/payment entries. + Action::CalendarBury { .. } => panic!("Unexpected Calendar command in log"), // Private queue revisions are live updates, never committed log entries. Action::QueueMoves { .. } | Action::QueueChoice { .. } => { panic!("Unexpected queued action in log"); diff --git a/docs/calendar-known-top.md b/docs/calendar-known-top.md new file mode 100644 index 00000000..eec60205 --- /dev/null +++ b/docs/calendar-known-top.md @@ -0,0 +1,48 @@ +# Calendar: private known-top state + +Calendar knowledge is live private state, not an action or a history entry. +`calendar_knowledge` stores the owner, actual turn identity (number of logged +turns), and last disclosed incident. It is outside undo patches. The existing +`undo_limit` remains the knowledge floor and cannot decrease during Undo. + +At the first legal Calendar/free-action boundary in the owner's actual turn, +`board_history::execute` records the current top privately and seals preceding +actions without awarding a clock credit. The boundary is after pending events, +automatic responses, and queued actions resolve. Acquiring Calendar mid-turn has +the same boundary: Astronomy is no longer refundable once its complete chain +has ended and the next incident has been privately supplied. The incident drawn +*inside* Astronomy or its Great Mausoleum continuation is not disclosed early. + +The turn marker prevents automatic disclosure of replacements after burial or +incident resolution. The owner must explicitly inspect the replacement, which +persists bounded private state and seals undo, but adds no action, log entry, +board snapshot, move count, or clock credit. Empty decks retain the existing +explicit authoritative inspection/refill behavior; no client simulates a refill. + +`strip_secret` only removes knowledge: it never creates it. Opponents and +spectators receive no cache. The owner receives a card identity only while it is +the actual known top. Internally the previous identity remains available so Undo +of burial or an incident restores the known card without another disclosure. +An incident that itself reveals a previously unknown top also remembers it. +Filtered states carry `secrets_stripped` so local execution cannot create +knowledge from their shuffled incident pile. The Calendar request renderer uses +the explicit identity, not that pile. Full reconstruction preserves the saved +cache and knowledge floor; historical cursors discard the private cache. + +The web controller opens/closes a known-card prompt locally, outside its move +outbox. Repeated opens, Keep, and Cancel send **zero backend calls**, leave all +committed history unchanged, and do not introduce an undo lock. Unknown-card +inspection and old saved transient prompts retain their existing host flow. + +A local prompt's paid choice sends `CalendarBury { turn, incident, payment }`. +The host validates ownership, availability, turn, current known top, and payment; +it then expands the command into the existing recorded Calendar start and paid +response. The command itself is never logged. Payments are never predicted. +Known recorded starts do not introduce a new information boundary; legacy +unknown starts still do. Learning the replacement seals the paid burial. + +Regression coverage includes turn entry, G5→F5→Stop→peek→Undo/Redo, acquisition, +Great Mausoleum deferral, empty piles, stale burial commands, filtered-state +privacy, full/historical reconstruction, and repeated local peek cycles. The +browser smoke checks local opens and closes in English/French at desktop/mobile +sizes, alongside the existing preview, privacy, and incident Undo/Redo checks. diff --git a/server/src/action.rs b/server/src/action.rs index d7ad83c6..65fa0bbb 100644 --- a/server/src/action.rs +++ b/server/src/action.rs @@ -37,6 +37,11 @@ pub enum Action { Playing(PlayingAction), Movement(MovementAction), Response(EventResponse), + CalendarBury { + turn: usize, + incident: u8, + payment: crate::resource_pile::ResourcePile, + }, QueueMoves { key: String, actions: Vec, @@ -100,7 +105,7 @@ pub fn try_execute_action( // mutate yet. Even lower-level callers must resolve it at the live boundary. // Recorded/replayed Calendar actions never carry this marker. Independent // private queue updates above must remain available to the other seats. - if game.uncommitted_calendar { + if game.uncommitted_calendar || matches!(action, Action::CalendarBury { .. }) { return crate::board_history::execute(game, action, player_index); } if game.civilization_draft.is_some() { @@ -133,12 +138,14 @@ pub fn try_execute_action( } let add_undo = !matches!(&action, Action::Undo); + let already_known = crate::calendar_knowledge::known(&game, player_index).is_some(); let calendar_incident = crate::incident::calendar_undo_candidate(&game, player_index); game.calendar_incident_undo = calendar_incident; let mut old = to_serde_value(&game); let old_player = game.active_player(); execute_without_undo(&mut game, action, player_index)?; - if game.calendar_incident_undo.take().is_none() && calendar_incident.is_some() { + if game.calendar_incident_undo.take().is_none() && calendar_incident.is_some() && !already_known + { // Treat this reveal like a free Calendar look just before the action. // Keep that knowledge boundary when applying the undo patch: otherwise // Undo could also refund Astronomy or a previous paid burial. diff --git a/server/src/board_history.rs b/server/src/board_history.rs index 43d8d18f..bedf7788 100644 --- a/server/src/board_history.rs +++ b/server/src/board_history.rs @@ -164,6 +164,37 @@ pub fn execute(mut game: Game, action: Action, player: usize) -> Result Result Result Result bool { diff --git a/server/src/calendar_knowledge.rs b/server/src/calendar_knowledge.rs new file mode 100644 index 00000000..ae23c2ec --- /dev/null +++ b/server/src/calendar_knowledge.rs @@ -0,0 +1,97 @@ +//! Private live knowledge, deliberately outside undo patches and public history. +use crate::content::custom_actions::{CustomActionType, SpecialAction}; +use crate::game::{Game, GameContext}; +use crate::playing_actions::PlayingActionType; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CalendarKnowledge { + pub player: usize, + pub turn: usize, + /// Last disclosed card, retained internally after a draw/burial for Undo. + /// Filtering hides it while it is not the actual top; never learns a replacement. + pub incident: Option, +} + +pub(crate) fn turn(game: &Game) -> usize { + game.log + .iter() + .flat_map(|a| &a.rounds) + .map(|r| r.turns.len()) + .sum() +} + +pub(crate) fn eligible(game: &Game, player: usize) -> bool { + game.civilization_draft.is_none() + && player == game.current_player_index + && player == game.active_player() + && game + .player(player) + .special_actions + .contains_key(&SpecialAction::Custom(CustomActionType::Calendar)) + && PlayingActionType::Special(SpecialAction::Custom(CustomActionType::Calendar)) + .is_available(game, player) + .is_ok() +} + +pub(crate) fn known(game: &Game, player: usize) -> Option { + let knowledge = game.calendar_knowledge.as_ref()?; + if knowledge.player != player || knowledge.turn != turn(game) { + return None; + } + let id = knowledge.incident?; + // Filtered clients use only the explicit disclosure, never their shuffled pile. + (game.secrets_stripped || game.incidents_left.first() == Some(&id)).then_some(id) +} + +pub(crate) fn disclose(game: &mut Game) { + if game.context != GameContext::Play || game.secrets_stripped { + return; + } + let player = game.current_player_index; + if !eligible(game, player) { + return; + } + let turn = turn(game); + if game + .calendar_knowledge + .as_ref() + .is_some_and(|k| k.turn == turn && k.player == player) + { + return; + } + // Empty piles deliberately retain the existing explicit authoritative reveal. + game.calendar_knowledge = Some(CalendarKnowledge { + player, + turn, + incident: game.incidents_left.first().copied(), + }); + if !game.incidents_left.is_empty() { + game.lock_undo(); + } +} + +pub(crate) fn remember(game: &mut Game, player: usize) { + game.calendar_knowledge = Some(CalendarKnowledge { + player, + turn: turn(game), + incident: game.incidents_left.first().copied(), + }); +} + +pub(crate) fn strip(game: &mut Game, viewer: Option) { + if viewer != Some(game.current_player_index) + || game + .calendar_knowledge + .as_ref() + .is_some_and(|k| Some(k.player) != viewer) + { + game.calendar_knowledge = None; + } else if !game.secrets_stripped { + let id = viewer.and_then(|p| known(game, p)); + if let Some(k) = &mut game.calendar_knowledge { + k.incident = id; + } + } + game.secrets_stripped = true; +} diff --git a/server/src/content/civilizations/greece.rs b/server/src/content/civilizations/greece.rs index 11bef3e0..d608fe75 100644 --- a/server/src/content/civilizations/greece.rs +++ b/server/src/content/civilizations/greece.rs @@ -64,6 +64,27 @@ fn sparta() -> SpecialAdvanceInfo { 0, |cost, units, game, p| { if units.infantry > 0 { + // Sparta substitutes only Draft's mood tokens. A leader recruited + // alongside Infantry still owes its normal mood token, including + // when the Infantry is bought with resources rather than Draft. + if units.leader.is_some() { + let leader_fee = ResourcePile::mood_tokens(1); + // Resolve the fee with general payment permissions only, + // before Draft/Sparta conversions can touch it. Colosseum + // may still substitute culture for the leader's mood. + let fee_options = p + .payment_options() + .resources(p.get(game), leader_fee.clone()); + cost.cost.separate_fee = vec![leader_fee]; + for resource in fee_options.possible_resource_types() { + let fee = ResourcePile::of(resource, 1); + if fee_options.is_valid_payment(&fee) + && !cost.cost.separate_fee.contains(&fee) + { + cost.cost.separate_fee.push(fee); + } + } + } cost.info .add_log(p, "Paid Draft with culture tokens"); cost.cost.conversions.insert( diff --git a/server/src/content/civilizations/maya.rs b/server/src/content/civilizations/maya.rs index 3b7503b2..3d364114 100644 --- a/server/src/content/civilizations/maya.rs +++ b/server/src/content/civilizations/maya.rs @@ -84,10 +84,11 @@ fn calendar() -> SpecialAdvanceInfo { "As a free action, look at the next event. You may pay 1 culture token to put it at the bottom of the deck, then use Calendar again.") .add_custom_action(CustomActionType::Calendar, |c| c.any_times().free_action().no_resources(), |b| b .add_persistent_event_listener(|e| &mut e.custom_action, 0, |game, p, _| { - let id = crate::card::draw_card_from_pile(game, p, "Events", |g| &mut g.incidents_left, + let known = crate::calendar_knowledge::known(game, p.index); + let id = if let Some(id) = known { id } else { crate::card::draw_card_from_pile(game, p, "Events", |g| &mut g.incidents_left, |g| g.cache.get_incidents().iter().map(|i| i.id).collect(), - |p| p.action_cards.iter().filter_map(|id| id.checked_sub(crate::content::incidents::great_persons::GREAT_PERSON_OFFSET)).collect()).expect("event deck"); - game.incidents_left.insert(0, id); + |p| p.action_cards.iter().filter_map(|id| id.checked_sub(crate::content::incidents::great_persons::GREAT_PERSON_OFFSET)).collect()).expect("event deck") }; + if known.is_none() { game.incidents_left.insert(0, id); } let card = game.cache.get_incident(id); let request = PaymentRequest::optional(p.payment_options().resources(p.get(game), ResourcePile::culture_tokens(1)), &format!("{} · {}\nPay 1 culture to put this event at the bottom, or keep it on top.", card.name, card.description(game).join(" "))); diff --git a/server/src/game.rs b/server/src/game.rs index e0764320..d1bcf838 100644 --- a/server/src/game.rs +++ b/server/src/game.rs @@ -138,6 +138,10 @@ pub struct Game { pub early_choice_update: bool, /// A private Calendar prompt, not yet part of the committed action history. pub uncommitted_calendar: bool, + /// Live private disclosure; not restored by undo patches. + pub calendar_knowledge: Option, + /// Filtered states must never create knowledge from shuffled hidden piles. + pub secrets_stripped: bool, pub action_plan: Option, // in turn order starting from starting_player_index and wrapping around pub players: Vec, diff --git a/server/src/game_api.rs b/server/src/game_api.rs index 9144d88f..9f7c5741 100644 --- a/server/src/game_api.rs +++ b/server/src/game_api.rs @@ -147,6 +147,7 @@ pub fn civilizations(game: Game) -> Vec { #[must_use] pub fn strip_secret(mut game: Game, player_index: Option) -> Game { + crate::calendar_knowledge::strip(&mut game, player_index); if game .action_plan .as_ref() diff --git a/server/src/game_data.rs b/server/src/game_data.rs index 30e98522..9664c9b6 100644 --- a/server/src/game_data.rs +++ b/server/src/game_data.rs @@ -51,6 +51,10 @@ pub struct GameData { #[serde(default, skip_serializing_if = "std::ops::Not::not")] uncommitted_calendar: bool, #[serde(default, skip_serializing_if = "Option::is_none")] + calendar_knowledge: Option, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + secrets_stripped: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] action_plan: Option, players: Vec, map: MapData, @@ -131,6 +135,8 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game { early_choices: data.early_choices, early_choice_update: data.early_choice_update, uncommitted_calendar: data.uncommitted_calendar, + calendar_knowledge: data.calendar_knowledge, + secrets_stripped: data.secrets_stripped, context, cache, options: data.options, @@ -198,6 +204,8 @@ pub fn data(game: Game) -> GameData { early_choices: game.early_choices, early_choice_update: game.early_choice_update, uncommitted_calendar: game.uncommitted_calendar, + calendar_knowledge: game.calendar_knowledge.clone(), + secrets_stripped: game.secrets_stripped, players: game.players.into_iter().map(player_data).collect(), map: game.map.data(), civilization_draft: game.civilization_draft, @@ -240,6 +248,8 @@ pub fn cloned_data(game: &Game) -> GameData { early_choices: game.early_choices.clone(), early_choice_update: game.early_choice_update, uncommitted_calendar: game.uncommitted_calendar, + calendar_knowledge: game.calendar_knowledge.clone(), + secrets_stripped: game.secrets_stripped, players: game.players.iter().map(cloned_player_data).collect(), map: game.map.cloned_data(), civilization_draft: game.civilization_draft.clone(), diff --git a/server/src/game_setup.rs b/server/src/game_setup.rs index 5d597144..2c279408 100644 --- a/server/src/game_setup.rs +++ b/server/src/game_setup.rs @@ -190,6 +190,8 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game { early_choices: vec![], early_choice_update: false, uncommitted_calendar: false, + calendar_knowledge: None, + secrets_stripped: false, seed: setup.seed.clone(), context: GameContext::Play, version: JSON_SCHEMA_VERSION, diff --git a/server/src/happiness.rs b/server/src/happiness.rs index 280a45d5..16cb7295 100644 --- a/server/src/happiness.rs +++ b/server/src/happiness.rs @@ -194,8 +194,30 @@ pub fn happiness_cost( city_size_steps, &[ResourceType::MoodTokens], ); - // either none or both can use Colosseum - payment_options.default += action_type.payment_options(game, player).default; + let activation_options = action_type.payment_options(game, player); + let activation_cost = activation_options.default.clone(); + // Voting's extra token is outside Rituals' city happiness payment, but + // retains its own legal conversions (notably Colosseum's mood/culture). + if matches!( + action_type, + PlayingActionType::Special(SpecialAction::Modifier( + PlayingActionModifier::VotingIncreaseHappiness + )) + ) { + // Voting has a one-token fee. Resolve its choices independently before + // the happiness listeners add Rituals' resource conversions. + assert_eq!(activation_cost.amount(), 1); + payment_options.separate_fee.push(activation_cost.clone()); + for resource in activation_options.possible_resource_types() { + let fee = ResourcePile::of(resource, 1); + if activation_options.is_valid_payment(&fee) + && !payment_options.separate_fee.contains(&fee) + { + payment_options.separate_fee.push(fee); + } + } + } + payment_options.default += activation_cost; p.trigger_cost_event( |e| &e.happiness_cost, diff --git a/server/src/incident.rs b/server/src/incident.rs index d7066b5b..eb188ba8 100644 --- a/server/src/incident.rs +++ b/server/src/incident.rs @@ -769,7 +769,11 @@ pub(crate) fn draw_and_discard_incident_card_from_pile( game.calendar_incident_undo = None; // This is equivalent to peeking immediately before the triggering // action, never to erasing a lock from dice, another card or a player. - let floor = game.log_index.saturating_sub(1); + let floor = if crate::calendar_knowledge::known(game, player.index).is_some() { + game.undo_limit + } else { + game.log_index.saturating_sub(1) + }; game.undo_limit = game.undo_limit.max(floor); for action in crate::log::current_turn_log_mut(game) .actions @@ -778,6 +782,9 @@ pub(crate) fn draw_and_discard_incident_card_from_pile( { action.undo.clear(); } + // The incident itself disclosed this card too. Keep that identity across + // Undo, without disclosing the replacement now at the top. + crate::calendar_knowledge::remember(game, player.index); game.incidents_left.remove(0) } else { draw_card_from_pile( diff --git a/server/src/lib.rs b/server/src/lib.rs index 861e457d..57860359 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -29,6 +29,7 @@ pub mod analysis; pub mod barbarians; pub mod board_history; pub mod cache; +pub mod calendar_knowledge; pub mod card; pub mod city; pub mod city_pieces; diff --git a/server/src/log.rs b/server/src/log.rs index f6c29004..74b5ecb6 100644 --- a/server/src/log.rs +++ b/server/src/log.rs @@ -457,7 +457,8 @@ fn action_origin(a: &Action, player: &Player) -> Option { Action::Movement(_) => Some(move_event_origin()), Action::Undo => panic!("Unexpected undo in log"), Action::Redo => panic!("Unexpected redo in log"), - Action::QueueMoves { .. } + Action::CalendarBury { .. } + | Action::QueueMoves { .. } | Action::QueueChoice { .. } | Action::StartTurn | Action::Response(_) diff --git a/server/src/move_summary.rs b/server/src/move_summary.rs index 8df188f6..3f686976 100644 --- a/server/src/move_summary.rs +++ b/server/src/move_summary.rs @@ -171,6 +171,7 @@ fn fallback(game: &Game, entry: &ActionLogAction) -> String { }, Action::Movement(_) => "Moved units".into(), Action::ChooseCivilization(name) => format!("Chose {name}"), + Action::CalendarBury { .. } => "Used an ability".into(), Action::QueueMoves { .. } => "Updated queued actions".into(), Action::QueueChoice { .. } => "Queued a choice".into(), Action::StartTurn => "Started turn".into(), diff --git a/server/src/payment.rs b/server/src/payment.rs index 15280709..84287469 100644 --- a/server/src/payment.rs +++ b/server/src/payment.rs @@ -77,6 +77,11 @@ pub struct PaymentOptions { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub alternatives: Vec, pub default: ResourcePile, + /// Separately converted fee: the first entry is included in `default` and + /// every alternative. Each entry is a complete legal fee payment; the outer + /// conversions apply only to the remaining cost, never to these entries. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub separate_fee: Vec, #[serde(default)] #[serde(skip_serializing_if = "Vec::is_empty")] pub conversions: Vec, @@ -97,6 +102,7 @@ impl PaymentOptions { PaymentOptions { alternatives: Vec::new(), default, + separate_fee: Vec::new(), conversions, modifiers, origin, @@ -109,6 +115,24 @@ impl PaymentOptions { } fn find_payment(&self, available: &ResourcePile, exact: bool) -> Option { + if let Some(default_fee) = self.separate_fee.first() { + let mut remainder = self.clone(); + remainder.default -= default_fee.clone(); + for alternative in &mut remainder.alternatives { + *alternative -= default_fee.clone(); + } + remainder.separate_fee.clear(); + return self.separate_fee.iter().find_map(|fee| { + if !available.has_at_least(fee) { + return None; + } + let mut remaining = available.clone(); + remaining -= fee.clone(); + remainder + .find_payment(&remaining, exact) + .map(|payment| payment + fee.clone()) + }); + } if !self.alternatives.is_empty() { let mut option = self.clone(); option.alternatives.clear(); @@ -277,6 +301,9 @@ impl PaymentOptions { for conversion in &self.conversions { vec.extend(conversion.to.types()); } + for fee in &self.separate_fee { + vec.extend(fee.types()); + } vec } @@ -642,6 +669,35 @@ pub(crate) fn base_resources() -> Vec { #[cfg(test)] mod tests { + #[test] + fn separate_fee_tries_all_choices_without_converting_the_fee() { + let mut cost = PaymentOptions::new( + ResourcePile::mood_tokens(2), + vec![PaymentConversion::unlimited( + ResourcePile::mood_tokens(1), + ResourcePile::wood(1), + )], + vec![], + check_event_origin(), + ); + cost.separate_fee = vec![ + ResourcePile::mood_tokens(1), + ResourcePile::culture_tokens(1), + ]; + // Spending mood on the fee first leaves an unusable culture token. + // The search must retry with culture reserved for the fee instead. + let payment = ResourcePile::mood_tokens(1) + ResourcePile::culture_tokens(1); + assert!(cost.is_valid_payment(&payment)); + assert_eq!(cost.first_valid_payment(&payment), Some(payment)); + assert!(!cost.is_valid_payment(&ResourcePile::wood(2))); + assert_eq!(cost.first_valid_payment(&ResourcePile::wood(2)), None); + assert!( + cost.possible_resource_types() + .contains(&ResourceType::CultureTokens) + ); + assert_eq!(cost.default_payment(), ResourcePile::mood_tokens(2)); + } + #[test] fn optional_token_discount_accepts_every_exact_payment_in_the_range() { use super::*; diff --git a/server/src/replay.rs b/server/src/replay.rs index 11de117b..274bece4 100644 --- a/server/src/replay.rs +++ b/server/src/replay.rs @@ -17,6 +17,8 @@ pub struct ReplayGameData { // Look-only information boundaries are intentionally absent from the log. #[serde(default)] undo_limit: Option, + #[serde(default)] + calendar_knowledge: Option, players: Vec, #[serde(default)] dropped_players: Vec, @@ -141,6 +143,9 @@ pub fn replay(data: ReplayGameData, to: Option) -> Result { game = try_execute_action(game, item.action.clone(), item.player) .map_err(|e| format!("Failed to replay move {}: {e}", i + 1))?; game.context = context; + if full_replay { + crate::calendar_knowledge::disclose(&mut game); + } } if log_length(&game) != to { return Err(format!( @@ -155,6 +160,7 @@ pub fn replay(data: ReplayGameData, to: Option) -> Result { // Reconstructing any cursor must neither earn nor revoke existing credits. game.time_increments = data.time_increments; if full_replay { + game.calendar_knowledge = data.calendar_knowledge; // Reconstructing a playable current save must not reopen actions sealed // by an unrecorded Calendar look. Historical cursors keep their own limits. if let Some(limit) = data.undo_limit { @@ -169,6 +175,9 @@ pub fn replay(data: ReplayGameData, to: Option) -> Result { } } game.finish_after_drop(); + } else { + // Historical cursors are not live private disclosures. + game.calendar_knowledge = None; } Ok(game) } diff --git a/server/src/undo.rs b/server/src/undo.rs index 9c842694..f8632759 100644 --- a/server/src/undo.rs +++ b/server/src/undo.rs @@ -5,7 +5,8 @@ use crate::movement::execute_movement_action; use json_patch::{PatchOperation, patch}; use serde_json::Value; -const IGNORE_PATHS: [&str; 6] = [ +const IGNORE_PATHS: [&str; 7] = [ + "/calendar_knowledge", "/log/", "/log_index", "/early_choices", @@ -44,8 +45,10 @@ pub(crate) fn undo(mut game: Game) -> Result { let mut v = to_serde_value(&game); + let floor = game.undo_limit; patch(&mut v, &p).map_err(|e| format!("Failed to apply patch: {e}"))?; + v["undo_limit"] = serde_json::json!(floor.max(v["undo_limit"].as_u64().unwrap_or(0) as usize)); Ok(Game::from_data( serde_json::from_value(v).map_err(|e| format!("Failed to deserialize game: {e}"))?, game.cache, diff --git a/server/tests/advances_tests.rs b/server/tests/advances_tests.rs index 073ffacc..9504742c 100644 --- a/server/tests/advances_tests.rs +++ b/server/tests/advances_tests.rs @@ -248,7 +248,7 @@ fn test_increase_happiness_voting_rituals() { (Position::from_offset("C2"), 1), (Position::from_offset("B3"), 2), ], - ResourcePile::new(1, 0, 1, 3, 1, 0, 0), + ResourcePile::new(1, 0, 1, 3, 0, 1, 0), PlayingActionType::Special(SpecialAction::Modifier( PlayingActionModifier::VotingIncreaseHappiness, )), diff --git a/server/tests/calendar_incident_undo_tests.rs b/server/tests/calendar_incident_undo_tests.rs index 44d9ae5e..8ebba347 100644 --- a/server/tests/calendar_incident_undo_tests.rs +++ b/server/tests/calendar_incident_undo_tests.rs @@ -216,9 +216,21 @@ fn deferred_astronomy_incident_does_not_use_new_calendar_through_a_wonder() { choosing.current_event_handler().unwrap().request, PersistentEventRequest::BoolRequest(_) )); + if !already_owned { + assert!( + choosing.calendar_knowledge.is_none(), + "deferred acquisition must not disclose the pending draw" + ); + } // The draw's direct origin is Great Mausoleum, not Astronomy. let resolved = play(choosing, Action::Response(EventResponse::Bool(false))); assert_eq!(resolved.can_undo(), already_owned); + if !already_owned { + assert_eq!( + resolved.calendar_knowledge.as_ref().unwrap().incident, + resolved.incidents_left.first().copied() + ); + } assert_eq!( time_increments(&resolved), if already_owned { [8, 5] } else { [9, 5] } @@ -231,7 +243,10 @@ fn implicit_calendar_knowledge_cannot_refund_earlier_astronomy() { let mut before = ready(29, false); before.player_mut(0).incident_tokens = 2; let astronomy = play(before, research(Advance::Astronomy)); - assert!(astronomy.can_undo()); + assert!( + !astronomy.can_undo(), + "acquisition disclosure seals Astronomy immediately" + ); assert!(astronomy.player(0).has_advance(Advance::Astronomy)); let game = play(astronomy.clone(), research(Advance::Storage)); let undone = play(load(saved(&game)), Action::Undo); @@ -260,9 +275,35 @@ fn implicit_calendar_knowledge_cannot_refund_a_previous_paid_burial() { ); assert!(buried.can_undo()); let game = play(buried.clone(), research(Advance::Storage)); + assert_eq!( + server::game_api::strip_secret(game.clone(), Some(0)) + .calendar_knowledge + .unwrap() + .incident, + None + ); let undone = play(game, Action::Undo); assert_same_position(&undone, &buried); assert!(!undone.can_undo()); + assert_eq!( + server::game_api::strip_secret(undone.clone(), Some(0)) + .calendar_knowledge + .unwrap() + .incident, + Some(29) + ); + let floor = undone.undo_limit; + let opened = play( + load(saved(&undone)), + Action::Playing(PlayingAction::Custom(CustomAction::new( + CustomActionType::Calendar, + None, + ))), + ); + assert_eq!( + opened.undo_limit, floor, + "the incident already disclosed this restored card" + ); } #[test] diff --git a/server/tests/calendar_preview_tests.rs b/server/tests/calendar_preview_tests.rs index 5d582b89..82590136 100644 --- a/server/tests/calendar_preview_tests.rs +++ b/server/tests/calendar_preview_tests.rs @@ -147,13 +147,12 @@ fn hundreds_of_keep_and_cancel_cycles_are_bounded_live_updates_without_clock_cre } #[test] -fn looking_seals_astronomy_but_cancels_only_the_uncommitted_prompt() { +fn acquisition_disclosure_seals_astronomy_but_cancels_only_the_uncommitted_prompt() { let before = before_astronomy(); let game = play(before.clone(), research(Advance::Astronomy)); - assert!(game.can_undo()); - let undone = play(game.clone(), Action::Undo); - assert!(!undone.player(0).advances.contains(Advance::Astronomy)); - assert_eq!(undone.player(0).resources, before.player(0).resources); + assert!(!game.can_undo()); + assert!(game.calendar_knowledge.as_ref().unwrap().incident.is_some()); + assert!(board_history::execute(game.clone(), Action::Undo, 0).is_err()); for close in [Action::Undo, keep()] { let peek = play(game.clone(), calendar()); assert_eq!(peek.undo_limit, peek.log_index); @@ -191,8 +190,8 @@ fn paid_burial_has_two_actions_and_one_step_undo_redo_until_the_next_look() { assert_eq!(undone.player(0).resources.culture_tokens, culture); assert!(!undone.uncommitted_calendar); assert!( - !undone.can_undo(), - "recorded look is an information boundary" + undone.can_undo(), + "recording an already known card introduces no information boundary" ); assert!(undone.can_redo()); assert!(prompt(&undone).starts_with(&undone.cache.get_incident(deck[0]).name)); @@ -370,6 +369,7 @@ fn full_replay_omits_transient_prompts_preserves_the_seal_and_reproduces_paid_ac assert_eq!(replayed.incidents_left, state.incidents_left); assert_eq!(replayed.rng.seed, state.rng.seed); assert_eq!(replayed.player(0).resources, state.player(0).resources); + assert_eq!(replayed.calendar_knowledge, state.calendar_knowledge); assert!(!replayed.uncommitted_calendar); assert!(replayed.events.is_empty()); assert!( @@ -385,9 +385,175 @@ fn full_replay_omits_transient_prompts_preserves_the_seal_and_reproduces_paid_ac assert_eq!(replayed.rng.seed, paid.rng.seed); assert_eq!(replayed.player(0).resources, paid.player(0).resources); assert_eq!(time_increments(&replayed), time_increments(&paid)); + assert_eq!(replayed.calendar_knowledge, paid.calendar_knowledge); + let historical = server::replay::replay( + serde_json::from_value(saved(&paid)).unwrap(), + Some(log_length(&paid) - 2), + ) + .unwrap(); + assert!(historical.calendar_knowledge.is_none()); assert!(replayed.can_undo()); let undone = play(replayed, Action::Undo); assert!(!undone.uncommitted_calendar); assert!(undone.can_redo()); assert_eq!(log_length(&undone), log_length(&paid) - 1); } + +#[test] +fn turn_start_known_card_survives_moves_repeated_peeks_reload_undo_and_redo() { + let game = play(ready(), Action::Playing(PlayingAction::EndTurn)); + assert!( + strip_secret(game.clone(), Some(0)) + .calendar_knowledge + .is_none() + ); + let start = board_history::execute(game, Action::Playing(PlayingAction::EndTurn), 1).unwrap(); + let known = start.calendar_knowledge.clone().unwrap(); + assert_eq!(known.incident, start.incidents_left.first().copied()); + assert_eq!(known.player, 0); + assert!(start.events.is_empty()); + let home = start.player(0).cities[0].position; + let mut moved = play( + start.clone(), + Action::Playing(PlayingAction::Collect(Collect::new( + home, + vec![PositionCollection::new(home, ResourcePile::food(1))], + PlayingActionType::Collect, + ))), + ); + let floor = moved.undo_limit; + let history = saved(&moved)["log"].clone(); + let frames = saved(&moved)["board_history"].clone(); + let clocks = time_increments(&moved); + for _ in 0..20 { + moved = play(play(reload(saved(&moved)), calendar()), keep()); + assert_eq!(moved.undo_limit, floor); + assert!(moved.can_undo()); + assert_eq!(saved(&moved)["log"], history); + assert_eq!(saved(&moved)["board_history"], frames); + assert_eq!(time_increments(&moved), clocks); + } + let undone = play(moved.clone(), Action::Undo); + assert_eq!(undone.player(0).resources, start.player(0).resources); + assert_eq!(undone.calendar_knowledge, Some(known.clone())); + let redone = play(undone, Action::Redo); + assert_eq!(redone.player(0).resources, moved.player(0).resources); + assert_eq!(redone.calendar_knowledge, Some(known)); +} + +#[test] +fn cached_burial_is_authoritative_stale_safe_and_does_not_disclose_replacement() { + let start = ready(); + let k = start.calendar_knowledge.clone().unwrap(); + let burial = Action::CalendarBury { + turn: k.turn, + incident: k.incident.unwrap(), + payment: ResourcePile::culture_tokens(1), + }; + assert!(board_history::execute(start.clone(), burial.clone(), 1).is_err()); + assert!( + board_history::execute(strip_secret(start.clone(), Some(0)), burial.clone(), 0).is_err() + ); + let paid = play(start.clone(), burial.clone()); + assert_eq!(log_length(&paid), log_length(&start) + 2); + assert!(paid.can_undo()); + assert_eq!( + strip_secret(paid.clone(), Some(0)) + .calendar_knowledge + .unwrap() + .incident, + None + ); + assert!(board_history::execute(paid.clone(), burial, 0).is_err()); + let undone = play(reload(saved(&paid)), Action::Undo); + assert_eq!( + strip_secret(undone, Some(0)) + .calendar_knowledge + .unwrap() + .incident, + k.incident + ); + let shape = history_shape(&paid); + let inspected = play(paid, calendar()); + assert_eq!(history_shape(&inspected), shape); + assert_eq!(inspected.undo_limit, inspected.log_index); + let closed = play(inspected, keep()); + assert!(!closed.can_undo()); + assert_eq!(history_shape(&closed), shape); +} + +#[test] +fn filtered_states_never_create_knowledge_or_leak_it_between_seats() { + let game = ready(); + for seat in [None, Some(1)] { + assert!( + strip_secret(game.clone(), seat) + .calendar_knowledge + .is_none() + ); + } + let owner = strip_secret(game.clone(), Some(0)); + let once = owner.calendar_knowledge.clone(); + assert_eq!( + strip_secret(owner.clone(), Some(0)).calendar_knowledge, + once + ); + let other = strip_secret(owner, Some(1)); + assert!(strip_secret(other, Some(0)).calendar_knowledge.is_none()); + let mut unknown = strip_secret(game, Some(0)); + unknown.calendar_knowledge = None; + assert!(board_history::execute(unknown, calendar(), 0).is_err()); +} + +#[test] +fn g5_f5_stop_then_known_calendar_does_not_seal_movement() { + let game = play(ready(), Action::Playing(PlayingAction::EndTurn)); + let start = board_history::execute(game, Action::Playing(PlayingAction::EndTurn), 1).unwrap(); + let mut data = saved(&start); + data["players"][0]["units"][0]["position"] = json!("G5"); + let mut second = data["players"][0]["units"][0].clone(); + second["id"] = json!(1); + data["players"][0]["units"] + .as_array_mut() + .unwrap() + .push(second); + data["players"][0]["next_unit_id"] = json!(2); + for tile in data["map"]["tiles"].as_array_mut().unwrap() { + if tile[0] == "G5" || tile[0] == "F5" { + tile[1] = json!("Fertile"); + } + } + let start = reload(data); + let unit = start.player(0).units[0].id; + let moved = play( + start.clone(), + serde_json::from_value(json!({"Movement":{"Move":{"units":[unit],"destination":"F5"}}})) + .unwrap(), + ); + assert!( + board_history::execute(moved.clone(), calendar(), 0).is_err(), + "not a free-action opportunity during movement" + ); + let stopped = play( + moved, + Action::Movement(server::movement::MovementAction::Stop), + ); + let floor = stopped.undo_limit; + let shape = history_shape(&stopped); + let closed = play(play(stopped.clone(), calendar()), Action::Undo); + assert_eq!(closed.undo_limit, floor); + assert_eq!(history_shape(&closed), shape); + assert!(closed.can_undo()); + let undone_stop = play(reload(saved(&closed)), Action::Undo); + let undone_move = play(undone_stop, Action::Undo); + assert_eq!( + undone_move.player(0).units[0].position, + start.player(0).units[0].position + ); + let redone = play(play(undone_move, Action::Redo), Action::Redo); + assert_eq!( + redone.player(0).units[0].position, + stopped.player(0).units[0].position + ); + assert_eq!(redone.calendar_knowledge, start.calendar_knowledge); +} diff --git a/server/tests/sparta_leader_payment_tests.rs b/server/tests/sparta_leader_payment_tests.rs new file mode 100644 index 00000000..8ee06745 --- /dev/null +++ b/server/tests/sparta_leader_payment_tests.rs @@ -0,0 +1,152 @@ +//! Sparta substitutes Draft's tokens, never a leader's normal mood cost. +use server::{ + cache::Cache, + game::{Game, GameContext}, + game_data::GameData, + leader::Leader, + player::CostTrigger, + position::Position, + recruit::recruit_cost_without_replaced, + resource_pile::ResourcePile, + unit::Units, +}; + +fn fixture(civil_liberties: bool) -> Game { + fixture_with_colosseum(civil_liberties, false) +} + +fn fixture_with_colosseum(civil_liberties: bool, colosseum: bool) -> Game { + let mut data: serde_json::Value = serde_json::from_str(include_str!( + "test_games/civilizations/greece/sparta_draft.json" + )) + .unwrap(); + data["players"][0]["available_leaders"] = serde_json::json!(["Alexander"]); + if civil_liberties { + data["players"][0]["advances"] + .as_array_mut() + .unwrap() + .push(serde_json::json!("CivilLiberties")); + } + if colosseum { + data["players"][0]["cities"][0]["city_pieces"]["wonders"] = + serde_json::json!(["Colosseum"]); + } + let data: GameData = serde_json::from_value(data).unwrap(); + let cache = Cache::new(&data.options); + Game::from_data(data, cache, GameContext::Play) +} + +#[test] +fn sparta_cannot_replace_a_leaders_mood_even_with_infantry() { + for civil_liberties in [false, true] { + let game = fixture(civil_liberties); + for infantry in [0, 1] { + let cost = recruit_cost_without_replaced( + &game, + game.player(0), + &Units::new(0, infantry, 0, 0, 0, Some(Leader::Alexander)), + Position::from_offset("A1"), + CostTrigger::NoModifiers, + ) + .unwrap() + .cost; + let resources = ResourcePile::food(infantry) + ResourcePile::ore(infantry); + let normal = + resources.clone() + ResourcePile::culture_tokens(1) + ResourcePile::mood_tokens(1); + assert!(cost.is_valid_payment(&normal)); + let illegal = resources + ResourcePile::culture_tokens(2); + assert!( + !cost.is_valid_payment(&illegal), + "leader mood converted: infantry={infantry}, civil liberties={civil_liberties}" + ); + if infantry > 0 { + let draft_tokens = if civil_liberties { 2 } else { 1 }; + let legal = + ResourcePile::culture_tokens(1 + draft_tokens) + ResourcePile::mood_tokens(1); + assert!(cost.is_valid_payment(&legal)); + assert_eq!(cost.first_valid_payment(&legal), Some(legal)); + let mood_draft = + ResourcePile::culture_tokens(1) + ResourcePile::mood_tokens(1 + draft_tokens); + assert!(cost.is_valid_payment(&mood_draft)); + let no_mood = ResourcePile::culture_tokens(2 + draft_tokens); + assert!(!cost.is_valid_payment(&no_mood)); + assert_eq!(cost.first_valid_payment(&no_mood), None); + } + } + } +} + +#[test] +fn sparta_still_pays_for_one_infantry_without_a_leader() { + for civil_liberties in [false, true] { + let game = fixture(civil_liberties); + let draft_tokens = if civil_liberties { 2 } else { 1 }; + for infantry in [1, 2] { + let cost = recruit_cost_without_replaced( + &game, + game.player(0), + &Units::new(0, infantry, 0, 0, 0, None), + Position::from_offset("A1"), + CostTrigger::NoModifiers, + ) + .unwrap() + .cost; + let remainder = ResourcePile::food(infantry - 1) + ResourcePile::ore(infantry - 1); + assert!(cost.is_valid_payment( + &(remainder.clone() + ResourcePile::culture_tokens(draft_tokens)) + )); + assert!(cost.is_valid_payment(&(remainder + ResourcePile::mood_tokens(draft_tokens)))); + if infantry == 2 { + assert!(!cost.is_valid_payment(&ResourcePile::culture_tokens(2 * draft_tokens))); + } + } + } +} + +#[test] +fn colosseum_can_convert_the_leader_fee_without_expanding_draft() { + for civil_liberties in [false, true] { + let game = fixture_with_colosseum(civil_liberties, true); + let draft_tokens = if civil_liberties { 2 } else { 1 }; + for infantry in [0, 1, 2] { + let cost = recruit_cost_without_replaced( + &game, + game.player(0), + &Units::new(0, infantry, 0, 0, 0, Some(Leader::Alexander)), + Position::from_offset("A1"), + CostTrigger::NoModifiers, + ) + .unwrap() + .cost; + for leader_tokens in [ + ResourcePile::culture_tokens(2), + ResourcePile::mood_tokens(2), + ResourcePile::culture_tokens(1) + ResourcePile::mood_tokens(1), + ] { + let normal = ResourcePile::food(infantry) + + ResourcePile::ore(infantry) + + leader_tokens.clone(); + assert!(cost.is_valid_payment(&normal), "normal: {normal:?}"); + assert_eq!(cost.first_valid_payment(&normal), Some(normal)); + if infantry > 0 { + for draft in [ + ResourcePile::culture_tokens(draft_tokens), + ResourcePile::mood_tokens(draft_tokens), + ] { + let payment = ResourcePile::food(infantry - 1) + + ResourcePile::ore(infantry - 1) + + leader_tokens.clone() + + draft; + assert!(cost.is_valid_payment(&payment), "Draft: {payment:?}"); + assert_eq!(cost.first_valid_payment(&payment), Some(payment)); + } + } + } + if infantry == 2 { + let illegal = ResourcePile::culture_tokens(2 + 2 * draft_tokens); + assert!(!cost.is_valid_payment(&illegal)); + assert_eq!(cost.first_valid_payment(&illegal), None); + } + } + } +} diff --git a/server/tests/test_games/advances/increase_happiness_voting_rituals.outcome.json b/server/tests/test_games/advances/increase_happiness_voting_rituals.outcome.json index 8e42122d..f3cdf545 100644 --- a/server/tests/test_games/advances/increase_happiness_voting_rituals.outcome.json +++ b/server/tests/test_games/advances/increase_happiness_voting_rituals.outcome.json @@ -8,8 +8,8 @@ "wood": 5, "ore": 4, "ideas": 2, - "gold": 4, - "mood_tokens": 9, + "gold": 5, + "mood_tokens": 8, "culture_tokens": 9 }, "resource_limit": { @@ -271,7 +271,7 @@ "food": 1, "ore": 1, "ideas": 3, - "gold": 1 + "mood_tokens": 1 }, "action_type": { "Special": { @@ -313,7 +313,7 @@ "food": 1, "ore": 1, "ideas": 3, - "gold": 1 + "mood_tokens": 1 }, "balance": "Pay" }, diff --git a/server/tests/voting_rituals_tests.rs b/server/tests/voting_rituals_tests.rs new file mode 100644 index 00000000..8f080c1e --- /dev/null +++ b/server/tests/voting_rituals_tests.rs @@ -0,0 +1,279 @@ +//! Voting's activation token is separate from Rituals' city happiness payment. +use serde_json::{Value, json}; +use server::{ + action::Action, + cache::Cache, + city::MoodState, + content::custom_actions::{PlayingActionModifier, SpecialAction}, + events::EventOrigin, + game::{Game, GameContext}, + game_api::execute, + game_data::GameData, + happiness::{IncreaseHappiness, happiness_cost}, + player::CostTrigger, + playing_actions::{PlayingAction, PlayingActionType}, + position::Position, + resource_pile::ResourcePile, + web_view, +}; + +fn fixture(mood: u8) -> Game { + let data: GameData = serde_json::from_str(include_str!( + "test_games/advances/increase_happiness_voting_rituals.json" + )) + .unwrap(); + let cache = Cache::new(&data.options); + let mut game = Game::from_data(data, cache, GameContext::Play); + game.players[0].resources.mood_tokens = mood; + game +} + +fn voting() -> PlayingActionType { + PlayingActionType::Special(SpecialAction::Modifier( + PlayingActionModifier::VotingIncreaseHappiness, + )) +} + +fn cities() -> Vec<(Position, u8)> { + vec![ + (Position::from_offset("C2"), 1), + (Position::from_offset("B3"), 2), + ] +} + +fn preview(game: &Game, variant: PlayingActionType, payment: Option) -> Value { + web_view::query( + game, + 0, + json!({ + "kind": "happiness", "variant": variant, "cities": cities(), + "includePayments": true, "payment": payment, + }), + ) + .unwrap() +} + +#[test] +fn voting_requires_actual_mood_in_generated_and_selected_payments() { + let game = fixture(1); + let cost = happiness_cost( + 0, + 5, + CostTrigger::NoModifiers, + &voting(), + &game, + &EventOrigin::Advance(server::advance::Advance::Voting), + ) + .cost; + assert_eq!(cost.default, ResourcePile::mood_tokens(6)); + assert_eq!(cost.separate_fee, vec![ResourcePile::mood_tokens(1)]); + for resource in [ + ResourcePile::food(6), + ResourcePile::wood(6), + ResourcePile::ore(6), + ResourcePile::ideas(6), + ResourcePile::gold(6), + ResourcePile::culture_tokens(6), + ] { + assert!(!cost.is_valid_payment(&resource)); + assert_eq!(cost.first_valid_payment(&resource), None); + } + let payment = ResourcePile::wood(5) + ResourcePile::mood_tokens(1); + assert!(cost.is_valid_payment(&payment)); + assert_eq!(cost.first_valid_payment(&payment), Some(payment.clone())); + assert_eq!(cost.first_valid_payment(&ResourcePile::wood(6)), None); + // Mixed resources may still pay all five city-size/step tokens. + assert!(cost.is_valid_payment(&ResourcePile::new(1, 1, 1, 1, 1, 1, 0))); + let rejected = preview(&game, voting(), Some(ResourcePile::wood(6))); + assert!(rejected["action"].is_null()); + let accepted = preview(&game, voting(), Some(payment.clone())); + assert_eq!(accepted["payment"], json!(payment)); + assert_eq!( + accepted["action"]["Playing"]["IncreaseHappiness"]["payment"], + json!(payment) + ); +} + +#[test] +fn voting_without_mood_is_unaffordable_despite_sufficient_resources() { + let game = fixture(0); + assert!(!server::happiness::available_happiness_actions(&game, 0).contains(&voting())); + assert_eq!( + web_view::query( + &game, + 0, + json!({ + "kind": "happiness", "variant": voting(), "cities": cities(), + }) + ) + .unwrap_err(), + "Happiness action unavailable" + ); + let cost = happiness_cost( + 0, + 5, + CostTrigger::NoModifiers, + &voting(), + &game, + &EventOrigin::Advance(server::advance::Advance::Voting), + ) + .cost; + assert_eq!(cost.first_valid_payment(&game.player(0).resources), None); +} + +#[test] +fn viewer_choices_and_generated_action_preserve_activation_token() { + let game = fixture(1); + let result = preview(&game, voting(), None); + let payment: ResourcePile = serde_json::from_value(result["payment"].clone()).unwrap(); + assert_eq!(payment.mood_tokens, 1); + assert_eq!(result["field"]["cost"], json!(ResourcePile::mood_tokens(6))); + assert_eq!(result["field"]["initial"], json!(payment)); + // A small stock keeps the choices list below the viewer enumeration cap. + let mut small = fixture(1); + small.players[0].resources = ResourcePile::wood(5) + ResourcePile::mood_tokens(1); + let choices = preview(&small, voting(), None); + assert_eq!( + choices["field"]["choices"], + json!([small.player(0).resources]) + ); + let action: Action = serde_json::from_value(result["action"].clone()).unwrap(); + let actions = game.actions_left; + let mut resources = game.player(0).resources.clone(); + let game = execute(game, action, 0); + assert_eq!(game.actions_left, actions); + resources -= payment; + assert_eq!(game.player(0).resources, resources); + assert_eq!( + game.player(0) + .get_city(Position::from_offset("C2")) + .mood_state, + MoodState::Neutral + ); + assert_eq!( + game.player(0) + .get_city(Position::from_offset("B3")) + .mood_state, + MoodState::Happy + ); +} + +#[test] +fn forged_resource_only_voting_action_is_rejected() { + let game = fixture(1); + let action = Action::Playing(PlayingAction::IncreaseHappiness(IncreaseHappiness::new( + cities(), + ResourcePile::wood(5) + ResourcePile::food(1), + voting(), + ))); + // Invalid resource payments use the engine's assertion-based validation. + assert!( + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| execute(game, action, 0))) + .is_err() + ); +} + +#[test] +fn payment_serialization_preserves_reserved_fee_and_legacy_defaults() { + let game = fixture(1); + let cost = happiness_cost( + 0, + 5, + CostTrigger::NoModifiers, + &voting(), + &game, + &EventOrigin::Advance(server::advance::Advance::Voting), + ) + .cost; + let value = serde_json::to_value(&cost).unwrap(); + assert_eq!(value["separate_fee"], json!([ResourcePile::mood_tokens(1)])); + let roundtrip: server::payment::PaymentOptions = serde_json::from_value(value).unwrap(); + assert_eq!(roundtrip, cost); + assert!(!roundtrip.is_valid_payment(&ResourcePile::wood(6))); + + let normal = happiness_cost( + 0, + 5, + CostTrigger::NoModifiers, + &PlayingActionType::IncreaseHappiness, + &game, + &EventOrigin::Ability("Increase Happiness".into()), + ) + .cost; + let value = serde_json::to_value(&normal).unwrap(); + assert!(value.get("separate_fee").is_none()); + let legacy: server::payment::PaymentOptions = serde_json::from_value(value).unwrap(); + assert!(legacy.separate_fee.is_empty()); + assert!(legacy.is_valid_payment(&ResourcePile::wood(5))); +} + +#[test] +fn normal_happiness_with_rituals_needs_no_mood() { + let game = fixture(0); + let payment = ResourcePile::wood(5); + let result = preview( + &game, + PlayingActionType::IncreaseHappiness, + Some(payment.clone()), + ); + assert_eq!(result["payment"], json!(payment)); + assert_eq!(result["field"]["cost"], json!(ResourcePile::mood_tokens(5))); + let action: Action = serde_json::from_value(result["action"].clone()).unwrap(); + let actions = game.actions_left; + let mut resources = game.player(0).resources.clone(); + let game = execute(game, action, 0); + assert_eq!(game.actions_left, actions - 1); + resources -= payment; + assert_eq!(game.player(0).resources, resources); + assert_eq!(game.player(0).resources.mood_tokens, 0); +} + +#[test] +fn colosseum_can_convert_voting_fee_but_rituals_still_cannot() { + let mut data: Value = serde_json::from_str(include_str!( + "test_games/advances/increase_happiness_voting_rituals.json" + )) + .unwrap(); + data["players"][0]["cities"][0]["city_pieces"]["wonders"] = json!(["Colosseum"]); + let data: GameData = serde_json::from_value(data).unwrap(); + let cache = Cache::new(&data.options); + let mut game = Game::from_data(data, cache, GameContext::Play); + let payment = ResourcePile::wood(5) + ResourcePile::culture_tokens(1); + game.players[0].resources = payment.clone(); + let cost = happiness_cost( + 0, + 5, + CostTrigger::NoModifiers, + &voting(), + &game, + &EventOrigin::Advance(server::advance::Advance::Voting), + ) + .cost; + assert_eq!( + cost.separate_fee, + vec![ + ResourcePile::mood_tokens(1), + ResourcePile::culture_tokens(1) + ] + ); + assert!(cost.is_valid_payment(&payment)); + assert_eq!(cost.first_valid_payment(&payment), Some(payment.clone())); + assert!(cost.is_valid_payment(&ResourcePile::culture_tokens(6))); + assert!(!cost.is_valid_payment(&ResourcePile::wood(6))); + assert_eq!(cost.first_valid_payment(&ResourcePile::wood(6)), None); + assert!(!cost.is_valid_payment(&(payment.clone() + ResourcePile::wood(1)))); + let roundtrip: server::payment::PaymentOptions = serde_json::from_value(json!(cost)).unwrap(); + assert!(roundtrip.is_valid_payment(&payment)); + assert!(!roundtrip.is_valid_payment(&ResourcePile::wood(6))); + assert!(server::happiness::available_happiness_actions(&game, 0).contains(&voting())); + let result = preview(&game, voting(), Some(payment.clone())); + assert_eq!(result["payment"], json!(payment)); + assert_eq!(result["field"]["choices"], json!([payment])); + let generated = preview(&game, voting(), None); + assert_eq!(generated["payment"], json!(payment)); + let action: Action = serde_json::from_value(result["action"].clone()).unwrap(); + let actions = game.actions_left; + let game = execute(game, action, 0); + assert_eq!(game.actions_left, actions); + assert_eq!(game.player(0).resources, ResourcePile::empty()); +} diff --git a/web-client/docs/viewer-publishing.md b/web-client/docs/viewer-publishing.md index c66d1018..251fd941 100644 --- a/web-client/docs/viewer-publishing.md +++ b/web-client/docs/viewer-publishing.md @@ -947,3 +947,9 @@ next-attempt effect is still consumed normally. Five regression tests cover building influence, defended and empty settlements, failures, and ineligible city centers. Publish the matching viewer rules bridge and engine together. Existing game history is not replayed or repaired. + +# Viewer 0.1.202 / engine 0.4.136 + +Calendar now persists owner-only known-top state at the first legal turn boundary. Reopening a known card, Keep and Cancel are local: no backend move, history entry or clock credit. Replacement cards require an explicit new inspection; stale-safe paid burial records the existing actions. Historical views omit private knowledge, and reload/reconstruction preserve knowledge and undo floors. + +Voting’s activation fee remains separate from Rituals’ city happiness conversions. Sparta can replace Draft tokens but cannot convert a recruited leader’s own mood fee. Both fees retain general Colosseum conversions. Publish the matching viewer and engine together; no production game repair or historical rewrite is needed. diff --git a/web-client/package-lock.json b/web-client/package-lock.json index 9186f43b..ee4615b1 100644 --- a/web-client/package-lock.json +++ b/web-client/package-lock.json @@ -1,12 +1,12 @@ { "name": "@boardgamers/clash-web-client", - "version": "0.1.201", + "version": "0.1.202", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@boardgamers/clash-web-client", - "version": "0.1.201", + "version": "0.1.202", "dependencies": { "@boardgamers/protocol": "0.9.0", "lucide-svelte": "^0.577.0", diff --git a/web-client/package.json b/web-client/package.json index f1c3f2ba..93021191 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -1,6 +1,6 @@ { "name": "@boardgamers/clash-web-client", - "version": "0.1.201", + "version": "0.1.202", "private": true, "type": "module", "scripts": { diff --git a/web-client/scripts/calendar-preview-smoke.mjs b/web-client/scripts/calendar-preview-smoke.mjs index bfa25607..067ae4ae 100644 --- a/web-client/scripts/calendar-preview-smoke.mjs +++ b/web-client/scripts/calendar-preview-smoke.mjs @@ -128,6 +128,17 @@ try { assert.deepEqual(engine.timeIncrements(closed), engine.timeIncrements(merchant)); await emit(closed); await preview.waitFor({ state: 'detached' }); + // Known peeks never enter the host move stream, even on repeated opens. + for (let cycle = 0; cycle < 2; cycle++) { + await page.getByRole('button', { name: t('Abilities'), exact: true }).click(); + await page.locator('.ability-offer').filter({ has: page.getByRole('heading', { name: t('Calendar'), exact: true }) }).getByRole('button').click(); + await preview.waitFor(); + assert.equal(await page.evaluate(() => sent.length), 0); + if (cycle === 0) await actions.getByRole('button', { name: t('Keep on top'), exact: true }).click(); + else await cancel.click(); + await preview.waitFor({ state: 'detached' }); + assert.equal(await page.evaluate(() => sent.length), 0, 'known Keep/Cancel is local too'); + } await emit(fixture('Great Merchant', 0)); await preview.waitFor(); assert.equal(await actions.getByRole('button').count(), 1); diff --git a/web-client/src/calendar-incident-undo.test.ts b/web-client/src/calendar-incident-undo.test.ts index 8b7db97a..3a48b7bd 100644 --- a/web-client/src/calendar-incident-undo.test.ts +++ b/web-client/src/calendar-incident-undo.test.ts @@ -30,7 +30,7 @@ async function ready(calendar = true) { } test('Calendar exposes Undo for the owner after a known incident, without predicting the hidden draw', async () => { - const before = await ready(); + const before = move(move(await ready(), { Playing: { Custom: { action: "Calendar" } } }), "Undo"); const action = research('Storage'); assert.deepEqual(predictMove(engine, strip(before), action, 0), { reason: 'hidden' }); const after = move(before, action); @@ -55,7 +55,7 @@ test('predicted Undo preserves the new knowledge floor and cannot refund Astrono const game = JSON.parse(await ready(false)); game.players[0].incident_tokens = 2; const astronomy = move(JSON.stringify(game), research('Astronomy')); - assert.equal(view(astronomy).canUndo, true); + assert.equal(view(astronomy).canUndo, false, "automatic acquisition disclosure seals Astronomy"); const after = move(astronomy, research('Storage')); assert.equal(view(after).canUndo, true); const undone = move(after, 'Undo'); diff --git a/web-client/src/controller.ts b/web-client/src/controller.ts index d7cf9251..1608559a 100644 --- a/web-client/src/controller.ts +++ b/web-client/src/controller.ts @@ -119,6 +119,7 @@ export class Controller { private raw = ''; /** The latest state received from the host. */ private confirmedRaw = ''; + private localCalendar: { base: string; turn: number; incident: number } | null = null; private planningInfo: {key: string; base: string; projected: string; actions: Move[]; waiting: boolean; other: string; label: string; pendingPlayer: number} | null = null; private planningQueue: ActionQueue | null = null; private confirmedPrint: string | null = null; @@ -341,9 +342,15 @@ export class Controller { // A predicted capture can already be showing the planning board while // the confirmed game still waits for the defender's replacement settler. // Keep queries on that same projection after acknowledging the capture. - this.raw = this.planningInfo && !this.planningInfo.waiting - ? this.planningInfo.projected - : raw; + if (this.localCalendar) { + // A private local prompt is not in the outbox. Confirm its underlying + // move without replacing the displayed prompt or its query state. + this.localCalendar.base = raw; + } else { + this.raw = this.planningInfo && !this.planningInfo.waiting + ? this.planningInfo.projected + : raw; + } this.markSeen(); if (get(this.session).error === WAITING) this.patch({ error: '' }); } @@ -366,8 +373,9 @@ export class Controller { this.notify('Game updated.'); return true; } - private apply(raw: string, { predicted = false, quiet = false } = {}) { + private apply(raw: string, { predicted = false, quiet = false, local = false } = {}) { if (!this.engine) return; + this.localCalendar = null; if (quiet) { // Withdrawn moves must not continue with their quoted payments or card flows. this.quotedActionPayment = null; @@ -396,7 +404,7 @@ export class Controller { this.raw = raw; this.moveCache.clear(); const view = JSON.parse(this.engine.webView(raw, old.seat)) as View; - this.undoPreview.remember(raw, game, view, old.seat); + if (!local) this.undoPreview.remember(raw, game, view, old.seat); if (view.influenceContext) this.influenceAttemptPending = true; const quotedPayment = this.quotedActionPayment; this.quotedActionPayment = null; @@ -608,7 +616,7 @@ export class Controller { } } } - this.commands.replaceLog(journal(game, view).map((entry) => entry.text)); + if (!local) this.commands.replaceLog(journal(game, view).map((entry) => entry.text)); if (view.decision || view.objectiveDecision || view.choiceDecision || view.explorationDecision) this.closeActivity(); const recruitedMover = bonusGranted @@ -654,8 +662,10 @@ export class Controller { this.influenceAttemptPending = false; } this.submittedMove = null; - this.afterPlaybackLoad(old, game, !predicted); - this.migrateRazeSetting(); + if (!local) { + this.afterPlaybackLoad(old, game, !predicted); + this.migrateRazeSetting(); + } if (automaticPayment) this.submit(automaticPayment); else if (!quiet) this.continueBoarding(); } @@ -1912,6 +1922,31 @@ export class Controller { ) return; if ((move === 'Undo' && !s.view?.canUndo) || (move === 'Redo' && !s.view?.canRedo)) return; + // A known card is a private local view, not a move or a prediction/outbox entry. + if (this.localCalendar) { + const local = this.localCalendar; + const payments = typeof move === 'object' && move !== null + ? (move as { Response?: { Payment?: Pile[] } }).Response?.Payment : undefined; + if (move !== 'Undo' && !payments) return; + this.localCalendar = null; + this.apply(local.base, { quiet: true, local: true }); + if (move === 'Undo' || !payments?.some(p => Object.values(p).some(Boolean))) return; + this.submit({ CalendarBury: { turn: local.turn, incident: local.incident, payment: payments[0] } }); + return; + } + const known = s.game?.calendar_knowledge; + if (known?.player === s.seat && known.incident != null && + typeof move === 'object' && move !== null && + (move as { Playing?: { Custom?: { action?: string } } }).Playing?.Custom?.action === 'Calendar' && + this.engine?.tryMove && s.view?.canPlay) { + try { + const base = this.raw; + const opened = this.engine.tryMove(base, JSON.stringify(move), s.seat); + this.apply(opened, { quiet: true, local: true }); + this.localCalendar = { base, turn: known.turn, incident: known.incident }; + } catch (error) { this.patch({ error: String(error) }); } + return; + } this.patch({ pending: true, error: '' }); this.submittedMove = move; this.quotedActionPayment = diff --git a/web-client/src/prediction.test.ts b/web-client/src/prediction.test.ts index 4a94d7d1..80dc4a68 100644 --- a/web-client/src/prediction.test.ts +++ b/web-client/src/prediction.test.ts @@ -559,7 +559,7 @@ test('Calendar Cancel never optimistically undoes the committed move before the await app.controller.load(strip(closed, seat)); assert.equal(app.session().pending, false); assert.ok(!app.session().view!.decision); - assert.equal(app.session().view!.canUndo, false); + assert.equal(app.session().view!.canUndo, true, 'known preview adds no knowledge lock'); assert.deepEqual(app.session().game!.players[seat].resources, collected.players[seat].resources); } finally { app.close(); } }); @@ -853,3 +853,97 @@ test('Great Person offers expose the normal queue and Wait controls', async () = assert.equal(app.session().view?.canPlay, true); } finally { app.close(); } }); + +test('known Calendar open/keep/cancel is purely local with zero history or calls; burial is authoritative', async () => { + let raw = await engine.init(2, [], { civilization: 'ChooseCivilization' }, 'calendar-local-cache', {}); + for (const civilization of ['Maya', 'Rome']) raw = move(raw, { ChooseCivilization: civilization }, engine.currentPlayer(raw)); + const seat = engine.currentPlayer(raw); + const initial = JSON.parse(raw); + initial.players[seat].advances.push('Fishing', 'Navigation', 'Cartography', 'Astronomy'); + initial.players[seat].resources.food = 0; + initial.players[seat].resources.culture_tokens = 2; + raw = JSON.stringify(initial); + const city = initial.players[seat].cities[0].position; + const collection = { Playing: { Collect: { city_position: city, + collections: [{ position: city, pile: { food: 1 }, times: 1 }], action_type: 'Collect' } } }; + const app = harness(); + try { + app.controller.setPlayer(seat); + await app.controller.load(strip(raw, seat)); + raw = move(raw, collection, seat); + await app.controller.load(strip(raw, seat)); + const base = structuredClone(app.session().game!); + const calendar = app.session().view!.specialActions!.find(a => a.name === 'Calendar')!.action; + assert.ok(base.calendar_knowledge?.incident != null); + const journalUpdates = app.logs.length; + for (let i = 0; i < 30; i++) { + app.controller.submit(calendar); + assert.ok(app.session().view!.decision); + assert.equal(app.session().pending, false); + assert.deepEqual(app.session().game!.log, base.log); + assert.deepEqual(app.session().game!.board_history, base.board_history); + assert.equal(app.session().game!.log_index, base.log_index); + app.controller.submit(i % 2 ? 'Undo' : { Response: { Payment: [{}] } }); + assert.ok(!app.session().view!.decision); + assert.equal(app.session().view!.canUndo, true); + assert.deepEqual(app.session().game, base); + assert.equal(app.sent.length, 0); + assert.equal(app.logs.length, journalUpdates, 'local peek does not even replace the host journal'); + } + app.controller.submit('Undo'); + assert.deepEqual(app.sent.map(s => JSON.parse(s)), ['Undo']); + const undone = move(raw, 'Undo', seat); + await app.controller.load(strip(undone, seat)); + assert.equal(app.session().game!.log_index, base.log_index - 1); + app.controller.submit('Redo'); + raw = move(undone, 'Redo', seat); + await app.controller.load(strip(raw, seat)); + assert.equal(app.session().game!.log_index, base.log_index); + app.controller.submit(calendar); + app.controller.submit({ Response: { Payment: [{ culture_tokens: 1 }] } }); + const burial = JSON.parse(app.sent.at(-1)!); + assert.ok(burial.CalendarBury); + assert.equal(app.session().pending, true); + assert.deepEqual(app.session().game!.players[seat].resources, base.players[seat].resources); + raw = move(raw, burial, seat); + await app.controller.load(strip(raw, seat)); + assert.equal(app.session().game!.calendar_knowledge?.incident, null); + assert.equal(app.session().view!.canUndo, true); + const count = app.sent.length; + app.controller.submit(calendar); + assert.equal(app.sent.length, count + 1, 'unknown replacement requires explicit server inspection'); + } finally { app.close(); } +}); + +test('known local Calendar stays local across an optimistic move acknowledgement', async () => { + let raw = await engine.init(2, [], { civilization: 'ChooseCivilization' }, 'calendar-pending-cache', {}); + for (const civilization of ['Maya', 'Rome']) raw = move(raw, { ChooseCivilization: civilization }, engine.currentPlayer(raw)); + const seat = engine.currentPlayer(raw); + const data = JSON.parse(raw); + data.players[seat].advances.push('Fishing', 'Navigation', 'Cartography', 'Astronomy'); + data.players[seat].resources.food = 0; + const calendar = { Playing: { Custom: { action: 'Calendar' } } }; + raw = move(move(JSON.stringify(data), calendar, seat), 'Undo', seat); + const city = data.players[seat].cities[0].position; + const collection = { Playing: { Collect: { city_position: city, + collections: [{ position: city, pile: { food: 1 }, times: 1 }], action_type: 'Collect' } } }; + const app = harness(); + try { + app.controller.setPlayer(seat); + await app.controller.load(strip(raw, seat)); + app.controller.submit(collection); + assert.equal(app.session().pending, false); + assert.equal(app.sent.length, 1); + app.controller.submit(calendar); + assert.ok(app.session().view!.decision); + assert.equal(app.sent.length, 1, 'cached preview never enters the pending outbox'); + raw = move(raw, collection, seat); + await app.controller.load(strip(raw, seat)); + assert.ok(app.session().view!.decision, 'acknowledgement preserves local prompt'); + app.controller.submit('Undo'); + assert.equal(app.sent.length, 1); + assert.ok(!app.session().view!.decision); + assert.equal(app.session().game!.players[seat].resources?.food, JSON.parse(raw).players[seat].resources.food); + assert.equal(app.session().view!.canUndo, true); + } finally { app.close(); } +}); diff --git a/web-client/src/prediction.ts b/web-client/src/prediction.ts index 1c9a1c13..c880f2ba 100644 --- a/web-client/src/prediction.ts +++ b/web-client/src/prediction.ts @@ -95,7 +95,9 @@ function excluded(raw: string, move: unknown, seat: number) { for (let skipped = 0; skipped < humans && next !== game.starting_player_index && game.dropped_players?.includes(next); skipped++) next = (next + 1) % humans; if (next === game.starting_player_index) return true; } - if ('ChooseCivilization' in move) return true; + if ('ChooseCivilization' in move || 'CalendarBury' in move) return true; + if ((game.events ?? []).some((e: Json) => e.event_type?.CustomAction?.action?.action === 'Calendar') && + (move as Json).Response?.Payment?.some((p: Json) => Object.values(p).some(Boolean))) return true; // Calendar's tentative look does not change the authoritative RNG or pile. // Two samples can coincidentally reveal the same card, so always wait for the // owner-only server prompt rather than previewing the shuffled browser deck. @@ -128,6 +130,15 @@ export function predictMove(engine: PredictionEngine, raw: string, move: unknown try { const result = engine.tryMove(raw, serialized, seat); const before = JSON.parse(raw) as Json, after = JSON.parse(result) as Json; + // A filtered simulation cannot supply a first-turn/acquisition disclosure. + // Wait for the host rather than briefly enabling Undo across that knowledge. + const owner = after.players?.[seat]; + const turn = (after.log ?? []).flatMap((a: Json) => a.rounds ?? []).reduce((n: number, r: Json) => n + r.turns.length, 0); + if (after.current_player_index === seat && after.state === 'Playing' && !(after.events?.length) && + owner?.civilization === 'Maya' && owner.advances?.includes('Astronomy') && + (after.calendar_knowledge?.player !== seat || after.calendar_knowledge?.turn !== turn)) { + return { reason: 'hidden' }; + } // Never guess a roll or hidden draw, even if two sampled outcomes happen // to coincide. Check before stripSecret resets the random stream. if (before.rng !== after.rng || @@ -166,6 +177,8 @@ export function predictUndo(previous: string, current: string): string | null { const before = JSON.parse(previous) as Json, after = JSON.parse(current) as Json; if (before.log_index !== after.log_index - 1) return null; + if (after.calendar_knowledge?.incident == null && after.calendar_knowledge && + before.calendar_knowledge?.incident == null) return null; const log = structuredClone(after.log); const actions = lastTurn({ log })?.actions; const undone = actions?.[after.log_index - 1]; @@ -175,8 +188,12 @@ export function predictUndo(previous: string, current: string): string | null { delete undone.combat_stats; delete undone.undo; before.log = log; + delete before.early_choice_update; // Calendar may let the triggering action be undone while sealing everything // before it, as if the owner had peeked first. Knowledge is not rewound. + // Knowledge is monotonic; do not restore a replacement card from an older snapshot. + if (after.calendar_knowledge) before.calendar_knowledge = { ...after.calendar_knowledge, + incident: after.calendar_knowledge.incident ?? before.calendar_knowledge?.incident ?? null }; before.undo_limit = Math.max(before.undo_limit ?? 0, after.undo_limit ?? 0); // Playback history is outside the undo patch: Undo only trims later frames. if (after.board_history) { diff --git a/web-client/src/types.ts b/web-client/src/types.ts index d3d25734..8e30e6cd 100644 --- a/web-client/src/types.ts +++ b/web-client/src/types.ts @@ -71,6 +71,8 @@ export interface Playback { animate: boolean; } export interface Game { + calendar_knowledge?: { player: number; turn: number; incident: number | null }; + secrets_stripped?: boolean; action_cards_discarded?: number[]; incidents_discarded?: number[]; successful_cultural_influence?: boolean;