Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
f93b24a
feat(game): zones watch world cells instead of polling them
patrickleet Oct 24, 2026
f903581
feat(game): settle zone facts in batches per lane and cell
patrickleet Oct 24, 2026
cd04f3e
perf(game): encode deltas once per patch, thin far update rates
patrickleet Oct 24, 2026
e4af194
fix(game): batch facts only for sinks that settle batches
patrickleet Oct 24, 2026
2053dc5
docs(cli): distributed-game skill for zones, facts and watches
patrickleet Oct 24, 2026
36054d8
feat(game): neighbours follow the player's view (observer Focus)
patrickleet Oct 24, 2026
da77ccb
refactor(game): opt into fact batches with one override
patrickleet Oct 24, 2026
7b9bef2
test(game): time Mob Pit room recovery after a celld crash
patrickleet Oct 24, 2026
a0d2051
feat(cell): run a fact batch under one command guard
patrickleet Oct 24, 2026
d909a0a
fix(game): never lose a fact to a cell without __batch
patrickleet Oct 24, 2026
1a27dda
feat(game): work counters for replication, facts and watches
patrickleet Oct 24, 2026
a61a9e0
feat(game): mobpit-load work lines and interleaved A/B runs
patrickleet Oct 24, 2026
310fdd5
Merge wsr/facts: one-override fact batches, batch replay test
patrickleet Oct 24, 2026
7c89cfe
feat(game): mobpit-load reports facts per request and deletes per fact
patrickleet Oct 24, 2026
682d93f
feat(game): negotiate protocol v2 with features and origin
patrickleet Oct 24, 2026
42def9e
feat(game): the SDK focuses placed neighbours from setPosition
patrickleet Oct 24, 2026
c9bc03b
Merge wsr/protocol: protocol v2 negotiation, placed auto focus
patrickleet Oct 24, 2026
2c6eea1
perf(game): no zone writes before a waking room's Welcome
patrickleet Oct 24, 2026
4548a8a
test(game): recovery bots rejoin as their room's own player
patrickleet Oct 24, 2026
2597bb6
Merge wsr/recovery: celld crash recovery harness, no writes before We…
patrickleet Oct 24, 2026
1168ad1
Merge wsr/counters: work counters, interleaved A/B, reconcile test
patrickleet Oct 24, 2026
e487715
fix(game): regenerate the Mob Pit client for hood/borough messages
patrickleet Oct 24, 2026
5a277a5
test(game): wait for each watched view in the bosses test
patrickleet Oct 24, 2026
01e000f
fix(game): regenerate the SvelteKit Mob Pit client too
patrickleet Oct 24, 2026
eccd9db
test(game): allow f32 rounding in the doorway jump bound
patrickleet Oct 24, 2026
45c922a
fix(game): retry a world push the zone could not take
patrickleet Oct 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 164 additions & 0 deletions distributed_cli/skills/distributed-game/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
---
name: distributed-game
description: Build authoritative game zones with distributed_game - a plain Rust Zone for the simulation, replicated entities with interest management, durable facts settled into cells, and zones that watch world cells as pushed read models. Use when writing or scaling a game zone, its facts, its replication, or its world cells (native host or celld).
---

# Game zones with distributed_game

A zone is a plain Rust struct that owns one authoritative simulation
(movement, physics, combat ticks). The framework hosts it, replicates it,
settles its outcomes and keeps it informed about the world. Game code holds
no storage, transport, retry or celld code. `distributed_game/README.md` is
the full reference; this skill is the shortest path to the common cases.

## The three rules

1. **Ticks are never stored.** Only meaningful outcomes leave the zone, as
*facts* (`ctx.emit`), and the tick never waits for them.
2. **Identity is bound by the host.** A fact's principal comes from the
player's verified ticket. Inputs never carry owner identity, XP amounts
or rewards chosen by a client.
3. **Read models are for display.** Watched world state flavours the zone
(weather, a boss tier, an event); rewards still go through the fact →
command path and are validated by the cell's handler.

## Facts: outcomes into cells

```rust
#[derive(Serialize, Deserialize, FactCommand)]
#[fact(command = RECORD_KILL)] // the same constant the cell mounts
pub struct RecordKillInput { pub mob: u32 }

// in a zone hook: never blocks, returns the key
ctx.emit(player, RecordKillInput { mob: id })?; // principal bound from the ticket
ctx.emit_zone(RoomAwakeInput { .. })?; // zone/system fact, no principal
```

