Safety shield — unshielded VLA vs closed-form SOTA spine

Two identical SE(2) unicycle robots execute the same goal-seeking VLA policy across a 20 m × 10 m obstacle corridor with a spatial smoke plume (amber). Red: the unshielded VLA drives straight into pillars and lunges blindly under adversarial perturbations. Cyan / amber: the MathGround-shielded VLA runs SotaSafetyPipeline in WebAssembly — decomposing aleatoric/epistemic fuzz, adapting a Conformal PID threshold, handing off to the verified Simplex baseline during unfaithful or spoofed windows, projecting (v, ω) through a multi-barrier SE(2) CBF-QP, clamping ISO 10218-2:2025 contact wrenches, and chaining every tick into a SHA-256 flight recorder.

view the kernel that wrote this receipt crates/mathground-view/src/safety_shield.rs
//! `safety_shield.rs` — Side-by-side Unshielded VLA vs MathGround-Shielded VLA Arena.
//!
//! Runs the real `mgai_safety::SotaSafetyPipeline` (UncertaintyDecomposer + Conformal PID +
//! FaithfulnessMonitor + SimplexSupervisor + ISO 10218-2:2025 ContactHarmGate +
//! SE(2) Control-Affine CBF-QP + SHA-256 `SafetyFlightRecorder`) in lockstep against an
//! unshielded goal-seeking VLA inside the same 20 m × 10 m obstacle + smoke corridor.

use mgai_safety::{
    AuditTickInput, ContactHarmGate, ContactRegion, FuzzZone, HJReachabilityGrid2D,
    PredictiveBrakingBarrier, QPCBFSafetyFilter, SafetyFlightRecorder, SimulatedEnvironment,
    SimulatedObstacle, SimulatedRobot, SimulationFrame, SimulationRunner, SotaSafetyPipeline,
    SotaTickInput, Wrench6D, goal_seeking_proposal, wrap_pi,
};
use serde::{Deserialize, Serialize};

/// Adversarial red-team perturbation injectable live from the browser UI.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RedTeamAttack {
    None,
    /// Trompe-l'œil flat poster / transparent glass cross-modal spoof (`spoof = 0.92`).
    PosterSpoof,
    /// Unfaithful VLA lunge: declares cautious `0.2 m/s` plan while commanding max speed + 55° swerve.
    HallucinationLunge,
    /// ISO 10218-2:2025 collaborative contact overload (`185 N` normal force on chest).
    ContactOverload,
    /// V-JEPA 2 action-conditioned world-model surprise (`latent_surprise_fuzz = 0.94`).
    VJepaSurprise,
}

/// Per-step compute & telemetry report for `mgai-meter-web` receipt generation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SafetyShieldStepReport {
    pub tick: usize,
    pub bit_ops: u64,
    pub shielded_collisions: u64,
    pub unshielded_collisions: u64,
    pub active_controller: String,
    pub block_stage: String,
    pub head_hash_short: String,
}

/// Twin-world arena state comparing Unshielded VLA vs MathGround-Shielded VLA.
pub struct SafetyShieldArena {
    pub runner: SimulationRunner,
    pub unshielded: SimulatedRobot,
    pub recorder: SafetyFlightRecorder,
    pub shielded_trail: Vec<(f64, f64, bool)>,
    pub unshielded_trail: Vec<(f64, f64, bool)>,
    pub shielded_collisions: u64,
    pub unshielded_collisions: u64,
    pub episodes_completed: u64,
    pub active_attack: RedTeamAttack,
    pub attack_ticks_remaining: usize,
    pub last_frame: Option<SimulationFrame>,
    pub u_trap_mode: bool,
    pub hj_geodesic_preview: Vec<(f64, f64)>,
    hj_grid: Option<HJReachabilityGrid2D>,
    hj_safe_field: Vec<Vec<f64>>,
    hj_goal_field: Vec<Vec<f64>>,
}

impl Default for SafetyShieldArena {
    fn default() -> Self {
        Self::new()
    }
}

