The Typeonce archive: written in 2024 and 2025, kept as it was. See what I build now

Trust your agent implementing your game with Ritmo ECS

@typeonce-dev/ritmo is a type safe ECS runtime built for coding agents. You are not supposed to read the code anymore, so here are the compile errors that make the agent's code trustworthy, from mildly useful to "how is this even a type?!"


This is ritmo, a type safe ECS runtime for TypeScript games.

Your coding agent writes the game code, and you are not supposed to read it. So this is not a tutorial.

Below are the mistakes ritmo refuses to compile, each with the real error TypeScript prints. If the compiler catches them, you can trust the agent's code and focus on the game.

What you'll see:

  • A short overview of ritmo
  • 14 mistakes that don't compile, from the simplest to the most surprising
  • What types can't catch, and the lint rules and devtools that do
pnpm add @typeonce/ritmo

Quick note from me, Sandro, the real human ✋

Agents are so good at ritmo, that I allowed one to draft and write this article:

Everything above and below this section is agent made ☝️👇

This is also to showcase how you should work with ritmo: the agent does the groundwork, you bring taste, ideas, and act as a reviewer 🎨


What ritmo is

ritmo runs the simulation of your game. Drawing, audio, and input stay in your code.

All the data is declared once, in a schema:

import { Descriptor, Schema } from "@typeonce/ritmo"

// Components: data attached to each entity
const Position = Descriptor.Component<{ x: number; y: number }>()("Game/Position")
const Health = Descriptor.Component<number>()("Game/Health")

// Tags: components without data, they mark what an entity is
const Player = Descriptor.Tag("Game/Player")
const Enemy = Descriptor.Tag("Game/Enemy")

// Resources: one value for the whole world
const DeltaTime = Descriptor.Resource<number>()("Game/DeltaTime")
const Score = Descriptor.Resource<number>()("Game/Score")

// Events: messages from one system to the others
const Damage = Descriptor.Event<{ readonly amount: number }>()("Game/Damage")

// Services: things your game provides to systems, like playing a sound
const Audio = Descriptor.Service<{ readonly play: (sound: string) => void }>()("Game/Audio")

// 👇 Systems, queries, and the runtime all come from Game
const Game = Schema.bind(Schema.fragment({
  components: { Position, Health, Player, Enemy },
  resources: { DeltaTime, Score },
  events: { Damage }
}))

Logic lives in systems. A system declares what it reads and writes, and receives only that:

const Heal = Game.System("Game/Heal", {
  // Spec: what this system is allowed to access
  queries: {
    // 👇 Every Player, with writable Health
    players: Game.Query({
      selection: { health: Game.Query.write(Health) },
      with: [Player]
    })
  }
}, ({ queries }) => {
  // Body: receives only what the spec declares
  for (const { data } of queries.players.each()) {
    data.health.update((health) => health + 1)
  }
})

Your game loop ticks a schedule of systems on every frame:

// The runtime holds the world
const runtime = Game.Runtime.make({
  // How this game plays sounds
  services: Game.Runtime.services(
    Game.Runtime.service(Audio, {
      play: (sound) => console.log(sound)
    })
  ),
  // Starting values of the resources
  resources: { DeltaTime: 1 / 60, Score: 0 }
}).value

// A schedule: the systems to run, in order
const update = Game.Schedule(Heal)

// Your game loop: tick the schedule once per frame, then draw
const loop = () => {
  const frame = runtime.tick(update) // 👈 runs every system in the schedule
  if (!frame.ok) console.error(frame.error) // a system failed: which one, and why
  drawGame() // your renderer
  requestAnimationFrame(loop)
}

requestAnimationFrame(loop)

Now let's break things.


1. The typo

Agents typo. Less than you, but they do.

const Move = Game.System("Game/Move", {
  // 👇 'resoruces' does not exist in type 'ExactAccess<...>'. Did you mean to write 'resources'?
  resoruces: { dt: Game.System.readResource(DeltaTime) }
}, () => {})

Specs are exact. A misspelled key is not silently ignored, leaving you to wonder why dt is undefined for 40 minutes.

The warm-up. It gets worse (better) from here.

2. Clock.hz(59.94)

Somebody read that NTSC runs at 59.94 Hz and got creative:

import { Clock } from "@typeonce/ritmo"

