CB-WP-0008-T02: cb-play — INTENT stage 0's CLI player
Some checks failed
ci / check (push) Failing after 3s

A human seat is a Policy like any bot, so the CLI adds no second driver:
HumanPolicy renders the projection, lists the legal commands and reads an
index or `pass`. `make play` runs it; `--all-bots` watches one.

K13's Project trait gains its first implementor after six passes with
none. Hidden: other seats' face-down selections until Reveal, hands and
deck (counts only), a face-down Problem's suit and value, and the seed —
not secret content, but a seat holding it can compute the deck.

A played session becomes an artifact: --record writes it as a scenario
the runner executes, --replay writes a .cbreplay bundle. record.rs is the
inverse of parse_command and its warrant is a round-trip test over every
command shape.

The acceptance test for the projection passed vacuously twice. First it
asserted the text contained "face-down", which every render does because
of Problems. Counted, it then reported zero inspected entries: seats are
asked in order, so a human at P1 is prompted before anyone has selected.
Seated at P3 it inspects ten entries and dies when the projection is
mutated to reveal everything. Counting what the harness examined caught
both, which is the second time that remedy has worked where a stronger
predicate would not have.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
tegwick 2026-08-01 14:43:53 +02:00
parent 6197677126
commit 25531e9d01
13 changed files with 1523 additions and 60 deletions

View file

