Skip to content
Unverified: This page has not yet been anchored to automated code tests.

Golden Examples: Working Vox Code

Working code examples demonstrating Vox language features. Each .vox file is a complete, self-contained program validated by the CI pipeline. See examples/PARSE_STATUS.md for the latest parse matrix and examples/STYLE.md for contribution guidelines.


The smallest valid Vox program: a typed function that returns a string. Demonstrates the fn keyword, explicit return type, string concatenation, and return.

fn hello(name: str) to str {
return "Hello " + name + "!"
}

CRUD API — Table, Query, Mutation, and Endpoint

Section titled “CRUD API — Table, Query, Mutation, and Endpoint”

A complete data layer in one file. table generates the database schema, query wires a read-only resolver, and mutation wires a write operation — all with the Rust Axum backend generated automatically.

table User {
name: str
active: bool
}
query user_count() to int {
return len(db.User.all())
}
query all_users() to int {
// Returns count of all users; filter by active is application-side logic
let users = db.User.all()
return len(users)
}
mutation seed_user(name: str) to str {
db.User.insert({ name: name, active: true })
return "created"
}
query handler() to int {
return len(db.User.all())
}

Counter Actor — Stateful Concurrent Actor

Section titled “Counter Actor — Stateful Concurrent Actor”

Actors are isolated units of concurrency. This actor holds an integer counter in its state and exposes an Increment message handler that returns the new count. Spawning the actor allocates a mailbox and an address.

fn CounterActor_Increment(current: int) to int {
return current + 1
}

Checkout Workflow — Durable Execution with Error Handling

Section titled “Checkout Workflow — Durable Execution with Error Handling”

Workflows survive server restarts by journaling each activity result. The charge_card activity is idempotent and retryable. Pattern matching on Result makes both happy-path and error-path explicit.

activity charge_card(amount: int) to Result[str] {
if amount > 1000 {
return Error("Amount too large")
}
return Ok("tx_123")
}
workflow checkout(amount: int) to str {
let result = charge_card(amount)
match result {
Ok(tx) => "Success: " + tx
Error(msg) => "Failed: " + msg
}
}

MCP Tools — AI-Callable Tool and Resource

Section titled “MCP Tools — AI-Callable Tool and Resource”

The @mcp.tool decorator generates a Model Context Protocol tool schema from the function signature. AI agents (including Vox’s built-in DEI orchestrator) can discover and call these functions without any glue code.

tool "read_file: Reads a file from disk" read_file(path: str) to str {
return "file contents"
}
tool "file_uri: Echo path as a logical file URI" file_uri(path: str) to str {
return "file://" + path
}
@mcp.resource("vox://golden/mcp-status", "Static status blob for golden tests")
fn mcp_golden_status() to str {
return "ok"
}

Agent Pipeline — Multi-Agent Message Passing

Section titled “Agent Pipeline — Multi-Agent Message Passing”

Demonstrates an actor-based multi-agent system. TaskMessage is a structured message type. WorkerAgent receives HandleTask messages and tracks the number of processed tasks in its actor state.

type TaskMessage =
| Msg(id: int, payload: str)
fn data_agent_ready() to str {
return "Ready"
}
fn HandleTask(id: int, payload: str) to str {
return "Task " + str(id) + " done"
}

Dashboard UI — Layout, Components, and Routes

Section titled “Dashboard UI — Layout, Components, and Routes”

Full-stack UI composition. component declarations lower to plain React/TSX for the external frontend to import. layout wraps every route with shared chrome. routes maps URL paths to components.

type DashboardStatus =
| Loading
| Ready(data: str)
component DataChart(data: list[int]) {
view: column(raw_class="chart") {
text() { "Chart placeholder" }
}
}
component DashboardView() {
view: column(raw_class="dashboard") {
heading(level=1) { "Dashboard" }
DataChart(data=[1, 2, 3])
}
}

Type System — ADTs, Generics, and Traits

Section titled “Type System — ADTs, Generics, and Traits”

Demonstrates algebraic data types with a type parameter, trait definition, and impl block. AppResult[T] is a generic union type (Vox’s alternative to exceptions). The Serializable trait requires a serialize method.