Route facts once, where the host is built (celld: `CelldZone::fact_routes`):

```rust
sink.route(FactRoute::by_principal::<RecordKillInput>("crawler")) // crawler/{principal}
.route(FactRoute::by_input_field::<RoomAwakeInput>("borough", "borough"))
```

You get:
- **Exactly once.** The key (zone + boot epoch + parts) becomes the command
id, and the cell's ledger turns a retry into a replay.
- **Order per principal.** Facts of one player commit in emission order;
different players overlap (`max_concurrent_commits`).
- **Backpressure, not loss.** Past `capacity` unsettled facts, `emit`
returns `Backpressure` and the game decides what to do.
- **Batches by default on celld.** A lane's waiting facts for one cell go
as one `POST …/__batch` (`ZONE_FACT_BATCH`, default 16), and the zone
outbox clears them with one delete. A batch stops at its first retryable
failure and resumes from there, so order and exactly-once hold. A custom
sink opts in with one override, `FactSink::batches` returning
`Some(self)` as a `&dyn FactBatchSink` (its `commit_batch`); a host,
`FactHost::fact_batches` returning a `&dyn FactBatchHost`. Otherwise it
gets one fact at a time.

Results come back on a later tick in `on_fact_settled`.

## Replication: what each client sees

```rust
// one #[replicated] per view struct (Mob Pit: examples/game/server/rooms/src/zone.rs)
#[replicated(kind = "mob", id = 2, of = Mob)] // interest-managed
#[replicated(kind = "pillar", id = 3, global, of = Pillar)] // everyone, always
#[replicated(kind = "hero", id = 4, every_patch, of = Hero)] // never rate-thinned
```

- Clients see entities within their view radius, under a per-Delta byte
budget (4 KiB) ranked by priority. Deferred entities gain priority until
they are sent.
- Far entities update less often (`HostConfig::interest.update_rates`):
- within 0.5 of the radius: every patch;
- up to 0.8: every 2nd patch;
- beyond that: every 4th.

Creates and removes are never held. `UpdateRates::every_patch()` turns
the rates off.
- Interest across borders: place each zone in the world and give its
players' view radius, once:

```rust
fn origin(&self) -> Option<Origin> { // world = origin + zone-local
let (x, y) = self.room.room;
Some(Origin::new(f64::from(x) * 48.0, f64::from(y) * 48.0))
}
fn view_radius(&self) -> Option<f32> { Some(VIEW_RADIUS) }
```

The client then reports the player once per frame or tick
(`client.setPosition(p.x, p.y, me.zoneId)`). The SDK focuses every
watched neighbour on the player in that neighbour's coordinates. The
default `Zone::on_observer_focus` gives that watcher the same view
radius there. No coordinate math in the game. Zones without an origin:
`watchZones(...).setFocus(at)`.
- Each changed entity is encoded once per patch and shared by every client
that was up to date. A dense room costs selection plus copying, not one
encode per client.
- The wire format and the JS SDK's prediction are unchanged by these
knobs.

## The world around: watched cells (CQRS)

World cells (hood, borough, city, content rollout, dev settings) are the
write model. Each zone keeps a pushed read model of the cells it declares,
and each view decodes into a plain struct that becomes a normal zone
message:

```rust
impl CelldZone for MobPit {
fn watch(zone: &str) -> Watches<PitMessage> {
Watches::new()
.cell(HOOD_KIND, &hood_of(zone), |read: HoodRead| read.state.map(PitMessage::hood))
.cell(CITY_KIND, CITY_SHARD, |read: CityRead| read.state.map(PitMessage::city))
}
}
```

A cell opts in with one field and two calls:

```rust
pub struct HoodCell { cell: AggregateCell<Hood>, env: Env, watchers: CellWatchers }
// fetch: self.watchers.serve(&self.env, &self.cell, req, read_hood, sessions).await
// alarm: self.watchers.alarm(&self.env, &self.cell, read_hood).await
```

How it behaves:
- **Reads.** A zone reads each watched cell on wake. The read leaves an
in-memory lease on the cell; nothing is written.
- **Pushes.** The cell pushes `{topic, version, view}` after a commit or
alarm that changes the view. A heartbeat that only bumps the version
pushes nothing.
- **Ordering.** The zone applies only newer versions.
- **Repair.** The zone re-reads every 45 ± 15 s, which renews its lease
and repairs a lost push.
- **Sleeping zones.** A sleeping zone is never woken by a push.
- **Scale.** Cost grows with view changes × watchers, not with zones ×
seconds.
- **Other reads.** `refresh`/`refresh_every` remain for async reads that
are not cell views.

