# Games as Effect components

> The programming model of a Minekube game: an Effect UI component with a Model, messages, an update function and Commands, children as failure boundaries, a scope per revision, and Java's failures as typed Effects.

Minecraft servers are programmed in Java. Minekube games are TypeScript with [Effect](https://effect.website), on the same Java API. This page explains the programming model, and why it carries most of what Minekube Games does beyond calling the API.

## Who writes the code

Often the code is written by your coding agent while you play, so the docs, the skill and the project template are written for agents as much as for people. The types tell an agent what exists, the strict check tells it when it guessed wrong, and Stories and replays test a change in seconds, all in Bun, without a JVM build in the loop.

## The model in one picture

A game is an [Effect UI](https://github.com/Effect-TS/effect/tree/main/packages/ui) component. Its shape is the one the Elm architecture made familiar: state changes only through messages, and side effects are data until a runtime carries them out.

| Part | Is | Where |
| --- | --- | --- |
| **Model** | The game's state, with a Schema | The rules |
| **Messages** | What happened, as a tagged union with Schemas (`UiSchema.TaggedEnum`) | The rules |
| **`init`** | The first Model, and the Commands to run at the start | The rules |
| **`update`** | One handler per message: the next Model and the Commands to run | The rules |
| **Commands** | What should happen, declared with `Command.Service` | Declared in the rules, implemented on the server |
| **Subscriptions** | Sources of messages, such as Paper events with `Game.event` | The server half |

An `update` handler receives `$`, a builder over the current Model:

```ts
update: {
  ClickedSign: ($, { player }) => {
    const count = ($.model.launches[player] ?? 0) + 1;
    return $.evolve({ launches: { ...$.model.launches, [player]: count } }).run(Launch.make({ player, count }));
  },
},
```

- `$.model` is the current Model.
- `$.set(model)` replaces the Model, and `$.evolve(fields)` changes some of its fields.
- `.run(command)` issues a Command. Return `$.model` when nothing changes.

The handler never calls Paper and never waits. It only decides. That is why a recorded message gives the same result when it is replayed months later.

## Commands

A Command is a declaration in the rules and an implementation on the server:

```ts
// In the rules: a name, its arguments, and optionally the message it answers with.
export class Launch extends Command.Service<Launch>()("launcher/Launch", {
  args: { player: PlayerId, count: Schema.Int },
}) {}

// On the server: an Effect that gets its services (here Paper) and returns the handler.
Launch.toLayer(Effect.gen(function* () {
  const { server } = yield* Paper;
  return ({ player, count }) => Effect.sync(() => { /* Paper calls */ });
}));
```

- **A silent Command** has no `success`. It acts on the world and returns nothing to the rules.
- **A Command with `success`** answers with a message, which goes through `update` like any other. The bot in [Test with bot clients](https://minekube.com/games/testing/bots) chains three such Commands.
- **A Command with `error`** declares a typed failure as a Schema, so the rules can react to an expected failure.
- **A Command runs as long as its Effect.** A trail of particles that repeats for a second is one Command. It is interrupted when the revision stops.

The server half provides the implementations as one Layer (`Layer.mergeAll(...)`) to `Game.mount`. In a Story, you answer each Command yourself, so the rules are tested without any implementation.

## Rules that run without Java

A game is an [Effect UI](https://github.com/Effect-TS/effect/tree/main/packages/ui) component with two halves:

- **The rules:** a Model, Messages, an `update` function, and Commands as declarations. They import no Java.
- **The server half:** Paper events become Messages, and Commands are implemented with Paper calls.

Because the rules never touch Java, they run in Bun. That is what makes the rest possible:

- **Stories** test the rules without a server: send Messages, check the Commands each step issues. `Story.explore` tries every order of a set of Messages up to a depth.
- **Recordings** are the Messages of a real session, encoded with the game's Schemas. `Story.fromLog` replays one through today's rules; the first Message that comes out differently is the failure.
- **Devtools and MCP** read the same entries: a timeline, the cause chain behind each entry, and what each Message changed in the Model. You see them in the browser, your agent reads them over MCP.

The [replay scene on Testing](https://minekube.com/games/testing/recordings#replays) shows one session go through this.

## Children are failure boundaries

A component can render other components as children. Every child is a failure boundary: when a child fails, it shows its `fallback`, the parent hears of it through `onFailure`, and the rest of the game keeps running. A child restarts when its `key` changes.

The runtime uses exactly this to keep your game alive. It mounts your game as the child of its own small component, the Supervisor, keyed by the number of restarts:

```ts title="packages/runtime/src/Supervisor.ts"
define(Supervisor).make({
  view: (h, model) =>
    model.stopped
      ? View.text("")
      : game(h, {
        key: String(model.restarts),
        props,
        onFailure: () => SupervisorMessage.FailedGame({ at: DateTime.toEpochMillis(DateTime.nowUnsafe()) }),
      }),
});
```

When your game fails, the Supervisor receives `FailedGame`, counts the restart and changes the key, so the game starts over from `init`. After more than three failures in a minute, it stops rendering the game until the next revision. The Supervisor is an Effect UI component like yours, so its decisions are recorded too: the game's instance path is `/Minekube/<Name>[<restart>]`.

Use the same tool in your game. Give per-player or per-arena state its own child, so that one player's bug does not restart everyone's round.

## A scope per revision

Everything a revision of your game starts, it starts inside its scope: listeners, timers, fibers and Commands. When the revision is replaced or uninstalled, the scope closes and all of it goes. There is no `onDisable` to forget and no listener left from the version before, which is what makes [swapping on save](https://minekube.com/games/local-development/live-swap) safe.

The same model pays off on the network side, where decisions wait on players:

- **Interruption.** A decision that waits for a server while its player leaves is interrupted and cleans up. With plain promises it would hang and run later for a player who is gone.
- **Time.** Every wait has a budget and a fallback, and `TestClock` plays "the server is gone for 30 seconds" in milliseconds.
- **Schemas as contracts.** The registry's messages are one Effect Schema, from which the Rust side's types are generated, so the TypeScript and Rust sides cannot drift apart.

## Java's failures, typed

Wrapping every Java call in an Effect would cost a `yield*` on every getter of more than 2,500 Paper classes, on the server thread, for calls that cannot fail in any expected way. Instead the generated types mark the calls where Java obliges you to do something:

- A method that **declares checked exceptions** cannot be called directly. `Jvm.attempt` turns it into an Effect whose failure is the declared exception, typed.
- A call that **hands you something to close** returns a `Resource`. `Jvm.acquire` opens it and closes it with the scope, at the latest when the revision stops.
- Anything else Java throws is a defect, a bug. The game starts over from `init` and the runtime reports it; one that fails more than three times in a minute stays off until its next revision, so a crash in `init` cannot loop on the server thread.

Nullability is in the types too: a `@Nullable` method returns `T | null`, and the strict check makes you handle it. See [Paper from TypeScript](https://minekube.com/games/write/paper-api) for the rules at the boundary.

## One strict check

Every project has one `check` script for you, your agent and CI: type checking and the Effect lint rules with Effect's `strict` preset, in a single invocation (`mk check`). `strict` turns Effect's default diagnostics into errors, so a mistake such as an Effect that is created but never run fails the check instead of reaching the server. Stories, replays and tests with real players are separate checks.

## Where Effect must stay out of the way

Effect is the language of the platform, not a toll on every line. A handler that only returns a value should not need Effect; Effect comes in where code waits, is interrupted or reads state. For network routing, which is planned, that is a design rule: a routing answer is plain data, such as "to the lobby" or "kick with this message".
