Rust ScriptBots
ScriptBots is a modern Rust reimagining of Andrej Karpathy’s classic agent-based evolution simulator. Our goal is a faithful, deterministic port with a GPU-accelerated UI, pluggable brain implementations, and first-class analytics. This is a multi-crate Cargo workspace separating simulation core, renderer-neutral runtime protocol, brains, storage, rendering, and the application shell.
The authoritative roadmap is PLAN_TO_REARCHITECT_AND_REVIVE_RUST_SCRIPTBOTS.md. The older GPUI port plan is retained as historical design evidence, and a sibling WebAssembly plan lives in PLAN_TO_CREATE_SIBLING_APP_CRATE_TARGETING_WASM.md.
First-run Lab guide
The opt-in terminal and GPUI walkthrough connects the live world, organism
inspector, Pause, one scientific tick, a food-growth change, a fresh checkpoint,
and a control/intervention study. In the terminal, open it with F1 or
First-run Lab Guide in the command palette; Esc hides it while retaining
progress. In GPUI, choose First-run guide in the Lab window. Its action
buttons open the relevant tools, show the proposed growth change, and wait for
evidence before enabling Next. Hiding and reopening keeps the same journey.
Food-growth proposals are applied through the normal command path with owner
checks for the observed control, scientific, and configuration revisions. If
another client changes that boundary, the owner rejects the stale proposal.
A user-interface precheck alone cannot protect against that race.
Progress follows the actual owner, command identity, applied publication and
journal receipt. A memory-only commitment is labelled CommittedVolatile.
Saving requires a fresh request/result pair; the study must match that saved
cut and its verified two-arm report. Its outcome describes one seed and does
not establish a general effect. This is an optional guided path; automatic
first-install onboarding and full native acceptance under bd-2z0.10.4 remain
open. The guide's newly authored tests and native builds have not been executed
in the current implementation session.
Philosophy & purpose
- Why this exists: ScriptBots is a minimalist artificial life laboratory. By rebuilding the original simulator with rigorously deterministic Rust systems, we can observe, measure, and reproduce emergent behavior at scale—without undefined behavior or global state muddying results.
- What we learn: How simple sensory channels and local rules produce complex population dynamics—cooperation vs. predation, resource gradients shaping migration, lineage divergence under different mutation schedules, and the role of perception in survival.
- LLM-in-the-loop science: The REST API, CLI, and MCP HTTP server expose the full control surface (knobs, patches, snapshots). This lets an external LLM agent act as an autonomous lab assistant: steering experiments, sweeping parameter spaces, logging observations into FrankenSQLite, and drafting human-readable reports.
- Example workflows:
- Parameter sweeps: vary
mutation.{primary,secondary} and temperature gradients; record birth/death ratios and equilibrium populations.
- Interventions: toggle
closed worlds, inject carnivore cohorts, or freeze food diffusion to test resilience.
- Reporting: query or export FrankenSQLite tables to generate charts and tables describing discovered phenomena (e.g., altruistic giving thresholds that stabilize mixed diets).
- A brain testbed: The
Brain trait and registry allow swapping decision engines—handwritten controllers, MLP/DWRAON/Assembly, or NeuroFlow—while holding the environment constant. This enables fair comparisons of:
- Perception encoding (multi-eye vision, smell/sound/blood) and how architectures exploit them.
- Locomotion control (exact legacy two-rotation parity by default, selectable differential drive) and energy/health trade-offs.
- Evolutionary operators (mutation/crossover) and speciation pressures.
- Reproducible research: Deterministic pipelines + a growing replay roadmap mean results can be shared and re-run bit-for-bit, making the project a solid platform for pedagogy, papers, and benchmarking new brain designs.
Why this exists
- Determinism and safety: Replace legacy C++/GLUT and global state with idiomatic Rust, tightly audited platform-boundary
unsafe, and reproducible runs.
- Performance at scale: Data-parallelism (Rayon) and cache-friendly layouts to simulate thousands of agents efficiently.
- Modern UX: Declarative, GPU-accelerated GPUI interface with an inspector, overlays, and smooth camera controls.
- Observability: Persist metrics and snapshots to FrankenSQLite for replay, analytics, and regression testing while the UI consumes lock-free immutable read models.
- Extensibility: Hot-swap brain implementations (MLP, DWRAON, experimental Assembly, plus optional NeuroFlow) without rewriting the world loop.
Architecture at a glance
The workspace is organized for clear boundaries and fast incremental builds:
rust_scriptbots/
├── Cargo.toml # Workspace manifest, shared deps/lints/profiles
├── rust-toolchain.toml # Pinned nightly toolchain and required components
├── crates/
│ ├── scriptbots-core # Simulation core (WorldState, AgentState, tick pipeline, config)
│ ├── scriptbots-runtime # Sole-owner HostCore, protocol, fixed-deadline lifecycle, null frontend
│ ├── scriptbots-brain # Brain trait + base implementations (mlp, dwraon, assembly)
│ ├── scriptbots-brain-ml # Candle tensors, Tract probe, optional Frankentorch FtBrain
│ ├── scriptbots-brain-neuro# NeuroFlow brain (optional), feature-gated
│ ├── scriptbots-index # Uniform-grid index; alternate backends are not implemented
│ ├── scriptbots-storage # FrankenSQLite persistence worker & analytics snapshots
│ ├── scriptbots-render # GPUI integration and visual layer (World + tabbed Lab)
│ ├── scriptbots-world-gfx # wgpu rendering pipeline, WGSL shaders, offscreen readback
│ ├── scriptbots-bevy # Bevy ECS 3D rendering backend and entity simulation
│ ├── scriptbots-app # Binary crate wiring everything together
│ ├── scriptbots-analytics # Offline analysis, statistical aggregations, and experiment metrics
│ └── scriptbots-web # Sibling WebAssembly harness (wasm-bindgen bindings; experimental)
├── docs/
│ └── wasm/ # ADRs, browser matrix, multithreading notes, rendering spikes
└── original_scriptbots_code_for_reference/ # Upstream C++ snapshot for parity
Architecture diagram (high-level)
Data flows left-to-right; control surfaces are orthogonal and non-invasive:
┌───────────────────────────────────────┐
│ scriptbots-brain family │
│ (brain, brain-ml, brain-neuro) │
└──────────────┬────────────────────────┘
│ BrainRegistry (attach by key)
┌──────────────────────────────────────────▼──────────────────────────────────────────┐
│ scriptbots-core (WorldState, Tick Pipeline) │
│ - SoA AgentColumns · Spatial index (scriptbots-index) │
│ - Deterministic: sense → brains → actuation → persistence projection │
└───────────────┬───────────────────────────┬───────────────────────────┬─────────────┘
│ AgentSnapshots │ StepOutcome │ ControlCommand ↑ / disposition ↓
│ │ + Arc<PersistenceBatch> │
┌───────▼────────┐ ┌────────▼───────────────┐ ┌─────▼──────────┐
│ Renderer (GUI) │ │ HostCore owner │ │ HostCore │
│ GPUI window │ │ PersistenceAdmission │ │ command driver│
│ or Terminal TUI│ │ Session / tick boundary│ └─────┬───────────┘
│ (console text) │ └────────┬───────────────┘ │
└───────┬────────┘ │ admitted batch │
│ World snapshots ┌────────▼───────────┐ │
│ HUD metrics │ scriptbots-storage │ │
┌───────▼────────┐ │ StoragePipeline │ │
│ scriptbots- │ └────────┬───────────┘ │
│ render │ ▼ │
└────────────────┘ ┌──────────────────────┐ │
│ FrankenSQLite │ │
│ run-name.sqlite │ │
└──────────────────────┘ │
│
┌─────────────────────────────────────────▼────────────────────┐
│ scriptbots-app (orchestrator) │
│ - launches ControlRuntime (Tokio thread) │
│ - starts HostThread; shares ChannelHostPort with clients │
│ - selects Renderer (CLI flag/env) │
│ - seeds world, installs brains, primes history │
└───────────────┬───────────────────────────────┬──────────────┘
│ REST (axum + Swagger UI) │ MCP HTTP (fastmcp-rust)
│ /api/knobs /api/config │ tools: list_knobs,get_config,
│ /api/knobs/apply PATCH config │ apply_updates,apply_patch
│ │
│ │
┌──────▼───────┐ │
│ control_cli │ (reqwest; TUI watch) │
│ list/get/set │ -> REST │
└──────────────┘ │
│
┌────────────────────────────────────────────────────────────────────────────────▼─────────────┐
│ scriptbots-web (wasm) │
│ - wasm-bindgen: default_init_options/init_sim/tick/snapshot/reset/registerBrain │
│ - snapshot_format: json | binary (Postcard) · wasm-vs-native parity tests │
│ - feeds JS renderer (WebGPU/Canvas) │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
- Background workers:
HostThread owns the simulation's HostCore and fixed-deadline driver. StoragePipeline is a bounded-admission writer whose separate thread creates and exclusively owns its FrankenSQLite connection; ControlRuntime (Tokio) is separately isolated. A successful enqueue is not a durability receipt: flush or shutdown must acknowledge the earlier transactions. Frontends and control servers submit commands through ChannelHostPort; the host applies them at owner boundaries.
- Startup is fail-closed and transactional. Renderer selection and control-environment validation happen first, then every enabled REST/MCP socket is prebound and held before configuration output, auto-tuning, process-priority changes, world construction, or storage reservation. Launch consumes those exact listeners, so a bind failure cannot leave config, tuning, or run-database artifacts behind and cannot race a later rebind.
- REST and MCP run as supervised sibling tasks. An unexpected error or clean task exit stops the sibling, preserves the original failure as the root cause, and publishes failed runtime health; the TUI, GPUI, and Bevy frontends observe that health and terminate with the same root failure. Graceful shutdown joins both tasks and releases both listeners.
- That supervision guarantee covers ordinary returned errors and task exits. Debug/test builds use unwinding boundaries to exercise panic reporting, while the shipped
panic = "abort" release profile intentionally cannot recover from a panic or promise destructor-based cleanup after one.
- Frontends do not query FrankenSQLite or wait on a storage mutex during paint. The app transfers the scientific world to
HostThread; TUI, GPUI, Bevy, and live server transports use ports to that same owner. Both GPUI windows are presentation-only projections, and repaint cadence does not drive scientific ticks. Host lifecycle publications distinguish recoverable blockers, terminal faults, and completed shutdown. The obsolete GPUI science driver has been removed; its boundary-failure tests now exercise HostCore. Scheduled scenario patches use that owner during bootstrap and interactive execution. The bd-pcfj cutover is closed; broader client interaction, lifecycle and native qualification remain with their open frontend/runtime acceptance owners.
scriptbots-runtime owns the renderer-neutral command, two-axis status, snapshot, event-cursor, and manual-drive contracts plus the exact sole-owner HostCore. Command lifecycle schema v1 retains the exact envelope, client namespace/sequence, optional admission order, typed control/scientific/config guards, and contiguous application transitions; every terminal runtime outcome has a journal obligation. Its optional native-asupersync feature drives that same !Send host as one current-thread root future at absolute deadlines. Commands and journal-ready signals wake the owner, catch-up is bounded and reported, quiescent paused worlds have no periodic timer, and ordered shutdown retains its exact host and journal obligations without spawning or detaching a simulation task. The lifecycle persistence work is bd-2z0.5.2 (closed).
- Brain introspection is an explicit read-only projection, never a per-tick side effect. A client issues a revisioned request for up to eight stable
AgentUid values; core and each brain family enforce independent bounds for layers, names, values, edges, source scalars, and retained payload. Responses carry the exact source tick and typed unavailable/clipped status, while TUI and GPUI cache by client, stable identity, and source tick. With no request, no brain is inspected and NeuroFlow performs no inspection JSON serialization; digest-neutrality and next-output purity are tested across the supported families.