## Checking your work

- `cargo test -p distributed_game --all-features` runs the native host, the
facts, replication and interest management with in-memory sinks.
- `mobpit-load` (in `examples/game/server/examples`) measures:
- `--steps 32,64` for one room;
- `--steps 64x1,128x1` for many rooms;
- `--no-attack` for movement only;
- `--var KEY=VALUE` for a worker var on every run.
- Compare work, not wall clock. Each step prints a `work` line from the
rooms' `WorkCounters` (`GET /zones/{zone}/info` → `work`) and the
watched cells' `__watchers` counts: records encoded and sent per patch,
updates held by rates, bytes per frame, fact commands, cell requests and
outbox deletes per room-second, world reads and pushes per room-minute.
Counts do not depend on machine load; timings do.
- A/B one switch with interleaved runs of the same build:
`--ab VAR=VAL --pairs 3` runs A,B then B,A … (fresh celld each) and
prints the median of each side and of the per-pair change. Switches:
`ZONE_FACT_BATCH=1` (fact batches off), `ZONE_UPDATE_RATES=0` (update
rates off), `ZONE_WORLD_PUSH=0` (watched cells polled every second
instead of pushed). Read timings only as these interleaved medians.
9 changes: 8 additions & 1 deletion distributed_cli/src/skills.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub struct EmbeddedSkill {
pub files: &'static [EmbeddedFile],
}

static SKILLS: [EmbeddedSkill; 4] = [
static SKILLS: [EmbeddedSkill; 5] = [
EmbeddedSkill {
name: "distributed-usage",
description: "Build Distributed CQRS/event-sourced Rust services where you mostly write models and handlers while the framework and distributed generate persistence, transports, manifests, and deploy wiring. Use model-first TDD to specify plain aggregate behavior with fast unit tests before implementing models and thin handlers. Use when designing, testing, writing, or modifying a Distributed service or domain model.",
Expand Down Expand Up @@ -72,6 +72,13 @@ static SKILLS: [EmbeddedSkill; 4] = [
relative_path: "SKILL.md",
contents: include_str!("../skills/distributed-graphql/SKILL.md"),
}],
}, EmbeddedSkill {
name: "distributed-game",
description: "Build authoritative game zones with distributed_game - a plain Rust Zone for the simulation, replicated entities with interest management, durable facts settled into cells, and zones that watch world cells as pushed read models. Use when writing or scaling a game zone, its facts, its replication, or its world cells (native host or celld).",
files: &[EmbeddedFile {
relative_path: "SKILL.md",
contents: include_str!("../skills/distributed-game/SKILL.md"),
}],
},
];

Expand Down
2 changes: 1 addition & 1 deletion distributed_cli/tests/cli_skills_init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ fn init_bootstraps_a_fresh_project_and_reruns_are_noops() {
let agents_md = read(&dir, "AGENTS.md");
assert!(agents_md.contains(BEGIN) && agents_md.contains(END));
assert!(stdout.contains("created .distributed/skills/distributed-ci/SKILL.md"));
assert!(stdout.contains("Initialized 4 skills at .distributed/skills (wired: claude, agents)"));
assert!(stdout.contains("Initialized 5 skills at .distributed/skills (wired: claude, agents)"));

// No strays at the harness skill roots (only skill folders).
for root in [".agents/skills", ".claude/skills"] {
Expand Down
2 changes: 1 addition & 1 deletion distributed_game/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ celld = ["cell", "command-host", "dep:reqwest", "dep:uuid"]
workers-rs = ["cell", "dep:worker", "distributed/workers-rs"]
# Zones as celld Durable Objects (wasm32): `celld_zone::ZoneObject`,
# `CelldObjectHost` (facts object to object), `celld_zone_object!`.
celld-zone = ["cell", "ticket", "workers-rs", "dep:js-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"]
celld-zone = ["cell", "ticket", "workers-rs", "dep:js-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:futures-util"]
# Per-zone Prometheus metrics (dependency-free text exposition).
metrics = []
# Load-test bots (library + `game-bots` binary).
Expand Down
Loading
Loading