# Adding a workflow

> Generated from the SDK's own source (`docs/durable/adding-a-workflow.md`) at build; edit there.

## The file

```ts
import { defineWorkflow } from "@durable-sdk/core";

export const helloWorkflow = defineWorkflow({
  name: "hello.say",
  describe: "Greets an order once, from the store that placed it.",
  key: ["shop", "orderId", "requestId"],
  example: { shop: "s", orderId: "o1", requestId: "r1" },
  async run(ctx) {
    return ctx.step("hello.greet", async () => ({ ok: true }), {
      irreversible: "a log line cannot be undone",
    });
  },
});
```

The name is `<domain>.<verb>` (ADR-0060 decision 4: segments joined by
one or more dots, each opening with a lower-case letter and going on
with letters, digits and `_`; `name: "Order Notify"` and `name:
"order.Ship"` are refused at definition with the grammar in the
sentence), never opens with a prefix the core keeps for its own
workflows (`listener.`, `run.`, `runs.`, `event.`, `schedule.`, `undo.`,
`retention.`: `name: "run.notify"` is refused naming the owner, "the
operator actions (run.redrive, run.dismiss, …)") and is never one of the
core's two names under `relay.` (`relay.backfill`,
`relay.policy.override`: refused naming the operator action, in every
mode; `relay.ping` and `relay.pong` are the first host's own). A name is defined
once: a second `defineWorkflow` under it in one process throws
`WorkflowRedefined` naming both modules (the dev server alone, under
`reconfigure: "rebind"`, warns and replaces, so a hot reload keeps
working), and `on()` holds a listener name the same way
(`ListenerRedefined`). A step name (`ctx.step`, `ctx.poll`, `ctx.batch`,
`defineStep`, `defineExternalStep`) is `[a-zA-Z0-9._-]+` opening with a
letter or digit (`.` or `-` alone is no name): `#` and `:` are the
engine's (a poll's probe is `<name>#<n>`, a reconcile row
`<name>:reconcile`, a divergence row `<name>:diverged`), so `ctx.step("shipment#1", …)` is refused before the
body runs. The input type is inferred from `example` (spell `defineWorkflow<Input,
Output>` when you want it named), the output from `run`. The import is
relative (`@durable-sdk/core` from `app/lib/` or `app/workflows/`; the
repository has no `~` alias). Four whole products written this way, each
a few steps against the verbs below and run in `testDurable()`, are in
[Recipes](https://durablesdk.com/docs/recipes.md) (an order saga with compensation, a campaign
send in batches with tracking webhooks, an intake with a provider's
approval and a follow-up, a booking with reminders and a reschedule). One line elsewhere is needed: the
file's `import(…)` in `src/workflows/index.ts`, a thunk in its
`MODULES` list, so the resumer and the redrive know the name (the manifest
guard says so when it is missing). The explicit list is the manifest by
decision (ADR-0051 §1 as landed, 2026-10-01): the manifest guard
(the `workflow-manifest` guard) reads it as text and pins the
sequential loop below, the identity and replay guards load it through
`loadAllWorkflows`, and a glob would buy nothing. The manifest loads its
modules one at a time, the engine stub first; never turn the loop back into
a `Promise.all` (2026-09-29: with the modules concurrent, Vite's module
runner handed a definer the stub mid-evaluation and it read `defineWorkflow`
as `undefined`; the manifest guard holds the order). Then `npx durable-sdk doctor --host` proves the rest.

## What changed

Three things, all additive; every definition written the old way keeps
working unchanged, and nothing stored changed.

