Build a Rail-Crossing Safety Sandbox

Use Claude vision and Python to simulate rail-crossing safety decisions.

Introduction

30 Second Summary

A rail crossing can look calm until its warning lights flash or its gate starts moving. Once a vehicle enters the crossing, the same warning can demand a very different response.

In this project, you will build a local educational sandbox that keeps uncertain multimodal perception separate from deterministic planning. It uses one permitted crossing image to create a typed observation before comparing two planners across five repeatable scenarios.

What You'll Build

Your finished sandbox turns five replay scenarios into a visual report where you can trace each planner across the gate, tracks, and clearance boundary.

By the end of this project, you'll have:

  • A typed perception result from the Claude API that converts one permitted JPEG or PNG into observations about warning lights, gate state, train visibility, vehicle position, downstream clearance, and confidence.
  • Five deterministic replays that let you rerun late activation, traffic blockage, low-confidence weather, and two labelled reconstruction patterns without paying for another image request.
  • A side-by-side safety report that reveals the naive planner's protected-zone stop. Its Markdown, HTML, and SVG views let you compare both scores and trajectories.
  • Secret Mission: A speed-by-deceleration sweep that shows where the planner switches between STOP and CLEAR.

Are there any prerequisites?

You need Python 3.10+ and Visual Studio Code

You also need a Claude Console account to generate a Claude API key.

Before We Start

Before any hands-on work, lock in the purpose and safety boundary of your sandbox. You are building an educational offline simulation that compares two planners while keeping Claude image perception separate from deterministic planning and disconnected from real vehicle hardware.

Set Up the Sandbox and Claude API

The deterministic simulator needs a reproducible Python workspace. A virtual environment keeps this sandbox's packages separate from the rest of your machine.

The live Claude API call also needs a credential. You will store that key in a local .env file that stays out of source control.

In this step, get ready to:
  • Prepare an isolated Python environment inside the local project folder.
  • Install the pinned dependencies from requirements.txt.
  • Store the Claude API key in an ignored .env file.
Prepare the Local Workspace

Visual Studio Code keeps the sandbox files beside the terminal that runs them. Before you isolate the project, confirm that the terminal can use Python 3.10 or higher.

  • Press Cmd+Space on macOS or the Windows key on Windows to open your search bar.
  • Type Visual Studio Code into the search bar.
  • Press Enter to open Visual Studio Code.
  • Create a folder named rail-crossing-sandbox on your Desktop, then use the folder-opening control on the welcome screen to open it.

You should see the selected folder at the top of the file sidebar. This confirms that new files and commands will stay inside the sandbox.

  • Use the terminal control in Visual Studio Code to start a terminal inside the selected folder.

macOS

  • Check the Python version available to this terminal by running this command:
python3 --version

You'll see the word Python followed by its version number.

Windows

  • Check the Python version available to this terminal by running this command:
py --version

You'll see the word Python followed by its version number.

  • Compare the first two numbers in the version output with 3.10.
  • Choose the tab below that matches your result.

✔️ I see version 3.10 or higher

You're set. The terminal can create the project environment with Python 3.10 or higher.

ⓧ I see an older version

This version is below the project's minimum, so update Python before creating the virtual environment.

  • Open the official Python releases page for macOS or Windows.
  • Download the installer for a current supported Python release.
  • Run the downloaded installer.
  • Close the current integrated terminal in Visual Studio Code.
  • Start a new integrated terminal inside the selected project folder.

macOS

  • Verify the updated Python version by running this command:
python3 --version

You should now see Python 3.10 or higher.

Windows

  • Verify the updated Python version by running this command:
py --version

You should now see Python 3.10 or higher.

Still Seeing the Older Version?

Your terminal may still point to the previous Python installation. Help me switch to the newer Python version.

ⓧ Command not found

Python is either not installed or its command is unavailable in the current terminal.

  • Open the official Python releases page for macOS or Windows.
  • Download the installer for a current supported Python release.
  • Run the downloaded installer.
  • Close the current integrated terminal in Visual Studio Code.
  • Start a new integrated terminal inside the selected project folder.

macOS

  • Confirm that Python is now available by running this command:
python3 --version

You should now see Python 3.10 or higher.

Windows

  • Confirm that Python is now available by running this command:
py --version

You should now see Python 3.10 or higher.

Command Still Missing?

The installer may not have registered its terminal command yet. Help me make Python available in my terminal.

macOS

  • Create the isolated environment on macOS by running this command:
python3 -m venv .venv

Windows

  • Create the isolated environment in PowerShell by running this command:
py -m venv .venv

You should see .venv appear in the Visual Studio Code file sidebar.

What Does This Command Do?

The venv module creates an isolated Python environment at .venv. Packages installed while it is active stay inside this sandbox.

macOS

  • Activate the environment in your macOS terminal by running this command:
source .venv/bin/activate

Windows

  • Activate the environment in PowerShell by running this command:
.\.venv\Scripts\Activate.ps1

You should see (.venv) at the start of the terminal prompt. That prompt confirms the isolated environment is active.

What Does Activation Change?

Activation points the current terminal at the Python interpreter inside .venv. The packages you install next become local to this project.

Your terminal prompt now identifies the virtual environment. That prompt is your signal that the sandbox has its own Python workspace.

Environment Did Not Activate?

  • Confirm the terminal is inside the local project folder.
  • Check that .venv appears in the file sidebar.

If Windows says that running scripts is disabled, PowerShell is blocking Activate.ps1. This next command changes the policy for your Windows account only.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Retry .\.venv\Scripts\Activate.ps1. If activation still fails, help me activate the Python virtual environment in PowerShell.

Pin the Sandbox Dependencies

The sandbox uses the Anthropic Python SDK at 2.10.0 and Pydantic at 2.14.3. It uses python-dotenv at 1.2.4 to load the local credential.

  • Use the file-creation control in the file sidebar to create requirements.txt inside the selected project folder.
  • Paste these pinned dependencies into requirements.txt:
anthropic==2.10.0
pydantic==2.14.3
python-dotenv==1.2.4

Why Pin Exact Versions?

Each == entry fixes a package to one tested version. Everyone following the project gets the same dependency behavior.

  • Save requirements.txt by pressing Cmd+S on macOS or Ctrl+S on Windows.
  • Confirm that the saved file contains exactly three dependency lines.
  • Install the pinned project dependencies from the saved file by running this command:
python -m pip install -r requirements.txt

What Does This Command Do?

  • The python -m pip portion runs the package installer from the active virtual environment.
  • The -r requirements.txt portion installs every pinned package listed in the file.

The terminal downloads the dependencies before returning to the prompt. Your isolated environment now contains the SDK, typed-model library, and local environment loader.

Dependencies Did Not Install?

  • Confirm that the terminal prompt still identifies the .venv environment.
  • Check that requirements.txt is saved inside the folder selected in Visual Studio Code.
  • Retry the installation after your network connection is stable.

Need another pair of eyes? Help me debug the dependency installation.

Store the Claude API credential

The ANTHROPIC_API_KEY environment variable gives the SDK access to your Claude Console credential. A local .env file lets the Python process load that value without placing it in source code.

The .env file sits beside requirements.txt. The matching .gitignore rule prevents Git from tracking the credential.

  • Open the Claude Console API keys page in your browser.
  • Sign in with your Claude Console account if prompted.
  • Select Create key.
  • Enter rail-crossing-sandbox as the key name.
  • Set an expiration date that covers the time you plan to keep using the sandbox.
  • Choose your personal account under Linked account.
  • Limit the key to the workspace you use for this sandbox.
  • Submit the form to create the scoped key.

Keep the Key Private

A live API key is a credential. Keep .env out of screenshots, commits, and shared project copies.

  • Copy the new API key to your clipboard.
  • Click the New File icon in the Visual Studio Code Explorer sidebar.
  • Enter .gitignore as the filename.
  • Add the credential-file rule by pasting this line into .gitignore:
.env

Why Ignore the .env File?

Git checks .gitignore before tracking files. The .env rule keeps the credential local when you commit or share the project.

  • Save .gitignore.
  • Confirm .gitignore contains the .env rule.
  • Click the New File icon in the Explorer sidebar.
  • Enter .env as the filename.
  • Add the credential template by pasting this line into .env:
ANTHROPIC_API_KEY=your-api-key-here
  • Replace your-api-key-here with the key on your clipboard.
  • Save .env.
  • Confirm .env and .gitignore appear in the Explorer sidebar.
  • Verify all three dependencies and load the credential without printing it by running this command:
python -c "import os; from anthropic import Anthropic; from pydantic import BaseModel; from dotenv import load_dotenv; load_dotenv(); print('setup-ready' if os.getenv('ANTHROPIC_API_KEY') else 'key-missing')"

What Does This Check Prove?

  • Importing Anthropic proves that the pinned Anthropic SDK is available.
  • Importing BaseModel proves that the pinned Pydantic package is available.
  • Calling load_dotenv() proves that the local environment loader is available.
  • Printing setup-ready confirms that the process found a non-empty key without revealing it.

You should see setup-ready in the terminal. That result confirms the isolated sandbox can load its dependencies and local credential.

Setup Check Did Not Pass?

  • Confirm that the current terminal still uses the .venv environment.
  • Check that .env is saved beside requirements.txt.
  • Check that the key line begins with ANTHROPIC_API_KEY= and contains no spaces before the name.

Still blocked? Help me diagnose why the setup-ready check is failing.

Your reproducible environment is ready for deterministic simulation. Next up, you will model five crossing scenarios and expose where the naive warning rule fails.

Make the Naive Rule Fail

Your Python environment is ready. You can now build a deterministic replay that gives both planners the same events every time.

A direct-warning rule can brake too late, and this step proves it by stopping the simulated vehicle inside the protected crossing area. The scripted replays stay offline, so your Claude API key stays unused.

In this step, get ready to:
  • Model the crossing state with typed Python objects.
  • Script five deterministic rail-crossing scenarios.
  • Run the naive rule through the simulator.
Model the crossing world

The simulator needs one shared vocabulary for observations, actions, scenarios, and results. The Pydantic perception model also becomes the typed contract used by the image adapter in the next step.

  • In the Visual Studio Code file sidebar, select the new-file control.
  • Enter models.py as the filename.