// 👇 Argument of type '59.94' is not assignable to parameter of type
//    '"Clock.hz needs a positive whole number of steps per second"'
const step = Clock.hz(59.94)

Same for Clock.hz(0). Your fixed-step loop will not divide by zero today.

Notice how the error is the parameter type. That trick shows up everywhere in ritmo.

3. Read means read

A query declares read or write for each component. The agent wanted to "just nudge" a position from a read slot:

const Nudge = Game.System("Game/Nudge", {
  queries: {
    // 👇 Position is declared as read
    moving: Game.Query({ selection: { position: Game.Query.read(Position) } })
  }
}, ({ queries }) => {
  for (const { data } of queries.moving.each()) {
    data.position.get().x = 10 // 👈 Cannot assign to 'x' because it is a read-only property.
    // 👇 Property 'set' does not exist on type 'ReadCell<{ x: number; y: number; }>'.
    data.position.set({ x: 0, y: 0 })
  }
})

Values from get() are deeply readonly. No mutation by reference, no "it worked in the test because the object was shared".

4. The callback only sees what the spec declares

The test asserts the score goes up. The agent wants the test to pass. You see where this is going.

const Move = Game.System("Game/Move", {
  resources: { dt: Game.System.readResource(DeltaTime) }
}, ({ resources }) => {
  resources.score.set(9999) // 👈 Property 'score' does not exist on type 'ResourceContext<...>'
})

A system can only touch what its spec declares. No sneaky writes to make a test pass, whether anyone is looking or not.

Nobody was going to read that body anyway. Now nobody needs to.

5. Wrong drawer

Events go in events, components in components. Your agent was in a hurry:

const Game = Schema.bind(Schema.fragment({
  // 👇 Damage is an event, not a component: move it to events: { ... }
  components: { Position, Damage }
}))

Not "type X is not assignable to type Y". The error tells you where to move it.

Declaring two components with the same name ("Game/Position" twice) is also rejected, with __schemaConflicts__: "components name \"Game/Position\"".

6. You forgot to plug in the speakers

A system plays a sound on every hit, so it declares the Audio service:

const PlaySound = Game.System("Game/PlaySound", {
  events: { damage: Game.System.readEvent(Damage) },
  services: { audio: Game.System.service(Audio) } // 👈 needs Audio to run
}, ({ events, services }) => {
  for (const hit of events.damage.all()) services.audio.play(hit.amount > 10 ? "crit" : "hit")
})

The runtime is created without it:

const runtime = Game.Runtime.make({
  services: Game.Runtime.services(), // 👈 no Audio here
  resources: { DeltaTime: 1 / 60, Score: 0 }
}).value

// 👇 __runtimeRequirementError__: "Missing service"; __requirement__: "Game/Audio"
runtime.tick(Game.Schedule(PlaySound))

See all the times you got Cannot read properties of undefined (reading 'play') the first time a player got hit? The compiler saw it before the player did.

Missing resources and state machines fail the same way.

7. Structural changes need a permission slip

Spawning, despawning, inserting, removing: all of these are commands. A system only gets commands if it asks for them:

// 👇 Empty spec: no commands declared
const SpawnEnemy = Game.System("Game/SpawnEnemy", {}, ({ commands }) => {
  // 👇 Property 'spawn' does not exist on type '"commands are not declared for this system:
  //    add commands: Game.System.commands(...) to its spec, with the permissions it needs
  //    (spawns, inserts, removes, despawns, despawnsScope, relates)"'
  commands.spawn(Game.Command.spawn([Health, 3]))
})

Read that again. The type of commands is a string that explains how to fix your code.

An agent reads that message and fixes it in one shot. That's the whole point of "agent-first".

8. Despawn by vibes

The agent "knows" the boss is entity 42. It has seen it in a log once.

const KillBoss = Game.System("Game/KillBoss", {
  queries: { enemies: Game.Query({ selection: { health: Game.Query.read(Health) }, with: [Enemy] }) },
  commands: Game.System.commands(Game.System.despawns(Enemy))
}, ({ commands }) => {
  // 👇 despawn needs an entity from a query proving Game/Enemy (declared in despawns),
  //    not a raw id: pass match.entity
  commands.despawn(42)
})