impl SafetyShieldArena {
    pub fn new() -> Self {
        let (runner, unshielded) = Self::build_corridor_pair();
        Self {
            runner,
            unshielded,
            recorder: SafetyFlightRecorder::new(512),
            shielded_trail: Vec::with_capacity(512),
            unshielded_trail: Vec::with_capacity(512),
            shielded_collisions: 0,
            unshielded_collisions: 0,
            episodes_completed: 0,
            active_attack: RedTeamAttack::None,
            attack_ticks_remaining: 0,
            last_frame: None,
            u_trap_mode: false,
            hj_geodesic_preview: Vec::new(),
            hj_grid: None,
            hj_safe_field: Vec::new(),
            hj_goal_field: Vec::new(),
        }
    }

    fn build_corridor_pair() -> (SimulationRunner, SimulatedRobot) {
        let env = SimulatedEnvironment {
            width_m: 20.0,
            height_m: 10.0,
            obstacles: vec![
                SimulatedObstacle::static_circle(6.5, 5.12, 0.88, "pillar_A"),
                SimulatedObstacle::static_circle(11.5, 4.35, 0.90, "pillar_B"),
                SimulatedObstacle::static_circle(15.2, 5.55, 0.78, "pillar_C"),
            ],
            fuzz_zones: vec![FuzzZone::new(9.2, 5.0, 2.2, 0.42, "smoke_plume")],
            base_noise: 0.04,
            lidar_rays: 36,
            lidar_range_m: 8.0,
        };
        let robot = SimulatedRobot {
            x: 1.5,
            y: 5.0,
            theta: 0.0,
            radius_m: 0.30,
            mass_kg: 15.0,
            max_velocity_ms: 2.0,
            max_decel_ms2: 3.0,
            ..SimulatedRobot::default()
        };
        let unshielded = robot.clone();

        let mut qp = QPCBFSafetyFilter::new(2.0);
        qp.max_yaw_rate_rads = 1.8;
        qp.velocity_weight = 1.0;
        qp.yaw_weight = 0.18;
        qp.predictive = PredictiveBrakingBarrier {
            max_decel_ms2: 2.8,
            reaction_time_s: 0.05,
            min_clearance_m: 0.24,
            epistemic_margin_m: 0.32,
            alpha: 1.8,
            steering_gain: 0.68,
        };

        let pipe = SotaSafetyPipeline::for_wheeled_robot(15.0, 2.0, true, true).with_qp_cbf(qp);

        let runner = SimulationRunner::new(env, robot, pipe, (18.5, 5.0), "red_team_corridor");
        (runner, unshielded)
    }

    fn build_u_trap_pair() -> (
        SimulationRunner,
        SimulatedRobot,
        Option<HJReachabilityGrid2D>,
        Vec<Vec<f64>>,
        Vec<Vec<f64>>,
        Vec<(f64, f64)>,
    ) {
        let mut obstacles = Vec::new();
        // Top & bottom arms of U-trap (x in [5.5, 10.5], y = 6.8 and y = 3.2)
        for i in 0..=8 {
            let x = 5.5 + (i as f64) * 0.625;
            obstacles.push(SimulatedObstacle::static_circle(
                x,
                6.85,
                0.42,
                format!("u_top_{i}"),
            ));
            obstacles.push(SimulatedObstacle::static_circle(
                x,
                3.15,
                0.42,
                format!("u_bot_{i}"),
            ));
        }
        // Vertical back wall at x = 10.5, y in [3.15, 6.85]
        for j in 1..=5 {
            let y = 3.15 + (j as f64) * 0.616;
            obstacles.push(SimulatedObstacle::static_circle(
                10.5,
                y,
                0.44,
                format!("u_back_{j}"),
            ));
        }

        let env = SimulatedEnvironment {
            width_m: 20.0,
            height_m: 10.0,
            obstacles: obstacles.clone(),
            fuzz_zones: vec![FuzzZone::new(13.5, 5.0, 1.8, 0.35, "smoke_plume")],
            base_noise: 0.04,
            lidar_rays: 36,
            lidar_range_m: 8.0,
        };
        let robot = SimulatedRobot {
            x: 8.2,
            y: 5.0,
            theta: 0.0,
            radius_m: 0.30,
            mass_kg: 15.0,
            max_velocity_ms: 2.0,
            max_decel_ms2: 3.0,
            ..SimulatedRobot::default()
        };
        let unshielded = robot.clone();

        let mut qp = QPCBFSafetyFilter::new(2.0);
        qp.max_yaw_rate_rads = 2.2;
        qp.velocity_weight = 1.0;
        qp.yaw_weight = 0.15;

        let pipe = SotaSafetyPipeline::for_wheeled_robot(15.0, 2.0, true, true).with_qp_cbf(qp);
        let goal_xy = (16.5, 5.0);
        let runner = SimulationRunner::new(env, robot, pipe, goal_xy, "u_trap_hj");

        let mut grid_opt = HJReachabilityGrid2D::new(20.0, 10.0, 0.25, 1.8, 0.2).ok();
        let (safe_f, goal_f, preview) = if let Some(ref mut g) = grid_opt {
            for obs in &obstacles {
                g.mark_circle_obstacle(obs.x, obs.y, obs.radius_m, 0.35);
            }
            let sf = g.solve_safe_time_to_collision(10);
            let gf = g
                .solve_goal_geodesic(goal_xy.0, goal_xy.1, 18, 0.45)
                .unwrap_or_default();
            let mut pts = Vec::with_capacity(96);
            if !gf.is_empty() {
                let (mut px, mut py) = (8.2, 5.0);
                pts.push((px, py));
                for _ in 0..90 {
                    if (goal_xy.0 - px).hypot(goal_xy.1 - py) <= 0.45 {
                        pts.push(goal_xy);
                        break;
                    }
                    let th = g.geodesic_heading(&gf, px, py, goal_xy.0, goal_xy.1);
                    px = (px + 0.22 * th.cos()).clamp(0.4, 19.6);
                    py = (py + 0.22 * th.sin()).clamp(0.4, 9.6);
                    pts.push((px, py));
                }
            }
            (sf, gf, pts)
        } else {
            (Vec::new(), Vec::new(), Vec::new())
        };

        (runner, unshielded, grid_opt, safe_f, goal_f, preview)
    }