You should see models.py beside requirements.txt in the file sidebar.

  • Define the gate states, vehicle zones, and planner actions by pasting this first block into models.py:
from dataclasses import dataclass
from enum import Enum
from pydantic import BaseModel


class GateState(str, Enum):
    UP = "up"
    MOVING = "moving"
    DOWN = "down"
    UNKNOWN = "unknown"


class VehicleZone(str, Enum):
    BEFORE_GATE = "before_gate"
    TRAP_ZONE = "between_gate_and_tracks"
    ON_TRACKS = "on_tracks"
    EXIT_ZONE = "past_tracks_not_clear"
    CLEAR = "clear"
    UNKNOWN = "unknown"


class Action(str, Enum):
    PROCEED = "proceed"
    BRAKE_TO_STOP = "brake_to_stop"
    HOLD = "hold"
    CLEAR_TRACKS = "clear_tracks"

What do these enums represent?

  • GateState limits the crossing gate to four explicit observations.
  • VehicleZone identifies where the simulated vehicle sits relative to the gate and tracks.
  • Action gives each planner the same four possible decisions.
  • Save models.py.
  • Confirm the editor now shows the three enum classes without red syntax markers.
  • Add the typed perception contract and replay event by pasting this below Action:
class Perception(BaseModel):
    lights_flashing: bool
    gate_state: GateState
    train_visible: bool
    vehicle_zone: VehicleZone
    clearance_beyond_tracks: bool
    confidence: float
    short_reason: str


@dataclass(frozen=True)
class ReplayEvent:
    lights_flashing: bool
    gate_state: GateState
    train_visible: bool
    actual_train_on_crossing: bool
    clearance_beyond_tracks: bool
    confidence: float

Why separate perception from replay events?

Perception contains the observations a planner receives. ReplayEvent also carries the hidden ground truth used to score that planner.

This separation prevents the planner from reading facts that its simulated perception never observed.

  • Save models.py.
  • Confirm the editor now shows all seven Perception fields.
  • Complete the result models by pasting this below ReplayEvent:
@dataclass(frozen=True)
class Scenario:
    slug: str
    name: str
    provenance: str
    initial_x_m: float
    initial_speed_mps: float
    deceleration_mps2: float
    events: list[ReplayEvent]


@dataclass(frozen=True)
class TimelinePoint:
    step: int
    x_m: float
    speed_mps: float
    zone: VehicleZone
    action: Action
    penalty: int
    penalty_reasons: list[str]


@dataclass(frozen=True)
class RunResult:
    scenario: Scenario
    planner_name: str
    points: list[TimelinePoint]
    score: int

How do the result models fit together?

  • Scenario packages the starting conditions and ordered replay events.
  • TimelinePoint records one simulated position, action, and penalty check.
  • RunResult combines the complete timeline with its final score.
  • Save models.py.
  • Confirm the file ends with the RunResult class.

Seeing model errors?

Check that every class begins at the far-left edge. Keep each field indented beneath its class.

If a type name is underlined, confirm GateState and VehicleZone match the enum names exactly.

Need another pair of eyes? Help me check the structure of models.py.

Script the five scenarios

A deterministic scenario is a fixed sequence of observations and hidden ground truth. Reusing those events makes planner comparisons reproducible.

Two fixtures reconstruct reported incidents: local news showed driverless cars in Austin stopping between the crossing gates and the tracks, and the San Diego case is hypothetical. Their numbers are educational assumptions, not incident measurements.

  • In the Visual Studio Code file sidebar, select the new-file control.
  • Enter scenarios.py as the filename.

The scenario catalog is one Python list. The first block opens it, and the fifth block closes it.

  • Start the catalog with the late gate activation fixture by pasting this into scenarios.py:
from models import GateState, ReplayEvent, Scenario


def e(lights, gate, visible, actual, clearance, confidence):
    return ReplayEvent(lights, gate, visible, actual, clearance, confidence)


SCENARIOS = [
    Scenario(
        "late-gate-drop",
        "Late gate activation",
        "Synthetic scenario with educational geometry and dynamics.",
        -18.0,
        8.0,
        3.0,
        [
            e(False, GateState.UP, False, False, True, 0.98),
            e(True, GateState.MOVING, True, False, True, 0.98),
            e(True, GateState.DOWN, True, True, True, 0.98),
            e(True, GateState.DOWN, True, True, True, 0.98),
            e(False, GateState.MOVING, False, False, True, 0.98),
            e(False, GateState.UP, False, False, True, 0.98),
        ],
    ),

What does the first fixture test?

The vehicle starts before the gate with forward speed. The warnings activate after the first event, which tests whether braking begins too late.

The positions and dynamics are educational assumptions for this simulator.

  • Confirm the first scenario slug is late-gate-drop.
  • Add the blocked-clearance fixture below the first scenario:
    Scenario(
        "backed-up-traffic",
        "Backed-up traffic beyond the tracks",
        "Synthetic scenario designed to test downstream-clearance checks.",
        -6.0,
        2.0,
        3.0,
        [
            e(False, GateState.UP, False, False, False, 0.95),
            e(False, GateState.UP, False, False, False, 0.95),
            e(False, GateState.UP, False, False, False, 0.95),
            e(True, GateState.MOVING, True, False, False, 0.95),
            e(True, GateState.DOWN, True, True, False, 0.95),
            e(True, GateState.DOWN, True, True, False, 0.95),
        ],
    ),

What does blocked clearance test?

Every event reports that the space beyond the tracks is unavailable. A planner that watches only the warning equipment can still enter the crossing.

  • Confirm the second scenario keeps clearance false in every event.
  • Add the low-confidence weather fixture below the second scenario:
    Scenario(
        "low-confidence-rain-night",
        "Low-confidence rain and night",
        "Synthetic uncertainty scenario with reduced available deceleration.",
        -15.0,
        5.0,
        2.0,
        [
            e(False, GateState.UNKNOWN, False, False, True, 0.35),
            e(False, GateState.UNKNOWN, False, False, True, 0.35),
            e(False, GateState.UNKNOWN, False, True, True, 0.30),
            e(False, GateState.UNKNOWN, False, True, True, 0.30),
            e(False, GateState.UNKNOWN, False, True, True, 0.30),
            e(False, GateState.UNKNOWN, False, False, True, 0.40),
        ],
    ),

What does uncertainty change?

The gate stays unknown while confidence remains low. The lower deceleration value models reduced available braking as a project assumption.

  • Confirm the third scenario uses 2.0 for available deceleration.
  • Add the Austin media-inspired fixture below the weather scenario:
    Scenario(
        "austin-media-inspired",
        "Austin media-inspired late braking",
        (
            "Qualitative reconstruction inspired by local news reports. "
            "All numeric parameters are educational assumptions, not incident measurements. "
            "Sources: https://foxsanantonio.com/news/local/waymo-driverless-cars-stop-between-railroad-and-crossing-gates "
            "and https://www.kvue.com/article/news/local/waymo-railroad-crossing-video-austin/269-373ef3bc-1571-4a33-965f-e1310de33bba"
        ),
        -12.0,
        10.0,
        3.0,
        [
            e(True, GateState.MOVING, True, False, True, 0.98),
            e(True, GateState.DOWN, True, True, True, 0.98),
            e(True, GateState.DOWN, True, True, True, 0.98),
            e(True, GateState.DOWN, True, True, True, 0.98),
            e(False, GateState.MOVING, False, False, True, 0.98),
            e(False, GateState.UP, False, False, True, 0.98),
        ],
    ),

Why include a provenance label?

The label separates qualitative inspiration from measured facts. Every numeric value remains an educational simulator choice.

  • Confirm the Austin provenance text labels its numbers as educational assumptions.
  • Finish the catalog with the hypothetical San Diego fixture:
    Scenario(
        "san-diego-hypothetical",
        "San Diego hypothetical trapped-on-tracks escape",
        (
            "Hypothetical reconstruction. It makes no factual claim "
            "about any real event."
        ),
        5.0,
        0.0,
        3.0,
        [
            e(True, GateState.DOWN, True, True, True, 0.90),
            e(True, GateState.DOWN, True, True, True, 0.90),
            e(True, GateState.DOWN, True, True, True, 0.90),
            e(True, GateState.DOWN, True, True, True, 0.90),
            e(False, GateState.MOVING, False, False, True, 0.95),
            e(False, GateState.UP, False, False, True, 0.95),
        ],
    ),
]

What does the final fixture represent?

The vehicle begins on the tracks with no initial speed. Its provenance states that the reconstruction is hypothetical.

The closing bracket also completes the shared SCENARIOS list.

  • Save scenarios.py.
  • Confirm the file contains the five distinct scenario slugs.
  • Check that the models and scenarios load by running:
python -c "import scenarios; print(len(scenarios.SCENARIOS))"

You should see 5.

Seeing an unfinished list?

Check that each Scenario entry ends with a comma. Confirm the final line contains the closing bracket.

Need help finding a missing bracket? Help me check the SCENARIOS list.

Replay the baseline

The baseline reacts only to flashing lights, a moving or down gate, or a visible train. It does not use confidence or downstream clearance.

The simulator applies the same one-dimensional motion rules to every scenario. Its penalty weights are labelled project choices for comparing policies.

  • In the Visual Studio Code file sidebar, select the new-file control.
  • Enter planners.py as the filename.
  • Paste the baseline planner into planners.py:
from models import Action, GateState, Perception, VehicleZone


def naive_warning_rule(perception, x_m, speed_mps, deceleration_mps2):
    del x_m, speed_mps, deceleration_mps2
    direct_warning = (
        perception.lights_flashing
        or perception.gate_state in {GateState.MOVING, GateState.DOWN}
        or perception.train_visible
    )
    return Action.BRAKE_TO_STOP if direct_warning else Action.PROCEED

What does the baseline decide?

naive_warning_rule() deliberately discards position, speed, and deceleration. It brakes only when a direct warning is visible.

  • Save planners.py.
  • Confirm the file ends with the return from naive_warning_rule().

Planner names underlined?

