Files
pokerfreak/src/engine/turn_subgame.rs
T
mmintelandClaude Opus 4.8 47d3ea8094 Engine: EV-neutrales Size-Mix, Stage-B-Solver-Infra, Turnier-Staerke-Leiter
Drei getestete/bewiesene Arbeitsstraenge dieser Session (128/128 Lib gruen):

- EV-neutrales Size-Mix (engine::postflop): das Postflop-Sizing war reiner
  EV-Argmax (deterministisch und damit lesbar). Es mischt jetzt seeded unter
  den Raise-Sizes, deren EV innerhalb 0.5 Standardfehlern des besten liegt
  (unter dem Modell nicht unterscheidbar) - nur Raises, nie check/call/fold.
  Gepaart gegen die deterministische Baseline bewiesen EV-neutral
  (-0.23 +/-0.59 bb/100, 112 Spots gemischt, jede Zeile ununterscheidbar von 0);
  der winzige Negativ-Punktschaetzer ist konstruktionsbedingt (Abweichung nur
  weg vom Argmax) und band-getrieben. Schalter SIZE_MIX / SIZE_MIX_BAND.
  Befund: docs/notizen/BEFUND-size-mix-ev-neutral.md.

- Stage B Turn+River-Subgame-Solver (cfr::turn_river, engine::turn_subgame) plus
  Per-Street-Aggression in der Belief (Profile turn_/river_aggression,
  sim::memory-Zaehler, believed_villain nimmt die Aggression als Parameter). Der
  Live-Turn-Fold-Veto wurde nach gepaarter Messung ZURUECKGENOMMEN (regressiert
  nemesis-1; Wurzel = draw-blinder Turn-Bucket, nicht Belief-Granularitaet ->
  Stage C). Solver- und Belief-Infra bleibt als getestete, Ladder-neutrale
  Primitive. Befund: docs/notizen/BEFUND-stage-b-turn-river-solver.md.

- Turnier-Staerke-Leiter (sim::turnier_leiter, bin turnier_leiter, icm::risk):
  ICM-$-gepaarte Leiter, die die ICM-Linie gegen Chip-EV beweist, Cash
  bit-identisch. Befunde: docs/notizen/BEFUND-turnier-*.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-12 12:06:39 +01:00

