# @demlik/tea

A TEA / Elm-Architecture TypeScript library for durable, replayable state machines — one pure reducer, every host adapter.

## Using tea with a coding agent

The package ships `AGENTS.md`. Paste this line into your project's `AGENTS.md` or `CLAUDE.md`:

Before writing @demlik/tea code, read node_modules/@demlik/tea/AGENTS.md.

## Install

```sh
pnpm add @demlik/tea
```

The runtime dependencies are `@standard-schema/spec`, a types-only package, and
`fossil-delta`, a small package with none of its own that `@demlik/tea/do` uses to
store an event log's recordings; both are installed for you. [`Cmd.define`](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/glossary.md#cmd) takes any Standard Schema, so bring the schema
library you already use (zod as it is, or Effect Schema through the
`Cmd.make` that `@demlik/tea/effect` exports). The host and
testing adapters ride on optional peers you add only for the surface you use:
`react` / `react-dom` (the `./react` hooks), `ws` (Node WebSocket subs),
`fast-check` (the `./pbt` property-testing helpers), `vitest` (the testing
utilities), `effect` (the `./effect` engine), and `@opentelemetry/api` (the
`./otel` spans).

## Quickstart

A [machine](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/glossary.md#machine) is plain data: an `init` and an [`update`](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/glossary.md#update) map keyed by [`Msg`](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/glossary.md#msg) type.
[`run`](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/glossary.md#run) drives it, and when it has effects you hand `run` the [`interpret`](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/glossary.md#interpret) map
that performs them; [`dispatch`](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/glossary.md#dispatch) folds a `Msg`; `getState` reads the current
[Model](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/glossary.md#model). You name the Model and the `Msg` union
once, under `types`; everything else is inferred from the machine itself. Each of
these words has an entry in the [glossary](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/glossary.md).

```ts
import { defineMachine } from "@demlik/tea";
import { run } from "@demlik/tea/promise";

type State = { readonly count: number };
type Msg = { readonly _tag: "increment" } | { readonly _tag: "reset" };

const counter = defineMachine({
  types: { model: {} as State, msg: {} as Msg },
  init: (loaded) => (loaded !== null ? [loaded, []] : [{ count: 0 }, []]),
  update: {
    increment: (s) => [{ count: s.count + 1 }, []],
    reset: () => [{ count: 0 }, []],
  },
});

const runtime = await run(counter, {}).ready;
await runtime.dispatch({ _tag: "increment" });
runtime.getState(); // { count: 1 }
```

## Two engines, one machine

The core is `@demlik/tea`, and each [engine](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/glossary.md#engine) has its own entry point. A machine
file imports only the core, so it runs unchanged on either engine.

- `@demlik/tea` — the core: `defineMachine`, `Cmd`, `replay` and the types. It
  imports no engine.
- `@demlik/tea/promise` — the Promise engine. Handlers return Promises.
- `@demlik/tea/effect` — the Effect engine (`stable`, Effect v4). Handlers
  return Effects, services come from your Layers, the handle's verbs return
  Effects with typed errors, and closing the scope interrupts whatever is in
  flight.

[Run a machine on the Promise engine](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/how-to/run-on-the-promise-engine.md)
and [on the Effect engine](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/how-to/run-on-the-effect-engine.md)
build on the same machine file.
[Run many machines under one parent](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/how-to/run-many-machines.md)
starts child machines on the Effect engine with `spawn`, `tell` and `stop`.
Coming from 0.15?
[The migration guide](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/how-to/migrate-from-0-15.md)
shows every removed or reshaped API, before and after.

## React

`useMachine` from `@demlik/tea/react` returns `[state, send]`; `send(msg)` returns
`undefined` immediately, and the run's `onError` hears step failures once. A Msg
held at unmount or sent after stop reaches the sink as `DispatchDiscardedError`
under `phase: "discard"`. `useRuntime(run, { onError })` renders a booted run from
either engine, or a hand-built handle with a Promise-returning `dispatch`, with
the same `[state, send]` contract. Its optional sink hears discards and hand-built
dispatch failures; a run keeps its own step-error sink.
`useMachine` takes either engine's `run`. For the Effect engine pass
`runIn(runtime)` from `@demlik/tea/effect`, with your `ManagedRuntime`; its
`interpret` cells return an `Effect` and its `subscribe` runners a `Stream`, and the
lifecycle (one run per mount under Strict Mode, Subs paused on an `<Activity>`
hide, the run stopped on unmount) is the same.
`useRuntime(run, (model) => model.views[id])` reads one part and re-renders on runtime updates only when that selected value changes (`Object.is`).

`useBackgroundRuntime` from `@demlik/tea/extension` keeps `{ state, dispatch }`,
with a void-returning `dispatch`. Its optional `onError` hears transport failures
under `phase: "follow-up"`; background step failures go to the background run.
The context Provider and `useDispatch` follow the same contract.

Read the state for the outcome. Code that previously awaited a hook's `dispatch`
should remove the await; host code that needs to wait should own the run and use
its engine's `dispatch`, `idle`, or `done`.

[Drive a machine from React](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/how-to/drive-from-react.md)
shows click handlers, lifecycle behavior, and error sinks.

## Durability

With `fileStore` or `doStore`, state is saved before commands run. Restarting loads it.
`agent.run` resumes pending work automatically; custom machines handle a boot
message. An effect can run again if its result was not saved before the crash.

[Make a machine durable](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/how-to/make-durable.md)
and [understand restore versus replay](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/explanation/durability-model.md).

## Documentation

The four Diátaxis quadrants live in [`docs/`](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/README.md):

- [Tutorials](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/tutorial/index.md) — learning-oriented lessons that take you through the library by building a real machine.
- [How-to guides](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/how-to/index.md) — goal-oriented directions for getting a specific job done.
- [Reference](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/reference/index.md) — information-oriented API description, generated per public module.
- [Explanation](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/explanation/index.md) — understanding-oriented discussion of how it works and why it is shaped this way.

The [glossary](https://github.com/kamp-us/demlik/blob/main/packages/tea/docs/glossary.md) defines each word those pages use: Model, Msg, Cmd, Sub, Store and the rest.

The package ships these pages: an installed copy holds them in `node_modules/@demlik/tea/docs/`.

Two more surfaces sit behind those, for people working on the library rather than using it:
[`.patterns/`](https://github.com/kamp-us/demlik/blob/main/.patterns/index.md) is how the code is shaped, and
[`.decisions/`](https://github.com/kamp-us/demlik/blob/main/.decisions/index.md) is why it was shaped that way.