Confirm models.py is saved in the same project folder. Check every imported class name against that file.

Need help with the imports? Help me trace the planner model imports.

  • In the Visual Studio Code file sidebar, select the new-file control.
  • Enter simulator.py as the filename.
  • Define the timeline settings and crossing zones by pasting this into simulator.py:
from collections.abc import Callable
from models import Action, Perception, RunResult, Scenario, TimelinePoint, VehicleZone

Planner = Callable[[Perception, float, float, float], Action]
TIME_STEP_S = 1.0
ESCAPE_SPEED_MPS = 12.0


def zone_for(x_m):
    if x_m < 0.0:
        return VehicleZone.BEFORE_GATE
    if x_m < 4.0:
        return VehicleZone.TRAP_ZONE
    if x_m < 10.0:
        return VehicleZone.ON_TRACKS
    if x_m < 14.0:
        return VehicleZone.EXIT_ZONE
    return VehicleZone.CLEAR

How is crossing position represented?

zone_for() maps a one-dimensional position to a named crossing zone. Negative positions remain before the gate.

The gate, rails, and clearance boundaries are educational geometry for this sandbox.

  • Save simulator.py.
  • Confirm the zone order runs from BEFORE_GATE to CLEAR.
  • Add deterministic motion by pasting this below zone_for():
def advance(x_m, speed_mps, action, deceleration_mps2):
    if action == Action.HOLD:
        return x_m, 0.0
    if action == Action.CLEAR_TRACKS:
        new_speed = max(speed_mps, ESCAPE_SPEED_MPS)
        return x_m + new_speed * TIME_STEP_S, new_speed
    if action == Action.BRAKE_TO_STOP:
        new_speed = max(0.0, speed_mps - deceleration_mps2 * TIME_STEP_S)
        return x_m + (speed_mps + new_speed) / 2 * TIME_STEP_S, new_speed
    return x_m + speed_mps * TIME_STEP_S, speed_mps

How does motion advance?

advance() applies a fixed one-second step. Each action selects a deterministic position and speed update.

The escape speed is a simulator parameter. It is not a recommendation for real-world driving.

  • Save simulator.py.
  • Confirm the function handles all four action outcomes.
  • Add the three scoring penalties below advance():
def penalties(x_m, speed_mps, zone, action, event):
    total, reasons = 0, []
    if event.actual_train_on_crossing and zone == VehicleZone.ON_TRACKS:
        total += 100
        reasons.append("occupied tracks while train is present")
    if speed_mps <= 0.1 and zone in {VehicleZone.TRAP_ZONE, VehicleZone.ON_TRACKS}:
        total += 60
        reasons.append("stopped in protected zone")
    if not event.clearance_beyond_tracks and x_m >= 0.0 and zone != VehicleZone.CLEAR and action != Action.CLEAR_TRACKS:
        total += 40
        reasons.append("entered without downstream clearance")
    return total, reasons

What do the penalties measure?

penalties() checks track occupancy, protected-zone stops, and entry without downstream clearance. Each reason is stored beside its project-defined weight.

These weights compare the two sandbox policies. They are not regulatory or manufacturer thresholds.

  • Save simulator.py.
  • Confirm the protected-zone reason reads stopped in protected zone.
  • Complete the replay loop by pasting this below penalties():
def simulate(scenario: Scenario, planner_name: str, planner: Planner):
    x_m, speed_mps = scenario.initial_x_m, scenario.initial_speed_mps
    points, total_penalty = [], 0
    for step, event in enumerate(scenario.events):
        perception = Perception(
            lights_flashing=event.lights_flashing,
            gate_state=event.gate_state,
            train_visible=event.train_visible,
            vehicle_zone=zone_for(x_m),
            clearance_beyond_tracks=event.clearance_beyond_tracks,
            confidence=event.confidence,
            short_reason="Deterministic replay fixture",
        )
        action = planner(perception, x_m, speed_mps, scenario.deceleration_mps2)
        x_m, speed_mps = advance(x_m, speed_mps, action, scenario.deceleration_mps2)
        zone = zone_for(x_m)
        penalty, reasons = penalties(x_m, speed_mps, zone, action, event)
        total_penalty += penalty
        points.append(TimelinePoint(step, x_m, speed_mps, zone, action, penalty, reasons))
    return RunResult(scenario, planner_name, points, max(0, 100 - total_penalty))

How does one replay run?

simulate() turns each scripted event into a Perception object. The selected planner sees only that typed object plus the current motion state.

Each action advances the vehicle before penalties are evaluated. The final score cannot fall below zero.

  • Save simulator.py.
  • Confirm the file ends by returning a RunResult.
  • Check that the planner and simulator load by running:
python -c "import planners, simulator; print('simulator-ready')"

You should see simulator-ready.

Simulator types not resolving?

Confirm models.py is saved. Check that TimelinePoint and RunResult use the same capitalization in both files.

Need help tracing a simulator name? Help me compare simulator.py with models.py.

  • In the Visual Studio Code file sidebar, select the new-file control.
  • Enter run_sandbox.py as the filename.
  • Create the baseline runner by pasting this into run_sandbox.py:
import argparse
from planners import naive_warning_rule
from scenarios import SCENARIOS
from simulator import simulate

NAIVE_NAME = "Naive warning rule"


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--baseline-only", action="store_true")
    args = parser.parse_args()
    planners = [(NAIVE_NAME, naive_warning_rule)]

    results = []
    print(f"{'Scenario':42} | {'Planner':22} | Score | Penalties")
    print("-" * 100)
    for scenario in SCENARIOS:
        for planner_name, planner in planners:
            result = simulate(scenario, planner_name, planner)
            results.append(result)
            found = sorted({r for p in result.points for r in p.penalty_reasons})
            print(f"{scenario.name:42} | {planner_name:22} | {result.score:5} | {', '.join(found) if found else 'none'}")


if __name__ == "__main__":
    main()

What does the runner print?

run_sandbox.py sends each scenario through naive_warning_rule(). It prints the scenario name, planner name, score, and unique penalty reasons.

The --baseline-only option keeps this run focused on the naive policy.

  • Save run_sandbox.py.
  • Confirm the file sidebar now lists all five new Python files.

Runner imports failing?

Confirm all five Python files sit beside requirements.txt in the same folder. Check that none of their names contain spaces.

Need help tracing an import? Help me find the missing project module.

Before you run the replay, consider whether every scenario keeps a perfect score.

  • Run the baseline across all five scenarios with this command:
python run_sandbox.py --baseline-only

What should the replay reveal?

You should see a table with five scenario rows. Every row scores 0, and at least one includes the stopped in protected zone penalty.

That shortfall is intentional. The baseline reacts to the warning after it has already committed too far to stop safely.

You have the evidence the project needs. The naive rule now fails visibly under deterministic replay.

Baseline did not run?

Read the first file name mentioned by the terminal. Compare that file with the complete-code reference below.

If the table appears without the protected-zone penalty, check the late gate scenario events and the braking branch in advance().

Still stuck? Help me debug the baseline replay.

✔️ Awesome, I've got everything!

Great. Save every new Python file, and keep the output that shows the stopped in protected zone penalty.

ⓧ I'd like to double check the full code

Compare each file with the complete baseline code below. Keep the filenames beside each reference block.

from dataclasses import dataclass
from enum import Enum
from pydantic import BaseModel


class GateState(str, Enum):
    UP = "up"
    MOVING = "moving"
    DOWN = "down"
    UNKNOWN = "unknown"


class VehicleZone(str, Enum):
    BEFORE_GATE = "before_gate"
    TRAP_ZONE = "between_gate_and_tracks"
    ON_TRACKS = "on_tracks"
    EXIT_ZONE = "past_tracks_not_clear"
    CLEAR = "clear"
    UNKNOWN = "unknown"


class Action(str, Enum):
    PROCEED = "proceed"
    BRAKE_TO_STOP = "brake_to_stop"
    HOLD = "hold"
    CLEAR_TRACKS = "clear_tracks"


class Perception(BaseModel):
    lights_flashing: bool
    gate_state: GateState
    train_visible: bool
    vehicle_zone: VehicleZone
    clearance_beyond_tracks: bool
    confidence: float
    short_reason: str


@dataclass(frozen=True)
class ReplayEvent:
    lights_flashing: bool
    gate_state: GateState
    train_visible: bool
    actual_train_on_crossing: bool
    clearance_beyond_tracks: bool
    confidence: float


@dataclass(frozen=True)
class Scenario:
    slug: str
    name: str
    provenance: str
    initial_x_m: float
    initial_speed_mps: float
    deceleration_mps2: float
    events: list[ReplayEvent]


@dataclass(frozen=True)
class TimelinePoint:
    step: int
    x_m: float
    speed_mps: float
    zone: VehicleZone
    action: Action
    penalty: int
    penalty_reasons: list[str]


@dataclass(frozen=True)
class RunResult:
    scenario: Scenario
    planner_name: str
    points: list[TimelinePoint]
    score: int

What belongs in models.py?

This file holds every shared enum, perception field, replay fixture type, timeline point, and run result used by the baseline.

from models import GateState, ReplayEvent, Scenario


def e(lights, gate, visible, actual, clearance, confidence):
    return ReplayEvent(lights, gate, visible, actual, clearance, confidence)