597 lines
26 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Engine bridge from a live TURN spot to the depth-limited turn+river CFR solver
//! (`cfr::turn_river`). The turn-street analogue of `engine::river_subgame`, one street deeper.
//!
//! # Construction (Option B: depth-limited turn, river-equilibrium leaf)
//!
//! The turn is NOT the last street, so a turn showdown is not exact — what a turn line is worth
//! depends on how the river then plays. This bridge solves only the turn betting round and evaluates
//! each "reach the river" leaf by the **equilibrium value of the river subgame** it leads to,
//! averaged over the runout:
//!
//! 1. Source the villain belief range (gated reads → `range_spec` → `range_filter` → `combos`), the
//! same pipeline as the river. Hero is modelled with the same range (symmetric prior), as on the
//! river. Bucket both by **turn** strength (`judge` on the 4-card board) into one shared ladder.
//! 2. For every river card (`deck::without_in` over the turn board), solve the heads-up river subgame
//! (`cfr::river`) at the two possible river-start pots (turn checked through, and a called turn
//! bet), and read its equilibrium value per river-bucket pair (`cfr::turn_river::pair_values`).
//! Fold those values back onto the **turn** buckets, weighted by card removal, to get two leaf
//! matrices `V_check[i][j]` and `V_bet[i][j]` (hero's expected river chips given the turn buckets).
//! 3. Build the turn tree (`cfr::turn_river::tree_with_leaf`) with those leaves and solve it. Read
//! hero's mixed action for the bucket its real turn hand sits in.
//!
//! This is the proven river construction lifted one street: the CFR core is unchanged, the leaf is a
//! real equilibrium value (not an equity guess), and when the river leaf degenerates to a showdown
//! the turn tree is identical to the river tree (`cfr::turn_river` tests). Multiway, or a range the
//! engine cannot enumerate, returns `None` and the caller keeps the heuristic.
//!
//! # Named approximations (beyond the river's own)
//!
//! - Hero's turn range is the villain's believed range (symmetric prior), as on the river.
//! - Turn and river buckets are equal-strength quantile cuts; a higher bucket wins the showdown on
//! that street. The leaf averages the river value over runouts at the combo level (card removal of
//! the river card is exact per pair), then aggregates to turn buckets.
//! - River sub-solves use one bet size (`cfr::river` v1) at `TARGET_BET_FRACTION` of the pot; the turn
//! likewise. Raises and multiple sizes are later versions.
use crate::card::{deck, Card};
use crate::cfr::kl_br::kl_best_response;
use crate::cfr::river::tree_with_chance;
use crate::cfr::solve::solve;
use crate::cfr::tree::Tree;
use crate::cfr::turn_river::{pair_values, tree_with_leaf};
use crate::engine::river_subgame::{believed_villain, lambda_from_confidence};
use crate::exploit::profile::Profile;
use crate::game::{Choice, Decision, Spot, Street};
use crate::hand::showdown::judge;
use crate::hand::strength::Strength;
use crate::rng::Rng;
use crate::sizing::candidates::candidates;
/// CFR+ iterations for the turn solve (tiny 9-node tree).
const TURN_SOLVE_ITERS: u32 = 6_000;
/// CFR+ iterations for each river sub-solve that feeds a leaf value. These feed an averaged value, not
/// a live decision, so a lighter budget than the live river solver (12k) is enough.
const RIVER_LEAF_ITERS: u32 = 3_000;
/// Target bet size as a fraction of the pot; the nearest legal candidate is used (turn), the exact
/// fraction is used for the river sub-solves.
const TARGET_BET_FRACTION: f64 = 0.66;
/// Below this read confidence the turn gearbox stands down (the heuristic keeps the edge). Mirrors the
/// river gearbox: at a weak read λ is huge and the tilt collapses to near-GTO, and a balanced turn line
/// is worse than the heuristic against an unread exploitable field.
const CONFIDENCE_FLOOR: f64 = 0.25;
/// Below this believed call frequency the defensive veto folds a heuristic turn call: the believed
/// (KL-bounded) best response calls hero's bucket less than half the time, so the believed turn bet is
/// value-heavy enough that the call is −EV. The turn analogue of the proven river `VETO_CALL_FLOOR`.
const VETO_CALL_FLOOR: f64 = 0.5;
/// Measurement toggle (read once): `TURN_VETO=0` disables the live turn veto so a single run can
/// measure the engine with the veto on vs off on the same deals (paired). Default on. Not read on the
/// hot path beyond the first call.
fn veto_enabled() -> bool {
use std::sync::OnceLock;
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var("TURN_VETO").as_deref() != Ok("0"))
}
/// CFR+ iterations per river leaf solve, overridable via `TURN_LEAF_ITERS` (read once) for a
/// speed/accuracy sweep — the dominant cost is `~44` of these per turn build. The default
/// `RIVER_LEAF_ITERS` leaves behaviour bit-identical; a lower value trades leaf-value precision for
/// speed. A non-numeric or zero value falls back to the default.
fn river_leaf_iters() -> u32 {
use std::sync::OnceLock;
static ITERS: OnceLock<u32> = OnceLock::new();
*ITERS.get_or_init(|| {
std::env::var("TURN_LEAF_ITERS")
.ok()
.and_then(|v| v.parse::<u32>().ok())
.filter(|&n| n > 0)
.unwrap_or(RIVER_LEAF_ITERS)
})
}
/// Hero's equilibrium mix at the turn node the spot sits on.
pub struct TurnPlan {
/// `true` = hero faces a turn bet (`mix` is `[fold, call]`); `false` = hero acts first
/// (`mix` is `[check, bet]`).
pub facing: bool,
/// The two action probabilities for hero's bucket, in the order above.
pub mix: [f64; 2],
/// The bet-to total when acting first; `0` facing a bet.
pub bet_to: f64,
/// Human reason for the decision log.
pub reason: String,
}
impl TurnPlan {
/// Probability of the aggressive action (bet, or call facing a bet).
pub fn forward(&self) -> f64 {
self.mix[1]
}
}
/// The legal bet-to total nearest `TARGET_BET_FRACTION * pot`, or `None` if nothing is bettable.
fn bet_to(spot: &Spot) -> Option<f64> {
let target = TARGET_BET_FRACTION * spot.pot;
candidates(spot)
.into_iter()
.filter(|to| *to > 0.0 && *to <= spot.hero_stack)
.min_by(|a, b| (a - target).abs().total_cmp(&(b - target).abs()))
}
/// Two hole-card hands can be dealt together only if they share no card.
fn disjoint(a: &[Card], b: &[Card]) -> bool {
a.iter().all(|c| !b.contains(c))
}
/// A solved turn subgame plus the shared turn-strength ladder, so hero's real hand can be placed on
/// the same buckets the solve used.
struct TurnGame {
tree: Tree,
solved: crate::cfr::solve::Solved,
ladder: Vec<Strength>,
}
impl TurnGame {
fn bucket(&self, s: Strength) -> usize {
self.ladder.partition_point(|d| *d < s).min(self.ladder.len() - 1)
}
}
/// Build the two river leaf-value matrices (`V_check`, `V_bet`) over the turn buckets by solving the
/// river subgame for every runout at both river-start pots and folding the equilibrium values back
/// onto the turn buckets with exact card removal. `turn_n` is the turn-bucket count, `turn_bucket`
/// maps a combo's turn strength to its bucket, `p`/`s` the turn pot and bet.
fn river_leaves(
spot: &Spot,
hero: &[(Vec<Card>, usize)], // (combo, turn bucket)
villain: &[(Vec<Card>, usize)],
turn_n: usize,
p: f64,
s: f64,
) -> Option<(Vec<f64>, Vec<f64>)> {
let rules = spot.rules();
let (pot_check, s_check) = (p, TARGET_BET_FRACTION * p);
let pot_bet = p + 2.0 * s;
let s_bet = TARGET_BET_FRACTION * pot_bet;
let mut leaf_check = vec![0.0; turn_n * turn_n];
let mut leaf_bet = vec![0.0; turn_n * turn_n];
let mut counts = vec![0.0; turn_n * turn_n];
let rivers = deck::without_in(rules.deck, &spot.board);
for r in &rivers {
let mut board5 = spot.board.clone();
board5.push(*r);
// River strengths of the combos that can still be dealt with this river out.
let judged = |src: &[(Vec<Card>, usize)]| -> Vec<(Vec<Card>, usize, Strength)> {
src.iter()
.filter(|(c, _)| !c.contains(r))
.filter_map(|(c, tb)| judge(&rules, c, &board5).ok().map(|st| (c.clone(), *tb, st)))
.collect()
};
let rh = judged(hero);
let rv = judged(villain);
if rh.is_empty() || rv.is_empty() {
continue;
}
// Shared river ladder (ascending, deduped) over both ranges on this runout.
let mut rladder: Vec<Strength> = rh.iter().chain(&rv).map(|(_, _, st)| *st).collect();
rladder.sort();
rladder.dedup();
let m = rladder.len();
let rbucket = |st: Strength| rladder.partition_point(|d| *d < st).min(m.saturating_sub(1));
// A degenerate river (one strength level): the showdown is always a split, river value 0
// around either pot. Still counts toward the average, contributing 0.
if m < 2 {
for (hc, tbh, _) in &rh {
for (vc, tbv, _) in &rv {
if disjoint(hc, vc) {
counts[tbh * turn_n + tbv] += 1.0;
}
}
}
continue;
}
// River joint deal table over river buckets, card removal between the two ranges (the river
// card is already removed by construction).
let mut rchance = vec![0.0; m * m];
for (hc, _, hst) in &rh {
let hb = rbucket(*hst);
for (vc, _, vst) in &rv {
if disjoint(hc, vc) {
rchance[hb * m + rbucket(*vst)] += 1.0;
}
}
}
let total: f64 = rchance.iter().sum();
if total <= 0.0 {
continue;
}
rchance.iter_mut().for_each(|x| *x /= total);
// Equilibrium river value per river-bucket pair, at each river-start pot.
let seed = spot.seed ^ u64::from(r.index());
let tree_check = tree_with_chance(m, rchance.clone(), pot_check, s_check);
let w_check = pair_values(&tree_check, &solve(&tree_check, river_leaf_iters(), Rng::seeded(seed)).strategy);
let tree_bet = tree_with_chance(m, rchance, pot_bet, s_bet);
let w_bet = pair_values(&tree_bet, &solve(&tree_bet, river_leaf_iters(), Rng::seeded(seed)).strategy);
// Fold the river values onto the turn buckets.
for (hc, tbh, hst) in &rh {
let rbh = rbucket(*hst);
for (vc, tbv, vst) in &rv {
if disjoint(hc, vc) {
let rbv = rbucket(*vst);
let k = tbh * turn_n + tbv;
leaf_check[k] += w_check[rbh * m + rbv];
leaf_bet[k] += w_bet[rbh * m + rbv];
counts[k] += 1.0;
}
}
}
}
// Average per turn-bucket pair. Pairs that never co-occur keep 0 (they carry no chance weight).
for k in 0..turn_n * turn_n {
if counts[k] > 0.0 {
leaf_check[k] /= counts[k];
leaf_bet[k] /= counts[k];
}
}
Some((leaf_check, leaf_bet))
}
/// Build and solve the turn subgame the engine believes it is in, with the river folded into the
/// leaves. `p`/`s` are the turn pot and bet. `None` when it cannot be built (fewer than two distinct
/// turn strengths, empty ranges).
fn build_turn(spot: &Spot, hero_combos: &[Vec<Card>], villain_combos: &[Vec<Card>], p: f64, s: f64) -> Option<TurnGame> {
let rules = spot.rules();
let judged = |combos: &[Vec<Card>]| -> Vec<(Vec<Card>, Strength)> {
combos.iter().filter_map(|c| judge(&rules, c, &spot.board).ok().map(|st| (c.clone(), st))).collect()
};
let hero = judged(hero_combos);
let villain = judged(villain_combos);
if hero.is_empty() || villain.is_empty() {
return None;
}
let mut ladder: Vec<Strength> = hero.iter().chain(&villain).map(|(_, st)| *st).collect();
ladder.sort();
ladder.dedup();
let n = ladder.len();
if n < 2 {
return None;
}
let tb = |st: Strength| ladder.partition_point(|d| *d < st).min(n - 1);
let hero_b: Vec<(Vec<Card>, usize)> = hero.iter().map(|(c, st)| (c.clone(), tb(*st))).collect();
let villain_b: Vec<(Vec<Card>, usize)> = villain.iter().map(|(c, st)| (c.clone(), tb(*st))).collect();
// Turn joint deal table over turn buckets (card removal between the two ranges).
let mut chance = vec![0.0; n * n];
for (hc, hb) in &hero_b {
for (vc, vb) in &villain_b {
if disjoint(hc, vc) {
chance[hb * n + vb] += 1.0;
}
}
}
let total: f64 = chance.iter().sum();
if total <= 0.0 {
return None;
}
chance.iter_mut().for_each(|x| *x /= total);
let (leaf_check, leaf_bet) = river_leaves(spot, &hero_b, &villain_b, n, p, s)?;
let tree = tree_with_leaf(n, chance, p, leaf_check, leaf_bet);
let solved = solve(&tree, TURN_SOLVE_ITERS, Rng::seeded(spot.seed));
Some(TurnGame { tree, solved, ladder })
}
/// Solve the heads-up turn subgame from the engine's belief and return hero's equilibrium mix at the
/// node the spot sits on, or `None` when the v1 slice does not apply (the caller keeps the heuristic).
pub fn turn_plan(spot: &Spot, villain_combos: &[Vec<Card>]) -> Option<TurnPlan> {
if spot.street != Street::Turn {
return None;
}
if spot.live_villains().count() != 1 || villain_combos.is_empty() {
return None;
}
let rules = spot.rules();
let hero_strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
if spot.to_call == 0.0 {
let s = bet_to(spot)?;
let game = build_turn(spot, villain_combos, villain_combos, spot.pot, s)?;
let hb = game.bucket(hero_strength);
let probs = game.solved.strategy.row(0, hb).to_vec(); // [check, bet]
let bet_p = probs.get(1).copied().unwrap_or(0.0);
Some(TurnPlan {
facing: false,
mix: [probs.first().copied().unwrap_or(1.0 - bet_p), bet_p],
bet_to: s,
reason: format!("turn subgame: bucket {hb}/{}, p(bet) {bet_p:.2}", game.ladder.len()),
})
} else {
// Facing a turn bet: the pre-bet pot is `pot - to_call`, the bet is `to_call`.
let p = spot.pot - spot.to_call;
let s = spot.to_call;
if p <= 0.0 || s <= 0.0 {
return None;
}
let game = build_turn(spot, villain_combos, villain_combos, p, s)?;
let hb = game.bucket(hero_strength);
let row = game.solved.strategy.row(4, hb).to_vec(); // [fold, call]
let call_p = row.get(1).copied().unwrap_or(0.0);
Some(TurnPlan {
facing: true,
mix: [row.first().copied().unwrap_or(1.0 - call_p), call_p],
bet_to: 0.0,
reason: format!("turn subgame: bucket {hb}/{} facing bet, p(call) {call_p:.2}", game.ladder.len()),
})
}
}
/// Build the villain belief combos the way `decide::postflop` does (gated reads, enumerated range)
/// and return hero's turn mix — the measurement entry point, faithful to what the live engine would
/// play. `None` when the slice does not apply.
pub fn turn_mix(spot: &Spot) -> Option<TurnPlan> {
if spot.street != Street::Turn {
return None;
}
let gated = crate::engine::read_gate::gate_reads(spot);
let spot = &gated;
if spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let rules = spot.rules();
let filter = crate::engine::range_filter::range_filter(
&crate::exploit::range_model::range_spec(spot, villain),
rules,
spot.variant,
&spot.board,
);
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?;
turn_plan(spot, &list)
}
/// The belief + trust version of `turn_plan`: solve the turn subgame for GTO, then tilt hero toward
/// best-responding to the **believed** villain (`believed_villain`, reused from the river — the turn
/// tree's `v_bet`/`v_check` nodes carry the same meaning) inside a KL ball of radius λ
/// (`lambda_from_confidence`). A strong read exploits; a weak/absent read collapses to the proven
/// GTO mix (λ → ∞). `None` outside the slice or below the confidence floor.
pub fn turn_exploit_plan(spot: &Spot, villain_combos: &[Vec<Card>], profile: Option<&Profile>) -> Option<TurnPlan> {
if spot.street != Street::Turn {
return None;
}
if spot.live_villains().count() != 1 || villain_combos.is_empty() {
return None;
}
if profile.and_then(|p| p.confidence).filter(|c| !c.is_nan()).unwrap_or(0.0) < CONFIDENCE_FLOOR {
return None;
}
let rules = spot.rules();
let hero_strength = judge(&rules, &spot.hero_cards, &spot.board).ok()?;
let (p, s, facing) = if spot.to_call == 0.0 {
(spot.pot, bet_to(spot)?, false)
} else {
let p = spot.pot - spot.to_call;
if p <= 0.0 || spot.to_call <= 0.0 {
return None;
}
(p, spot.to_call, true)
};
let game = build_turn(spot, villain_combos, villain_combos, p, s)?;
let n = game.ladder.len();
let opponent = believed_villain(&game.tree, n, profile, p, s, profile.and_then(|pr| pr.turn_aggression.or(pr.aggression)));
let lambda = lambda_from_confidence(profile.and_then(|p| p.confidence), p);
let tilted = kl_best_response(&game.tree, &opponent, &game.solved.strategy, 0, lambda);
let hb = game.bucket(hero_strength);
let node = if facing { 4 } else { 0 };
let row = tilted.row(node, hb).to_vec();
let forward = row.get(1).copied().unwrap_or(0.0);
Some(TurnPlan {
facing,
mix: [row.first().copied().unwrap_or(1.0 - forward), forward],
bet_to: if facing { 0.0 } else { s },
reason: format!(
"turn gearbox: bucket {hb}/{n}{}, λ {:.2}, p(fwd) {forward:.2}",
if facing { " facing bet" } else { "" },
lambda
),
})
}
/// Live entry for the turn belief + trust gearbox: source the villain belief from the **raw** read and
/// hand the solver the opponent's real `Profile`. Like the river gearbox, the KL trust radius is its
/// own safety, so it reads the true opponent and the confidence floor keeps it off thin reads.
pub fn turn_exploit_mix(spot: &Spot) -> Option<TurnPlan> {
if spot.street != Street::Turn {
return None;
}
if spot.live_villains().count() != 1 {
return None;
}
let villain = spot.live_villains().next()?;
let profile = villain.profile.as_ref();
let rules = spot.rules();
let filter = crate::engine::range_filter::range_filter(
&crate::exploit::range_model::range_spec(spot, villain),
rules,
spot.variant,
&spot.board,
);
let dead: Vec<Card> = spot.hero_cards.iter().chain(&spot.board).copied().collect();
let list = crate::engine::range_combos::combos(&rules, &filter, &dead)?;
turn_exploit_plan(spot, &list, profile)
}
/// Defensive turn veto: on a confident read that the villain UNDER-bluffs its turn bet, fold a heuristic
/// CALL the belief+trust gearbox would not make — the turn analogue of `river_subgame::fold_veto`. It
/// only ever turns a call into a fold facing a bet, never touches a bet/check/raise, and stands down on
/// a thin read or off the heads-up turn slice. The caller gates it to cash (no ICM premium). Builds the
/// (expensive) subgame only when the base is already a Call and the read clears the confidence floor.
pub fn turn_fold_veto(spot: &Spot, base: Decision) -> Decision {
if !veto_enabled() {
return base;
}
if base.choice != Choice::Call {
return base;
}
let Some(plan) = turn_exploit_mix(spot) else {
return base;
};
if !plan.facing || plan.mix[1] >= VETO_CALL_FLOOR {
return base;
}
Decision {
choice: Choice::Fold,
reason: format!("defensive turn veto: {} (heuristic would call)", plan.reason),
..base
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::game::{ActionKind, Villain};
use crate::variant::Variant;
/// A heads-up turn spot where hero is first to act into `pot` with check or a two-thirds bet.
fn turn_to_act(board: &[Card], hero: &str, pot: f64) -> Spot {
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 2,
hero_seat: 1,
button_seat: Some(1),
hero_cards: Card::parse_list(hero).unwrap(),
board: board.to_vec(),
street: Street::Turn,
pot,
to_call: 0.0,
hero_stack: pot * 4.0,
min_raise_to: Some(pot * 0.66),
max_raise_to: Some(pot * 4.0),
legal: vec![ActionKind::Check, ActionKind::Raise],
allowed_sizes: Some(vec![pot * 0.66]),
villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile: None }],
seed: 0x5EED_B17E,
history: Vec::new(),
}
}
fn sample_villain() -> Vec<Vec<Card>> {
["Ad Jc", "Qh Qd", "Jd Jh", "8c 8d", "6h 6d", "5c 4c", "Td 9c", "Kc Qc"]
.iter()
.map(|c| Card::parse_list(c).unwrap())
.collect()
}
/// A heads-up turn spot in the slice returns a mix, and a strong made hand leans to betting.
/// Guards the wiring (range → runout leaves → turn solve → readback), not the exact frequency.
#[test]
fn a_made_hand_to_act_gets_a_turn_mix_that_leans_to_bet() {
let board = Card::parse_list("Ah Kd 7c 2s").unwrap(); // turn: 4 cards
let villain = sample_villain();
let spot = turn_to_act(&board, "Ac As", 6.0); // top set on this board
let plan = turn_plan(&spot, &villain).expect("heads-up turn to-act is in slice");
assert!(!plan.facing);
assert!(plan.bet_to > 0.0);
assert!(plan.forward() > 0.5, "a strong made hand should lean to betting, got p(bet) {:.2}", plan.forward());
}
/// Off the turn (river) the slice declines, so the caller keeps the heuristic.
#[test]
fn the_slice_declines_off_the_turn() {
let river = Card::parse_list("Ah Kd 7c 2s 9h").unwrap(); // 5 cards = river
let mut spot = turn_to_act(&river[..4], "Ac As", 6.0);
spot.board = river;
spot.street = Street::River;
assert!(turn_plan(&spot, &sample_villain()).is_none(), "river is not the turn slice");
}
// --- belief + trust gearbox (L4) ---
fn prof(fold_to_bet: f64, aggression: f64, confidence: f64) -> Profile {
Profile {
fold_to_bet: Some(fold_to_bet),
aggression: Some(aggression),
confidence: Some(confidence),
..Default::default()
}
}
fn turn_to_act_vs(board: &[Card], hero: &str, pot: f64, profile: Option<Profile>) -> Spot {
Spot { villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile }], ..turn_to_act(board, hero, pot) }
}
fn turn_vs_bet(board: &[Card], hero: &str, pot: f64, bet: f64, profile: Option<Profile>) -> Spot {
Spot {
variant: Variant::Nlhe,
big_blind: 1.0,
seats: 2,
hero_seat: 1,
button_seat: Some(1),
hero_cards: Card::parse_list(hero).unwrap(),
board: board.to_vec(),
street: Street::Turn,
pot: pot + bet,
to_call: bet,
hero_stack: pot * 4.0,
min_raise_to: None,
max_raise_to: None,
legal: vec![ActionKind::Fold, ActionKind::Call],
allowed_sizes: None,
villains: vec![Villain { seat: 2, stack: pot * 4.0, folded: false, profile }],
seed: 0x5EED_B17E,
history: Vec::new(),
}
}
/// Below the confidence floor the turn gearbox stands down (`None`), so the heuristic keeps the edge.
#[test]
fn the_turn_gearbox_stands_down_below_the_confidence_floor() {
let board = Card::parse_list("Ah Kd 7c 2s").unwrap();
let villain = sample_villain();
let thin = turn_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.2, 0.3, 0.10)));
assert!(
turn_exploit_plan(&thin, &villain, thin.live_villains().next().unwrap().profile.as_ref()).is_none(),
"confidence 0.10 < floor ⇒ no plan"
);
let confident = turn_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.2, 0.3, 0.80)));
assert!(
turn_exploit_plan(&confident, &villain, confident.live_villains().next().unwrap().profile.as_ref()).is_some(),
"confidence 0.80 ≥ floor ⇒ a plan"
);
}
/// A confident calling-station read makes hero value-bet a strong made hand on the turn (exploit,
/// not balance) — the offense direction of the gearbox.
#[test]
fn a_confident_station_read_value_bets_a_strong_turn_hand() {
let board = Card::parse_list("Ah Kd 7c 2s").unwrap();
let villain = sample_villain();
let spot = turn_to_act_vs(&board, "Ac As", 6.0, Some(prof(0.08, 0.15, 0.85)));
let plan = turn_exploit_plan(&spot, &villain, spot.live_villains().next().unwrap().profile.as_ref())
.expect("confident heads-up turn to-act is in slice");
assert!(!plan.facing);
assert!(plan.forward() > 0.5, "value-bet a strong hand into a station, got p(bet) {:.2}", plan.forward());
}
/// The veto never touches hero's offense: a base that is not a call is returned unchanged even
/// though a plan exists (guards against a full-replacement regression, as on the river).
#[test]
fn the_turn_veto_leaves_a_non_call_decision_untouched() {
let board = Card::parse_list("Ah Kd 7c 2s").unwrap();
let spot = turn_vs_bet(&board, "Qc Qd", 6.0, 6.0, Some(prof(0.30, 0.06, 0.85)));
let check = Decision::new(Choice::Check, 0.7, "heuristic check");
assert_eq!(turn_fold_veto(&spot, check.clone()), check, "a non-call base is never vetoed");
}
}