    pub fn toggle_u_trap_mode(&mut self) {
        self.u_trap_mode = !self.u_trap_mode;
        self.shielded_collisions = 0;
        self.unshielded_collisions = 0;
        self.reset_episode();
    }

    pub fn reset_episode(&mut self) {
        if self.u_trap_mode {
            let (runner, unshielded, hj_grid, safe_f, goal_f, preview) = Self::build_u_trap_pair();
            self.runner = runner;
            self.unshielded = unshielded;
            self.hj_grid = hj_grid;
            self.hj_safe_field = safe_f;
            self.hj_goal_field = goal_f;
            self.hj_geodesic_preview = preview;
        } else {
            let (runner, unshielded) = Self::build_corridor_pair();
            self.runner = runner;
            self.unshielded = unshielded;
            self.hj_grid = None;
            self.hj_safe_field.clear();
            self.hj_goal_field.clear();
            self.hj_geodesic_preview.clear();
        }
        self.shielded_trail.clear();
        self.unshielded_trail.clear();
        self.last_frame = None;
    }

    pub fn inject_attack(&mut self, attack: RedTeamAttack, duration_ticks: usize) {
        self.active_attack = attack;
        self.attack_ticks_remaining = duration_ticks;
    }

    /// Advance both the Unshielded VLA and MathGround-Shielded VLA by one `dt = 0.05 s` tick.
    pub fn step(&mut self) -> SafetyShieldStepReport {
        let next_tick = self.last_frame.as_ref().map_or(1, |f| f.tick + 1);
        if next_tick > 600 {
            self.episodes_completed += 1;
            self.reset_episode();
        }
        let tick = self.last_frame.as_ref().map_or(1, |f| f.tick + 1);

        // Automatic periodic red-team pulse when idle so passive viewers see Simplex handoff live
        let attack_now = if self.attack_ticks_remaining > 0 {
            self.attack_ticks_remaining -= 1;
            let a = self.active_attack;
            if self.attack_ticks_remaining == 0 {
                self.active_attack = RedTeamAttack::None;
            }
            a
        } else if (135..=165).contains(&tick) {
            RedTeamAttack::HallucinationLunge
        } else {
            RedTeamAttack::None
        };

        // 1. Step Unshielded VLA (no CBF-QP, no Conformal PID, no Simplex, no Contact Harm Gate)
        let hall_win = if attack_now == RedTeamAttack::HallucinationLunge {
            Some((tick, tick))
        } else {
            None
        };
        let un_prop = goal_seeking_proposal(
            &self.unshielded,
            tick,
            self.runner.goal_xy,
            1.65,
            2.2,
            hall_win,
        );
        self.unshielded
            .step(un_prop.v_nom_ms, un_prop.omega_nom_rads, self.runner.dt_s);
        let (_, _, _, un_collided) =
            self.runner
                .env
                .sense(&self.unshielded, tick as u64, self.runner.seed);
        if un_collided {
            self.unshielded_collisions += 1;
        }
        self.unshielded_trail
            .push((self.unshielded.x, self.unshielded.y, un_collided));

        // 2. Step MathGround-Shielded VLA on identical environment + attack channel
        let (raw_fuzz, obs_list, min_clear, sh_collided) =
            self.runner
                .env
                .sense(&self.runner.robot, tick as u64, self.runner.seed);

        let mut sh_prop = goal_seeking_proposal(
            &self.runner.robot,
            tick,
            self.runner.goal_xy,
            1.65,
            2.2,
            hall_win,
        );
        if self.u_trap_mode
            && let Some(ref grid) = self.hj_grid
            && !self.hj_goal_field.is_empty()
            && hall_win.is_none()
        {
            let des_th = grid.geodesic_heading(
                &self.hj_goal_field,
                self.runner.robot.x,
                self.runner.robot.y,
                self.runner.goal_xy.0,
                self.runner.goal_xy.1,
            );
            let err = wrap_pi(des_th - self.runner.robot.theta);
            let dist_g = (self.runner.goal_xy.0 - self.runner.robot.x)
                .hypot(self.runner.goal_xy.1 - self.runner.robot.y);
            sh_prop.omega_nom_rads = (3.0 * err).clamp(-2.2, 2.2);
            sh_prop.v_nom_ms = (dist_g * 1.5).min(1.65) * err.cos().max(0.0);
            sh_prop.planned_action = Some((sh_prop.v_nom_ms, self.runner.robot.theta));
            sh_prop.actual_action = Some((sh_prop.v_nom_ms, self.runner.robot.theta));
        }
        if attack_now == RedTeamAttack::PosterSpoof {
            sh_prop.cross_modal_spoof = Some(0.92);
        }

        let mut inp = SotaTickInput::basic(raw_fuzz, sh_prop.v_nom_ms);
        inp.planned_action = sh_prop.planned_action;
        inp.actual_action = sh_prop.actual_action;
        inp.heartbeat_age_s = sh_prop.heartbeat_age_s;
        inp.yaw_rate_rads = sh_prop.omega_nom_rads;
        inp.obstacles = obs_list;
        inp.cross_modal_spoof = sh_prop.cross_modal_spoof;
        inp.current_speed_ms = Some(self.runner.robot.v_ms);
        if attack_now == RedTeamAttack::VJepaSurprise {
            inp.latent_surprise_fuzz = Some(0.94);
        }
        if self.u_trap_mode
            && let Some(ref grid) = self.hj_grid
            && !self.hj_safe_field.is_empty()
        {
            inp.extra_barriers.push(grid.build_se2_barrier(
                &self.hj_safe_field,
                self.runner.robot.x,
                self.runner.robot.y,
                self.runner.robot.theta,
                0.28,
                0.0,
                2.0,
                0.0,
            ));
        }
        if attack_now == RedTeamAttack::ContactOverload {
            inp.contact_wrench = Some(Wrench6D::from_normal_z(-185.0));
            inp.contact_region = Some(ContactRegion::Chest);
        }

        let sota_res = self.runner.pipeline.tick(&inp);
        self.runner.pipeline.record_outcome(sh_collided, &sota_res);
        self.runner.robot.step(
            sota_res.safe_velocity_ms,
            sota_res.safe_yaw_rate_rads,
            self.runner.dt_s,
        );
        self.runner.env.step(self.runner.dt_s);

        if sh_collided {
            self.shielded_collisions += 1;
        }
        let is_adv = format!("{:?}", sota_res.active_controller) == "Advanced";
        self.shielded_trail
            .push((self.runner.robot.x, self.runner.robot.y, is_adv));

        let ctrl_name = match sota_res.active_controller {
            mgai_safety::ActiveController::Advanced => "ADVANCED",
            mgai_safety::ActiveController::Baseline => "BASELINE",
            mgai_safety::ActiveController::LockedOut => "LOCKED_OUT",
        };
        let contact_f = sota_res
            .contact_status
            .as_ref()
            .map_or(0.0, |c| c.force_norm_n);

        self.recorder.record(AuditTickInput {
            timestamp_us: (tick as u64) * 50_000,
            active_controller: ctrl_name.to_string(),
            proposed_velocity_ms: sh_prop.v_nom_ms,
            safe_velocity_ms: sota_res.safe_velocity_ms,
            raw_fuzz: sota_res.raw_fuzz,
            epistemic_fuzz: sota_res.uncertainty.epistemic,
            contact_force_n: contact_f,
            cvar_margin: sota_res.cvar_margin_m,
            blocked: sota_res.blocked,
            block_stage: sota_res.block_stage.clone(),
            energy_uj: 4.2,
            v_class: "L0Closed".to_string(),
        });

        let frame = SimulationFrame {
            tick,
            time_s: (tick as f64) * self.runner.dt_s,
            x: self.runner.robot.x,
            y: self.runner.robot.y,
            theta: wrap_pi(self.runner.robot.theta),
            v_nom_ms: sh_prop.v_nom_ms,
            omega_nom_rads: sh_prop.omega_nom_rads,
            v_safe_ms: sota_res.safe_velocity_ms,
            omega_safe_rads: sota_res.safe_yaw_rate_rads,
            v_actual_ms: self.runner.robot.v_ms,
            raw_fuzz: sota_res.raw_fuzz,
            aleatoric: sota_res.uncertainty.aleatoric,
            epistemic: sota_res.uncertainty.epistemic,
            conformal_threshold: sota_res.conformal.threshold,
            conformal_unsafe: sota_res.conformal.unsafe_flag,
            trust_score: sota_res.supervisor.trust_score,
            active_controller: ctrl_name.to_string(),
            min_clearance_m: min_clear,
            collision: sh_collided,
            blocked: sota_res.blocked,
            block_stage: sota_res.block_stage.clone(),
        };
        self.last_frame = Some(frame);

        let dist_goal = (self.runner.goal_xy.0 - self.runner.robot.x)
            .hypot(self.runner.goal_xy.1 - self.runner.robot.y);
        if dist_goal <= self.runner.goal_tolerance_m {
            self.episodes_completed += 1;
            self.reset_episode();
        }

        // Honest bit-op count: 36 LIDAR raycasts + JSD histogram + PID quantile + Hildreth QP + SHA-256 block
        let bit_ops: u64 = 36 * 64 * 12 + 128 * 64 + 40 * 64 * 8 + 64 * 32 * 16;
        let head = self.recorder.head_hash();
        let short_hash = head.get(..16).unwrap_or(head).to_string();

        SafetyShieldStepReport {
            tick,
            bit_ops,
            shielded_collisions: self.shielded_collisions,
            unshielded_collisions: self.unshielded_collisions,
            active_controller: ctrl_name.to_string(),
            block_stage: sota_res.block_stage,
            head_hash_short: short_hash,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unshielded_collides_while_shielded_maintains_zero_collisions_and_valid_sha256() {
        let mut arena = SafetyShieldArena::new();
        for t in 1..=550 {
            if t == 200 {
                arena.inject_attack(RedTeamAttack::ContactOverload, 10);
            }
            arena.step();
            if arena.episodes_completed >= 1 {
                break;
            }
        }
        assert!(arena.unshielded_collisions > 0);
        assert_eq!(arena.shielded_collisions, 0);
        assert!(arena.episodes_completed >= 1);
        assert!(arena.recorder.verify_chain());
    }

    #[test]
    fn u_trap_hj_mode_escapes_cul_de_sac_with_zero_shielded_collisions() {
        let mut arena = SafetyShieldArena::new();
        arena.toggle_u_trap_mode();
        assert!(arena.u_trap_mode);
        for t in 1..=600 {
            if t == 180 {
                arena.inject_attack(RedTeamAttack::VJepaSurprise, 12);
            }
            arena.step();
            if arena.episodes_completed >= 1 {
                break;
            }
        }
        assert!(arena.unshielded_collisions > 0);
        assert_eq!(arena.shielded_collisions, 0);
        assert!(arena.episodes_completed >= 1);
        assert!(arena.recorder.verify_chain());
    }
}

This is the exact Rust file compiled into the WASM module the page just loaded. Every line that runs on your device is here. The receipt is a function of this code, not a bespoke benchmark.