SCENARIOS = [
    Scenario(
        "late-gate-drop",
        "Late gate activation",
        "Synthetic scenario with educational geometry and dynamics.",
        -18.0,
        8.0,
        3.0,
        [
            e(False, GateState.UP, False, False, True, 0.98),
            e(True, GateState.MOVING, True, False, True, 0.98),
            e(True, GateState.DOWN, True, True, True, 0.98),
            e(True, GateState.DOWN, True, True, True, 0.98),
            e(False, GateState.MOVING, False, False, True, 0.98),
            e(False, GateState.UP, False, False, True, 0.98),
        ],
    ),
    Scenario(
        "backed-up-traffic",
        "Backed-up traffic beyond the tracks",
        "Synthetic scenario designed to test downstream-clearance checks.",
        -6.0,
        2.0,
        3.0,
        [
            e(False, GateState.UP, False, False, False, 0.95),
            e(False, GateState.UP, False, False, False, 0.95),
            e(False, GateState.UP, False, False, False, 0.95),
            e(True, GateState.MOVING, True, False, False, 0.95),
            e(True, GateState.DOWN, True, True, False, 0.95),
            e(True, GateState.DOWN, True, True, False, 0.95),
        ],
    ),
    Scenario(
        "low-confidence-rain-night",
        "Low-confidence rain and night",
        "Synthetic uncertainty scenario with reduced available deceleration.",
        -15.0,
        5.0,
        2.0,
        [
            e(False, GateState.UNKNOWN, False, False, True, 0.35),
            e(False, GateState.UNKNOWN, False, False, True, 0.35),
            e(False, GateState.UNKNOWN, False, True, True, 0.30),
            e(False, GateState.UNKNOWN, False, True, True, 0.30),
            e(False, GateState.UNKNOWN, False, True, True, 0.30),
            e(False, GateState.UNKNOWN, False, False, True, 0.40),
        ],
    ),
    Scenario(
        "austin-media-inspired",
        "Austin media-inspired late braking",
        (
            "Qualitative reconstruction inspired by local news reports. "
            "All numeric parameters are educational assumptions, not incident measurements. "
            "Sources: https://foxsanantonio.com/news/local/waymo-driverless-cars-stop-between-railroad-and-crossing-gates "
            "and https://www.kvue.com/article/news/local/waymo-railroad-crossing-video-austin/269-373ef3bc-1571-4a33-965f-e1310de33bba"
        ),
        -12.0,
        10.0,
        3.0,
        [
            e(True, GateState.MOVING, True, False, True, 0.98),
            e(True, GateState.DOWN, True, True, True, 0.98),
            e(True, GateState.DOWN, True, True, True, 0.98),
            e(True, GateState.DOWN, True, True, True, 0.98),
            e(False, GateState.MOVING, False, False, True, 0.98),
            e(False, GateState.UP, False, False, True, 0.98),
        ],
    ),
    Scenario(
        "san-diego-hypothetical",
        "San Diego hypothetical trapped-on-tracks escape",
        (
            "Hypothetical reconstruction. It makes no factual claim "
            "about any real event."
        ),
        5.0,
        0.0,
        3.0,
        [
            e(True, GateState.DOWN, True, True, True, 0.90),
            e(True, GateState.DOWN, True, True, True, 0.90),
            e(True, GateState.DOWN, True, True, True, 0.90),
            e(True, GateState.DOWN, True, True, True, 0.90),
            e(False, GateState.MOVING, False, False, True, 0.95),
            e(False, GateState.UP, False, False, True, 0.95),
        ],
    ),
]

What belongs in scenarios.py?

This file holds five ordered replay fixtures. Each one includes educational parameters, event data, and a provenance label.

from models import Action, GateState, Perception, VehicleZone


def naive_warning_rule(perception, x_m, speed_mps, deceleration_mps2):
    del x_m, speed_mps, deceleration_mps2
    direct_warning = (
        perception.lights_flashing
        or perception.gate_state in {GateState.MOVING, GateState.DOWN}
        or perception.train_visible
    )
    return Action.BRAKE_TO_STOP if direct_warning else Action.PROCEED

What belongs in planners.py?

This baseline file contains the naive direct-warning rule. Step 4 adds the stopping-distance helper and the commit-aware planner.

from collections.abc import Callable
from models import Action, Perception, RunResult, Scenario, TimelinePoint, VehicleZone

Planner = Callable[[Perception, float, float, float], Action]
TIME_STEP_S = 1.0
ESCAPE_SPEED_MPS = 12.0


def zone_for(x_m):
    if x_m < 0.0:
        return VehicleZone.BEFORE_GATE
    if x_m < 4.0:
        return VehicleZone.TRAP_ZONE
    if x_m < 10.0:
        return VehicleZone.ON_TRACKS
    if x_m < 14.0:
        return VehicleZone.EXIT_ZONE
    return VehicleZone.CLEAR


def advance(x_m, speed_mps, action, deceleration_mps2):
    if action == Action.HOLD:
        return x_m, 0.0
    if action == Action.CLEAR_TRACKS:
        new_speed = max(speed_mps, ESCAPE_SPEED_MPS)
        return x_m + new_speed * TIME_STEP_S, new_speed
    if action == Action.BRAKE_TO_STOP:
        new_speed = max(0.0, speed_mps - deceleration_mps2 * TIME_STEP_S)
        return x_m + (speed_mps + new_speed) / 2 * TIME_STEP_S, new_speed
    return x_m + speed_mps * TIME_STEP_S, speed_mps


def penalties(x_m, speed_mps, zone, action, event):
    total, reasons = 0, []
    if event.actual_train_on_crossing and zone == VehicleZone.ON_TRACKS:
        total += 100
        reasons.append("occupied tracks while train is present")
    if speed_mps <= 0.1 and zone in {VehicleZone.TRAP_ZONE, VehicleZone.ON_TRACKS}:
        total += 60
        reasons.append("stopped in protected zone")
    if not event.clearance_beyond_tracks and x_m >= 0.0 and zone != VehicleZone.CLEAR and action != Action.CLEAR_TRACKS:
        total += 40
        reasons.append("entered without downstream clearance")
    return total, reasons


def simulate(scenario: Scenario, planner_name: str, planner: Planner):
    x_m, speed_mps = scenario.initial_x_m, scenario.initial_speed_mps
    points, total_penalty = [], 0
    for step, event in enumerate(scenario.events):
        perception = Perception(
            lights_flashing=event.lights_flashing,
            gate_state=event.gate_state,
            train_visible=event.train_visible,
            vehicle_zone=zone_for(x_m),
            clearance_beyond_tracks=event.clearance_beyond_tracks,
            confidence=event.confidence,
            short_reason="Deterministic replay fixture",
        )
        action = planner(perception, x_m, speed_mps, scenario.deceleration_mps2)
        x_m, speed_mps = advance(x_m, speed_mps, action, scenario.deceleration_mps2)
        zone = zone_for(x_m)
        penalty, reasons = penalties(x_m, speed_mps, zone, action, event)
        total_penalty += penalty
        points.append(TimelinePoint(step, x_m, speed_mps, zone, action, penalty, reasons))
    return RunResult(scenario, planner_name, points, max(0, 100 - total_penalty))

What belongs in simulator.py?

This file maps positions to zones, advances motion, assigns penalties, and returns a complete scored timeline.

import argparse
from planners import naive_warning_rule
from scenarios import SCENARIOS
from simulator import simulate

NAIVE_NAME = "Naive warning rule"


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--baseline-only", action="store_true")
    args = parser.parse_args()
    planners = [(NAIVE_NAME, naive_warning_rule)]

    results = []
    print(f"{'Scenario':42} | {'Planner':22} | Score | Penalties")
    print("-" * 100)
    for scenario in SCENARIOS:
        for planner_name, planner in planners:
            result = simulate(scenario, planner_name, planner)
            results.append(result)
            found = sorted({r for p in result.points for r in p.penalty_reasons})
            print(f"{scenario.name:42} | {planner_name:22} | {result.score:5} | {', '.join(found) if found else 'none'}")


if __name__ == "__main__":
    main()

What belongs in run_sandbox.py?

This baseline runner accepts the command-line option, replays every scenario, and prints each score with its unique penalty reasons.

The baseline failure is now reproducible, and Step 4 builds the planner that fixes it. First, you'll turn one permitted crossing image into the same typed Perception contract.

Turn a Dashcam Still into Structured Perception

Your offline replay now exposes the naive rule's protected-zone failure. The next layer gives the sandbox a typed view of one crossing still.

The planner reads fields such as gate_state and vehicle_zone, so an image result only helps in that exact shape. You'll use the Claude API to convert one permitted image into a validated Perception object.

The object remains an observation. It never controls a vehicle.

In this step, get ready to:
  • Confirm the fixed perception contract from the deterministic simulator.
  • Create a vision adapter that requests a typed structured output.
  • Validate one permitted crossing image with a live Claude request.
Confirm the perception contract

The existing Perception model is the boundary between uncertain image analysis and deterministic planning. Its seven fields force each response into the same shape.

  • Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
  • Type Visual Studio Code in the search bar.
  • Press Enter to bring Visual Studio Code to the front.
  • Click File in the top menu bar.
  • Click Open Folder.
  • Select the existing project folder that contains models.py.
  • Click Open.

You should see models.py beside the other baseline files in the Explorer sidebar.

  • Select models.py in the Explorer sidebar.
  • Find class Perception(BaseModel):.
  • Confirm each field described below appears once in the model.
  • Keep models.py unchanged.

What Does the Contract Capture?

  • lights_flashing records whether the warning lights appear active.
  • gate_state stores a fixed gate-state value.
  • train_visible records whether a train appears in the frame.
  • vehicle_zone places the viewpoint in a fixed crossing zone.
  • clearance_beyond_tracks records whether the downstream space appears open.
  • confidence preserves the estimated observation quality.
  • short_reason gives a concise basis for the estimate.

Confidence describes the quality of an observation. The deterministic planner decides how to use that observation.

Build the image adapter

The adapter needs image-format mappings plus an educational prompt before it can make a request. It also needs the existing Perception model as its structured output contract.

  • Click the New File icon in the Explorer sidebar.
  • Type vision.py.
  • Press Enter.
  • Confirm vision.py appears beside models.py.
  • Add the imports plus the image configuration by pasting this code into vision.py:
import base64
import sys
from pathlib import Path
from anthropic import Anthropic
from dotenv import load_dotenv
from models import Perception

# Load the local credential before the SDK client is created.
load_dotenv()

MODEL_ID = "claude-haiku-5-5"
MEDIA_TYPES = {
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".png": "image/png",
    ".gif": "image/gif",
    ".webp": "image/webp",
}
PROMPT = """
Analyze this rail-crossing image as an educational scene-understanding task.
Estimate warning lights, gate state, train visibility, the vehicle zone, downstream
clearance, and confidence from 0 to 1. Use unknown states and lower confidence
when evidence is missing. Never provide real-world driving control.
""".strip()