1. **The key is a field list.** `key: ["shop", "orderId", "requestId"]`
   becomes the function `(i) => "hello.say:shop=…:orderId=…:requestId=…"`,
   each part spelled over its **stored form** (the same walk the run
   store gives the input, so the live value and the stored copy key
   alike: a `Date` is its ISO string, a bigint its decimal, `NaN` is
   `null`, a `Map` its entries, a `toJSON` unwrapped): a string with its
   `%`, `:`, `=` and `~` **escaped** (`%25`, `%3A`, `%3D`, `%7E`; a gid
   reads `gid%3A//shopify/Order/1`), so two different inputs never spell
   one key and never share a run; a number or boolean as its decimal; a
   missing value (`null`, `undefined`) as `~`; and an object or array as
   its content hash (the ledger's own, over the canonical form, so
   property order never matters). Within a field a value is one JSON
   type, the input's own: `1` and `"1"` are not two parts of one field,
   and `null` and `undefined` are one (the stored copy drops
   `undefined`). A part the redaction policy would redact (a field named
   like a secret, `token`, `pin`, …; a credential's shape; a `Secret<T>`)
   is refused at key time, so `execute` answers `RunNotStarted` before
   any run exists: a secret never names an intent. Such a key reads fields
   and nothing else, so it cannot read the clock; the registered
   definition carries the function as `key` and the list as `keyFields`.
   The function form stays for a key that needs more (an upper-cased
   code, a hash of two fields together). An empty list is refused at
   definition. A field not on the input is a type error.
2. **`scope` and `summary` default.** Without a `scope` (or `shop`)
   resolver the definition reads the input's own `scope`, else its `shop`
   (most 3PL inputs name the store so), else nothing (the ledger partition
   is then the instance's `defaultScope`, `mky`, as before). A string
   counts and a `null` or absent field falls through; a `scope` or `shop`
   of any other shape (a number, an object) is refused by name, and
   `execute` answers `RunNotStarted` before a run exists, so a mistyped
   store field never lands a run in the default partition without a word.
   Without a `summary`, a list-keyed definition stores the key's fields as
   the run's input for display; a function-keyed one stores the whole
   input as before; a `summary` the definition names wins over both.
   Beside it, `tags` (ADR-0063 B33): a pure function of the input
   answering a flat string map (at most 16 tags, each value at most 64
   characters, no colon in a key), computed once at `beginRun`, stored on
   `WorkflowRun.tags` and never rewritten, what `GET runs?tag=k:v`
   (repeatable: every pair must match) finds through the GIN index and
   what the run page shows as chips (`tags: (i) => ({ job: i.jobId, site:
i.device.siteKey })` on the first host's `pick.start`, `pack.start` and
   `pack.complete`). A tag is never a key part: the key is the intent, a
   tag is what a person searches by. A map over the bounds is refused at
   definition over the example (`workflow.tags.invalid`) and at `execute`
   for every input (`execute.tags_invalid`, before any run exists).
3. **Steps are written inline.** `ctx.step(name, body, undo, input?)`
   builds the step and runs it through the same recorder as a defined one:
   replay by `seq:name` on a later attempt, the strict assertions, the
   compensation truth. `undo` is `{ undo: async (i, out) => …, effect }`
   or `{ irreversible: "why" }`. **A step with an undo declares what it
   changed** (ADR-0060 decision 2): beside `undo`, `effect` is required
   and is `"provider"` when the body calls a provider and hands its
   answer back (ADR-0051 "As landed (the strains)": the recorder then
   appends the call's row to the ledger itself, `provider/<step>`, the
   request as the row stores it and the answer, through the policy, and,
   when the saga ran the undo, a row reversing it, so a plain call with
   an undo is on the ledger without a spec or a pending write),
   `"ledgered"` when the body ledgers its own row, or `"external"` when
   it writes through a spec; never `"read"`, since an undo reverses a
   record and a read writes none. The type refuses the pair, and so does
   the door, in every mode, before the body runs: `card.charge: a step
with an undo declares what it changed; say effect: "provider" (a call
whose answer the ledger keeps), "ledgered" or "external"`. The same
   door refuses an undo whose body is blank (`undo: async () => {}`:
   `card.charge: compensate has no body; restore the before image or say
why with irreversible: '<reason>'`) and an `irreversible` with no word
   in it (`irreversible: ""`: `card.charge: irreversible needs a reason a
person can read on the Errors page, not ""`); `defineStep`,
   `defineExternalStep`, `ctx.poll` (under the poll's name) and
   `ctx.batch` (under the batch's) hold the same three rules. An
   `irreversible` step is `read` unless it says so (its reason can be "a
   look at the outside"), and under strict steps (on for every test) a
   `read` whose body appended a ledger row under the step's name fails
   the step (rows counted before and after the body, so a row of an
   earlier attempt or of an earlier step of the same name is not held
   against it; two inline steps may share a name, replay is by
   `seq:name`). The body sees
   the context (`i.runId`, `i.actor`, `i.shop`, `i.admin`, `i.signal`,
   `i.cancel`, `i.stop`, `i.deadlineAt`) merged over the `input` you
   pass, and `i` is typed from that input; a context key spelled in that
   input is the engine's to override. The three signals of a step
   (ADR-0063 B32): `i.signal` aborts with an `AttemptFenced` when the
   attempt loses its lease and on nothing else; `i.cancel` aborts with a
   `Cancelled` the moment a fenced touch (the heartbeat, a step boundary)
   reads a person's `run.cancel` on the run row; `i.stop` is the two as
   one (`AbortSignal.any([signal, cancel])`) and is what a provider call
   or a read passes, so a lost lease or a cancel ends it within a
   heartbeat, the step failing on the signal's reason (a `Cancelled` lands
   the run `cancelled by <actor>` with no signature, as a boundary cancel
   does). A write the provider cannot repeat goes through an external
   spec (`defineExternalStep`, `recordedWrite`) whose phases are handed
   their signal by the engine: `read` the stop, `write` the stop under
   `retry.idempotent: true` and the lease's signal alone under `false`,
   so a cancel never aborts a non-idempotent write in flight (it
   completes, and the boundary after it ends the attempt), and an undo's
   `i.stop` is the lease's alone, so the rollback a cancel asked for runs
   to its end. `i.signal` by itself is read by nothing but an attempt
   identity (the `step-bodies` guard holds the sites). A step's answer is its stored form on every attempt
   (ADR-0060 decision 8): `ctx.step`, `ctx.poll` and `ctx.batch` hand
   back `serializeStored(output).value`, typed `Stored<SO>`, on the
   attempt that ran the body as on the one that replays the row (a
   `Date` or a bigint its string, a `Map` its entries, a `Set` an array,
   a function or an `undefined` dropped from an object and `null` in an
   array, a body typed `void` answering `null`), so `out.createdAt.getTime()`
   is a type error and never a crash after a crash, a wait or a redrive;
   the undo sees the same form. A row the memo cannot serve (past the
   cap, or holding a value the policy redacts) hands the body the same
   walk uncapped and unredacted, since the next attempt re-invokes the
   step: a token minted inside a step reaches `ctx.reply` on the attempt
   that minted it. A recorded write's intent (its before and after
   images on the step row's `pending` list) is held to the same walk at
   the intent, before its call (ADR-0063 amendment 2026-10-08,
   `step.pending.unstorable`): a list the policy would redact or the
   row's cap (256 000 characters) would cut is refused by name and
   nothing is asked of the world, since the next attempt reconciles the
   write from those images; under `{ ledger: "chunk" }` a chunk's
   intents accumulate on its row until the flush and share that one cap,
   so size a chunk under it, and the intent that passes the cap is the
   one refused; the door judges every entry as stamped `refusedAt` (the
   one thing a rate park or a provider's refusal adds to a stored entry
   after its intent), so the size the verdict names is the stamped one
   and a stamp never carries an admitted list past the cap. A step that
   hands a moment on returns the ISO string
   and lets the reader `new Date(it)`; a Prisma row's fields go into a
   bounded plain object, never the row. On the first host a pick job on a
   step's output is `pickJobDelta(row)` (ADR-0060 decision 9, V06: the
   view's columns and counts, never its `lines`, a snapshot's list or a
   rider's name), `tote_transfer.create`'s orders are `JobRef`s, and the
   floor route reads `pickJobView` once more after the run into the
   delta's place (`withJobViews`); `pickJobView(` behind a step or
   workflow door, or `PickJobView` in its type arguments, fails the
   invariants guard (`job-view-off-step-outputs`).

## The sentence and the example

`describe` is one sentence, the intent in words (ADR-0060 decision 11):
what a run does, as the catalog (`GET catalog/workflows`, the row's
`describe`) and the console's Workflows page show it beside the name.
Every definition under `app/` carries one (the authoring guard lists one
without it).

`example: Input` is an input the workflow accepts: what the engine keys,
stores and re-keys as a run's input would, and what the identity guard
proves (there is no fixture map; every definition carries one). It must
key to the same string live and after `serializeStored` (a list key does
by construction; a function key must not read a `Date` or anything else
the serializer rewrites) and never through the clock. Write it as a
thunk, `example: () => Input`, when the value must be fresh at each read
or carries a secret by design (an operator's PIN, a pairing token): the
guard, the verifier and the catalog read it through `exampleOf`, called
at each read, so it never sits on the registry as data, and the catalog
serves it as every stored copy is served, through the redaction policy,
so a secret reads `[redacted]` on the wire. A listener needs no example:
its run's input is the fact row, keyed by the event's payload fixture in
`tests/fixtures/event-payloads.ts`.

Both fields are the definition's to carry under `createDurable({
definitions: "strict" })` (ADR-0060 decision 11, V12), the factory's
default for a new host: a definition without one is refused at
`defineWorkflow` with `DefinitionIncomplete`, naming the module, the
field and the remedy, and the definitions registered before the
configuration (the core's own, at import) are swept the same way, so the
boot refuses before any run. `bindDurable` and `testDurable()` default to
`"lenient"` (a test's ad-hoc definition needs no example). This host binds
`definitionsPolicy()` of `app/lib/env.server.ts` in `durable.config.ts`:
strict on a deployment and a laptop's `pnpm start`, lenient under a test
alone (the inverse of `steps`: under vitest the registry holds every
test file's ad-hoc definitions beside the manifest's, and the manifest's
completeness is the definitions guard's and the doctor's). There is no
fixture map: `tests/fixtures/workflow-inputs.ts` retired when its last row
moved onto its definition, and `tests/fixtures/event-payloads.ts` keeps
the listeners' payloads and builds their runs' inputs.

`world` is the rows the example needs (FW-022; ADR-0060 V12 as landed),
when the empty doubles do not hold them: `world: { host?: { <Table>:
[rows] }, engine?: { runs | keys | steps | entries | events | waits:
[rows] }, channel?: { fulfillmentOrders, stock, transfers, shipments,
fulfillmentStates }, providers?: { admin, mdm } }` beside the example, or
a thunk `world: () => …` where it must be fresh. `host` is the first host's
own tables by name (`WORLD_HOST_TABLES` of
`tests/helpers/world-tables.ts`: the bundle composer's `PickJob`, `Tote`,
`ToteTransfer`, `ToteTransferLine` and `Device`, the floor's `PickEvent`,
`ToteActivity`, `FloorUser` and `DeviceSession` since FW-040, and the
app database's `Warehouse`, `Shop`, `ShopLocation` and `SyncState` since
FW-040 and FW-042, each landed in its own double by its primary key; a
`ShopLocation` row may carry its `warehouse` object for the double's
`include`), each an array of rows in their stored form, the row's key
column present and no credential (a device's token hash left out, as a
bundle leaves it out) and no address (the policy redacts one by shape);
`engine` the engine's own rows by table, what `memoryStores().seed`
takes; `channel` what the fake channel answers (the fulfillment orders
by id, a location's stock by `<inventoryItemId>@<locationId>`, the
transfers and shipments the store already holds, the fulfillment
orders' states by id); `providers` what the other fakes answer (FW-042:
`admin`, the fake Admin's store behind `gql`, `AdminWorld` of
`tests/helpers/fakes/admin.ts`: the shop's record, the locations, the
metaobjects and metafields the store holds, the variant metafield
definitions, the variants a page walks; `mdm`, the fake MDM's records
as `fakeMdm().seed` takes them, `{ records: [{ id, serial, enrolled,
supervised, info, location, … }] }`). The double-run guard seeds it
through `t.seedWorld` after every reset it makes, the clean run and
each crash boundary, so the example meets the same rows at every
attempt and is proved at every boundary instead of listed; `pick.scan`
carries the first (the device, the tote and the job the scan reads),
since FW-040 every floor door does (`pick.*`, `pack.*`, `tote.*`,
`tote_transfer.*`, `pickup.*`: `floorWorld` over the builders of
`app/lib/floor-worlds.ts` and the sites every floor world shares), the
store's and the fleet's land with FW-042 (`app/lib/example-worlds.ts`
spells the fixture store, its locations, a phone at each site and the
fleet's record once; the definitions compose theirs), and a world lands
per domain as its doors are proved. The verifier holds its shape
(`world-shape`: the four parts alone, each table an array of row
objects, a host table the seeder accepts, the engine's tables by name,
plain data under the cap with nothing the policy redacts) and never
runs it; `doctor --definitions` prints `world: value | thunk` on the
definition's line.

The engine verifies its own definitions: `durable.verifyDefinitions()`
(`verifyDefinitions()` of the core) reads every registered example once
and judges it as the identity guard judged a fixture row, with no run, no
store write and no clock, answering findings as values (`{ workflow,
rule, finding, remedy, module }`) under `definitions/<rule>`:
`describe-missing`, `example-missing` (none, or a thunk that threw),
`example-unstorable` (decision 7's door, or past the stored input cap),
`example-names-context-key` (`attempt`, `actor`, `cancel`, `stop`,
`deadlineAt`, `priorAttempt`, `client` or `admin` in the input where the
key does not read it; `scope`, `shop`, `origin`, `runId` and `signal` an input names by
design, and a field the key reads is the intent's own, as
`pickjob.shipstation.match` keys its probe count as `attempt`),
`example-does-not-key` (the key throws, is empty, differs between two
calls or carries a redacted part), `example-does-not-rekey` (the stored
form keys elsewhere), `example-resolver-invalid` (`scope`, `scopeId` not
a string or null, or differing once stored; `summary` throws; `tags` no
string map within the bounds, differing once stored, or throwing, with
the tags' own remedy),
`example-cap-key-invalid`, `schedule-slots-key-one-run` (two slots key
one run, live or stored; the host's retention schedule the same for
`retention.apply`) and `world-shape` (the world's shape, above).
`durable.describeDefinitions()` says what each declares. The host's guard the `definitions` guard is the one
line of the suite that calls it (one `it` per rule, the rows in
the guard rules' registry), and `npx durable-sdk doctor --definitions`
runs that guard through the repository's vitest and prints the
declarations and the findings (`docs/runbook.md` "The doctor over the
definitions").

The input is storable by type (ADR-0060 decision 7): `defineWorkflow<I>`
holds `I` to `StoredInput<I>` (`packages/durable-core/src/stored.ts`),
so a field typed with the admin client (`Admin`, under any name: this
host declares it on the core's `ClientShapes` in
`app/workflows/workflow.server.ts`, the type-level twin of the policy's
`isClient`), a function (a client-shaped object of another type is
refused by its `graphql` member), a `Secret<T>`, a
`Date`, a `Map`, a `Set`, a bigint, bytes or a promise, at any depth, is
a compile error naming the field, what it is and the remedy (`Type
'AdminApiContext' is not assignable to type 'Unstorable<"a client; hand
it on execute options as client">'`). A string, a number, a boolean,
`null`, an optional, an array, a tuple, a plain object or an interface
of those, a JSON alias (`Prisma.JsonValue`, the shape of a `Json`
column; a hand-written recursive `JsonValue`), and a field typed
`unknown` (the host's own word, judged at the door) pass; a refusal
below the field carries its path in the message (`a Date at
.items[].at; …`). Every attempt after the first reads the stored form,
where none of the refused shapes survives: put a moment in the input as
its ISO string, a credential on execute options or read it inside the
step, and a computed value as data. The same rule holds the example. A
helper generic over the input spells the constraint itself, `function
make<I extends StoredInput<I> & { id: string }>(…)`, since the compiler
cannot prove a bare `I` storable. The type judges a declared shape, so
an `Error` (to the type `{ name, message }`, a shape a plain input may
spell) passes it and is refused at the door; the door judges own
enumerable fields alone, so a prototype getter or a method-only object
passes it and is the type's to refuse.

## `execute`, `requestId` and `executeOrThrow`

`execute(input, { actor, admin, requestId })` appends `requestId` to an
input without one before keying and storing (a route mints it and hands it
here in place of `{ ...body, requestId }`); the input's own is never
overwritten, and a list key that names no `requestId` takes none.
`execute` still answers a value (`describeResult` has the words).
`executeOrThrow(input, options)` is for a route that must not go on
without the output: it returns the completed run's output, memoized or
fresh, and throws `RunFailed { runId, status, error, result }` for every
other outcome, a run another caller is still running included (`status:
"in_progress"`, `error: null`; not a failure, but nothing to go on with:
a route that would rather wait passes `awaitMs`). `RunNotStarted` and
`KeyCollision` throw as before, before a run exists. A listener never
calls `executeOrThrow` (its outcome is a value; a throw is transport that
backs off), and the authoring guard holds it to that: under `app/` a call
of it stands in `app/routes/` alone, never in a module a listener could
import.

`execute` judges the live input at the door (ADR-0060 decision 7): it
compares the input with the form it stores for a resume, once, before any
run row exists, and throws `RunNotStarted` wrapping `UnstorableInput`,
which names the path and the remedy: `order.place: the input carries a
client at input.admin; hand it on execute options as client` (a client is
what the redaction policy's `isClient` names, the first host's `isClientLike`,
under any field name; the core names no shape of its own); `… carries
a secret at input.auth.token; a secret rides on execute options or is
read inside the step`; `… carries a function at input.probe; an input is
data, so the step computes what the function would`; `… carries a Date
at input.at; stored data holds its ISO string, which attempt 2 would
read; put the string in the input` (a `Map`, a `Set`, a bigint, bytes, a
promise, an `Error`, a `RegExp`, a non-finite number, a cycle, a
throwing getter, a nesting past the depth stored data walks, and a value
under the client slot `admin` or `client` the policy drops by name each
have their sentence). The door judges the live value whatever its size
(an input past the stored cap is judged the same, and the cap keeps its
own reason for what passes) and never throws anything but the refusal.
A cast past the type, a field typed `unknown` or a JavaScript caller
meets the same answer, and nothing is written: the store's counts are
what they were. `ctx.child` hands its input to the same `execute`, so a
parent whose child input carries a client fails at that step naming the
path and no child run exists. A credential the redaction policy blanks
by its key's name or by its value's shape (a `pin`, a `token` string) is
not the door's: the type cannot see a string, and the run would proceed
stored not resumable (`run.not_resumable`); the identity guard's
`SECRET_INPUTS` holds that set to exactly the workflows whose stored
input is redacted, and the set is empty since FW-043 (2026-10-09): the
four that carried one by design (`device.pair`'s pairing token,
`device.push_token.set`'s push token, `floor.login`'s and
`floorUser.upsert`'s PIN) moved it onto the channel below, so a
workflow that puts a secret in its input is red there, and the remedy
is the channel, never an entry.

A credential a run needs rides on execute options as `secrets` (ADR-0060
decision 7 as landed by FW-030, 2026-10-08): `execute(input, { actor,
secrets: { token: new Secret(token) } })`, a record of `Secret<string>`
by name, the inbound twin of `ctx.reply`. A step reads it as
`i.secrets?.token` (a `Secret<string> | undefined`: the type holds the
body to the check) and reveals it in the module that speaks the
provider's wire. The record rides on the attempt `execute` opened with
it and nowhere else: `secrets` is a `CONTEXT_KEYS` name, dropped by the
recorder from every stored step input and the memo's hash, never in the
input, never on `resumeInput`, so a resumed attempt (a crash, a wait, a
park), a redriven one and an undo's context read an empty record and the
body answers a value where the name is undefined; a step attempt 1
completed replays from its row on attempt 2 without the secret. Read it
before the first step's first provider call, or reveal it into that
call's own argument before `acquireToken` can park: a run parked before
or inside its first step (its cap's slot, the budget, a provider's
`rate` wait on an empty bucket, a retry past the budget) wakes as a
resumed attempt, without it, and the first step itself runs again
meeting the absence. A value that is no
`Secret` is refused before any run exists (`execute.secrets.shape`), and
an example naming `secrets` is refused by `durable.verifyDefinitions()`
as any context key is. The host's four ride it since FW-043
(2026-10-09): `device.pair` (`secrets.pairingToken`, the key on its
digest, the step revealing it against the digest; a resumed attempt
whose earlier attempt intended the spend reads the intent back by the
write's key, `i.priorAttempt.pending`, finds the row by the intent's
own resource and reconciles it, minting no second bearer),
`device.push_token.set` (`secrets.pushToken`), `floor.login`
(`secrets.pin`, a resumed or redriven attempt answering `{ ok: false,
reason: "pin_absent", retry }`) and `floorUser.upsert` (`secrets.pin`
behind the input's `setPin`, the absence answered as `refused`); each
reads the channel first in its step and answers a value where the name
is undefined.

## A schedule in four lines

A workflow that runs on its own clock (ADR-0050 decision 2) says so on the
definition; no cron route, no `vercel.json` entry, no bucket computed by
the caller:

```ts
export const digestWorkflow = defineWorkflow<{ bucket: string }, void>({
  name: "digest.send",
  key: (i) => `digest.send:${i.bucket}`,
  schedule: { every: "1h", input: (slot) => ({ bucket: slot.id }) },
  example: { bucket: "497000" },
  run: async (ctx) => {
    /* … */
  },
});
```

`every` is `"<n>s" | "<n>m" | "<n>h" | "<n>d"` (at least a minute), or
write `cron: "17 4 * * *"` (five fields, UTC). The core's `schedules` tick
task computes the slot once per cron tick (`slot.id` is the period's
index for `every`, the occurrence's ISO instant for `cron`; `slot.at` and
`slot.until` its bounds, `until` null for a cron whose next occurrence
lies past a year), fires `schedule.due`, and the core's
`run-schedule` listener executes the workflow with `input(slot)` under
`system:schedule:<name>` (`actor` names another). The key reads the
input alone, as ever: put `slot.id` (or `slot.at.slice(0, 10)` for a day)
into the field the key names, never `Date.now()`. Both are held at the
boot (ADR-0060 decision 5): a function key, a `scope`, a `scopeId`, a
`summary`, a `tags` or a `concurrency.key` whose source reads the clock or
randomness is refused at definition (`digest.send: key reads the clock
or randomness; put the moment in the input as requestId`), and a
schedule whose `input` keeps the slot out of every key field is refused
naming the key two slots would share (`digest.send: schedule.input must
put the slot in a key field: two slots key the same run
(digest.send:kind=hourly); use slot.id or slot.at in a field the key
names`), since the engine would reuse that one run for every slot, and
an `input` (or a key over it) that throws for the probe's slot is
refused with its message (`digest.send: schedule.input threw for slot
…: …; input is a function of the slot alone`): the slot is data, so an
input that throws for one slot throws for every slot of that shape. A
step body is never read there: a step body may read the clock, while a
run body between its steps may not (ADR-0044 §1 `body-no-clock-no-io`,
the guard `step-bodies/clock-outside-step`: `new Date()`, `Date.now`,
`Math.random`, `randomUUID`, `process.env` and the rest sit inside a
`ctx.step`, `ctx.batch`, `ctx.poll` or `ctx.waitFor`, an emit's payload
or a log line, never between the steps, since a body that branches on
the clock between two id'd steps walks other steps on the resumed
attempt; the moment is the input's, `slot.at` or a `requestId`, or a
read step's answer). `catchUp: 1` fires one
missed slot after an outage. The Workers page lists every schedule with
its last slot, last run and next fire ([Workflows](https://durablesdk.com/docs/workflows.md) "Schedules";
`docs/runbook.md` "A schedule that did not fire").

## A wait in one line

A workflow that must wait for a moment, a fact, a person or another run
parks instead of holding a function (ADR-0050 decision 3): one line in
the body, one `WorkflowWait` row, the run `WAITING` until it is woken as
the next attempt and the line answers what fired it.

```ts
run: async (ctx) => {
  await ctx.step(reserveStep, { id: ctx.input.id });
  await ctx.sleep("2h"); // a timer: { fired: "timer" }
  const matched = await ctx.waitFor("shipment.matched", {
    match: { id: ctx.input.id },
    deadline: new Date(instance().now() + 24 * 3600_000), // or `forever: true`, written out
  }); // a fact: { fired: "fact", payload }; WaitTimedOut at the deadline
  const ok = await ctx.waitForApproval<Decision>({ token: "approve" }); // { fired: "signal", payload: Decision }
  const out = await ctx.child(reviewWorkflow, { id: ctx.input.id }); // { runId, status, output }
},
```

A delayed fact whose reason is gone before its moment is cancelled by key
inside a step: `await ctx.cancelScheduled(packFollowupKey(shop, jobId,
cycle))` answers `{ cancelled: true, id }` or `{ cancelled: false, reason }`
(delivered, absent, not scheduled), ledgered under the run's actor; spell
the key once beside the emit (ADR-0050 amendment 2026-09-28).

A timer wakes its run at its moment (ADR-0063 B01: the park's `timer`
wake, a delayed queue message or a `setTimeout` held under `keepAlive`,
asks `GET /jobs/dispatch?resume=<runId>` inside the deploy window, the
resumer's claim-by-id; the tick's resumer sweeps the rest at the cron
minute); the
dispatcher wakes a fact wait when a local fact of that name matches the
`match` fields; a person wakes a signal from the console's Signal button,
`POST /admin/api/runs/:id/signal` or the MCP `run_signal`; a child's end
wakes its parent. A fact wait looks back before it parks (ADR-0060
decision 10): once its row stands, the park reads the facts of the name
the dispatcher took since the run began and fires the wait with the
newest match, so a fact quicker than the body never strands the run;
`since` moves that start later (the step the fact must follow), never
earlier; a fact an earlier wait of the run took on the same name and
match is never a hit again, so a loop that waits on one match waits for
the next fact each time; and `check` stays for what lives outside the
outbox (a change no fact recorded: the body's own re-read, run after the
park and not asked once the look-back fired). A look-back lost between
the park's commit and the fire (a crash) is made good by the tick's
sweep a minute later (`wait.lookback_swept`). A wait says how long it waits: a `deadline`
(from the input, a prior output or the bound clock, never a key), or
`forever: true` written out; neither is a type error and, cast past it,
a `StepError` at the door before any row. The drawback: a `WAITING` run
holds one `WorkflowWait` row and no function; nothing wakes a `forever`
wait but the fact or a person's `run.signal` under the fact's name; a
deadline that passes fails the step (`WaitTimedOut`: catch it by name,
never `RunParked`) and a redrive after it waits again on a fresh row with
the moment the body computes then. [Workflows](https://durablesdk.com/docs/workflows.md) "Waiting" has the
rules; `docs/runbook.md` "A run that never wakes" the remedies.

A long run parks by itself (ADR-0063 B02; ADR-0066 D04 to D06). Your
step runs inside one function invocation; the platform tells the engine
when it will kill that function, the engine keeps the last second of it
for its own rows (`i.budget.reserveMs`, `PLATFORM_RESERVE_MS`) and
everything before that is yours: `i.budget.deadlineAt` (the kill less the
reserve, or the attempt's lease when it comes first; `i.deadlineAt` is
the same moment), `i.budget.leftMs()`, both read live, and
`i.budget.signal`, which fires with a `BudgetEnded` at the deadline and
is part of `i.stop`. Pass `i.stop` to every call and call `i.yield()`
on every turn of a loop; to stop at the budget, throw: `i.yield()` throws
the stop's reason the moment it aborted (the `BudgetEnded`, a person's
`Cancelled`, a lost lease's `AttemptFenced`) and does nothing before, and
a call under `i.stop` ends with an `AbortError` you rethrow (the loop's
one line, ADR-0066 feasibility C10; FW-014). The step then parks the run
on a `continue` wait at itself, its row STARTED with its lines and its
intents, and runs again in a fresh invocation within seconds with any
write it had intended reconciled first (`run.parked_at_budget`); a body
that returns is complete, whatever it returned, so a catch never returns
a value or goes on before it rethrew the abort (`if (signal.aborted) throw
signal.reason`, `if (isAbortError(error)) throw error`, or a rethrow of
everything but the one shape the catch answers for, `if
(!isUniqueViolation(error)) throw error`, a shape the guard can prove no
abort takes: the predicates it admits are pinned abort-free, and a
`Cancelled` alone, a `.catch(` chain, a catch that neither throws nor
returns and a `return` in a `finally` each swallow the abort): a partial
value returned under `i.stop` would land the row COMPLETED and never run
again, and the guard `step-bodies/catch-returns-under-stop` refuses every
such shape before it ships.
Say how long a step needs and it never starts in a window it
cannot finish: `ctx.step(name, body, { needs: "30s" })` (also on
`defineStep`, `defineExternalStep`, a poll's probe and a batch's chunk;
`0` says start me with whatever is left, I read `i.budget`). At the
boundary before each step, when less of the budget is left than the step
needs (its `needs`, else `min(20 s, timeout)`, `STEP_NEEDS_DEFAULT_MS`)
and the platform knows the kill, the engine parks the run on a `continue`
wait at that step (no row for it yet), the timer's wake resumes it within
seconds in a fresh function, the landed rows replay and the step starts
(`run.parked_before_kill`). The most a step may hold in one invocation is
`userStepMaxMs`, the function limit less the reserve: a `needs`, a
`timeout`, a batch's `needs` or an external spec's `timeout` above it
is refused at the door naming the number. A step that ignores its signal
is killed by the platform at the limit; the attempt that reclaims the run
names it `FunctionKilled` on the cut step's row with the remedy, re-runs
it in a fresh invocation and reconciles its pending writes, the price
being the wait before the next attempt (the lease today). What a step
must tolerate: being the last before a park (its row COMPLETED, the next
not started; what it handed back is the stored form the replay serves)
and being the first after one (it starts fresh, at the same seq, in
another process: nothing in memory from the step before it survives, so
read what you need from that step's output, never from a closure's
variable). A batch keeps its own park (after the chunks in flight, over
the chunk's need), a wait step its own wait, and a laptop or the harness
with no known kill never parks this way (`i.budget.killAt` is null and
the deadline is the lease). The drawback: one more invocation per
function's worth of work, and a `WAITING` run on `continue` for the
seconds between the park and the wake ("continues at <step>" on the
Waiting tab).

## A query and an update in eight lines

A workflow with a state a person or an agent can read and change while
it runs (ADR-0076 FP-031; Temporal's Query and Update) declares the
handlers beside its body and keeps the state on `ctx.state`:

```ts
queries: { count: (state) => state.count },                     // GET runs/:id/query/count, no row written
updates: { add: { validate: (s, a) => { if (!(a.by > 0)) throw new Error("by > 0"); },
                  apply: (s, a) => { s.count += a.by; return { count: s.count }; } } },
run: async (ctx) => {
  ctx.state.count = 0;                                          // written at the next step boundary, in its own statement
  await ctx.step(reserveStep, { id: ctx.input.id });
  await ctx.waitForApproval({ token: "update", deadline });     // parks until an update lands
  await ctx.updates();                                          // one row: the values and the state after them
},
```

The validator runs in the route before any row (`POST runs/:id/update/:name
{ updateId, args }` is 409 by name when it throws), the update lands as
one `run.signalled` fact under its id (a resend the same run, never a
second), the body applies it once at its door whatever crashed, and the
route answers the value once the door's row landed (`in_flight` past
20 s: ask again under the same id). A query is one read of the run row
(`console.query.statements` is 1). The state is plain data under the
step-output cap, never a secret (`run.state.unstorable`); keep the
counts, the ids and the flags a query reads on it and the rest on the
steps' rows. [Workflows](https://durablesdk.com/docs/workflows.md) "Queries and updates" has the whole
contract.

## Durations, one grammar

Every duration a door takes is one string grammar (ADR-0064 P15, FW-066):
`"<n>ms"`, `"<n>s"`, `"<n>m"`, `"<n>h"` or `"<n>d"`, a whole number and
one unit, never a bare number (`Duration` of `@durable-sdk/core`, spelled
once in `engine/duration.ts`). A step's `timeout`, a retry's `delays` and
`backoff.base`/`.max`, a batch listener's `maxWait`, a poll's `every` and
`until`, `ctx.sleep`, the definition's `timeout` and a schedule's `every`
all read it; the platform's `maxDurationS` stays the adapter's seconds,
since it mirrors Vercel's `maxDuration`. The `*Ms` names the doors took
before (`timeoutMs`, `delaysMs`, `baseMs`/`maxMs`, `maxWaitMs`) are
`@deprecated` aliases for one release: admitted alone and folded onto the
word, refused by name beside it (`step.option.alias`,
`listener.option.alias`); the engine's own row keeps milliseconds
(`declared.timeoutMs` on the step row, the catalog's `StepDeclaration`),
so nothing moves on the wire. The strictness word is `steps: "strict" |
"lenient"` on `createDurable` beside `definitions` and `replay`,
`strictSteps: true | false` its alias under the same window. And every
door now reads its literal's keys: an option no door takes is refused by
name (`workflow.option.unknown`, `step.option.unknown`,
`listener.option.unknown`, `durable.option.unknown`), where a mis-spelled
option past the type (a cast, a spread of a loose object) was silently
ignored before. One block, every door:

```ts duration-doors.ts
import {
  defineExternalStep,
  defineStep,
  defineWorkflow,
  on,
  type Duration,
  type ExternalStepInput,
} from "@durable-sdk/core";

const perTry: Duration = "10s";

export const look = defineStep<{ id: string }, { seen: boolean }>({
  name: "look",
  invoke: async () => ({ seen: true }),
  irreversible: "a read",
  timeout: perTry,
  retry: {
    attempts: 3,
    delays: ["400ms", "2s"],
    codes: ["http_5xx", "StepTimedOut"],
  },
});

export const mirror = defineExternalStep<
  ExternalStepInput & { id: string },
  { v: number }
>({
  name: "mirror",
  irreversible: "the provider keeps the write",
  resource: (i) => ({
    shop: i.shop,
    resourceType: "thing",
    resourceId: i.id,
    operation: "update",
  }),
  read: async () => ({ v: 1 }),
  compare: (current, desired) => desired?.v === current.v,
  desired: () => ({ v: 1 }),
  image: (s) => s,
  write: async () => ({ v: 1 }),
  retry: { idempotent: true, classify: () => false, delays: ["400ms"] },
  timeout: "30s",
});

export const nightly = defineWorkflow<{ slotId: string }, void>({
  name: "guide.nightly",
  key: ["slotId"],
  describe: "walks the doors under one duration grammar",
  example: { slotId: "0" },
  timeout: "1h",
  schedule: { every: "30m", input: (slot) => ({ slotId: slot.id }) },
  async run(ctx) {
    await ctx.step("peek", async () => ({ ok: true }), {
      irreversible: "a read",
      timeout: "500ms",
      retry: {
        attempts: 2,
        backoff: { base: "250ms", max: "2s" },
        codes: ["http_5xx"],
      },
    });
    await ctx.poll("again", async () => ({ done: true }), {
      every: "90s",
      until: "10m",
      done: (out) => out.done,
      irreversible: "a read",
      timeout: "5s",
    });
    await ctx.sleep("1500ms");
  },
});

export const greeted = on(
  "run.failed",
  "guide-greet-batched",
  async (events) => {
    void events.length;
  },
  { batch: { maxSize: 100, maxWait: "5s" } },
);
```

## A retry that parks

A retry's next try runs inside the attempt by default: the saga sleeps
the delay out and parks the run on a `retry` wait only when the delay
would end past the attempt's budget (ADR-0063 B03). A transient that is
the process's own (a function instance that stood still, a socket pool
every call of which aborts late) is met again by that sleep, since the
next try runs where the last one failed. `resume: "park"` on the policy
(LB-004, ADR-0063 B03 amendment 2026-10-10) parks at every retry,
whatever the budget: the run lands `WAITING` on a `retry` wait at the
delay's end, holds no invocation, and the tick's resumer wakes it as
attempt + 1, where the step re-runs from its row with the count resumed
(`declared.retry.tries`), so a crash between tries never exceeds
`attempts`. Same row, same wake and same cap as the budget park; the
line `step.retry_parked` says `resume: "park"` for the word's park and
`"inline"` for the budget's. `resume: "inline"` is the default spelled;
any other word is refused by name (`step.retry.resume`). Declare it on
a read whose failures the audit traced to the invocation (a provider
read aborted at a timer that fired minutes late) and leave it off a
read whose transient is the provider's (a 503, a throttle), where the
inline sleep is the cheaper try.

```ts
retry: { attempts: 3, delays: ["30s"], codes: ["StepTimedOut"], resume: "park" }
```

## A read step's completion, behind

A step's boundary is two statements: the fenced insert that opens its
row and the completion that lands its answer on that row before the body
goes on, so a crash anywhere after it replays the answer from the row
and never reads the world again (ADR-0063 B22: a resync that read "not
installed" and crashed before the sync replays "not installed" into a
sync that skips, whatever the store looks like at the wake). That is the
default, `completion: "now"`, spelled or left out, and it holds for every
step. A `read` step may give the second statement up with
`completion: "behind"` (FP-011 as landed, ADR-0076 D05 (3) opt-in): the
recorder keeps its COMPLETED row in memory and the next step's fenced
insert carries it as a CTE of its one statement, the run's landing the
last, so a ten-step run of such reads sends 12 statements where the
default sends 22 (`throughput.statements.perRun`, the bench's ten-step
workflow opted in; the pin's knob and nothing else's). The price is the
knob's alone: a crash between the step's body returning and the next
boundary leaves its row STARTED, and the next attempt re-invokes the
read. Declare it on a read whose re-run costs nothing and decides
nothing (a pure computation, a lookup of a world that never moves) and
leave it off a read whose answer must stand once taken, where the
default's replay is the promise. The door holds the knob to
`effect: "read"` (`step.completion.effect`: a provider, ledgered or
external step's row is the proof the world was touched, so its
completion is never carried behind) and to the two words
(`step.completion.value`); a poll's probe and a batch's chunk take no
knob. The row's declaration carries it (`declared.completion`, the run
page's `completion behind`), the double-run proof admits an open row for
such a step alone and says so in its finding, and a provider write
inside one is the doubled side effect it names.

```ts
await ctx.step("order.lines", async () => countLines(ctx.input), {
  irreversible: "a count",
  completion: "behind",
});
```

## A lightweight run in one word

A run's rows are its memory: one row per step, the answer landed before
the body goes on, so a resumed attempt replays what the crashed one did
and re-invokes only what it did not finish. A body that reads and
computes and never writes has nothing to remember between its steps, and
such a body may say so: `defineWorkflow({ lightweight: true, … })` or
`on(event, name, body, { lightweight: true })` (ADR-0076 FP-038, D07).
A lightweight run is one run row and no step row: every `ctx.step` is a
`read` kept in memory for the attempt, the outputs landed on the run
row's `stepOutputs` with the finish (schema version 29; the list `[{ seq,
step, ms, output }]` in the stored form under the step output cap), the
facts in the finish statement as on every run, the key and the ledger as
they were. The price is the word's alone: a crash before the landing
re-runs the body whole on the wake (the resumer claims the run past its
lease and the body starts at its first line), and nothing of the first
attempt is served; two resumers racing for the claim move the attempt
once and report one resume, the loser's compare-and-set missing and its
answer the row as it stands, reported skipped whatever attempt the row
reached meanwhile (ADR-0076 FP-038 as amended 2026-10-13). So the door
holds the shape by name, each a
`REFUSALS` row under `lightweight.*`: a step with an `undo` or an
`irreversible` reason (`lightweight.step.declares`: every step is a
read), a recorded write or an external step (`lightweight.write`), a wait
of any kind (`lightweight.wait`: no row to park on), a child
(`lightweight.child`), a batch (`lightweight.batch`), a poll
(`lightweight.poll`), a hook with a handler registered on it
(`lightweight.hook.handlers`, the verifier's
`definitions/lightweight-shape`) and `ctx.cancelScheduled`
(`lightweight.cancel_scheduled`); the word itself is `true` or `false`
(`workflow.lightweight.shape`). The inline step's third argument takes
`retry`, `timeout`, `id`, `needs` and `onFail` and nothing else under
the word, and the type follows it: `ctx.step(name, body)` compiles under
`lightweight: true` and refuses an undo. The ten-step bench run reads 2
rows as a lightweight run where its durable twin reads 12
(`throughput.rows.perRun.lightweight`, `throughput.rows.perRun`, both
exact). Declare it on a counter, a projection, a lookup that answers a
fact or a quote the next run re-derives; keep it off any body that
touches a provider or a row, since a provider write inside it is made
again on the wake with nothing to reconcile it from (the double-run proof
names such a write at the finish boundary, the one boundary a
lightweight run has). The run page says `lightweight` beside the version
and lists the steps' outputs off the run row (API 2.142); the catalog row
carries the word.

```ts
export const quoteCount = defineWorkflow<
  { shop: string; requestId: string },
  { n: number }
>({
  name: "quote.count",
  key: ["shop", "requestId"],
  lightweight: true,
  async run(ctx) {
    const quotes = await ctx.step("quotes.read", () =>
      readQuotes(ctx.input.shop),
    );
    return { n: quotes.length };
  },
});
```

## A cap in one line

A workflow whose provider, or whose store, cannot take every run at once
says so on the definition (ADR-0052 decision 5), and the engine parks a
start over the cap as a `slot` wait admitted in start order as runs
finish; never a drop, never a retry loop:

```ts
concurrency: { max: 8, key: (i) => i.shop }, // at most 8 RUNNING per store; `key` optional
```

A provider call inside a step needs nothing: the provider client takes a
token from the account's bucket before every request (`app/lib/rate-limit.server.ts`),
waits inside the step for the refill within the attempt's deadline, and
parks the run on a `rate` wait past it; a `429` lowers the bucket for the
window the provider names. [Workflows](https://durablesdk.com/docs/workflows.md) "Concurrency" and "Rate
limits" have the rules; `docs/runbook.md` "A run waits for a slot" and "A
connector is rate limited" the remedies.

## A poll in four lines

A run that must ask the outside again until it answers polls (ADR-0050
decision 4): each probe is a step row, a miss writes nothing, the run
sleeps between probes, and the window ends as a value.

```ts
run: async (ctx) => {
  const found = await ctx.poll("shipment", (i) => lookUp(i.jobId), {
    every: "10m",
    until: "24h",
    done: (out) => out !== null,
    input: { jobId: ctx.input.jobId },
    irreversible: "a look at the outside",
  }); // the probe's output once done, else { timedOut: true, last }
  if (pollTimedOut(found)) throw new Error("no shipment within a day");
  found.id; // `done` was a type guard to the compiler, so `found` is the shipment here
},
```

The probes are `shipment#1`, `shipment#2`, … on the run page; between
them the run parks on a timer (`shipment#<n>:sleep`) and the tick's
resumer continues it; the deadline is `until` from the first probe's own
row, never the clock. `done` reads each probe's output in its stored
form (`Stored<SO>`, ADR-0060 decision 8) and the answer is that form. A
probe ledgers only under `effect: "ledgered"` with a body that appends.

For host rows a sweep watches outside any run (jobs without a shipment),
write a `dueScan({ name, select, delay, check, onHit })` and list it in
`tickTasks`: the core keeps what is watched and when to look again in
`DueItem`, a miss is one row of the pass's one update (`check` answers
`{ hit: false }`, or with an `error` to show on the row, or `{ hit:
false, retire: true, reason }` once the host no longer watches the key),
and a hit is your keyed workflow's run, keyed on the row's `createdAt`
so a repeat finds it ([Workflows](https://durablesdk.com/docs/workflows.md) "Polls";
`app/lib/rematch-scan.server.ts` is the 3PL's). Every scan's due page is
one statement a tick (the cron tick's pulse over the scans the process
registered at their definition, ADR-0076 FP-024) and the sweep of what
is a day past runs hourly, so a scan costs a quiet tick its record write
alone: list as many as the host watches.

## A batch in six lines

A step over many items (ADR-0052 decision 2) makes the chunk the unit:
one step row per chunk, the resume point after a crash, the console's row
and the compensation's unit; the items read through a cursor so nothing
sits in memory; and a park on a `continue` wait when the function's
deadline nears, so a batch of any size runs to the end on a function of
any limit (time) without a cron route or a state row of its
own. Under
`concurrency` the chunks in flight are a wave (ADR-0061 decision 1): a
park, whatever asks for it (the deadline, a provider bucket's refusal
inside a chunk), waits for the wave to settle and happens once, so the
siblings' work is never fenced away.

```ts
run: async (ctx) => {
  const swept = await ctx.batch(
    "placements.sweep.page",
    { next: (cursor, size) => readPlacementsPage(admin, cursor, size) }, // or an array
    { size: 100, needs: "120s", ledger: "chunk" }, // concurrency (≤ 8, with any undo; the chunks in flight are one wave, which every park waits for), needs (what a chunk needs of the budget to start, when over 20 s; `budget` in ms is its alias for one release), ledger ("chunk": the page's recorded writes land in one transaction at the chunk's flush)
    async (placements, index, i) => deleteOrphans(placements, i), // the chunk's body, its output on the row; `i.record(image)` ledgers an image under the chunk
    { irreversible: "a deleted orphan mirror is not restored", effect: "external" }, // or { undo(chunk, out, i) }
  ); // { chunks, items, outs, truncated? }
},
```

Each chunk is the inline step `<name>#<index>` with `{ index, cursor }` as
its input; its output carries the cursor after it, so a resumed attempt
replays the chunks done and starts the next from the recorded cursor;
`outs` are the chunks' outputs in their stored form (`Stored<O>`,
ADR-0060 decision 8), as the undo's `out` is. A
failed chunk fails the run and is not undone itself; the completed
chunks are undone in reverse with their items and outputs (`null` items
when the reader no longer reads the same chunk). Under `concurrency`
above one the chunks in flight are a wave under the attempt's one lease
and one signal (ADR-0061 decision 1): the next chunk starts once the
previous read answered its cursor; a chunk's `RateLimited` (a provider
bucket past the attempt's window) is held as a value while the siblings
complete (their rows COMPLETED, their flushes landed, the lease
untouched), and the batch then parks the run once on a `rate` wait at
the first refused chunk on the latest refusal's moment (one tick if the
bucket refilled meanwhile), the refused chunks re-invoked from their
STARTED rows on the wake; the deadline park waits for the wave the same
way, a failure or a fence among the siblings wins over either park, a
crash mid-wave leaves the wave's STARTED rows to the next attempt, and a
`RateLimited` in a step outside the batch while a wave is open parks at
once and fences the wave. Under a wave the chain's `seq` follows commit
order while the step rows keep index order: read the ledger by
`prevHash` and `seq`, never by chunk index (ADR-0061 U2). A chunk's output must
fit its row (the recorder's cap): keep it to counts, a cursor and a
bounded delta, never the items, or the chunk fails by name. A chunk's
ledger rows (ADR-0052 decision 4) land in one fenced transaction just
before its row completes: an image the body records (`i.record(image)`)
always, and its recorded writes when the batch says `ledger: "chunk"`
(each intent on the row before its call as always; the default keeps
them per write); the chunk's output then carries `ledger: { count,
firstSeq, lastSeq }`. Every recorded write of a chunk carries its own
`writeKey`, minted with the item's id in the second slot
(`writeKey("placement.set", id)`): two under one key in one chunk are
refused at the second's door in every mode, the chunk failing by name
(`<id>#<index>`) with the first write's intent still on its row
(`step.write_key.shared`; ADR-0060 decision 3). A key is a `WriteKey`
minted by `writeKey(base, id?)` (from `@durable-sdk/core`): the base
`<step>` or `<step>:<resource>`, segments of `[a-zA-Z0-9._-]+` joined by
`:`, the id the row's own, at most 200 characters, a plain string a
compile error at every door.
A step's output must replay from its row: one past the recorder's cap
(16 000 characters of stored JSON) or holding a value the policy redacts
is served to no later attempt, so the step re-invokes after any crash or
wait, and a `provider` step then calls its provider again. A batch chunk
fails on it at once (`BatchOutputNotReplayable`); every other step with
an effect other than `read` is counted (`step.output_unreplayable` on its
row naming the step, the effect, the verdict and the size; the Workers
page's "Unreplayable outputs" and the Overview's tile; ADR-0060 decision
9, whose refusal on the attempt that ran the body is gated on a zero
count after one release on beta). Return a bounded delta and put the
rest on the ledger; hand a one-time value back with `ctx.reply`, never
as output. The cap is `MAX_IO_CHARS` of `app/events/limits.ts` (spelled
once in the core's limits module), and the double-run guard holds every
registered example's step outputs under it on the fakes
(`output-bounded`: a clean run's row stored as the truncated preview is a
finding naming the step and the uncut size, before any boundary meets the
memo it lost; `tests/lib/rating-bounded.test.ts` proves `rate.shop` on a
seeded forty-line combined order, the shape beta's 43 hits had). A delta
is the ids, the moments and the columns a caller keys on: a pick job as
`pickJobDelta(row)`, never `pickJobView(row)` (the floor route puts the
view back after the run, `withJobViews`).
A body must also walk the same steps with the same inputs on every
attempt: a step inserted or reordered without ids moves every step after
it onto a seq whose prior row carries another name, and a step handed an
input read from the clock, randomness or a row outside a step moves its
hash; either diverges from the run's own rows, and since ADR-0063 B04 PR 2 the
memo refuses it under the definition's default replay policy: the step's
row lands FAILED `ReplayDiverged` before any re-invoke (the sentence on
the row names the seq and the prior row's name and attempt, or says the
input moved; `step.replay_diverged` under the row's logs) and the run
fails as any step failure does, to be redriven once the body is fixed.
`defineWorkflow({ replay: "lenient" })` keeps the older count-and-serve
for a definition that says so with its reason in the ADR (said on the
row as `step.name_changed` or `step.input_changed`, counted on the
Workers page's Pressure section, "Names changed" and "Inputs changed").
A `read` step re-invokes unsaid either way. Add a step at the end, never
reorder, give an id to a step that may move, and read what a step needs
inside it.
[Workflows](https://durablesdk.com/docs/workflows.md) "Batches" has the rules; the
first host's two batches are its catalogue sync and its orphan sweep (the
per-chunk ledger's proof).

## When to still write `defineStep` or `defineExternalStep`

- A **ledgered write** (`appendLedger`, `recordedRowWrite`, a
  compare-and-set on a warehouse row): `defineStep` with `effect:
"ledgered"`, its `compensate` reading the ledger row it wrote. Inline is
  allowed with `effect: "ledgered"`, but the undo is usually longer than
  the step, and a step object keeps the two side by side. A warehouse row
  written inside a step is a `recordedRowWrite` (ADR-0063 B06: the guard
  the `step-bodies` guard refuses a raw
  `warehouseDb.<model>.update(` in a `defineStep` or `ctx.step` body
  outside a `recordedWrite`'s `write` or `undo` callback; the floor's
  `transition()` and the scans' `writeLines()` in `app/lib/floor.server.ts`
  are the two shapes). Its fence is the compared columns and the row's
  `updatedAt`; a write whose compared columns are everything it owns on a
  row other steps write says `stamp: false` and is fenced on those columns
  alone, of the write and of its undo (`rate.shop`'s plan write, ADR-0063
  B06 amended 2026-10-04), while a write that sets a column its `compared`
  does not name keeps the stamp. **A write that may do nothing still
  reaches its key** (ADR-0029 amendment 2026-10-05): the engine judges the
  fate of an earlier attempt's write only through the same recorded write
  under the same key, and an intent the re-invoked body never reaches
  fails the step on every attempt (`step.pending_write.unreached`, a run
  no redrive completes), so a body never returns past its write once it
  has read the world. Judge first, as a value (the columns to write, or
  the row's own with the reason), then call the write once: the primitive
  answers the row's own columns `changed: false` and writes nothing, and
  the body reads its answer from the write's images (`result.before`,
  `result.after`), never from the row it read. A write that replaces a
  value whole, never a state, says `transition: false`, so a redrive that
  finds another run's value on the row records the divergence and goes
  on instead of failing `WriteDiverged`. **A divergence is never this
  run's write** (ADR-0063 amended 2026-10-05): it lands under its own row
  name, `<step>:diverged` (the world's image after the intent's before),
  which the undo never reverts (the verdict names it under `diverged`
  with the reason, `undo.run` leaves it alone and counts it), the next
  attempt never reads as a prior record of the step (it reconciles afresh
  from the world: the record took the carried intent off the row), and
  the drift read lists as `source: "diverged"` with the other writer's
  run as `movedBy` when the ledger names it; a reverter's judge may
  refuse the name from the row alone as a second lock (`rate.shop`'s
  does), never as the first. A body whose keys come from the world
  reaches what an earlier attempt left pending through
  `pendingWriteKeys()`. The guard
  the `step-bodies` guard reads the shape off every forward
  step body (`rate.shop` is the model: `judgePlan`, then the one write).
  **A compensation restores a row by
  compare-and-set** (ADR-0063 B21): `restoreRow(model, { writeKey, id,
expect, data, ledger })` in `app/lib/restore-row.server.ts` is the one
  shape, `expect` the after image (the columns the step wrote, as the
  client spells them in a `where`; a Json column is the stamp's), `data`
  the before image (as the client takes it: a `Date`, the model's own
  client's `Prisma.DbNull`, since the other generated client's goes out as
  the JSON `{}`, in a `where` as in `data`: the batch 6 regression of
  2026-10-09, ADR-0063 B06),
  `ledger` the undoing step's own name (`<step>.undo`), the resource and
  the forward row it reverses (`reversesId`, read through `forwardRowFor`
  before the row is touched). One compare-and-set on `expect` and the
  row's `updatedAt` as read, writing `data`: a row already at its before
  image is counted without a write, a row that moved is refused as
  `StaleWrite` naming the column (`status is "SHIPPED" now, the
compensation expected "PICKING"`), which the saga reports as the
  compensation's `failed` with the step named, so the run stays FAILED
  for a person and nothing is written over what a later actor did; the
  same guard refuses a raw `update` in a compensate body outside it
  (`step-bodies/compensation-cas`), and the console's undo holds the
  same sentence in the warehouse reverters. A **provider
  call with an undo** (a hold the provider releases, a charge it refunds)
  is inline with `effect: "provider"`: the recorder ledgers the call and
  the undo for it.
- An **external write** (a storefront, the shipping connector, the printer):
  `defineExternalStep`, whose phases (read, compare, write, image) and
  `writeKey` the saga drives; there is no inline form of it.
- A **step two workflows share** (`setToteStatusStep`, the storefront steps
  in `shopify-steps.server.ts`): a `defineStep` both import, so its name,
  effect and undo are declared once.

Everything else, a read, a log line, a value computed for the next step,
a fact prepared from what a step found, is an inline step.

## The listener, in ten lines

A listener body lives in `src/listeners.ts` (AGENTS.md; `on(`
at the top level of any other module is refused by the invariants guard);
`on` is in the primitives barrel for the tests (no glob manifest reads it:
the explicit `MODULES` list is the manifest by decision, ADR-0051 §1 as
landed). The registration reacts with the value form and never spreads
`ctx.admin` into a workflow's input:

```ts
on("order.paid", "greet-on-paid", async (e, ctx) => {
  const result = await helloWorkflow.execute(
    { shop: e.payload.shop, orderId: e.payload.orderId, requestId: e.key },
    { actor: ctx.actor, admin: ctx.admin },
  );
  if (result.status !== "completed")
    ctx.log.warn("greet.not_completed", { result: describeResult(result) });
});
```

(`e.shop` is `string | null` on every event; the store comes from the
payload, which `order.paid` carries as a string. The snippet compiles as
written: `tests/workflows/ten-line.test.ts` holds it against the catalog.)
Its run is `listener.greet-on-paid`, keyed by the outbox row; the
event's payload fixture in `tests/fixtures/event-payloads.ts` is its
example; `{ relay: "execute" }` on the registration says a relayed copy
runs it too (ADR-0040; default `record`).

`ctx.client` (`ctx.admin`, the alias) is the fact's scope's client
(ADR-0063 B22 PR 2): the dispatcher hands a listener run its own the way
the resumer hands a resumed run its own, through the bound session
factory's `lazyClientFor` (the first host's `lazyAdminFor`; a factory without
one hands a listener run no client), for a local fact of a scope alone (a
copy's run is handed none). The client opens its session on its first
call, inside the step that needed it, so a body that never asks reads no
session, and a store with no
session fails that step by name (`session.absent`); a body reads it with
`clientOf(ctx)` (from `app/workflows/context.ts`), the refusal
`run.client.absent` by name on a run handed none, and never opens one
itself (`unauthenticated.admin(shop)` is a read outside a step, refused
by the body-off-world guard). A listener reads the world through steps
and its client through the context: a read whose answer shapes a fact is
a `ctx.step("<domain>.read", …, { irreversible: "a read", effect: "read",
id })` answering the columns the fact needs, never a row with its lines.

## A batch listener, in three lines

A listener that would rather see a burst than a fact declares a window
(ADR-0052 decision 3): `fn` then takes the slice, one run over up to
`maxSize` consecutive facts of one partition, or fewer once the oldest
waited `maxWait` (the latency it trades for the batch):

```ts
on(
  "order.paid",
  "greet-on-paid-batched",
  async (events, ctx) => {
    ctx.log.info("greet.batch", {
      orders: events.map((e) => e.payload.orderId),
    });
  },
  { batch: { maxSize: 100, maxWait: "5s" } },
);
```

Its run is `listener.greet-on-paid-batched`, keyed by the slice's head
(`listener.<name>:<headId>`, FW-004: a slice re-formed from the same head
finds the one run, whose stored slice says which rows it reacted to), its
summary the slice; the fixture is the event's payload fixture as a slice of one
(`batchListenerInputFixture`); the Events page shows "batch of N" on
each row of the slice, with the one run. The body's type follows the
options, so a body over an array without `batch` (or `batch` on a body
over one fact) fails to compile. [Workflows](https://durablesdk.com/docs/workflows.md) "Events and the
dispatcher" has the slice rule in full; the 3PL's `mirror-product` is
the worked example (a burst of `product.updated` for one product syncs
it once).

## Changing a workflow with runs in flight

A run that parked on a wait, or that failed and waits in limbo, replays
its completed steps from their rows on its next attempt, under whatever
body is deployed then (ADR-0051 §15). Three tools keep that honest, each
for its own kind of change: a stable `id` on a step that may move, a
`version` bump when the old rows no longer mean what the new body
expects, and, since ADR-0076 D07 (FP-034), `ctx.patched` for a branch
that must replace another while runs are in flight. The rules:

- **Add a step at the end, never reorder.** The recorder replays a step
  by `seq:name` unless it carries an id: a step inserted in the middle
  shifts every seq after it, the next attempt misses every memo, and the
  steps after the insertion run again (the ledger's before image then
  refuses the second write, or the effect lands twice).
- **Give a step an `id` when it may move**, and give every step of a
  workflow that waits or has children an id from the start:
  `ctx.step("label", body, { id: "label", undo })`, `ctx.sleep("1h", {
id: "nap" })`, `ctx.waitFor(…, { id })`, `ctx.child(…, { id })`,
  `ctx.poll(…, { id })` (its probes are `<id>#<n>`, their sleeps
  `<id>#<n>:sleep`), `ctx.batch(name, source, { id }, …)` (its chunks are
  `<id>#<index>`, its parks `<id>#<index>:park:<n>`). An id is
  `[a-z0-9._-]+`, unique within the definition, checked at every door
  before the step runs; the derived ids carry `#` and `:`, outside the
  grammar, so a declared id never collides with one. The recorder replays
  the step by the newest prior row with that id whatever seq it sits at
  now, so an inserted step no longer re-invokes the ones after it; a wait
  step finds its parked row the same way whether the memo serves it or
  the wake invokes it (a deadline under `onTimeout: "fail"`, a child
  under `onFail: "throw"`).
- **Bump `version`** (`defineWorkflow({ version: 2 })`, a positive
  integer, 1 when absent) when a step's meaning changes, when one is
  removed, or when a compensate body changes what it undoes, and no patch
  can carry the change. The version is stored on every run at its start
  and compared by the resumer and the redrive with the deployed
  definition's; every run in flight under the old number lands FAILED and
  waits for a person.
- **Put a replaced branch behind `ctx.patched`** (ADR-0076 D07, FP-034;
  Temporal's `patched`) when a step is replaced by another and the runs in
  flight should finish under the branch they started, with no bump and no
  person: `if (await ctx.patched("invoice-v2")) await ctx.step("invoice.v2", …); else await ctx.step("invoice", …);`.
  The call runs between steps (never inside one, never inside a `ctx.all`
  member: refused by name) with an id of the step id's grammar. On the
  attempt that first reaches it, it answers true and writes a marker row,
  `patch:<id>`: a step row with no body, declared `read`, its id the
  marker's own (`:` is the engine's in a name and an id, so no declared
  step collides with it), one row whose COMPLETED rides the next
  boundary's statement, served by the memo on every later attempt and
  shown on the run page as `patch`. A resumed or redriven attempt answers
  what the run's rows say: the marker anywhere in the run → true; another
  step's row at this point (the attempt that parked walked the old branch
  past here before the deploy) → false, nothing written, the seq left to
  that step, the replay verdict untouched (`step.patch_old_branch` on the
  run); no row at this point (the frontier: the run parked before the
  patch) → true and the marker written. A second call under one id in an
  attempt answers the first's answer. The dance has three steps, as
  Temporal's: (1) deploy `patched` with both branches; (2) once no
  pre-patch run is open, deploy `ctx.deprecatePatch("invoice-v2")` with
  the new branch alone behind it, which serves or writes the marker as
  `patched` does and is refused as a value (`PatchStillOpen`, the run
  FAILED with the remedy on its row, nothing of the new branch run) while
  a RUNNING or WAITING run of the definition carries no marker (one
  statement, `runs.openRunsWithoutStep`, this run excluded) or while this
  run itself walked the old branch; (3) once that deploy landed, remove
  the call: a marker a body no longer asks for is skipped by the step
  after it, which takes the next seq (`step.patch_marker_skipped`), so
  the rows after it align. A rollback to the patched body after step 2
  reads the marker the deprecation wrote and takes the new branch.
  `tests/durable/workflow-patching.test.ts` proves each sentence; the
  double-run guard proves the fixture `guard.patched` at every boundary.
- **Read the world inside a step, and give a loop's step an id.** An
  awaited `warehouseDb.`, `db.`, `channelFor(`, `connectorFor(`,
  `unauthenticated.admin(`, `adminForShop(`, `mdmFor(` or `notifyFor(`
  call in a run body, a listener body or a helper handed their context
  (`ListenerContext`, `BatchListenerContext`, `WorkflowContext`) sits
  inside a `ctx.step` (`{ irreversible: "a read", effect: "read", id }`:
  the answer replays from its row, where the body's read would run again
  and walk other steps than the crashed attempt did), and a `ctx.step`
  inside a loop or a `.map`/`.forEach` callback spells `id` per iteration
  at the call (the inline form's third argument, a defined step spread
  into `{ ...step, id: \`sync-${stepIdPart(gid)}\` }`, `stepIdPart`of`app/lib/step-id.ts`), both held over `app/`bythe `step-bodies` guard(ADR-0063 B22; today's sites are`BODY_OFF_WORLD_HOLDOUTS`, exact both ways and only shrinking), which
does not see a read through a helper handed no context, a connector
held in a variable, a `Promise.all`, a step in a helper the loop calls,
or an `id` in an options variable.

What a run in flight sees at each:

- **A new step at the end:** the completed prefix replays, the new step
  is invoked. No id, no bump.
- **An inserted step, with ids:** the steps before and after it replay by
  id, the new step is invoked once. No bump.
- **An inserted step, without ids:** the inserted step meets the earlier
  attempt's row under another name at its seq, and the memo refuses it
  (ADR-0063 B04 PR 2, `ReplayDiverged`): its row lands FAILED before any
  re-invoke, nothing after it runs, and the run fails as any step failure
  does (a step this attempt served with an undo is undone). Bump the
  version (an id on the inserted step alone does not help: the rows
  behind it carry none), redeploy, and redrive. Under `replay: "lenient"`
  the steps after it re-invoke with no prior row to reconcile against: a
  recorded write that finds its `desired` already in the world answers
  `changed: false` and records nothing (the first attempt's row is the
  record); a write of its own compare-and-set on the world refuses
  (`StaleWrite`); any other effect lands twice (a second label, a second
  message, a counter moved again).
- **A step renamed under its id, or a step's input that moves between
  attempts** (the clock, randomness, a row read outside a step): refused
  the same way, `ReplayDiverged` on the row with the sentence that says
  which; a `read` step re-invokes unsaid. Fix the body (the step's input
  a pure function of the run's input; the read inside a step with an id)
  and redrive.
- **Ids added to a workflow with runs in flight:** the id-less rows key
  `seq:name` and the steps now key `id:<id>`, so every completed step
  re-invokes once on the next attempt, as an insertion without ids would
  under `lenient` (the wait itself is found, by its own seq and name);
  the names at each seq are unchanged, so nothing is refused. Add them in
  a release that inserts nothing, or bump the version with them.
- **A branch behind `ctx.patched`:** a run that walked the old branch
  before the deploy replays it (the marker's question answers false at
  the old step's seq, which the old step then takes and is served from
  its row); a run parked before the patch point takes the new branch at
  its frontier and writes the marker; a fresh run writes the marker and
  takes the new branch. No `VersionMismatch`, no `ReplayDiverged`, no
  person. A deprecation deployed while such a run is open fails the
  fresh runs (`PatchStillOpen`, naming the open run and the count) and
  the woken old-branch run (`this run walked the old branch`), nothing
  re-invoked; redeploy `patched` and redrive them, or wait for the open
  runs to land and redrive the failed fresh ones under the deprecation.
- **A version bump:** every run in flight under the old version lands
  FAILED `abandoned: version 1 → 2` with no compensation attempted (the
  new undo bodies are not the old steps' inverses; the run's record says
  `skipped: "version mismatch"`), one cause on the Errors page for the
  whole deploy; a person redrives it under the new version from the
  console ("Accept version 2" on the run, "Redrive under version 2" on
  the cause) or dismisses it. A redrive without the acceptance is refused
  `version 1 → 2`; a stale acceptance (read before the next deploy) is
  refused naming the number. An attempt already executing the old body
  finishes under it; only the next attempt compares. A rollback is a bump
  the other way: a run stored under 3 after 2 is registered again lands
  `abandoned: version 3 → 2`, is refused `version 3 → 2`, and is accepted
  with `acceptVersion: 2`.

`tests/durable/workflow-versioning.test.ts` proves each sentence on the
harness; `docs/runbook.md` "Runs in limbo and redrive" has the operator's
side.

## A run that outgrows its history

A run replays its completed steps from their rows on every attempt and
every wake walks every row it has, so a run of thousands of steps pays
more per step the longer it lives (0.6 ms per step at step 10, 0.9 to
1.0 at step 1 000 across ten wakes: the `continuation` bench family's
before). A run that walks a cursor, a page or a day of work at a time
closes itself and goes on as a fresh run under the same key (ADR-0076
FP-032):

```ts
export const walkCatalog = defineWorkflow({
  name: "catalog.walk",
  key: ["shop", "walkId"],
  describe: "Walks a store's catalog a page at a time, one run per page.",
  example: { shop: "veiled.myshopify.com", walkId: "w1", from: null },
  async run(ctx) {
    const { shop, walkId, from } = ctx.input;
    const page = await ctx.step("page", () => readPage(shop, from), {
      irreversible: "a read",
      effect: "read",
      id: "page",
    });
    await ctx.step("apply", () => apply(page.rows), {
      undo: () => revert(page.rows),
      effect: "provider",
      id: "apply",
    });
    if (page.next !== null)
      await ctx.continueAsNew({ shop, walkId, from: page.next });
    return { walked: page.rows.length };
  },
});
```

- `await ctx.continueAsNew(next)` after a step and never inside one (a
  step, a batch chunk, a poll probe, a hook handler, a `ctx.all` member:
  `continue.inside_step`, `continue.inside_all`). The call never returns:
  the run lands `CONTINUED` naming the next run, which starts at once in
  the same invocation with the input handed and its steps from seq 1.
- The next input keys to the same key: `from` above is no key field
  (`continue.key.moved`), and `shop` stays (`continue.scope.moved`).
- `{ carry: "state" }` carries the run's declared state (`ctx.state`,
  FP-031) onto the next run; without it the next run starts with none.
- The chain is one intent: `execute` of the same input again answers the
  newest run's outcome, `GET runs/:id` of a closed run says `continued
into run <next>` with `continuedFrom` and `continuedTo` on the detail,
  the run page links the chain each way, and `verifyLedger` is green
  across it. A closed run is landed: not in limbo, never redriven,
  dismissed, cancelled, held or undone by itself (each refused by name,
  naming the chain's newest run), pruned as a COMPLETED run.
- Keep each run's history bounded, a page, a hundred steps, a day: the
  chain's cost per step is then flat whatever its length (ten
  continuations of a hundred steps: 0.6 ms per step at step 10 and at
  step 1 000, `continuation.chain.msPerStep.*`).

[Workflows](https://durablesdk.com/docs/workflows.md) "Continue-as-new" has the statement, the doors and
the proof.

## Testing it

A workflow test is one import and the harness (ADR-0051 §3): the setup
module mocks the two databases (so import it first), binds the engine to
this app's configuration over `memoryStores()` with a clock the test
moves, and its readers answer what the console would show.

```ts
import { testDurable } from "@durable-sdk/testing";
import { helloWorkflow } from "../src/workflows/hello";

const t = testDurable({ clock: { start: "2026-09-28T12:00:00Z" } });
const r = await t.run(helloWorkflow, {
  shop: "s",
  orderId: "o1",
  requestId: "r1",
});
expect(r).toMatchObject({ status: "completed", output: { ok: true } });
expect(await t.steps(r.runId)).toMatchObject([{ name: "hello.greet" }]);
await t.advance("3h"); // a tick a minute: a delayed fact, a timer, a slot fire when due (never early; mid-minute lands at the next tick)
expect(await t.outbox({ undelivered: true })).toEqual([]);
```

`t.run` executes as `system:test` (pass `{ actor }` for another); `t.emit`
queues a fact as a route would; `t.tick()` is one whole tick; `t.detail`,
`t.runs`, `t.ledger`, `t.waits` and `t.wakes` read the rest; `t.db` and
`t.warehouseDb` are the memory doubles and `t.reset()` empties them with
the engine's stores. A connector is a fake from `tests/helpers/fakes`
(`fakeShipping().install()`, then `answer`, `answers`, `fail`, `flip`,
`calls`). The clock is the harness's: a body reads a moment from
`instance().now()`, never `Date.now()`, and `advance` is the only way
time moves ([Workflows](https://durablesdk.com/docs/workflows.md) "Testing"). An external step's in-flight
wait runs on it too (ADR-0063 B12's finding F1): a non-idempotent write
whose fate is unknown leaves its intent stamped at the clock's moment,
the next attempt inside `EXTERNAL_CALL_TIMEOUT_MS` of it sleeps through
`durable.sleep` until the window's end (`t.sleeping()` names the moment),
and `advance` past it ends the wait, a real second never passing; an
attempt past the window reads at once. A retry's delay between tries and
the rate limiter's wait for a refill go through the same `durable.sleep`
(finding F4), so a test of a retried step or of a client over an empty
bucket advances through each wait rather than waiting it.

**Crash it and let it resume** (ADR-0060 decision 1). The double-run
guard, the `workflow-replay` guard, judges every registered
definition on the harness with every connector a fake and the network
fenced: one whose example walks a step runs twice, crashed after each
step it walks and once at the finish (the body returned whole, the
outcome never landed) and claimed by the resumer past the lease, and the
guard refuses a body invoked twice (a fake's provider-call count that
grew, named with the step it sits in, or as a call made outside any step
before the boundary it first grew at: a call after the last step is seen
at the finish alone), a memo lost to the cap or a secret
(`step.replay_missed`) and a body that diverged from the crashed
attempt's rows (the engine's own refusal, `ReplayDiverged` on the step
row with its sentence, ADR-0063 B04), naming the step and the remedy;
your workflow is in it the day it is registered. An example that needs
rows the empty doubles do not hold carries them on the definition as its
`world` (below, "The world": seeded before every run the guard makes),
one whose world is not yet written is listed in `CANNOT_RUN_ON_FAKES`
with its reason and the sentence the clean run says (held to the run's
own words, ADR-0064 P17; empty since FP-042: every registered
definition carries its world, a core action through
`operatorAction({ world })`, a listener through `on()`'s `world`, or is
lent one by the guard), one that decides before any step in
`WALKS_NO_STEP_ON_EMPTY_WORLD` (proved at the finish boundary alone),
and a finding held against a definition until its unit lands in
`FINDINGS_ON_THE_FAKES` with its sentence (empty since FP-042); each
list is exact both ways
(a listed one that runs, walks a step, no longer fails or says another
sentence is stale and fails), and the step boundaries crash-tested have
a floor that only rises. Since ADR-0063
B07 the guard also crashes **inside** every step that writes the
warehouse double: after the write and before the step's row, where a
raw `warehouseDb.<model>.update` is made again by the resumed attempt
and a `recordedRowWrite` is reconciled from the landed row or the world;
the warehouse double counts its writes per step (`t.warehouseWrites()`,
the double's journal `$memory.writes`) and a count that grew names the
step, the statements and the remedy (`DOUBLE_WRITES_ON_CRASH_INSIDE_STEP`
holds such a finding; the static guard
the `step-bodies` guard refuses a new raw write in a step
body). Since FW-015 (2026-10-08) the guard also crashes inside every
step that calls a provider: where the crash fired at the record of a
write the row holds the intent of (`t.crashed().where === "record"`:
the provider took the write, the attempt died before the ledger row),
the resumed attempt's read phase must find it and reconcile it as
`<step>:reconcile`, and a provider **write** made again (the fakes'
`write` methods, `t.fakes.writesByStep()`: a purchase, a send, a
command, a create; a read is made again by the reconcile by design)
names the step, whether a reconcile row landed and the remedy: a read
phase that looks the provider up by the intent's identity, or a
`recordedWrite` of its own for a plain write in the step. The fakes
remember what they wrote so such a read phase works on them as on the
wire (the shipping fake its labels by shipment, read by `listLabels`
and `findShipmentForOrder`, marked by `voidLabel`; the notify fakes
their sends by idempotency key, a second send adopted), and
`fake.failAfter(method, error)` plants "applied, then the answer was
lost": the implementation runs, the call is recorded, the error is
thrown, which is how `tests/lib/labels.test.ts` proves a purchase whose
answer was lost is reconciled by the redrive and never bought twice. A
crash at the row (every record landed, the row lost; a plain step with
no intent among them) re-invokes the body by the engine's contract and
judges the provider's write counts there as it judges the warehouse's
(FW-015's review, finding 2): a `recordedWrite` whose read phase adopts
is served from its landed row and writes nothing, while a blind read
phase, or a plain provider write in a `ctx.step` with no `recordedWrite`
at all (whose only inside boundary the row is), writes again and is
named with the row's own sentence. A step is walked record by record: one
inside boundary per recorded write at its own record, by ordinal
(`t.crashInsideStep(seq, { after: "write", record: n })`), then one at
the row, so a provider write behind another write of the step is
crashed at its own record and never passed over. The
same seams are yours in a test: `t.crashAfterStep(seq, { workflow })`
arms one crash on the memory store (once the step row at that seq lands
COMPLETED the attempt loses its lease, and `t.run` answers
`in_progress, fenced: true` with the run RUNNING),
`t.crashBeforeFinish(true, { workflow })` arms the other (the body
returns whole, the lease is gone before the outcome lands, so the
resumed attempt replays every row and runs the trailing code again),
`t.crashInsideStep(seq, { after: "write", workflow })` arms the third
(the lease is gone after the step's write and before its row: at the
record of a write the row holds the intent of, the row STARTED with its
`pending` entry and no ledger row, so the next attempt reconciles it
from the world; else at the row's own COMPLETED update, refused, so a
plain step's body runs again), `t.advance(t.durable.leaseMs + 60_000)`
lets the resumer claim it as attempt 2, `t.crashed()` says which
attempt it took and where (`at: "step" | "finish" | "inside"`, and for
an inside crash `where: "record" | "row"`),
`testDurable({ fakes: true })` installs every fake with
`t.fakes.calls()` counting their provider calls per method,
`t.fakes.callsByStep()` per step the call was made under and
`t.fakes.writesByStep()` the writes alone,
`t.warehouseWrites()` counts the warehouse double's writes per step,
`logs: "collect"` keeps the engine's lines (`step.replayed`,
`run.fenced`, `step.replay_missed`) for `t.logged()` (one collecting
harness at a time), and `prove()` of `@durable-sdk/testing` (ADR-0072),
bound to the first host by `tests/helpers/replay-proof.ts`, runs the whole
proof of one definition and answers its findings (a
seeded world goes inside the run callback it takes, as
`tests/lib/floor-crash-inside-step.test.ts` seeds the job `pick.scan`'s
example names).

**A red test from a production failure** (ADR-0051 §8). A run that
failed on a deployment is one document, its bundle (`GET
/admin/api/runs/<id>/bundle`, the MCP `run_bundle`), and one command
turns it into a failing test:

```
ADMIN_TOKEN=… npx durable-sdk replay <runId> --api https://<your app's hostname>
pnpm vitest run tests/replays/<workflow>/<runId>.replay.test.ts
```

The file it writes seeds the bundle into `testDurable()` and redrives
the run through the engine as the console's Redrive would
(`replayRun(bundle, "<workflow>", { harness: t, seedHost: mkySeedHost })`
of `@durable-sdk/testing`: the completed steps served from their rows,
the warehouse rows the bundle carries under `host` (the job, the tote,
the transfer, the device without its secrets; ADR-0051 §8 follow-up)
seeded into the warehouse double, the failed step re-invoked against
those rows and the fakes you bind), then expects
`completed`: red until the cause is fixed. Bind a fake before the replay
when the failed step calls a connector (`fakeShipping().install()`),
keep the file as the regression test once it is green, and review the
bundle before adding the pair (it is redacted at the source but may name
order ids; `tests/replays/` is gitignored). A bundle the API's bounds
cut (`truncated` above zero) is refused; a WAITING run's replays to the
redrive's refusal, and the test fires the wait on `t` afterwards
(`t.under(() => t.durable.operator.signal.run(...))`, then
`t.advance("1m")`). The pair's import of `testDurable` is proved by
`tests/durable/cli-replay-host.test.ts`, which writes one under
`tests/replays/` and runs it here.

## An inbound webhook in five lines

An inbound webhook is one route file on `webhookRoute` (ADR-0051 amendment
2026-09-28; `@durable-sdk/vercel/react-router` through the routes stub):
how to verify it and which facts it is. The binding does the rest in a
fixed order: the deployment marker's adoption, the method (POST alone
unless `methods` says otherwise), `verify(request)`, `toFacts(context)`,
each fact emitted under the catalog's key (a redelivery collapses on the
first row), `record(context, facts)` for the audit row, an empty 200.

```ts
// app/routes/webhooks.orders.tsx
import { durable } from "../durable";
import { webhookRoute, type WebhookFact } from "../lib/routes.server";
import {
  shopifyWebhook,
  type StoreWebhook,
} from "../lib/webhooks/shopify.server";

export const config = { maxDuration: 800 }; // the pin pnpm gen:platform writes from the plan row (time.md)
const toFacts = ({
  shop,
  topic,
  payload,
  webhookId,
}: StoreWebhook): WebhookFact[] =>
  payload.id
    ? [
        {
          name: "order.changed",
          payload: {
            shop,
            orderId: String(payload.id),
            topic,
            updatedAt: null,
            webhookId,
          },
        },
      ]
    : [];
export const action = webhookRoute({
  durable,
  verify: shopifyWebhook,
  toFacts,
});
```

`verify` is one function per provider, in `app/lib/webhooks/<provider>.server.ts`,
the only module that spells the check (`durable` is handed by name here
because the route file must reach the barrel, the client-bundle rule; the
binding reads the bound instance itself when none is handed, which is how
the recipes page exports a route with no host): it answers `{ ok: true, context }`
or `{ ok: false, status, body? }`, and a `Response` it throws is returned
as it is (a storefront's `authenticate.webhook` fits unchanged). `toFacts`
answers the facts, `null` or `[]` for nothing, or `{ ignored: reason }` to
say why on the log (`webhook.ignored`). `record` is optional and its
failure never fails the answer (`webhook.record_failed`): the fact is the
receipt. A route whose delivery has no fact (the compliance route) writes
its row inside `toFacts` instead, so a failed row is the 500 the provider
redelivers on: where there is no fact, the row is the receipt. A throw of
`toFacts` is not caught: nothing was written, so the provider redelivers;
a throw of `verify` that is not the provider's own `Response` is answered
a bare 500 (`webhook.verify_failed`), never a 401. The invariants guard holds every
`app/routes/webhooks.*.tsx` to this shape (nothing exported but `config`
and `action`, no handler, the verify from `app/lib/webhooks/`).

## A plugin in one object

A product that spans more than one workflow is one `definePlugin` object
(ADR-0063 Appendix M U5): its facts, the modules that define its
workflows, register its listeners and register its hook handlers, and
the families `createDurable` takes at the top level today. The host binds
the plugins beside its own fields, which stay and are the implicit plugin
(named by `createDurable({ name })`, `"host"` when unsaid; `mky` on this
host).

```ts
import { definePlugin } from "@durable-sdk/core";

import { ORDER_EVENTS } from "./orders/catalog";

export const orders = definePlugin({
  name: "orders",
  events: ORDER_EVENTS,
  workflows: [() => import("./orders/place")],
  listeners: [() => import("./orders/listeners")],
  hooks: [() => import("./orders/loyalty")],
  // tickTasks, retention: { rules }, reverters, remedies, logs, routes,
  // services, observers: the shapes createDurable takes at the top level.
});

// durable.config.ts
createDurable({ name: "shop", plugins: [orders, campaigns], … });
```

What the boot does with it: the keyed families fold into the
configuration with a duplicate refused naming both plugins (a reverter's
type, a log row's name, a service's name, a console entry's name), the
listed ones append after the host's (a tick task, a retention rule, a
remedy or an observer; a name spelled twice is the factory's own
refusal), the facts merge into the catalog with a name two plugins
declare refused naming both (the host's own catalog is typed to the
names no plugin declares, so a payload without a descriptor is still a
compile error), and every family runs under the boot assertion it ran
under before: a plugin bypasses none. What `load()` does: the host's own
two loaders first, then each plugin in order, its workflows, its
listeners and its hooks one module after another, never two plugins at
once (the one-at-a-time rule of the manifest), each under the plugin's
name on the loading slot, so every definition, listener and handler
registered meanwhile carries `plugin: <name>` on `GET catalog/workflows`
(`plugin` on the row, on each hook handler), `GET catalog/events` (the
fact's declaring plugin, each listener's) and `GET catalog/graph` (the
fact, listener, workflow and handler nodes, and `plugins`, each plugin's
node ids; the generated page's "Plugins" section lists each plugin's
counts and draws the edges that cross from one plugin to another). A
module two plugins list is evaluated once and is the first's; a module
the host's own code imports statically before any load is the implicit
plugin's; a plugin's console entries are stamped at the composition and
listed by `consoleApi` after the host's own.

The host's listeners live in the plugin's listener modules: the one file
`durable.config.ts`'s `listeners` loader imports for the implicit plugin,
and whatever a `definePlugin()` value under `app/` lists under
`listeners` (the invariants guard reads both). `testDurable({ name,
plugins })` binds the same way, and the recipes page binds its four
products as four plugins (`docs/durable/recipes.md`, `plugins.ts`).

## Observers

An observer (ADR-0063 B08) is what a host binds to see the engine move
without reading its tables afterwards: `createDurable({ observers })`
takes a list of objects with any of five hooks, `runStarted`,
`stepLanded`, `runFinished`, `factEmitted` and `delivered`, each called
strictly after the row committed (the run row at `beginRun`, the step
row's landing in the recorder, `finishRun`'s transaction and the park's,
the outbox insert, the dispatcher's marks) with a frozen `info`: the
workflow, the run, the attempt, the step and its effect, the outcome and
the bound clock's moment (`{ workflow, runId, attempt, step?, seq?,
effect?, outcome, at }` for a run or a step; `{ name, id, key, partition,
deliverAt, at }` for a fact; `{ listener, eventId, outcome, at }` for a
delivery). A hook runs on its own microtask under the platform's
`keepAlive`, outside the step's log capture, and is never awaited: it
cannot delay, fail or change a run, and a throw is one `observer.failed`
line naming the observer, the boundary, the run and the step. It is not
an interceptor: nothing wraps the write path, and the saga's `around`
stays the recorder's own (the invariants guard holds it there). The
printed `step.*` line carries no `runId` and no `step` (they sit on the
row); the observer's `info` carries both, so a tracer or a metric reads
them from the hook.

An OpenTelemetry exporter is the sketch below, compiled by the snippet
compiler and run under `testDurable({ observers })` by
`tests/docs/guide-observers.test.ts`: one span per run from its start to
its finish, one per step landing, one per fact and per delivery; a
tracer of `@opentelemetry/api`'s shape fits the `Tracer` it names.

```ts observers-otel.ts
// observers-otel.ts: one span per run, one per step landing, from the
// observer alone; bound as `observers: [otelObserver(tracer)]`.
import type { Observer } from "@durable-sdk/core";

/** The slice of a tracer the sketch needs (`@opentelemetry/api`'s `Tracer` and `Span` fit). */
export type Span = {
  setAttribute(key: string, value: string | number): unknown;
  end(): void;
};
export type Tracer = {
  startSpan(
    name: string,
    options?: { attributes?: Record<string, string | number> },
  ): Span;
};

export function otelObserver(tracer: Tracer): Observer {
  const runs = new Map<string, Span>();
  return {
    name: "otel",
    runStarted(info) {
      runs.set(
        info.runId,
        tracer.startSpan(`run ${info.workflow}`, {
          attributes: { runId: info.runId, attempt: info.attempt },
        }),
      );
    },
    stepLanded(info) {
      tracer
        .startSpan(`step ${info.step}`, {
          attributes: {
            runId: info.runId,
            seq: info.seq,
            effect: info.effect,
            outcome: info.outcome,
          },
        })
        .end();
    },
    runFinished(info) {
      const span = runs.get(info.runId);
      if (span === undefined) return;
      span.setAttribute("outcome", info.outcome);
      span.end();
      if (info.outcome !== "waiting") runs.delete(info.runId);
    },
    factEmitted(info) {
      tracer
        .startSpan(`fact ${info.name}`, { attributes: { key: info.key } })
        .end();
    },
    delivered(info) {
      tracer
        .startSpan(`delivery ${info.listener}`, {
          attributes: { eventId: info.eventId, outcome: info.outcome },
        })
        .end();
    },
  };
}
```

An observer is bound in `durable.config.ts` alone, from a module of its
own that reaches no scope resolver, connector or warehouse client (the
invariants guard reads the module and what it imports); the first host binds
none. The memory store's tables and the bench's rows per run are the same
with an observer bound and without: an observer reads, and writes to a
transport it owns.

## Testing the workflow

One scenario per workflow (ADR-0072 TQ-003; `@durable-sdk/testing`'s
`scenario`, the host's `scenario` of `tests/helpers/scenario.ts` over
`testDurable`): given the definition's own world, when the door is
called or the fact arrives, expect the runs, the ledger rows, the facts
and the provider calls, each by the fields you name and nothing else.
The file lives in `tests/scenarios/`, imports the harness module first
(the doubles) and reads

```ts
import { testDurable } from "@durable-sdk/testing";

import { execute } from "@durable-sdk/testing";
import { worldOf } from "@durable-sdk/core";
import { afterAll, it } from "vitest";

import { helloWorkflow } from "../src/workflows/hello";
import { scenario } from "../helpers/scenario";

const t = testDurable({ fakes: true, tickTasks: [] });
afterAll(() => t.dispose());

it("greets once and says so", async () => {
  await scenario(t, "a greeting")
    .given({ world: worldOf(helloWorkflow)! })
    .when(execute(helloWorkflow, { shop: "s", orderId: "o1", requestId: "r1" }))
    .expect({
      runs: [
        {
          workflow: "hello.greet",
          steps: ["hello.greet"],
          output: { ok: true },
        },
      ],
      noFacts: ["pickjob.cancelled"],
      provider: { shipping: { total: 0 } },
    });
});
```

`emit(name, payload)` with `tick()` is the fact's path through the
listener (the run is `listener.<name>`), `crashAfterStep(seq, {
workflow })` then `advance(t.durable.leaseMs + 60_000)` and `tick()` is
the crash and its replay (expect the step's one row and the fact's one
delivery), `signal(token, payload)` fires a person's approval on the last
run, and `act(fn)` runs anything else over the harness. A failed
expectation is one sentence naming what was expected and what was found
(a run's outcome in `describeResult`'s words); the answer carries every
row read for the assertions the DSL does not spell.
`tests/scenarios/queue-set.test.ts`, `pickjob-sync.test.ts` and
`pick-scan.test.ts` are the three shapes on real definitions; the
harness's own verbs ("Testing it" above) stay for what a scenario does
not say.

---

Prompt for an agent:

```text
Read https://durablesdk.com/docs/workflows.md, then apply what it says to this app; run durable-sdk doctor --host before and after; a refused line is a refusal id: durable-sdk explain <id>
```
