# Concepts

> Services, virtual objects, workflows, the journal and the three rules of handler code.

Source: https://cairnflow.dev/docs/concepts

## Invocations and the journal

Each call to a handler is an **invocation**. While it runs, every `ctx` command — a step, a sleep,
a call to another handler, a state write — is appended to the invocation's **journal**. When the
handler has to run again (after a crash, a deploy, or a wait), cairnflow replays it: commands that
are already in the journal return their recorded result instead of running again, and the handler
carries on from the first step that is not.

## Three kinds of service

| Kind | Declared with | Has state | Runs |
|---|---|---|---|
| Service | `service(name, handlers)` | No | Any number at once |
| Virtual object | `service(name, handlers, { type: "VIRTUAL_OBJECT" })` | Yes, per key | One exclusive handler per key at a time |
| Workflow | `workflow(name, { run, … })` | Yes, per workflow ID | `run` once per ID |

A **virtual object** is addressed by a key — a chat ID, a user ID, an order number. Its state belongs
to that key, and two exclusive handlers on the same key never run at the same time. That makes it
the natural home for a conversation: the agent's history lives in the object's state.

State (`ctx.get`, `ctx.set`) and durable promises exist only on virtual objects and workflows. A
plain service gets a `ServiceContext` without them.

## Durable steps

```ts
const receipt = await ctx.run("charge", () => chargeCard(amount));
```

`ctx.run` runs the closure once and records the result. On replay the closure is not called again.
The step's name is part of the journal: renaming a step between two deploys stops in-flight
invocations that reach it, so keep names stable and put configuration (model IDs, prompt versions)
in span attributes instead.

## Waiting

`ctx.sleep`, calls to other handlers, durable promises and signals end the current turn instead of
holding a connection. The invocation is suspended in storage and resumes when the result is there —
seconds or weeks later. Nothing runs and nothing is billed as compute while it waits.

## Errors and retries

- A normal error thrown from a `ctx.run` closure fails the turn, and cairnflow retries it under the
  handler's retry policy: completed steps are replayed, only the failed step runs again.
- `TerminalError` is for failures a retry cannot fix (bad input, a refused payment). It is recorded
  and can be caught, so you can compensate and carry on.

## The three rules of handler code

1. **Every side effect goes through `ctx.run`** (or a cairnflow wrapper such as `cairnTools`).
   The handler body runs again on every replay.
2. **No `Date.now()`, `Math.random()` or generated IDs outside `ctx.run`.** Replay must take the
   same path as the first run.
3. **Do not catch and swallow errors around `ctx` commands.** A suspended or failed turn stays
   suspended or failed whatever your `catch` does.