What Does This Configuration Do?

  • base64 converts the local image bytes into data the request can carry.
  • Path provides file checks plus file-reading methods.
  • load_dotenv() loads ANTHROPIC_API_KEY from the ignored .env file.
  • Anthropic creates the SDK client after the credential is available.
  • MODEL_ID selects claude-haiku-5-5 for the bounded extraction request.
  • MEDIA_TYPES maps each accepted extension to its request media type.
  • PROMPT limits the task to educational scene understanding.
  • Save vision.py by pressing Cmd+S (macOS) or Ctrl+S (Windows).
  • Confirm the unsaved indicator disappears from the vision.py tab.

Seeing Editor Warnings?

Check that every media-type entry keeps its comma. Check that the prompt begins plus ends with three double quotes.

If the warning remains, help me compare the configuration with the required Python syntax.

A command-line guard prevents an incomplete invocation from reaching the live API. It requires exactly one image path.

  • Move to the blank line below PROMPT in vision.py.
  • Add the command-line entry point by pasting this code:
def main():
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python vision.py path/to/frame.png")
    path = Path(sys.argv[1])
    if not path.is_file():
        raise SystemExit(f"Image not found: {path}")
    print(inspect_frame(path))


if __name__ == "__main__":
    main()

What Does the Entry Point Do?

  • main() checks that the command includes exactly one image path.
  • Path(sys.argv[1]) turns the supplied path into a file object.
  • path.is_file() stops the request when the image cannot be found.
  • print(inspect_frame(path)) prints the typed result returned by the adapter.
  • Save vision.py.

Before you run this check, predict whether the missing-path guard stops before any API request.

  • Check the command-line guard by intentionally omitting the image path:
python vision.py

What Should Happen?

You should see Usage: python vision.py path/to/frame.png. This intentional stop proves that a missing path cannot reach the live request.

🙋‍♀️ Did the Guard Fail Differently?

Confirm the project terminal still shows (.venv) in its prompt. Confirm the terminal is in the folder that contains vision.py.

If Python reports a syntax problem, help me check the main function against the project code.

The request function now needs to encode the image before placing it ahead of the prompt. The parsed response must also pass two validation checks before it returns.

  • Place your cursor on the blank line directly above def main():.
  • Add the image request function by pasting this code:
def inspect_frame(path: Path):
    suffix = path.suffix.lower()
    if suffix not in MEDIA_TYPES:
        raise ValueError("Use a JPEG, PNG, GIF, or WebP image.")
    data = base64.b64encode(path.read_bytes()).decode("utf-8")
    response = Anthropic().messages.parse(
        model=MODEL_ID,
        max_tokens=600,
        messages=[{
            "role": "user",
            "content": [
                {"type": "image", "source": {"type": "base64", "media_type": MEDIA_TYPES[suffix], "data": data}},
                {"type": "text", "text": PROMPT},
            ],
        }],
        output_format=Perception,
    )
    perception = response.parsed_output
    if perception is None:
        raise RuntimeError("Claude returned no parsed perception.")
    if not 0.0 <= perception.confidence <= 1.0:
        raise ValueError("Perception confidence must be between 0 and 1.")
    return perception

How Does the Adapter Work?

  • suffix identifies the local image format.
  • data holds the base64-encoded image bytes.
  • messages places the image block before the educational text prompt.
  • output_format=Perception asks the SDK parser for the existing typed contract.
  • parsed_output holds the validated Pydantic result when parsing succeeds.
  • The final checks reject a missing result plus confidence outside the allowed range.
  • Save vision.py.
  • Re-run the missing-path guard to check that the completed file still parses:
python vision.py

What Does This Check Prove?

You should see the same Usage: python vision.py path/to/frame.png guidance. The completed module parses before the guard stops the missing-path invocation.

🙋‍♀️ Seeing a Syntax Error Now?

Confirm inspect_frame() sits above main(). Check the closing brackets around messages plus content.

If the brackets are hard to trace, help me find the mismatched delimiter in inspect_frame().

✔️ Awesome, I've got everything!

Your completed vision.py is saved. Its missing-path guard prints the expected usage guidance.

ⓧ I'd like to double check the full code

Compare your complete vision.py with this reference line by line.

import base64
import sys
from pathlib import Path
from anthropic import Anthropic
from dotenv import load_dotenv
from models import Perception

# Load the local credential before the SDK client is created.
load_dotenv()

MODEL_ID = "claude-haiku-5-5"
MEDIA_TYPES = {
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
    ".png": "image/png",
    ".gif": "image/gif",
    ".webp": "image/webp",
}
PROMPT = """
Analyze this rail-crossing image as an educational scene-understanding task.
Estimate warning lights, gate state, train visibility, the vehicle zone, downstream
clearance, and confidence from 0 to 1. Use unknown states and lower confidence
when evidence is missing. Never provide real-world driving control.
""".strip()


def inspect_frame(path: Path):
    suffix = path.suffix.lower()
    if suffix not in MEDIA_TYPES:
        raise ValueError("Use a JPEG, PNG, GIF, or WebP image.")
    data = base64.b64encode(path.read_bytes()).decode("utf-8")
    response = Anthropic().messages.parse(
        model=MODEL_ID,
        max_tokens=600,
        messages=[{
            "role": "user",
            "content": [
                {"type": "image", "source": {"type": "base64", "media_type": MEDIA_TYPES[suffix], "data": data}},
                {"type": "text", "text": PROMPT},
            ],
        }],
        output_format=Perception,
    )
    perception = response.parsed_output
    if perception is None:
        raise RuntimeError("Claude returned no parsed perception.")
    if not 0.0 <= perception.confidence <= 1.0:
        raise ValueError("Perception confidence must be between 0 and 1.")
    return perception


def main():
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python vision.py path/to/frame.png")
    path = Path(sys.argv[1])
    if not path.is_file():
        raise SystemExit(f"Image not found: {path}")
    print(inspect_frame(path))


if __name__ == "__main__":
    main()

What Should Match?

The reference keeps inspect_frame() above main(). It contains the exact model ID plus the seven-field output contract.

Validate one permitted frame

The adapter accepts JPEG, PNG, GIF, or WebP input. This walkthrough uses the example JPEG still at frames/your-crossing-frame.jpg.

Keep the Input Controlled

Use one still that you are allowed to analyze. The adapter sends that image only when you run the live request command.

  • Confirm you have permission to analyze the crossing image.
  • Click the New Folder icon in the Visual Studio Code Explorer toolbar.
  • Type frames.
  • Press Enter.
  • Locate your permitted still in Finder (macOS) or File Explorer (Windows).
  • Drag the image into the frames folder in Visual Studio Code.
  • Right-click the copied image in the Explorer sidebar.
  • Click Rename.
  • Type your-crossing-frame.jpg, or your-crossing-frame.png if your still is a PNG.
  • Press Enter.
  • Confirm the Explorer sidebar shows frames/your-crossing-frame.jpg.

Example still: “Locomotives HLCX 1075 and Union Pacific Y1388 at night” by Scott A. Miller, CC BY 3.0, via Wikimedia Commons. Open the link, select Download, and save the original JPEG.

One Live API Request

The next command makes this step's only required billable Claude request. Re-running the command can add token charges.

Your API key stays in the ignored .env file from earlier. The adapter loads it into the Python process without placing it in vision.py.

Before you send the image, predict which scene details the typed object makes explicit.

macOS

  • Reactivate the environment in a new macOS terminal by running this command:
source .venv/bin/activate

Windows

  • Reactivate the environment in a new PowerShell terminal by running this command:
.\.venv\Scripts\Activate.ps1
  • Analyze the permitted frame by running:
python vision.py frames/your-crossing-frame.jpg

What Should I See?

You should see a Perception object containing all seven contract fields from models.py.

The printed result gives the sandbox one typed observation. It does not issue a driving instruction.

  • Open the source image beside the terminal result.
  • Compare each printed field with the visible evidence in the image.
  • Check that uncertain visual evidence is reflected in the returned confidence plus short reason.

Did the Live Request Fail?

If the image cannot be found, confirm the Explorer sidebar shows the exact frames/your-crossing-frame.jpg path. Keep the file extension consistent with the actual image format.

If you see The image was specified using the image/png media type, but the image appears to be a image/jpeg image, the file's extension doesn't match its format. Rename the file to .jpg and run the command with the new name.

If the request reports an authentication problem, confirm .env is saved beside vision.py and its line begins with ANTHROPIC_API_KEY=. Do not paste the key into your source code.

If the typed result is missing, help me debug the image request without exposing my API key.

You now have a typed multimodal observation that stays separate from vehicle control. Next, you will use deterministic physics plus crossing state to build the commit-aware planner.

Build the Commit-Aware Safety Planner

Your vision adapter now turns a permitted image into a typed observation. The replay suite still exposes the baseline's post-commitment failure.

A safer policy first calculates whether stopping distance still fits. It then checks the current vehicle zone.

The decision also checks downstream clearance. Available deceleration, latency, and uncertainty shape the stop-or-clear boundary.

In this step, get ready to:
  • Calculate the stop-or-clear boundary from braking distance, latency, and margin.
  • Encode deterministic states for holding, braking, proceeding, and clearing.
  • Compare both planners across the same five replays.
Calculate the stop-or-clear boundary

A new stopping_distance() function provides the physical boundary for the new policy. It combines the distance used during braking with the distance covered during reaction latency.

  • In planners.py from earlier, add the boundary constants and stopping_distance() below the models import:
CONFIDENCE_THRESHOLD = 0.60
REACTION_TIME_S = 0.70
SAFETY_MARGIN_M = 1.50


def stopping_distance(speed_mps, deceleration_mps2, reaction_time_s=REACTION_TIME_S, safety_margin_m=SAFETY_MARGIN_M):
    braking = speed_mps**2 / (2 * deceleration_mps2)
    latency = speed_mps * reaction_time_s
    return braking + latency + safety_margin_m

How does the boundary work?

  • The braking value estimates the distance needed to reduce the current speed to zero.
  • The latency value accounts for movement during the configured reaction time.
  • The safety margin adds extra distance to the educational model.
  • Each scenario supplies its own deceleration_mps2. The rain replay therefore produces a longer required distance.