Despawn takes match.entity from a query that proves the entity has Enemy. No more despawning the player because the ids shifted.

9. Components that always come together

Some components make no sense alone. A Player without Health can never lose.

Say it once in the schema with requires:

const Game = Schema.bind(Schema.fragment({
  components: { Position, Health, Player, Enemy },
  requires: [Schema.requires(Player, Position, Health)] // 👈 a Player always has both
}))

Now the agent "forgets" one:

const SpawnPlayer = Game.System("Game/SpawnPlayer", {
  commands: Game.System.commands(Game.System.spawns(Player))
}, ({ commands }) => {
  // 👇 "Game/Player requires Game/Health: add the missing entries to the draft"
  commands.spawn(Game.Command.spawn([Player, {}], [Position, { x: 0, y: 0 }]))
})

The missing component, by name. Nothing filled in with a default behind your back.

The same check runs on insert and remove: removing Health from something that may still be a Player doesn't compile either.

10. The query that can never match

In plain TypeScript this is perfectly valid code. It runs fine, and does nothing. Forever.

const Lonely = Game.Query({
  selection: { position: Game.Query.read(Position) },
  with: [Enemy],
  without: [Enemy] // 👈 Game/Enemy is both required and excluded (without): this query can never match; remove it from one side
})

In most ECS libraries this is a silent no-op system. Good luck finding it in a 3000-line diff.

11. The state machine draws its own graph

An enemy's attack goes ready → windup → active → ready. Skipping the windup is cheating:

const Attack = Descriptor.EntityState("Game/Attack", ["ready", "windup", "active"] as const, {
  transitions: { ready: ["windup"], windup: ["active", "ready"], active: ["ready"] } // 👈 the allowed moves
})

const Strike = Game.System("Game/Strike", {
  queries: {
    attackers: Game.Query({ selection: { attack: Game.Query.write(Attack) } })
  }
}, ({ queries }) => {
  for (const { data } of queries.attackers.each()) {
    // 👇 Argument of type '"active"' is not assignable to parameter of type '"windup"'.
    data.attack.transition("ready", "active")
  }
})

The transition graph is checked at compile time. From "ready" the only way out is "windup", and TypeScript knows it.

Game-wide modes work the same: nextMachines.flow.set("Paused") on a machine with ["Menu", "Playing", "GameOver"] doesn't compile.

12. Every way a frame can fail, in one union

Expected failures are values, not exceptions:

const SpendHealth = Game.System("Game/SpendHealth", {
  queries: { target: Game.Query({ selection: { health: Game.Query.write(Health) }, with: [Player] }) }
}, ({ queries }) => {
  const target = queries.target.single()
  // 👇 Expected failures are returned, not thrown
  if (!target.ok) return Result.failure("TargetMissing" as const)
  const health = target.value.data.health.get()
  if (health <= 0) return Result.failure("AlreadyDead" as const)
  target.value.data.health.set(health - 1)
})

runtime.tick collects the failures of every system in the schedule:

const result = runtime.tick(Game.Schedule(SpendHealth))
if (!result.ok) {
  result.error // 👈 SystemFailure<"Game/SpendHealth", "TargetMissing" | "AlreadyDead">
}

But there is more! A failed system has its writes rolled back and its commands and events dropped. No half-applied frame where health went down but the hit never registered.

13. Order of systems, checked by the compiler

This is the one that made me stop and stare.

ShakeCamera must react to damage dealt in the same tick. Mark the read with thisTick:

const Deal = Game.System("Game/Deal", { events: { damage: Game.System.writeEvent(Damage) } }, ({ events }) => {
  events.damage.emit({ amount: 1 })
})

const ShakeCamera = Game.System("Game/ShakeCamera", {
  // 👇 Needs the Damage written in this same tick
  events: { damage: Game.System.thisTick(Game.System.readEvent(Damage)) }
}, ({ events }) => {
  // shake for every hit
})

Now the agent shuffles the schedule:

// 👇 Game/ShakeCamera needs Game/Damage from this tick, but its writer Game/Deal runs after it:
//    move Game/Deal before Game/ShakeCamera, or read Game/Damage without thisTick
runtime.tick(Game.Schedule(ShakeCamera, Deal))

The order of the arguments is a compile error. With the reader, the data, the writer, and two ways to fix it.

