From a768057e5cf91eeeb23e5ff8c7c664c3593fbb34 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Tue, 1 Dec 2026 13:36:22 +0100 Subject: [PATCH] Sicherung 01.12.: ungesicherte Dateien aus Worktree D:\Projects\pokerfreak\.claude\worktrees\agent-a1e73576494a60631 (Zweig worktree-agent-a1e73576494a60631, HEAD 1738208b) 3 Dateien. Nicht enthalten: 0 Dateien (Bau, Binaer, > 25 MB, archiv/lauf, Spuren echter Haende), 0 Loeschungen nicht nachgezogen. Der Worktree selbst ist unveraendert. Co-Authored-By: Claude Opus 5.5 --- src/bin/turn_veto_ab.rs | 36 + src/engine/decide.rs | 3 +- src/engine/turn_subgame.rs | 1291 +++++++++++++++++++----------------- 3 files changed, 733 insertions(+), 597 deletions(-) create mode 100644 src/bin/turn_veto_ab.rs diff --git a/src/bin/turn_veto_ab.rs b/src/bin/turn_veto_ab.rs new file mode 100644 index 00000000..6e4b360c --- /dev/null +++ b/src/bin/turn_veto_ab.rs @@ -0,0 +1,36 @@ +//! One opponent, Memory read only: the measurement cell of the turn-veto A/B. The configuration is +//! switched by environment (`TURN_VETO=0` off, `TURN_BUCKET=strength` legacy draw-blind buckets, +//! `TURN_PER_STREET=0` pooled belief aggression), so independent processes over the same seed and +//! deals are paired and can run in parallel. +//! +//! Run: `cargo run --release --bin turn_veto_ab [deals]` with opp in +//! n1 n2 n3 fish reg nit maniac. + +use rechner::sim::opponent::Opponent; +use rechner::sim::reader::{Rules, Style}; +use rechner::sim::session::{measure, ReadMode, Setup}; + +const SEED: u64 = 0x5EED_0001; + +const N1: Rules = Rules { call_margin: 0.215, raise_at: 0.587, bet_at: 0.548, open_at: 0.729, bluff: 0.068, size: 0.441 }; +const N2: Rules = Rules { call_margin: 0.173, raise_at: 0.579, bet_at: 0.748, open_at: 0.800, bluff: 0.229, size: 0.996 }; +const N3: Rules = Rules { call_margin: 0.396, raise_at: 0.769, bet_at: 0.615, open_at: 0.468, bluff: 0.261, size: 1.148 }; + +fn main() { + let mut args = std::env::args().skip(1); + let which = args.next().unwrap_or_else(|| "n1".into()); + let deals: u32 = args.next().and_then(|s| s.parse().ok()).unwrap_or(2000); + let opponent = match which.as_str() { + "n1" => Opponent::Styled(N1), + "n2" => Opponent::Styled(N2), + "n3" => Opponent::Styled(N3), + "fish" => Opponent::Reader(Style::Fish), + "reg" => Opponent::Reader(Style::Reg), + "nit" => Opponent::Reader(Style::Nit), + "maniac" => Opponent::Reader(Style::Maniac), + other => panic!("unknown opponent {other}"), + }; + let setup = Setup { players: 2, opponent, deals, stack_bb: 100.0, seed: SEED, read: ReadMode::Memory }; + let m = measure(&setup); + println!("{which} Memory {:>+8.2} bb/100 ±{:>6.2} (raw {:>+8.2} ±{:>6.2}) deals {deals}", m.bb_per_100, m.ci95, m.raw_bb_per_100, m.raw_ci95); +} diff --git a/src/engine/decide.rs b/src/engine/decide.rs index 6b356b74..5b66a5b8 100644 --- a/src/engine/decide.rs +++ b/src/engine/decide.rs @@ -92,7 +92,8 @@ fn postflop(spot: &Spot, thresholds: &Thresholds, raw: &Spot, premium: f64) -> D // the offline/value-function form, not a live fold-veto. The turn solver + per-street belief // stay as tested primitives. See BEFUND-stage-b-turn-river-solver.md. if premium <= 0.0 { - return super::river_subgame::fold_veto(raw, floored); + let after_river = super::river_subgame::fold_veto(raw, floored); + return super::turn_subgame::turn_fold_veto(raw, after_river); } floored } diff --git a/src/engine/turn_subgame.rs b/src/engine/turn_subgame.rs index ff048957..945266f4 100644 --- a/src/engine/turn_subgame.rs +++ b/src/engine/turn_subgame.rs @@ -1,596 +1,695 @@ -//! 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 = 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 = OnceLock::new(); - *ITERS.get_or_init(|| { - std::env::var("TURN_LEAF_ITERS") - .ok() - .and_then(|v| v.parse::().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 { - 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, -} - -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, usize)], // (combo, turn bucket) - villain: &[(Vec, usize)], - turn_n: usize, - p: f64, - s: f64, -) -> Option<(Vec, Vec)> { - 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, usize)]| -> Vec<(Vec, 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 = 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], villain_combos: &[Vec], p: f64, s: f64) -> Option { - let rules = spot.rules(); - let judged = |combos: &[Vec]| -> Vec<(Vec, 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 = 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, usize)> = hero.iter().map(|(c, st)| (c.clone(), tb(*st))).collect(); - let villain_b: Vec<(Vec, 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]) -> Option { - 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 { - 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 = 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], profile: Option<&Profile>) -> Option { - 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 { - 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 = 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> { - ["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) -> 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) -> 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"); - } -} +//! 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 = 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 = OnceLock::new(); + *ITERS.get_or_init(|| { + std::env::var("TURN_LEAF_ITERS") + .ok() + .and_then(|v| v.parse::().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 { + 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, + /// Bucket count. + n: usize, + /// Current-strength ladder (legacy, draw-blind bucketing) - used when `cuts` is `None`. + ladder: Vec, + /// Equity cut points (draw-aware bucketing): a hand whose river-averaged equity is `e` sits in + /// bucket `cuts.partition_point(|c| *c <= e)`. + cuts: Option>, +} + +impl TurnGame { + /// The bucket of hero's real hand: by river-averaged equity (draw-aware) or, in legacy mode, by + /// the current-strength rank. + fn hero_bucket(&self, spot: &Spot, villain: &[Vec]) -> Option { + let rules = spot.rules(); + match &self.cuts { + Some(cuts) => { + let e = equities(spot, &[spot.hero_cards.clone()], villain)[0]?; + Some(cuts.partition_point(|c| *c <= e)) + } + None => { + let st = judge(&rules, &spot.hero_cards, &spot.board).ok()?; + Some(self.ladder.partition_point(|d| *d < st).min(self.ladder.len() - 1)) + } + } + } +} + +/// Number of equity buckets for the draw-aware turn abstraction. +const EQUITY_BUCKETS: usize = 10; + +/// Measurement switch (read once): `TURN_BUCKET=strength` restores the legacy draw-blind bucketing so +/// one binary measures old vs new on the same deals. Default: draw-aware equity buckets. +fn equity_bucketing() -> bool { + use std::sync::OnceLock; + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("TURN_BUCKET").as_deref() != Ok("strength")) +} + +/// Measurement switch (read once): `TURN_PER_STREET=0` makes the turn belief read the POOLED +/// postflop aggression instead of the per-street turn aggression. +fn per_street_belief() -> bool { + use std::sync::OnceLock; + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("TURN_PER_STREET").as_deref() != Ok("0")) +} + +/// River-averaged showdown equity of each subject hand against the `opp` range on this 4-card turn +/// board: for every river card, win=1 / tie=0.5 over the card-disjoint opponent combos, averaged over +/// runouts and opponents. This is what the draw-blind current-strength ladder lacks: a flush or +/// straight draw has weak turn strength but real realisable equity, and sits where the equity says. +/// `None` for a subject that cannot be judged. +fn equities(spot: &Spot, subjects: &[Vec], opp: &[Vec]) -> Vec> { + let rules = spot.rules(); + let mut score = vec![0.0f64; subjects.len()]; + let mut count = vec![0.0f64; subjects.len()]; + for r in &deck::without_in(rules.deck, &spot.board) { + let mut board5 = spot.board.clone(); + board5.push(*r); + let ov: Vec<(&Vec, Strength)> = opp + .iter() + .filter(|c| !c.contains(r)) + .filter_map(|c| judge(&rules, c, &board5).ok().map(|st| (c, st))) + .collect(); + for (k, sc) in subjects.iter().enumerate() { + if sc.contains(r) { + continue; + } + let Ok(sst) = judge(&rules, sc, &board5) else { continue }; + for (oc, ost) in &ov { + if disjoint(sc, oc) { + score[k] += match sst.cmp(ost) { + std::cmp::Ordering::Greater => 1.0, + std::cmp::Ordering::Equal => 0.5, + std::cmp::Ordering::Less => 0.0, + }; + count[k] += 1.0; + } + } + } + } + score.iter().zip(&count).map(|(s, c)| (*c > 0.0).then(|| s / c)).collect() +} + +/// 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, usize)], // (combo, turn bucket) + villain: &[(Vec, usize)], + turn_n: usize, + p: f64, + s: f64, +) -> Option<(Vec, Vec)> { + 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, usize)]| -> Vec<(Vec, 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 = 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], villain_combos: &[Vec], p: f64, s: f64) -> Option { + let rules = spot.rules(); + let judged = |combos: &[Vec]| -> Vec<(Vec, 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 = hero.iter().chain(&villain).map(|(_, st)| *st).collect(); + ladder.sort(); + ladder.dedup(); + type Placed = Vec<(Vec, usize)>; + let (n, cuts, hero_b, villain_b): (usize, Option>, Placed, Placed) = if equity_bucketing() { + // Draw-aware: bucket by river-averaged equity vs the opposing range, equal-mass cuts over + // both ranges together (one shared ladder, as before). + let hc: Vec> = hero.iter().map(|(c, _)| c.clone()).collect(); + let vc: Vec> = villain.iter().map(|(c, _)| c.clone()).collect(); + let he = equities(spot, &hc, &vc); + let ve = if hc == vc { he.clone() } else { equities(spot, &vc, &hc) }; + let mut all: Vec = he.iter().chain(&ve).filter_map(|e| *e).collect(); + all.sort_by(|a, b| a.total_cmp(b)); + if all.len() < 2 { + return None; + } + let mut cuts: Vec = (1..EQUITY_BUCKETS).map(|i| all[i * all.len() / EQUITY_BUCKETS]).collect(); + cuts.dedup(); + let n = cuts.len() + 1; + if n < 2 { + return None; + } + let place = |src: &[(Vec, Strength)], eq: &[Option]| -> Placed { + src.iter() + .zip(eq) + .filter_map(|((c, _), e)| e.map(|e| (c.clone(), cuts.partition_point(|x| *x <= e)))) + .collect() + }; + let (hb, vb) = (place(&hero, &he), place(&villain, &ve)); + (n, Some(cuts), hb, vb) + } else { + let n = ladder.len(); + if n < 2 { + return None; + } + let tb = |st: Strength| ladder.partition_point(|d| *d < st).min(n - 1); + let hb = hero.iter().map(|(c, st)| (c.clone(), tb(*st))).collect(); + let vb = villain.iter().map(|(c, st)| (c.clone(), tb(*st))).collect(); + (n, None, hb, vb) + }; + + // 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, n, ladder, cuts }) +} + +/// 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]) -> Option { + if spot.street != Street::Turn { + return None; + } + if spot.live_villains().count() != 1 || villain_combos.is_empty() { + return None; + } + 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.hero_bucket(spot, villain_combos)?; + 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.n), + }) + } 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.hero_bucket(spot, villain_combos)?; + 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.n), + }) + } +} + +/// 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 { + 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 = 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], profile: Option<&Profile>) -> Option { + 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 (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.n; + let aggr = profile.and_then(|pr| if per_street_belief() { pr.turn_aggression.or(pr.aggression) } else { pr.aggression }); + let opponent = believed_villain(&game.tree, n, profile, p, s, aggr); + 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.hero_bucket(spot, villain_combos)?; + + 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 { + 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 = 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> { + ["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) -> 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) -> 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"); + } +}