The planner compares this required distance with max(-x_m, 0.0). That available distance reaches zero once the simulated vehicle passes the gate.

Encode the safety states

The commitment boundary separates decisions that can still stop before entry from decisions that must clear forward. Vehicle zones make that boundary explicit in the policy.

  • Switch back to planners.py from earlier.
  • Add commit_aware_planner() below naive_warning_rule() by pasting this function:
def commit_aware_planner(perception, x_m, speed_mps, deceleration_mps2):
    if perception.vehicle_zone == VehicleZone.CLEAR:
        return Action.PROCEED
    if perception.vehicle_zone in {VehicleZone.TRAP_ZONE, VehicleZone.ON_TRACKS, VehicleZone.EXIT_ZONE}:
        return Action.CLEAR_TRACKS
    if not perception.clearance_beyond_tracks:
        return Action.HOLD

    uncertain = perception.confidence < CONFIDENCE_THRESHOLD
    direct_warning = (
        perception.lights_flashing
        or perception.gate_state != GateState.UP
        or perception.train_visible
    )
    if not uncertain and not direct_warning:
        return Action.PROCEED

    available = max(-x_m, 0.0)
    required = stopping_distance(speed_mps, deceleration_mps2)
    return Action.BRAKE_TO_STOP if available >= required else Action.CLEAR_TRACKS

What does this planner do?

  • A vehicle in VehicleZone.CLEAR can continue because it has passed the protected area.
  • A vehicle in the trap, tracks, or exit zone receives Action.CLEAR_TRACKS because commitment has already happened.
  • Blocked downstream clearance returns Action.HOLD while the vehicle remains before entry.
  • Low confidence or a direct warning triggers the distance comparison.
  • Save planners.py.
  • Confirm the original baseline remains runnable by running:
python run_sandbox.py --baseline-only

You should still see five baseline rows. At least one row includes the stopped in protected zone penalty.

Good. The baseline still runs after the new policy was added.

Baseline no longer runs?

  • Check that VehicleZone appears in the import from models.
  • Check the indentation inside commit_aware_planner() against the reference below.
  • Use the terminal traceback to find the first line in planners.py that needs attention.

Still stuck? Help me debug my commit-aware planner without changing its safety-state order.

✔️ Awesome, I've got everything!

Your planners.py now contains both policies. Save the file before updating the runner.

ⓧ I'd like to double check the full code

Compare your complete planners.py with this reference line by line.

from models import Action, GateState, Perception, VehicleZone

CONFIDENCE_THRESHOLD = 0.60
REACTION_TIME_S = 0.70
SAFETY_MARGIN_M = 1.50


def stopping_distance(speed_mps, deceleration_mps2, reaction_time_s=REACTION_TIME_S, safety_margin_m=SAFETY_MARGIN_M):
    braking = speed_mps**2 / (2 * deceleration_mps2)
    latency = speed_mps * reaction_time_s
    return braking + latency + safety_margin_m


def naive_warning_rule(perception, x_m, speed_mps, deceleration_mps2):
    del x_m, speed_mps, deceleration_mps2
    direct_warning = (
        perception.lights_flashing
        or perception.gate_state in {GateState.MOVING, GateState.DOWN}
        or perception.train_visible
    )
    return Action.BRAKE_TO_STOP if direct_warning else Action.PROCEED


def commit_aware_planner(perception, x_m, speed_mps, deceleration_mps2):
    if perception.vehicle_zone == VehicleZone.CLEAR:
        return Action.PROCEED
    if perception.vehicle_zone in {VehicleZone.TRAP_ZONE, VehicleZone.ON_TRACKS, VehicleZone.EXIT_ZONE}:
        return Action.CLEAR_TRACKS
    if not perception.clearance_beyond_tracks:
        return Action.HOLD

    uncertain = perception.confidence < CONFIDENCE_THRESHOLD
    direct_warning = (
        perception.lights_flashing
        or perception.gate_state != GateState.UP
        or perception.train_visible
    )
    if not uncertain and not direct_warning:
        return Action.PROCEED

    available = max(-x_m, 0.0)
    required = stopping_distance(speed_mps, deceleration_mps2)
    return Action.BRAKE_TO_STOP if available >= required else Action.CLEAR_TRACKS

This full-file reference preserves the original baseline while adding the commit-aware policy beneath it.

Compare both planners

A fair comparison sends identical external events through both policies. The deterministic simulator then applies the same motion model and penalty weights to each result.

  • Switch back to run_sandbox.py from earlier.
  • Replace the top runner configuration with this block:
import argparse
from planners import commit_aware_planner, naive_warning_rule
from scenarios import SCENARIOS
from simulator import simulate

NAIVE_NAME = "Naive warning rule"
SAFETY_NAME = "Commit-aware planner"

Why add planner names?

The runner pairs each function with a readable label. Those labels keep the score table clear when both policies process the same scenario.

  • Find the existing main() function in run_sandbox.py.
  • Keep the bottom if __name__ == "__main__": guard unchanged.
  • Replace that function with this version:
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--baseline-only", action="store_true")
    parser.add_argument("--no-report", action="store_true")
    args = parser.parse_args()
    planners = [(NAIVE_NAME, naive_warning_rule)]
    if not args.baseline_only:
        planners.append((SAFETY_NAME, commit_aware_planner))

    results = []
    print(f"{'Scenario':42} | {'Planner':22} | Score | Penalties")
    print("-" * 100)
    for scenario in SCENARIOS:
        for planner_name, planner in planners:
            result = simulate(scenario, planner_name, planner)
            results.append(result)
            found = sorted({r for p in result.points for r in p.penalty_reasons})
            print(f"{scenario.name:42} | {planner_name:22} | {result.score:5} | {', '.join(found) if found else 'none'}")

    if not args.baseline_only and not args.no_report:
        from report import build_report
        md_path, html_path = build_report(results)
        print(f"\nCreated {md_path}\nCreated {html_path}")

How does the comparison stay fair?

  • The runner sends every entry in SCENARIOS through both planner functions.
  • The simulator passes each scenario's available deceleration into the selected planner.
  • The existing score subtracts 100 for occupied tracks while a train is present.
  • The existing score subtracts 60 for stopping in the protected zone. It subtracts 40 for entering without downstream clearance.
  • Save run_sandbox.py.

Before you run the comparison, which planner do you expect to score higher across the five fixed replays?

  • Compare both policies without generating reports by running:
python run_sandbox.py --no-report

You should see ten result rows. Every scenario has one row for the naive rule and one for the commit-aware planner.

The commit-aware planner scores higher than the naive rule in all five replays. That's the core comparison working with repeatable inputs.

Scores not comparing correctly?

  • If you see only five rows, check that commit_aware_planner is appended when baseline_only is false.
  • If the runner cannot load the new planner, confirm that both edited files are saved.
  • If any safety score fails to improve, compare planners.py with its full-code reference before changing the scenarios.

Need another pair of eyes? Help me trace why my two-planner replay scores differ from the expected comparison.

✔️ Awesome, I've got everything!

Both policies now run against all five deterministic scenarios. Your comparative score table is ready for reporting.

ⓧ I'd like to double check the full code

Compare your complete run_sandbox.py with this reference line by line.

import argparse
from planners import commit_aware_planner, naive_warning_rule
from scenarios import SCENARIOS
from simulator import simulate

NAIVE_NAME = "Naive warning rule"
SAFETY_NAME = "Commit-aware planner"


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--baseline-only", action="store_true")
    parser.add_argument("--no-report", action="store_true")
    args = parser.parse_args()
    planners = [(NAIVE_NAME, naive_warning_rule)]
    if not args.baseline_only:
        planners.append((SAFETY_NAME, commit_aware_planner))

    results = []
    print(f"{'Scenario':42} | {'Planner':22} | Score | Penalties")
    print("-" * 100)
    for scenario in SCENARIOS:
        for planner_name, planner in planners:
            result = simulate(scenario, planner_name, planner)
            results.append(result)
            found = sorted({r for p in result.points for r in p.penalty_reasons})
            print(f"{scenario.name:42} | {planner_name:22} | {result.score:5} | {', '.join(found) if found else 'none'}")

    if not args.baseline_only and not args.no_report:
        from report import build_report
        md_path, html_path = build_report(results)
        print(f"\nCreated {md_path}\nCreated {html_path}")


if __name__ == "__main__":
    main()

This full-file reference runs both policies by default. The --no-report option keeps this step focused on the terminal comparison.

Both policies now process the same replay events with deterministic results. Next, you'll turn those scores and trajectories into a visual safety report.

Generate the Visual Safety Report

Your deterministic replay now proves that the commit-aware planner beats the naive rule across all five fixtures. Console scores still hide where each planner stops or clears during a scenario.

This step turns those runs into a visual evidence pack. Each SVG timeline shows the gate, rails, clearance boundary, vehicle positions, and planner actions.

The report then packages the comparisons as Markdown and self-contained HTML. The same offline fixtures remain responsible for every score.

In this step, get ready to:
  • Draw one comparative timeline for each replay scenario.
  • Assemble Markdown and self-contained HTML reports.
  • Generate the report files and inspect their visual evidence.
Draw the timeline geometry

A timeline converts every simulation point into a horizontal position. Shared gate and rail markers make the planners easy to compare at each replay step.

  • Return to Visual Studio Code from earlier.
  • Select the new-file control in the project file tree.
  • Enter report.py to create the file beside run_sandbox.py.
  • Add the report imports, labels, output folder, and position mapper by pasting this code:
from html import escape
from pathlib import Path
from models import RunResult

REPORT_DIR = Path("reports")
NAIVE_NAME = "Naive warning rule"
SAFETY_NAME = "Commit-aware planner"


def map_x(x_m):
    x_m = max(-25.0, min(25.0, x_m))
    return 100.0 + (x_m + 25.0) / 50.0 * 800.0

What does this code do?

  • REPORT_DIR keeps every generated artifact inside the reports folder.
  • NAIVE_NAME and SAFETY_NAME match the planner labels already stored in each RunResult.
  • map_x() clamps simulated positions to the displayed range.
  • The returned coordinate places every vehicle marker on the same 800-pixel track diagram.
  • Save report.py.
  • Confirm report.py appears beside run_sandbox.py in the file tree.