ritmo never reorders systems for you. It refuses to compile the wrong order.

14. The applyDeferred() you forgot

Commands are not applied until a schedule reaches Game.Schedule.applyDeferred(). Classic ECS footgun: you spawn a wave, then aim at it in the same tick, and the query is empty.

const SpawnWave = Game.System("Game/SpawnWave", {
  commands: Game.System.commands(Game.System.spawns(Enemy, Position, Health)) // 👈 can spawn enemies
}, ({ commands }) => {
  commands.spawn(Game.Command.spawn([Enemy, {}], [Position, { x: 0, y: 0 }], [Health, 3]))
})

const AimAtNewest = Game.System("Game/AimAtNewest", {
  // 👇 Needs the enemies spawned in this same tick
  queries: { enemies: Game.System.thisTick(Game.Query({ selection: { position: Game.Query.read(Position) }, with: [Enemy] })) }
}, ({ queries }) => {
  // aim at the wave that just spawned
})
// 👇 Game/AimAtNewest needs this tick's commands for queries.enemies, but Game/SpawnWave queues
//    them with no applyDeferred() in between: add Game.Schedule.applyDeferred() after Game/SpawnWave
runtime.tick(Game.Schedule(SpawnWave, AimAtNewest))

The compiler knows that SpawnWave can spawn something AimAtNewest matches (from spawns(Enemy, Position, Health)), and that nothing in between applies it.

How many hours have you lost to an empty query on the first frame? 🤔

AI won't lose them. And even if it does, ritmo won't let it ship.


Extra: what types can't see

Some mistakes are perfectly valid TypeScript and still break a game. ritmo has two more nets for those.

Lint rules for the source

@typeonce/oxlint-plugin-ritmo adds oxlint rules for the patterns types can't express:

pnpm add -D @typeonce/oxlint-plugin-ritmo oxlint

Below a system that compiles fine, and the lint reports on it:

const Wander = Game.System("Game/Wander", {
  queries: { moving: Game.Query({ selection: { position: Game.Query.write(Position) } }) }
}, ({ queries }) => {
  for (const { data } of queries.moving.each()) {
    const angle = Math.random() * 2 * Math.PI // 👈 ritmo/use-random-for-randomness: Math.random() cannot be seeded or saved, so the run cannot replay
    // 👇 ritmo/use-ops-for-math: Math.cos may return a different last bit on another browser or CPU
    data.position.update((p) => ({ x: p.x + Math.cos(angle), y: p.y + Math.sin(angle) }))
  }
})

// 👇 ritmo/handle-tick-result: The result of `runtime.tick(...)` is dropped
runtime.tick(Game.Schedule(Wander))

Every report names the ritmo API to use instead (Random.draw(resources.rng), Ops.cos, if (!ran.ok)). Same deal as the type errors: the agent reads it and fixes it.

Debug sessions for the run

NaN sneaking into a Position, entities that are never despawned, an event that nobody reads: those only show up when the game runs.

@typeonce/ritmo-devtools runs the game headless and answers questions as plain text, again built for agents first:

const session = Session.make(runtime, { hostClock, schedules: { setup, update }, invariants: [HealthNeverNegative] })

session.run("update", { frames: 300 }) // 👈 stops at the first violated invariant
session.why(12, Health) // 👈 latest changes to entity 12's Health, and which system made them

The agent debugs by asking why, instead of sprinkling console.log and asking you to "check the browser".


That's all!

You don't need to read anything. Talk with the agent about mechanics and feel, playtest, and let the compiler argue with the agent about the rest.

ritmo on GitHub

What it doesn't do

  • It doesn't draw. Rendering, assets, audio, physics stay in your game. ritmo provides bridges (@typeonce/ritmo-render, @typeonce/ritmo-pixi, @typeonce/ritmo-browser), not an engine.
  • It can't roll back the outside world. A failed system's ECS writes are undone, but a sound already played stays played.
  • Types don't see everything. Two systems' commands applied in the same applyDeferred() can still conflict at runtime: ritmo re-checks, skips the command, and reports it in a lint.

See the thinking behind the code.

Get one focused idea about type-safe software, AI-assisted development, and the architecture behind maintainable systems.

Join 1,000+ readers. Free, no spam, unsubscribe anytime. See the privacy policy.