@ -123,6 +123,9 @@ pub struct BotGame {
pub state: GroundState,
/// Every event, in order — the log a replay bundle would carry.
pub events: Vec<crate::GroundEvent>,
/// Every accepted command, in order, as issued. `record::to_step`
/// turns these into a scenario a replay bundle can carry.
pub steps: Vec<(Actor, GroundCommand)>,
/// Commands accepted, player and system alike.
pub commands: usize,
pub rounds: u8,
@ -405,9 +408,11 @@ const MAX_ATTEMPTS: usize = 8;
///
/// Seats are matched to `policies` by index: `PlayerId(n)` gets
/// `policies[n]`.
pub fn play(mut state: GroundState, policies: &mut [Box<dyn Policy>]) -> Result<BotGame, BotError> {
let mut events = Vec::new();
let mut commands = 0usize;
pub fn play<'a>(
mut state: GroundState,
policies: &mut [Box<dyn Policy + 'a>],
) -> Result<BotGame, BotError> {
let mut log = Log::default();
let seats: Vec<PlayerId> = state.players.keys().copied().collect();
for seat in &seats {
@ -438,15 +443,7 @@ pub fn play(mut state: GroundState, policies: &mut [Box<dyn Policy>]) -> Result<
detail: format!("player {seat} never selected an action"),
});
}
step_seat(
&mut state,
&mut events,
&mut commands,
policies,
*seat,
round,
false,
)?;
step_seat(&mut state, &mut log, policies, *seat, round, false)?;
}
}
// Positive control: the driver must have done the work it claims.
@ -461,13 +458,7 @@ pub fn play(mut state: GroundState, policies: &mut [Box<dyn Policy>]) -> Result<
});
}
apply(
&mut state,
&mut events,
&mut commands,
Actor::System,
&GroundCommand::Reveal,
)?;
apply(&mut state, &mut log, Actor::System, &GroundCommand::Reveal)?;
// GR-R05 — after Reveal: modes are obligatory for a seat that
// revealed GROUND; Support responses and DARVO targets are not.
@ -489,31 +480,16 @@ pub fn play(mut state: GroundState, policies: &mut [Box<dyn Policy>]) -> Result<
if !obligatory && legal_commands(&state, *seat).is_empty() {
break;
}
if !step_seat(
&mut state,
&mut events,
&mut commands,
policies,
*seat,
round,
!obligatory,
)? {
if !step_seat(&mut state, &mut log, policies, *seat, round, !obligatory)? {
break;
}
}
}
apply(&mut state, &mut log, Actor::System, &GroundCommand::Resolve)?;
apply(
&mut state,
&mut events,
&mut commands,
Actor::System,
&GroundCommand::Resolve,
)?;
apply(
&mut state,
&mut events,
&mut commands,
&mut log,
Actor::System,
&GroundCommand::EndRound,
)?;
@ -521,19 +497,26 @@ pub fn play(mut state: GroundState, policies: &mut [Box<dyn Policy>]) -> Result<
Ok(BotGame {
state,
events,
commands,
commands: log.steps.len(),
events: log.events,
steps: log.steps,
rounds,
})
}
/// What the driver accumulates while a game runs.
#[derive(Default)]
struct Log {
events: Vec<crate::GroundEvent>,
steps: Vec<(Actor, GroundCommand)>,
}
/// Offer one seat its legal commands and apply what the policy picks.
/// `Ok(false)` means the seat passed.
fn step_seat(
state: &mut GroundState,
events: &mut Vec<crate::GroundEvent>,
commands: &mut usize,
policies: &mut [Box<dyn Policy>],
log: &mut Log,
policies: &mut [Box<dyn Policy + '_>],
seat: PlayerId,
round: u8,
may_pass: bool,
@ -565,7 +548,7 @@ fn step_seat(
index: i,
offered: legal.len(),
})?;
apply(state, events, commands, Actor::Player(seat), cmd)?;
apply(state, log, Actor::Player(seat), cmd)?;
Ok(true)
}
}
@ -573,8 +556,7 @@ fn step_seat(
fn apply(
state: &mut GroundState,
events: &mut Vec<crate::GroundEvent>,
commands: &mut usize,
log: &mut Log,
actor: Actor,
cmd: &GroundCommand,
) -> Result<(), BotError> {
@ -591,8 +573,8 @@ fn apply(
for event in &produced {
state.fold(event);
}
events.extend(produced);
*commands += 1;
log.events.extend(produced);
log.steps.push((actor, cmd.clone()));
Ok(())
}
@ -694,16 +676,8 @@ mod tests {
let ghost = PlayerId(9);
assert!(legal_commands(&state, ghost).is_empty());
let mut ps = policies("greedy", 10, 0);
let err = step_seat(
&mut state,
&mut Vec::new(),
&mut 0,
&mut ps,
ghost,
1,
false,
)
.expect_err("a seat with nothing legal must fail");
let err = step_seat(&mut state, &mut Log::default(), &mut ps, ghost, 1, false)
.expect_err("a seat with nothing legal must fail");
assert!(matches!(err, BotError::NoLegalMove { seat, .. } if seat == ghost));
}

View file

@ -8,6 +8,16 @@
/// presets currently live behind that feature (see `bot.rs`).
pub mod bot;
/// K13's per-player projection (CB-WP-0008 T02) — the trait's first
/// implementor. Needs the runtime's `Project`, which the game already
/// depends on, so it is not feature-gated either.
pub mod view;
/// The inverse of `parse_command` (CB-WP-0008 T02): a played game becomes
/// a scenario. Needs the scenario vocabulary, so it is gated with it.
#[cfg(feature = "scenarios")]
pub mod record;
#[cfg(feature = "scenarios")]
use cb_game_runtime::{parse_actor, CommandStep, ScenarioGame, Setup};
use cb_kernel::{Actor, Aggregate, ChaChaRng, KernelRng, PlayerId, Rejection, Seed};

364
games/ground/src/record.rs Normal file
View file

@ -0,0 +1,364 @@
//! Turn a played game back into a scenario (CB-WP-0008 T02).
//!
//! `ScenarioGame::parse_command` reads a `CommandStep` into a typed
//! command. This is its inverse, so a game somebody played becomes a
//! scenario the runner can re-execute and a `.cbreplay` bundle can carry.
//!
//! **The round trip is the test**, and it is the only reason this is
//! trustworthy: `parse_command(to_step(actor, cmd)) == (actor, cmd)` for
//! every command shape. An encoder checked only against hand-written
//! expectations agrees with itself.
use crate::{Action, GroundChoice, GroundCommand, GroundMode, SupportResponse};
use cb_game_runtime::{CommandStep, Setup};
use cb_kernel::{Actor, PlayerId};
use std::collections::BTreeMap;
fn seat(p: PlayerId) -> serde_yaml::Value {
serde_yaml::Value::String(format!("P{}", p.0 + 1))
}
fn num(n: u64) -> serde_yaml::Value {
serde_yaml::Value::Number(n.into())
}
fn text(s: &str) -> serde_yaml::Value {
serde_yaml::Value::String(s.to_string())
}
fn actor_name(actor: Actor) -> String {
match actor {
Actor::Player(p) => format!("P{}", p.0 + 1),
Actor::System => "SYSTEM".into(),
}
}
fn action_name(action: Action) -> &'static str {
match action {
Action::Investigate => "INVESTIGATE",
Action::Solve => "SOLVE",
Action::Support => "SUPPORT",
Action::Attack => "ATTACK",
Action::Ground => "GROUND",
}
}
fn mode_name(mode: GroundMode) -> &'static str {
match mode {
GroundMode::Gr => "GR",
GroundMode::Ou => "OU",
GroundMode::Nd => "ND",
}
}
fn response_name(r: SupportResponse) -> &'static str {
match r {
SupportResponse::AcceptBond => "accept_bond",
SupportResponse::DeclineBond => "decline_bond",
SupportResponse::FlipToBond => "flip_to_bond",
SupportResponse::BreakRivalry => "break_rivalry",
}
}
/// One issued command as a scenario step.
pub fn to_step(actor: Actor, command: &GroundCommand) -> CommandStep {
let mut args: BTreeMap<String, serde_yaml::Value> = BTreeMap::new();
let cmd = match command {
GroundCommand::SelectAction {
action,
target,
problem,
} => {
args.insert("action".into(), text(action_name(*action)));
if let Some(t) = target {
args.insert("target".into(), seat(*t));
}
if let Some(p) = problem {
args.insert("problem".into(), num(u64::from(*p)));
}
"select_action"
}
GroundCommand::SpendFreedom => "spend_freedom",
GroundCommand::ChooseGroundMode { mode, choice } => {
args.insert("mode".into(), text(mode_name(*mode)));
match choice {
None => {}
Some(GroundChoice::RestoreProblem { problem }) => {
args.insert("choice".into(), text("restore_problem"));
args.insert("problem".into(), num(u64::from(*problem)));
}
Some(GroundChoice::ProtectProblem { problem }) => {
args.insert("choice".into(), text("protect_problem"));
args.insert("problem".into(), num(u64::from(*problem)));
}
Some(GroundChoice::CancelAttack { attacker }) => {
args.insert("choice".into(), text("cancel_attack"));
args.insert("seat".into(), num(u64::from(attacker.0)));
}
Some(GroundChoice::RemoveBlame { owner }) => {
args.insert("choice".into(), text("remove_blame"));
args.insert("seat".into(), num(u64::from(owner.0)));
}
Some(GroundChoice::BreakRelation { with }) => {
args.insert("choice".into(), text("break_relation"));
args.insert("seat".into(), num(u64::from(with.0)));
}
Some(GroundChoice::RejectReverse) => {
args.insert("choice".into(), text("reject_reverse"));
}
}
"choose_ground_mode"
}
GroundCommand::RespondToSupport { response } => {
args.insert("response".into(), text(response_name(*response)));
"respond_to_support"
}
GroundCommand::ChooseDarvoTarget { target } => {
if let Some(p) = target.problem {
args.insert("problem".into(), num(u64::from(p)));
}
if let Some(t) = target.player {
args.insert("target".into(), seat(t));
}
"choose_darvo_target"
}
GroundCommand::Reveal => "reveal",
GroundCommand::Resolve => "resolve",
GroundCommand::EndRound => "end_round",
};
CommandStep {
actor: actor_name(actor),
cmd: cmd.into(),
args,
}
}
/// A whole played game as a scenario file.
///
/// `covers` is deliberately **empty**: a recorded game exercises whatever
/// it happened to exercise, and claiming rule coverage from it would
/// inflate AM-1 with rules nobody asserted. `expect.state_hash` carries
/// the end-state hash, which is the assertion that a replay must satisfy.
pub fn to_scenario(
name: &str,
seed: u64,
players: u8,
steps: &[(Actor, GroundCommand)],
end_state_hash: Option<String>,
) -> cb_game_runtime::ScenarioFile {
cb_game_runtime::ScenarioFile {
scenario: name.to_string(),
description: "recorded by cb-play (CB-WP-0008 T02)".into(),
covers: vec![],
provisional: false,
provisional_owner: String::new(),
provisional_raised: String::new(),
seed,
setup: Setup {
players,
preset: format!("standard-{players}p"),
patch: BTreeMap::new(),
},
commands: steps.iter().map(|(a, c)| to_step(*a, c)).collect(),
expect: cb_game_runtime::scenario::Expect {
state_hash: end_state_hash,
..Default::default()
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{DarvoTarget, GroundState};
use cb_game_runtime::ScenarioGame;
/// A game somebody played becomes a scenario the runner re-executes
/// to the same hash. This is the acceptance clause "the same
/// transcript replays identically", taken through the *scenario
/// runner* rather than through a second call to the same driver —
/// which would only prove the driver is deterministic.
#[test]
fn a_recorded_bot_game_replays_as_a_scenario() {
use crate::bot::{play, GreedyPolicy, Policy};
use cb_events::state_hash_hex;
use cb_game_runtime::{run, RunOutcome, Setup};
let setup = Setup {
players: 3,
preset: "standard-3p".into(),
patch: BTreeMap::new(),
};
let game = play(
GroundState::setup(&setup, 42).expect("preset"),
&mut (0..3)
.map(|_| Box::new(GreedyPolicy) as Box<dyn Policy>)
.collect::<Vec<_>>(),
)
.expect("bot game");
let hash = state_hash_hex(&game.state);
let scenario = to_scenario(
"ground/recorded-bot-game",
42,
3,
&game.steps,
Some(hash.clone()),
);
assert_eq!(scenario.commands.len(), game.steps.len());
match run::<GroundState>(&scenario) {
RunOutcome::Passed { .. } => {}
RunOutcome::Failed { reason, .. } => {
panic!("recorded game did not replay: {reason}")
}
}
// Control: the recorded hash is what the replay is checked
// against, so a wrong hash must fail. Without this the pass above
// is satisfied by a scenario that asserts nothing.
let tampered = to_scenario(
"ground/recorded-bot-game",
42,
3,
&game.steps,
Some("0".repeat(hash.len())),
);
assert!(
matches!(run::<GroundState>(&tampered), RunOutcome::Failed { .. }),
"a tampered end-state hash must fail the replay"
);
}
/// Every command shape must survive encode → parse unchanged. This is
/// the whole warrant for the encoder: nothing else compares it to the
/// reader it must agree with.
#[test]
fn every_command_shape_round_trips() {
let p2 = PlayerId(1);
let cases: Vec<(Actor, GroundCommand)> = vec![
(
Actor::Player(PlayerId(0)),
GroundCommand::SelectAction {
action: Action::Investigate,
target: None,
problem: Some(3),
},
),
(
Actor::Player(PlayerId(0)),
GroundCommand::SelectAction {
action: Action::Attack,
target: Some(p2),
problem: None,
},
),
(
Actor::Player(PlayerId(2)),
GroundCommand::SelectAction {
action: Action::Ground,
target: None,
problem: None,
},
),
(Actor::Player(PlayerId(0)), GroundCommand::SpendFreedom),
(
Actor::Player(PlayerId(0)),
GroundCommand::ChooseGroundMode {
mode: GroundMode::Gr,
choice: None,
},
),
(
Actor::Player(PlayerId(0)),
GroundCommand::ChooseGroundMode {
mode: GroundMode::Ou,
choice: Some(GroundChoice::RestoreProblem { problem: 2 }),
},
),
(
Actor::Player(PlayerId(0)),
GroundCommand::ChooseGroundMode {
mode: GroundMode::Ou,
choice: Some(GroundChoice::ProtectProblem { problem: 1 }),
},
),
(
Actor::Player(PlayerId(0)),
GroundCommand::ChooseGroundMode {
mode: GroundMode::Ou,
choice: Some(GroundChoice::CancelAttack { attacker: p2 }),
},
),
(
Actor::Player(PlayerId(0)),
GroundCommand::ChooseGroundMode {
mode: GroundMode::Nd,
choice: Some(GroundChoice::RemoveBlame { owner: p2 }),
},
),
(
Actor::Player(PlayerId(0)),
GroundCommand::ChooseGroundMode {
mode: GroundMode::Nd,
choice: Some(GroundChoice::BreakRelation { with: p2 }),
},
),
(
Actor::Player(PlayerId(0)),
GroundCommand::ChooseGroundMode {
mode: GroundMode::Nd,
choice: Some(GroundChoice::RejectReverse),
},
),
(
Actor::Player(PlayerId(1)),
GroundCommand::RespondToSupport {
response: SupportResponse::AcceptBond,
},
),
(
Actor::Player(PlayerId(1)),
GroundCommand::RespondToSupport {
response: SupportResponse::BreakRivalry,
},
),
(
Actor::Player(PlayerId(0)),
GroundCommand::ChooseDarvoTarget {
target: DarvoTarget {
problem: Some(2),
player: None,
},
},
),
(
Actor::Player(PlayerId(0)),
GroundCommand::ChooseDarvoTarget {
target: DarvoTarget {
problem: None,
player: Some(p2),
},
},
),
(Actor::System, GroundCommand::Reveal),
(Actor::System, GroundCommand::Resolve),
(Actor::System, GroundCommand::EndRound),
];
for (actor, command) in &cases {
let step = to_step(*actor, command);
let parsed = GroundState::parse_command(&step)
.unwrap_or_else(|e| panic!("{step:?} does not parse back: {e}"));
assert_eq!(parsed, (*actor, command.clone()), "round trip: {step:?}");
}
// Positive control: the case list must cover every variant. A
// shape added to GroundCommand and forgotten here would encode
// untested — the failure this test exists to prevent.
let shapes: std::collections::BTreeSet<String> = cases
.iter()
.map(|(_, c)| to_step(Actor::System, c).cmd)
.collect();
assert_eq!(shapes.len(), 8, "every GroundCommand variant must appear");
}
}

313
games/ground/src/view.rs Normal file
View file

@ -0,0 +1,313 @@
//! K13's first implementor (CB-WP-0008 T02).
//!
//! `cb_game_runtime::Project` has existed since CB-WP-0001 with **zero
//! implementors** — a trait shaped for a consumer that had not been
//! written. This is that consumer: `cb-play` shows one seat what it may
//! see, and nothing else.
//!
//! K13 says a projection is *a total function from state to what one seat
//! may see*, and that projections can never feed back into validation.
//! Nothing here is `pub` to the aggregate; `validate` does not import it.
//!
//! ## What is hidden, and by which rule
//!
//! | hidden | rule |
//! |---|---|
//! | other seats' face-down selections, until Reveal | GR-R02/R04 |
//! | other seats' Solution hands (count only) | GR-S02 |
//! | the undealt Solution deck (count only) | GR-S04 |
//! | a face-down Problem's suit and value | GR-S01 |
//! | `seed` | it determines every future shuffle |
//!
//! The last one is the interesting one: `seed` is not secret *content*,
//! but a seat holding it can compute the deck. It is omitted from the
//! view for the same reason the deck is.
use crate::{
Coalition, DarvoStage, DarvoTarget, GroundChoice, GroundMode, GroundState, Outcome, Pair,
ProblemState, Relation, RoundStep, ScoringMode, Selection, SolutionCard, SupportResponse,
};
use cb_game_runtime::{Project, Viewer};
use cb_kernel::PlayerId;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// What one seat may see of a `GroundState`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GroundView {
/// `None` for a spectator.
pub viewer: Option<PlayerId>,
pub round: u8,
pub lead: PlayerId,
pub step: RoundStep,
pub mode: ScoringMode,
pub players: BTreeMap<PlayerId, PlayerView>,
pub relations: BTreeMap<Pair, Relation>,
pub problems: BTreeMap<u32, ProblemView>,
pub focus: BTreeMap<PlayerId, PlayerId>,
/// GR-R02: `Hidden` for other seats until Reveal.
pub selections: BTreeMap<PlayerId, SelectionView>,
pub ground_modes: BTreeMap<PlayerId, GroundMode>,
pub ground_choices: BTreeMap<PlayerId, GroundChoice>,
pub support_responses: BTreeMap<PlayerId, SupportResponse>,
pub darvo_targets: BTreeMap<PlayerId, DarvoTarget>,
/// GR-S04: how many Solutions remain, not which.
pub solution_deck_len: usize,
/// Discards are public — they have been played.
pub solution_discard: Vec<SolutionCard>,
pub outcome: Option<OutcomeView>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlayerView {
pub stress: u8,
pub freedom_ready: bool,
pub freedom_gate_lifted: bool,
pub darvo: DarvoStage,
pub protection: u8,
pub blame_from: Vec<PlayerId>,
/// GR-S02: only the viewer's own hand.
pub hand: Option<Vec<SolutionCard>>,
pub hand_size: usize,
}
/// GR-S01: a face-down Problem shows nothing but its priority (the map
/// key) and that it exists.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state")]
pub enum ProblemView {
FaceDown,
FaceUp {
suit: crate::Suit,
value: u8,
denied: bool,
claimed_by: Option<PlayerId>,
protected_this_round: bool,
},
}
/// GR-R02/R04: face-down means face-down, including to the projection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state")]
pub enum SelectionView {
/// Someone has selected; what, this seat may not see.
Hidden,
Shown(Selection),
}
/// The final outcome is public once it exists (GR-E01..E04).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OutcomeView {
pub total: u32,
pub threshold: u32,
pub group_success: bool,
pub personal: BTreeMap<PlayerId, i32>,
pub coalitions: Vec<Coalition>,
pub mastery: Option<i32>,
pub winners: Vec<PlayerId>,
}
impl From<&Outcome> for OutcomeView {
fn from(o: &Outcome) -> Self {
Self {
total: o.total,
threshold: o.threshold,
group_success: o.group_success,
personal: o.personal.clone(),
coalitions: o.coalitions.clone(),
mastery: o.mastery,
winners: o.winners.clone(),
}
}
}
impl From<&ProblemState> for ProblemView {
fn from(p: &ProblemState) -> Self {
if p.face_up {
ProblemView::FaceUp {
suit: p.suit,
value: p.value,
denied: p.denied,
claimed_by: p.claimed_by,
protected_this_round: p.protected_this_round,
}
} else {
ProblemView::FaceDown
}
}
}
impl Project for GroundState {
type View = GroundView;
fn project(&self, viewer: Viewer) -> GroundView {
let seat = match viewer {
Viewer::Player(p) => Some(p),
Viewer::Spectator => None,
};
// GR-R04: once Reveal has happened, selections are public for the
// rest of the round.
let revealed = self.step != RoundStep::Select;
GroundView {
viewer: seat,
round: self.round,
lead: self.lead,
step: self.step,
mode: self.mode,
players: self
.players
.iter()
.map(|(id, p)| {
(
*id,
PlayerView {
stress: p.stress,
freedom_ready: p.freedom_ready,
freedom_gate_lifted: p.freedom_gate_lifted,
darvo: p.darvo,
protection: p.protection,
blame_from: p.blame_from.clone(),
hand: (Some(*id) == seat).then(|| p.hand.clone()),
hand_size: p.hand.len(),
},
)
})
.collect(),
relations: self.relations.clone(),
problems: self.problems.iter().map(|(k, p)| (*k, p.into())).collect(),
focus: self.focus.clone(),
selections: self
.selections
.iter()
.map(|(id, sel)| {
let visible = revealed || Some(*id) == seat;
(
*id,
if visible {
SelectionView::Shown(*sel)
} else {
SelectionView::Hidden
},
)
})
.collect(),
ground_modes: self.ground_modes.clone(),
ground_choices: self.ground_choices.clone(),
support_responses: self.support_responses.clone(),
darvo_targets: self.darvo_targets.clone(),
solution_deck_len: self.solution_deck.len(),
solution_discard: self.solution_discard.clone(),
outcome: self.outcome.as_ref().map(OutcomeView::from),
}
}
}
#[cfg(all(test, feature = "scenarios"))]
mod tests {
use super::*;
use crate::{Action, Actor, Aggregate, GroundCommand};
use cb_game_runtime::{ScenarioGame, Setup};
fn setup(players: u8, seed: u64) -> GroundState {
GroundState::setup(
&Setup {
players,
preset: format!("standard-{players}p"),
patch: Default::default(),
},
seed,
)
.expect("preset")
}
fn select(state: &mut GroundState, seat: u8, action: Action, problem: Option<u32>) {
let cmd = GroundCommand::SelectAction {
action,
target: None,
problem,
};
let events = state
.validate(Actor::Player(PlayerId(seat)), &cmd)
.expect("legal");
for e in &events {
state.fold(e);
}
}
/// The acceptance clause: a seat's projection never contains another
/// seat's hidden selection. Asserted on the serialized form, because
/// that is what a CLI prints and what leaks.
#[test]
fn a_seat_never_sees_another_seats_face_down_selection() {
let mut state = setup(3, 42);
// Distinct actions, so finding the other seat's is unambiguous.
select(&mut state, 0, Action::Investigate, Some(2));
select(&mut state, 1, Action::Solve, Some(1));
// GR-R04 needs every seat before Reveal.
select(&mut state, 2, Action::Ground, None);
let view = state.project(Viewer::Player(PlayerId(0)));
let json = serde_json::to_string(&view).expect("serialize");
assert!(json.contains("Investigate"), "own selection must be shown");
assert!(
!json.contains("Solve"),
"seat 1's face-down SOLVE leaked into seat 0's view: {json}"
);
assert_eq!(
view.selections.get(&PlayerId(1)),
Some(&SelectionView::Hidden)
);
// And the same view after Reveal shows it — otherwise the
// assertion above passes for a projection that shows nothing.
let events = state
.validate(Actor::System, &GroundCommand::Reveal)
.expect("reveal");
for e in &events {
state.fold(e);
}
let after = state.project(Viewer::Player(PlayerId(0)));
assert!(matches!(
after.selections.get(&PlayerId(1)),
Some(SelectionView::Shown(_))
));
}
/// GR-S02/S04: hands and deck are hidden; counts are not.
#[test]
fn hands_and_deck_are_hidden_but_counted() {
let state = setup(3, 7);
let view = state.project(Viewer::Player(PlayerId(0)));
assert!(view.players[&PlayerId(0)].hand.is_some());
assert!(view.players[&PlayerId(1)].hand.is_none());
assert_eq!(view.players[&PlayerId(1)].hand_size, 2);
assert_eq!(view.solution_deck_len, state.solution_deck.len());
let json = serde_json::to_string(&view).expect("serialize");
assert!(
!json.contains("\"seed\""),
"the seed determines every future shuffle and must not project"
);
}
/// GR-S01: a face-down Problem shows nothing about itself.
#[test]
fn a_face_down_problem_shows_nothing() {
let state = setup(3, 7);
let view = state.project(Viewer::Spectator);
assert_eq!(view.problems[&1], (&state.problems[&1]).into());
assert!(matches!(view.problems[&1], ProblemView::FaceUp { .. }));
assert_eq!(view.problems[&2], ProblemView::FaceDown);
assert_eq!(view.viewer, None);
}
/// A spectator sees no hand at all — the `Some(*id) == seat` test must
/// not accidentally match `None`.
#[test]
fn a_spectator_sees_no_hands() {
let view = setup(3, 7).project(Viewer::Spectator);
assert!(view.players.values().all(|p| p.hand.is_none()));
}
}