Report file missing?

Check that you created report.py in the same folder as run_sandbox.py. A nested copy cannot be imported by the runner.

Still stuck? Help me place report.py beside run_sandbox.py in my Python project.

The timeline uses one row per replay event, with orange markers for the naive rule and blue markers for the commit-aware planner.

  • Add the timeline renderer below map_x() by pasting this code:
def timeline_svg(naive: RunResult, safety: RunResult):
    height = 100 + 78 * len(naive.points)
    gate, near, far, clear = map_x(0), map_x(4), map_x(10), map_x(14)
    parts = [
        f'<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="{height}">',
        '<rect width="100%" height="100%" fill="#fbfbfd"/>',
        '<style>text{font-family:system-ui,sans-serif;fill:#172033}.s{font-size:12px}.l{font-size:14px;font-weight:600}</style>',
        f'<text x="20" y="28" class="l">{escape(naive.scenario.name)}</text>',
        f'<line x1="{gate}" y1="42" x2="{gate}" y2="{height-20}" stroke="#d1495b" stroke-width="4"/>',
        f'<line x1="{near}" y1="42" x2="{near}" y2="{height-20}" stroke="#333" stroke-width="5"/>',
        f'<line x1="{far}" y1="42" x2="{far}" y2="{height-20}" stroke="#333" stroke-width="5"/>',
        f'<line x1="{clear}" y1="42" x2="{clear}" y2="{height-20}" stroke="#2a9d8f" stroke-width="3" stroke-dasharray="8 6"/>',
        f'<text x="{gate-18}" y="48" class="s">gate</text>',
        f'<text x="{near+6}" y="48" class="s">rails</text>',
        f'<text x="{clear+6}" y="48" class="s">clear</text>',
    ]
    for n, s in zip(naive.points, safety.points):
        y = 82 + n.step * 78
        parts += [
            f'<line x1="90" y1="{y+22}" x2="920" y2="{y+22}" stroke="#d9dde7"/>',
            f'<text x="20" y="{y+4}" class="l">t{n.step}</text>',
            f'<circle cx="{map_x(n.x_m)}" cy="{y}" r="8" fill="#e76f51"/>',
            f'<circle cx="{map_x(s.x_m)}" cy="{y+26}" r="8" fill="#277da1"/>',
            f'<text x="940" y="{y+4}" class="s">Naive: {escape(n.action.value)} at {n.x_m:.1f} m</text>',
            f'<text x="940" y="{y+30}" class="s">Safety: {escape(s.action.value)} at {s.x_m:.1f} m</text>',
        ]
    parts.append("</svg>")
    return "".join(parts)

How does the timeline work?

  • gate marks the entry boundary at 0 metres.
  • near and far mark the two rail positions.
  • clear marks the point beyond the protected area.
  • zip() pairs matching replay points from both planners.
  • escape() protects scenario names and action labels before placing them in the SVG markup.
  • Save report.py.
  • Check that report.py loads by running:
python -c "import report; print('report-ready')"

You should see report-ready. A syntax error in report.py shows here with its line number.

Seeing a Python syntax error?

Check that timeline_svg() starts at the left edge of report.py. Its nested lines must remain indented beneath the function.

Need another pair of eyes? Help me compare my timeline_svg function with the expected indentation.

Assemble the report formats

A timeline explains motion. The surrounding report adds scores, penalty reasons, provenance, and limitations so each diagram keeps its educational context.

  • Add the penalty summarizer and report setup below timeline_svg() by pasting this code:
def reasons(result):
    found = sorted({r for p in result.points for r in p.penalty_reasons})
    return ", ".join(found) if found else "none"


def build_report(results):
    REPORT_DIR.mkdir(exist_ok=True)
    by_key = {(r.scenario.slug, r.planner_name): r for r in results}
    scenarios, seen = [], set()
    for result in results:
        if result.scenario.slug not in seen:
            seen.add(result.scenario.slug)
            scenarios.append(result.scenario)

    md = [
        "# Rail-Crossing Safety Sandbox Report", "",
        "Educational simulation only. Scores and geometry are project choices, not safety certification.", "",
        "| Scenario | Naive score | Commit-aware score |", "| --- | ---: | ---: |",
    ]
    html = [
        "<!doctype html><html><head><meta charset='utf-8'><title>Rail-Crossing Safety Sandbox</title>",
        "<style>body{font-family:system-ui,sans-serif;max-width:1250px;margin:32px auto;color:#172033}section{margin:42px 0}</style>",
        "</head><body><h1>Rail-Crossing Safety Sandbox Report</h1>",
        "<p>Educational simulation only. Scores and geometry are project choices, not safety certification.</p>",
    ]

How is the report prepared?

  • reasons() collects unique penalty explanations from a completed run.
  • by_key indexes each result by scenario slug and planner name.
  • scenarios preserves one ordered entry for each of the five replay fixtures.
  • md starts the Markdown score table.
  • html starts the self-contained HTML document.
  • Save report.py.
  • Confirm the editor shows definitions for reasons() and build_report().

Functions missing from the editor?

Make sure def reasons and def build_report begin at the left edge. An extra indent can place them inside timeline_svg().

Still unsure? Help me check where my report functions begin and end.

Each scenario adds one table row and one detailed section. The Markdown version links each SVG file, while the HTML version embeds the same SVG markup.

  • Continue build_report() directly below the html list by pasting this indented code:
    rows, body = [], []
    for scenario in scenarios:
        naive = by_key[(scenario.slug, NAIVE_NAME)]
        safety = by_key[(scenario.slug, SAFETY_NAME)]
        rows.append(f"| {scenario.name} | {naive.score} | {safety.score} |")
        svg = timeline_svg(naive, safety)
        (REPORT_DIR / f"{scenario.slug}.svg").write_text(svg, encoding="utf-8")
        body += [
            "", f"## {scenario.name}", "", f"Provenance: {scenario.provenance}", "",
            f"Naive penalties: {reasons(naive)}", "", f"Commit-aware penalties: {reasons(safety)}", "",
            f"![{scenario.name} timeline]({scenario.slug}.svg)",
        ]
        html += [
            "<section>", f"<h2>{escape(scenario.name)}</h2>",
            f"<p><strong>Provenance:</strong> {escape(scenario.provenance)}</p>",
            f"<p>Naive score: {naive.score}. Commit-aware score: {safety.score}.</p>", svg, "</section>",
        ]

What does each scenario add?

  • naive retrieves the baseline result for the current fixture.
  • safety retrieves the commit-aware result for the same fixture.
  • timeline_svg() renders both trajectories against shared crossing geometry.
  • write_text() saves the scenario timeline using its stable slug.
  • The provenance text keeps synthetic, media-inspired, and hypothetical scenarios clearly labelled.
  • rows collects one score-table row per scenario, and body collects each scenario's section, so the table stays in one piece above the sections.
  • Save report.py.
  • Check that the finished scenario loop loads by running:
python -c "import report; print('report-ready')"

You should see report-ready. An indentation error in the scenario loop shows here with its line number.

Editor highlighting an indentation problem?

Keep the scenario loop four spaces inside build_report(). Keep the statements beneath for scenario in scenarios another four spaces inward.

Need help locating the mismatch? Help me fix the indentation in my build_report scenario loop.

The final section records the simulator limitations. It then writes both report formats and returns their paths to the runner.

  • Finish build_report() directly below the scenario loop by pasting this indented code:
    md += rows + body + [
        "", "## Limitations", "",
        "- One-dimensional model with hand-authored events.",
        "- Claude output never controls a vehicle.",
        "- Parameters and penalties are not regulatory or manufacturer thresholds.",
        "- The San Diego scenario is hypothetical.",
    ]
    html.append("</body></html>")
    md_path = REPORT_DIR / "safety_report.md"
    html_path = REPORT_DIR / "safety_report.html"
    md_path.write_text("\n".join(md) + "\n", encoding="utf-8")
    html_path.write_text("".join(html), encoding="utf-8")
    return md_path, html_path

Why end with limitations?

The limitations separate this educational simulator from safety certification or vehicle control. They also identify the hand-authored events and one-dimensional geometry behind the results.

The Markdown file ends with those boundaries. The self-contained HTML file embeds every timeline for single-file sharing.

  • Save report.py.
  • Compare your completed file with the reference below before generating the artifacts.

✔️ Awesome, I've got everything!

Great. Confirm report.py is saved beside run_sandbox.py.

ⓧ I'd like to double check the full code

Here is the complete report.py file. Compare it with yours line by line.

from html import escape
from pathlib import Path
from models import RunResult

REPORT_DIR = Path("reports")
NAIVE_NAME = "Naive warning rule"
SAFETY_NAME = "Commit-aware planner"


def map_x(x_m):
    x_m = max(-25.0, min(25.0, x_m))
    return 100.0 + (x_m + 25.0) / 50.0 * 800.0