type AppResult =
| Success(value: int)
| Failure(err: str)
fn serialize_app_result(r: AppResult) to str {
match r {
Success(val) => "num:" + str(val)
Failure(err) => "err:" + err
}
}

Test Suite — Fixtures, Mocks, and Assertions

Section titled “Test Suite — Fixtures, Mocks, and Assertions”

@fixture sets up shared test data. @mock replaces external dependencies. @test declares a test function. The |> pipe operator and len built-in demonstrate Vox’s functional style.

fn setup_user() to list[str] {
return ["alice", "bob"]
}
fn mock_db_read() to str {
return "mock_data"
}
@test
fn test_user_count() to Unit {
let users = setup_user()
assert(len(users) > 0)
let db_val = mock_db_read()
assert(db_val is "mock_data")
}

Config and Deploy — Environment Configuration

Section titled “Config and Deploy — Environment Configuration”

Typed configuration blocks and named environment definitions. config generates validated config structs. environment names deployment targets with typed key-value pairs.

type DatabaseConfig =
| DatabaseConfig(url: str, pool_size: int)
fn sample_database_url() to str {
return "libsql://example.turso.io"
}
fn prod_replica_count() to int {
return 3
}
fn prod_debug_enabled() to bool {
return false
}

Reactive component — state, derived, effect, lifecycle

Section titled “Reactive component — state, derived, effect, lifecycle”

Counter demo using the current component surface: state, derived, effect, on mount, on cleanup, and a view with click handlers.

/// Reactive counter demo (current `component` surface). Uses `on mount` / `on cleanup`
/// (not bare `mount:` / `cleanup:`). See `crates/vox-compiler/tests/reactive_smoke.rs`.
component Counter(initial: int) {
state count: int = initial
derived double = count * 2
derived label = "Count is " + str(count)
effect: {
print("count changed to " + str(count))
}
on mount: {
print("Counter mounted with initial=" + str(initial))
}
on cleanup: {
print("Counter unmounted")
}
view: column(raw_class="counter") {
heading(level=2) { "Count: {count}" }
text() { "Doubled: {double}" }
text() { "Label: {label}" }
button(on_click={count = count + 1}) { "Increment" }
button(on_click={count = count - 1}) { "Decrement" }
button(on_click={count = 0}) { "Reset" }
}
}

Narrow host HTTP helpers on std.http (dotted path; see parser tests). Suitable for scripting and smoke tests against real endpoints.

// Narrow `std.http` wrapper demo (`get_text` / `post_json`). Requires `http` to parse as a
// dotted path segment (see `parse_ident_name` / `parse_import_path`).
// RUNTIME: std.http performs real network I/O in BOTH `--mode interp` (blocking, on a
// worker thread) and `--mode script` (native codegen), so this example runs end-to-end
// in either tier. Failures surface as a typed `Result::Err`.
fn main() {
let ping = std.http.get_text("https://example.com")
let payload = "{\"source\":\"vox\",\"kind\":\"health\"}"
let posted = std.http.post_json("https://httpbin.org/post", payload)
std.log.info("std.http wrapper demo")
print(str(ping))
print(str(posted))
}

Small UI handlers using the mobile namespace pattern (onclick={fn() { … }}).

// Minimal notify demo — same handler shape as `examples/golden/mobile_camera.vox`.
import std.mobile
component App() {
view: button(on_click={fn() { mobile.notify("Hello", "From Vox!") }}) {
"Notify Me"
}
}

Bundled as /opt/vox/mesh-noop.vox in the Docker image for compose-based workers (vox run --mode script).

// Minimal script worker for mesh/compose examples (`vox run --mode script`).
// EXPECT: 0
fn main() to int {
return 0
}

Rosetta inventory (multi-language walkthrough)

Section titled “Rosetta inventory (multi-language walkthrough)”

Two golden files back the Rosetta inventory explanation: core merge + table in inventory_rosetta_core.vox, and actor / workflow / MCP / UI / capability layers in inventory_rosetta_platform.vox. Use that page for C++ / Rust / Python contrast snippets; Vox sections pull anchored regions from these files.