# Rules in the backend

Author backend rules in native Flow text and save them with `apply`;
see the [default MCP loop](app-lifecycle.md#default-mcp-loop).
The JSON below shows candidates for non-writing preflight checks with `test`.

## Choosing databases

New App tables share the App's `main` database by default. Declare
`database: "incoming"` in an entity's spec to put a hot ingest in a separate
database within that App. Each database serializes its own writes. Keep tables
that a command must change atomically together; a related write guard across
databases is refused. Read-only guards and references may read across databases.
`describe` returns the declared location. Omitting the property in
a Flow edit keeps the saved location. Statement edits cannot
move saved data. Another App's tables still require table references and grants.

Every command must declare `spec.fields`: list the fields it takes, or `[]`
for no inputs. Omission is refused. Delete requires `fields: []` and only
recordId/key plus expectedVersion where used. Use `require` for record-state
preconditions. Commands never implicitly inherit all entity fields.

A command `transition` derives the next state of an existing record on the
server, in the same save as the caller's patch. Use `operation:"patch"`.
`code` is a plain JavaScript function body (statements followed by a return),
not a standalone function definition or an expression. Read `current` (stored
row), `input` (caller values), `now` (UTC instant string), and `today`
(`YYYY-MM-DD`). Return exactly `{ok:true,set:{…}}` or `{ok:false}`; refusal
writes nothing and is `409` `command_precondition`. A refusal may carry
`{ok:false,reason:"…"}` (at most 226 characters): the caller then reads that
sentence instead of the generic "not allowed in its current state" refusal.

The sandbox has no network, imports, filesystem, `Date`, timers, or randomness.
Code is limited to 1–10,000 characters, with bounded work (a nominal 100 ms
allowance enforced by interpreter interrupts), 256 KiB input, and 64 KiB output.
Exhausting the budget or returning an invalid result is a rule failure, not an
accepted write. Saved scenarios use this same evaluator with comparison tracing,
so test representative rule complexity rather than relying only on small inputs.

Declare 1–32 unique scalar `derivedFields`. Each must exist on the entity and
be listed in the command's `fields` with `computed:true`. An accepted `set`
assigns every derived field and no others. Do not assign these fields in a
static command `set` or in caller input. A command input field that is never
stored on the row — a find string, a requested rate, a bounded list of edits —
declares `"input": true` in `fields` and needs no entity column. A transition
cannot be combined with a stock change.

When the rule is only a calculation or a precondition, prefer the declarative
form over `transition` code: a `set` value of `{"expression":"…"}` computes a
column from `current.` and `input.`, and a `require` entry of
`{"when":"…","message":"…"}` refuses the write with your own sentence.
Reach for `transition` when the decision still needs JavaScript.

Provide 2–12 distinct `tests`, each with `current`, `input`, optional UTC `now`,
and `expect`. Accepted examples use `expect:{ok:true,set:{…}}`; refused examples
use `expect:{ok:false}`. When the rule can accept and refuse, demonstrate both,
with an accepted/refused pair using the same input field names. If it always
accepts, use two distinct accepted examples. Example time defaults to
`2026-01-01T00:00:00.000Z`; pass `now` to test time-dependent branches.

## Copyable example

The JSON below illustrates candidate specs for non-writing preflight checks.
Pass `{spec: ...}` to `test {appId, kind, scenario}` or
`wf advanced test <flow-id> <kind> '{"spec":...}'` on an App-owned Flow.
Save the corresponding statements in Flow text with
`apply {appId, text, expectedRevision, idempotencyKey}`. Read the current Flow
and its revision before editing it.
The caller supplies a rate; the server computes the total from stored quantity.

```json
{
  "appId": "<app-id>",
  "kind": "entity",
  "spec": {
    "name": "invoices", "keyField": "invoice_id",
    "fields": [
      {"name": "invoice_id", "kind": "text", "required": true},
      {"name": "quantity", "kind": "number", "required": true},
      {"name": "rate", "kind": "number", "required": true},
      {"name": "total", "kind": "number"}
    ]
  }
}
```

```json
{
  "appId": "<app-id>",
  "kind": "command",
  "spec": {
    "name": "set-rate", "entity": "invoices", "operation": "patch",
    "fields": [
      {"name": "rate", "kind": "number", "required": true},
      {"name": "total", "kind": "number", "computed": true}
    ],
    "transition": {
      "code": "if (input.rate <= 0) return {ok:false}; return {ok:true,set:{total:current.quantity * input.rate}};",
      "derivedFields": ["total"],
      "tests": [
        {"current": {"invoice_id":"i1","quantity":2,"rate":5,"total":10}, "input": {"rate":6}, "expect": {"ok":true,"set":{"total":12}}},
        {"current": {"invoice_id":"i1","quantity":2,"rate":5,"total":10}, "input": {"rate":0}, "expect": {"ok":false}}
      ]
    }
  }
}
```

A saved scenario checks the resulting record with `expect.fields`, rather than
the transition examples' `expect.set`. Seed an existing record for a patch:

```json
{
  "appId": "<app-id>",
  "kind": "scenario",
  "spec": {
    "name": "rate-derives-total",
    "seed": {"invoices":[{"invoice_id":"i1","quantity":2,"rate":5,"total":10}]},
    "steps": [
      {"command":"set-rate","recordId":"i1","input":{"rate":6},"expect":{"ok":true,"fields":{"rate":6,"total":12}}},
      {"command":"set-rate","recordId":"i1","input":{"rate":0},"expect":{"refused":{"status":409,"code":"command_precondition"}}}
    ]
  }
}
```

For an owner-only App (commands with `access` limited to the owner), every step that should succeed carries `"as": {"owner": true}`; without it the step runs as an anonymous
visitor and is refused with 403. Leave `as` off a step that expects that refusal (a visitor refused). In Flow text: `scenario(name: "owner-logs-habit") do` with `call(command: log_habit, as: owner, inputs: {...})` for the owner (or wrapped in `expectRefusal(status: 403) do` with `as: anonymous` for a visitor refusal), closed with `end`.

After saving its Flow statement, run it with MCP `test` (the App's Flow id returned by creation, `kind:"scenario"`,
`scenario:{"name":"rate-derives-total"}`), or
`wf advanced test <flow-id> scenario '{"name":"rate-derives-total"}'`.
Scenario state is isolated from real App rows. Omit `seed` or an entity's key
when starting empty, such as a create-command story; `seed:{"invoices":[]}`
is refused. Limits: 1–12 action steps per story, 30 stories and 150 saved steps
per Flow, 32 KiB JSON per story, at most 8 seeded entities, 1–50 rows per seeded
entity and 100 seed rows total. These action-step limits are separate from the
transition interpreter's work allowance.


## A status that moves in steps

When a column may only take a few values and only some moves between them are
legal (a claim that moves from `pending` to `approved` or `rejected`), make it
an enum column with a default and write one patch command per move. Each
command reads the row, checks where it is, and writes the next value:

```flow
flow 1
let login = signin(draft: true)
let claims = table(
  name: "claims",
  columns: {
    reason: text(required: true),
    status: enum(options: ["pending", "approved", "rejected"], defaultValue: "pending")
  },
  access: {rows: [creator, roles("manager")]}
)
let file_claim = command(inputs: {reason: type(claims.reason)}, access: {call: signedIn}) do
  insert(table: claims, set: {reason: input.reason})
end
let decide = command(
  inputs: {
    recordId: reference(table: claims),
    decision: enum(required: true, options: ["approved", "rejected"])
  },
  access: {call: roles("manager"), edits: [roles("manager")]}
) do
  let current = claims |> filter(where: id == input.recordId) |> one()
  check(current.status == "pending", message: "Only a pending claim can be decided")
  patch(table: claims, recordId: input.recordId, set: {status: input.decision})
end
let reopen = command(
  inputs: {recordId: reference(table: claims)},
  access: {call: roles("manager"), edits: [roles("manager")]}
) do
  let current = claims |> filter(where: id == input.recordId) |> one()
  check(current.status != "pending", message: "The claim is already pending")
  patch(table: claims, recordId: input.recordId, set: {status: "pending"})
end
```

- A new row starts at `pending`: the insert leaves `status` out of `set:`, so
  the column's `defaultValue` fills it.
- `decision` is an input with its own type, not a column: a call with any other
  value than the two listed is refused.
- `access:` says who may call the command and whose rows it may change:
  `access: {call: roles("manager"), edits: [roles("manager")]}`. For either of two
  roles write `roles(["manager", "operator"])`. For a person named by an email
  column of the row write `edits: [{email: reviewer}]`.
- The `check` is enforced with the write: a wrong starting status refuses the
  call and nothing is saved.
- `status` is an ordinary column: the column does not list the allowed moves. It
  changes wherever a `set:` writes it, so the moves are the commands that write
  it. Leave it out of every other command's `set:`.
- Test each move with a scenario: the allowed caller succeeds, another caller is
  refused, and a wrong starting status is refused.
- A table that already declares `state(...)` keeps running and its text still
  saves; `docs/FLOW-LANGUAGE.md` ("State rules") describes that form.

## Email the owner when a row comes in

For "email me when a new booking comes in", put an `email(to: [owner], ...)` line
below the write in the command that creates the row, not a scheduled digest:

```flow
flow 1
let bookings = table(
  name: "bookings",
  columns: {name: text(required: true), day: date(required: true)}
)
let book = command(
  inputs: {name: type(bookings.name), day: type(bookings.day)},
  access: {call: public},
  rateLimit: {per: visitor, max: 10, every: minute}
) do
  let saved = insert(table: bookings, set: {name: input.name, day: input.day})
  email(
    to: [owner],
    subject: "New booking: {{saved.name}} on {{saved.day}}",
    body: "{{saved.name}} booked {{saved.day}}."
  )
end
```

It sends after the write commits; a refused or failed write sends nothing, and a
failed email never undoes the write. A public command that sends email needs the
visitor `rateLimit:` in its header.

## Referencing seeded rows and aggregate views

A scenario command addresses a seeded row by the entity's declared key value.
The example above declares `invoice_id` as the key, so its seeded
`"invoice_id":"i1"` row uses `"recordId":"i1"`. Without a declared key,
use the deterministic `seed-<entity>-<1-based row number>` ID, such as
`seed-invoices-1`. A composite key (several key fields) has no single
value: the record ID is the JSON-encoded tuple of its parts in declared order,
such as `"recordId":"[\"sam\",\"lunch\"]"`. Do not use `_wf_record_id`; it is response metadata, not
a scenario reference.

A view step asserts ordinary output rows with `expect.rows`. For an aggregate
view, assert the ordered output with `expect.groups`. Each group puts its
grouping fields under `key` and its calculated aggregate fields under
`metrics`. A metric is named `count`, or `<op>_<field>` (`sum_amount` for a
`sum` over `amount`), not a custom alias. This is one scenario step, not a
whole call:

```jsonc
{
  "view": "unpaid-totals-per-client",
  "expect": {
    "ok": true,
    "total": 3,
    "groups": [
      {"key": {"client": "Acme"}, "metrics": {"sum_amount": 125}},
      {"key": {"client": "Beta"}, "metrics": {"sum_amount": 40}}
    ]
  }
}
```

Here, `total` is the JSON scenario's count of source rows the view matched before grouping (three invoices, not two output groups); in a scenario written as text, a grouped view has no `total`, so check it with `expectGroups(listed.groups, inOrder: [...])`. A page reading a grouped view receives `groups` without `total`. Metric values are numbers or `null`.
With no matching rows, a grouped view returns `groups: []` (assert
`"groups":[]` with `total:0`; there is no metric to assert). An ungrouped
aggregate still returns one group with an empty `key`, and a `sum` over no
input rows is `null` there, so assert `"groups":[{"key":{},"metrics":{"sum_amount":null}}]`
rather than `0`.

## Uploaded external UI scripts

When Wrapflow hosts an uploaded external static build, its CSP currently uses
`script-src 'self' 'unsafe-inline'`. Inline scripts and same-origin bundle
files are allowed; remote scripts are blocked even from a host declared in
`egressHosts`, so bundle scripts locally. Egress covers backend/network calls
and passive resources (images, fonts, media, styles).
These uploaded bundles differ from hosted scriptless presentations, where
authored JavaScript is refused. A frontend hosted elsewhere follows that
host's own CSP. Use the generated App client in either external setup.