def timeline_svg(naive: RunResult, safety: RunResult):
    height = 100 + 78 * len(naive.points)
    gate, near, far, clear = map_x(0), map_x(4), map_x(10), map_x(14)
    parts = [
        f'<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="{height}">',
        '<rect width="100%" height="100%" fill="#fbfbfd"/>',
        '<style>text{font-family:system-ui,sans-serif;fill:#172033}.s{font-size:12px}.l{font-size:14px;font-weight:600}</style>',
        f'<text x="20" y="28" class="l">{escape(naive.scenario.name)}</text>',
        f'<line x1="{gate}" y1="42" x2="{gate}" y2="{height-20}" stroke="#d1495b" stroke-width="4"/>',
        f'<line x1="{near}" y1="42" x2="{near}" y2="{height-20}" stroke="#333" stroke-width="5"/>',
        f'<line x1="{far}" y1="42" x2="{far}" y2="{height-20}" stroke="#333" stroke-width="5"/>',
        f'<line x1="{clear}" y1="42" x2="{clear}" y2="{height-20}" stroke="#2a9d8f" stroke-width="3" stroke-dasharray="8 6"/>',
        f'<text x="{gate-18}" y="48" class="s">gate</text>',
        f'<text x="{near+6}" y="48" class="s">rails</text>',
        f'<text x="{clear+6}" y="48" class="s">clear</text>',
    ]
    for n, s in zip(naive.points, safety.points):
        y = 82 + n.step * 78
        parts += [
            f'<line x1="90" y1="{y+22}" x2="920" y2="{y+22}" stroke="#d9dde7"/>',
            f'<text x="20" y="{y+4}" class="l">t{n.step}</text>',
            f'<circle cx="{map_x(n.x_m)}" cy="{y}" r="8" fill="#e76f51"/>',
            f'<circle cx="{map_x(s.x_m)}" cy="{y+26}" r="8" fill="#277da1"/>',
            f'<text x="940" y="{y+4}" class="s">Naive: {escape(n.action.value)} at {n.x_m:.1f} m</text>',
            f'<text x="940" y="{y+30}" class="s">Safety: {escape(s.action.value)} at {s.x_m:.1f} m</text>',
        ]
    parts.append("</svg>")
    return "".join(parts)


def reasons(result):
    found = sorted({r for p in result.points for r in p.penalty_reasons})
    return ", ".join(found) if found else "none"


def build_report(results):
    REPORT_DIR.mkdir(exist_ok=True)
    by_key = {(r.scenario.slug, r.planner_name): r for r in results}
    scenarios, seen = [], set()
    for result in results:
        if result.scenario.slug not in seen:
            seen.add(result.scenario.slug)
            scenarios.append(result.scenario)

    md = [
        "# Rail-Crossing Safety Sandbox Report", "",
        "Educational simulation only. Scores and geometry are project choices, not safety certification.", "",
        "| Scenario | Naive score | Commit-aware score |", "| --- | ---: | ---: |",
    ]
    html = [
        "<!doctype html><html><head><meta charset='utf-8'><title>Rail-Crossing Safety Sandbox</title>",
        "<style>body{font-family:system-ui,sans-serif;max-width:1250px;margin:32px auto;color:#172033}section{margin:42px 0}</style>",
        "</head><body><h1>Rail-Crossing Safety Sandbox Report</h1>",
        "<p>Educational simulation only. Scores and geometry are project choices, not safety certification.</p>",
    ]
    rows, body = [], []
    for scenario in scenarios:
        naive = by_key[(scenario.slug, NAIVE_NAME)]
        safety = by_key[(scenario.slug, SAFETY_NAME)]
        rows.append(f"| {scenario.name} | {naive.score} | {safety.score} |")
        svg = timeline_svg(naive, safety)
        (REPORT_DIR / f"{scenario.slug}.svg").write_text(svg, encoding="utf-8")
        body += [
            "", f"## {scenario.name}", "", f"Provenance: {scenario.provenance}", "",
            f"Naive penalties: {reasons(naive)}", "", f"Commit-aware penalties: {reasons(safety)}", "",
            f"![{scenario.name} timeline]({scenario.slug}.svg)",
        ]
        html += [
            "<section>", f"<h2>{escape(scenario.name)}</h2>",
            f"<p><strong>Provenance:</strong> {escape(scenario.provenance)}</p>",
            f"<p>Naive score: {naive.score}. Commit-aware score: {safety.score}.</p>", svg, "</section>",
        ]
    md += rows + body + [
        "", "## Limitations", "",
        "- One-dimensional model with hand-authored events.",
        "- Claude output never controls a vehicle.",
        "- Parameters and penalties are not regulatory or manufacturer thresholds.",
        "- The San Diego scenario is hypothetical.",
    ]
    html.append("</body></html>")
    md_path = REPORT_DIR / "safety_report.md"
    html_path = REPORT_DIR / "safety_report.html"
    md_path.write_text("\n".join(md) + "\n", encoding="utf-8")
    html_path.write_text("".join(html), encoding="utf-8")
    return md_path, html_path
Generate and inspect the artifacts

The default sandbox run evaluates both planners before passing the completed results to build_report(). This keeps the console table and visual report tied to the same replay data.

Before you run the full suite, do you expect report generation to change the planner scores or only create new files?

  • Generate the complete report by running:
python run_sandbox.py

You should see the same comparative scores followed by Created reports/safety_report.md and Created reports/safety_report.html.

Report generation failed?

  • Check that report.py is beside run_sandbox.py.
  • Compare the planner labels with Naive warning rule and Commit-aware planner.
  • Check the terminal traceback for the first referenced line in report.py.

Still blocked? Help me debug why python run_sandbox.py cannot generate my safety report.

  • Expand the reports folder in the Visual Studio Code file tree.
  • Confirm safety_report.md and safety_report.html are listed.
  • Confirm late-gate-drop.svg and backed-up-traffic.svg are listed.
  • Confirm low-confidence-rain-night.svg and austin-media-inspired.svg are listed.
  • Confirm san-diego-hypothetical.svg is listed.
  • Select safety_report.md from the file tree.
  • Use the Markdown preview control in the editor toolbar.
  • Inspect one scenario timeline in the rendered report.

You should see a score table followed by five labelled scenario sections. Each timeline shows gate and rail geometry with separate naive and safety markers.

  • Confirm each scenario section includes its provenance label.
  • Confirm each timeline labels the planner actions and positions.
  • Confirm the report ends with the educational limitations.

Choose the right format

Share reports/safety_report.html when you want one self-contained file. Share reports/safety_report.md together with all five SVG files when you want a Markdown version.

Strong finish. Your five deterministic replays now have scores, provenance, limitations, and visual trajectories that can be reviewed without another live API request.

Secret mission

Map the Commit Boundary

Your report compares both planners through five fixed replays. This extension maps how speed plus available deceleration move the boundary between stopping before commitment and clearing after commitment.

Clean Up Your Resources

Clean Up Your Resources

Your offline simulator creates no ongoing costs. Your generated reports create no ongoing costs either.

Only new Claude API requests can add usage costs while your API key stays enabled. Decide whether to keep your resources running, pause them to come back later, or delete them entirely.

Cost warning

Live image analysis is billable. Choose Pause or Delete if you have finished making Claude API calls.

Resources you used:

  • Your Python source files in the current project folder.
  • Your pinned dependency file named requirements.txt.
  • Your Python virtual environment in .venv.
  • Your permitted local frame at frames/your-crossing-frame.jpg.
  • Your generated Markdown report at reports/safety_report.md.
  • Your generated HTML report at reports/safety_report.html.
  • Your six generated SVG files in reports.
  • Your personal API key in the Claude Console.

Keep everything running

No action is needed. Choose this if you want to keep testing the deterministic replays or generating visual reports.

  • Keep the source files plus requirements.txt in the current project folder.
  • Keep .venv available for the pinned Python packages.
  • Keep frames/your-crossing-frame.jpg for future permitted image analysis.
  • Keep reports so you can revisit the comparative timelines plus the commit-boundary sweep.
  • Keep the Claude Console key enabled only if you plan to make more live image-analysis requests.

Offline Replays Stay Free

The deterministic simulator plus the saved reports work without another API request. You only need the key when you run live image analysis again.

Pause - I'll come back to this later

End the active shell session while keeping every local artifact. Your source files plus generated reports remain ready for later.

macOS

  • Remove the credential from the current macOS shell and exit the virtual environment by running:
unset ANTHROPIC_API_KEY
deactivate
  • Close the terminal window from earlier.
  • Keep the current project folder so its source files plus reports remain available.

Windows

  • Remove the credential from the current PowerShell session and exit the virtual environment by running:
$env:ANTHROPIC_API_KEY = $null
deactivate
  • Close the terminal window from earlier.
  • Keep the current project folder so its source files plus reports remain available.

What Do These Commands Change?

The first command removes the credential from the current shell. The deactivate command exits .venv while preserving the environment on disk.

The personal key remains enabled in Claude Console for a future session.

Delete - I don't want to use this again

Deleting the local artifacts is permanent, so the commands target only files and folders named by this project. Claude Console key deletion is permanent too.

Choose Disable if you may return. Choose Delete only when you no longer need the credential.

macOS

  • Return to the project terminal from earlier.
  • Clear the credential and exit the virtual environment by running:
unset ANTHROPIC_API_KEY
deactivate
  • Remove the named project artifacts by running this command:
rm -rf .venv reports frames models.py planners.py report.py requirements.txt run_sandbox.py scenarios.py simulator.py sweep.py vision.py

Windows

  • Return to the project PowerShell terminal from earlier.
  • Clear the credential and exit the virtual environment by running:
$env:ANTHROPIC_API_KEY = $null
deactivate
  • Remove the named project artifacts by running this command:
Remove-Item -LiteralPath .venv, reports, frames -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath models.py, planners.py, report.py, requirements.txt, run_sandbox.py, scenarios.py, simulator.py, sweep.py, vision.py -Force -ErrorAction SilentlyContinue

What Does This Remove?

The selected command removes the virtual environment plus the local frame directory. It also removes the generated reports and every project source file.

Other unnamed files in the surrounding folder remain untouched.

  • Switch back to Visual Studio Code.
  • Check the open project folder.

You should no longer see .venv, reports, or frames. The project Python files plus requirements.txt should also be gone.

  • Visit the Claude Console API keys page.
  • Locate the personal key created for this project.
  • Choose Disable for reversible cleanup.
  • Choose Delete for permanent removal.

That closes the final external access point. The credential can no longer authorize live image-analysis requests.

Nice Work!

Nice Work!

You did it! You built an educational rail-crossing safety sandbox that separates multimodal perception from deterministic planning.

You've learned how to:

  • Created a typed multimodal perception adapter that turns one permitted local image into a validated Perception object. The typed contract keeps uncertain observations separate from planning decisions.
  • Compared a naive warning rule with a commit-aware planner across five deterministic replays. The comparison makes the post-commitment failure visible.
  • Produced a comparative Markdown report. Built a self-contained HTML report with five per-scenario SVG timelines.
  • Secret Mission: Mapped how speed plus available deceleration move the commit boundary in reports/commit_threshold.svg.

Ready to quiz yourself?