# backend.js — the app's server-side backend

> server-side backend.js file: answer HTTP/webhook requests at the app's /_api URL, react to committed data changes, and run scheduled jobs — its writes go through the app's own access rules; keeps a copy of another system's records (a shop's orders, a CRM's contacts) with a scheduled read from a watermark, one record per outside id, which the shop's order email can ring through a Zap;reads each message someone pastes or sends and acts on it with an agent run over the app's own tools (ctx.agent.run: file the order an email describes, set the rest aside with a reason);reads a web page, feed or API the person names and hands it to the page through /_api; emails, notifies and reminds people through ctx.notify by handle — a weekly digest, a summary for the owner, a Monday email to the manager — and invites a recipient who is not in the app yet; texts the app's followers, takes their replies into a replies database, and runs a first-to-reply-gets-it offer as a claims database the texted #claim=<id> link points at; sends a record to a tool the person names (Slack, Google Sheets, a CRM, Zapier) through a Zapier Catch Hook the owner connects; and takes records in from Zapier — a Google Forms response, a new sheet row, an email — at its /_api URL, checked against a shared secret, including the person's own Gmail: a Zap they filter forwards only the mail they choose, which is how an app reads receipts or newsletters from an inbox; and reads mail sent to the app's own email address in its `email` export — order confirmations or receipts the person forwards to the app, messages a venue or a supplier sends it, a club's shared inbox

Source: https://good.vibes.diy/docs/reference/backend

`backend.js` is an optional **server-side** file, a sibling of `access.js`. It
runs on the platform's servers — never in the browser — and gives the app four
server superpowers, each an exported function:

- **`fetch(request, ctx)`** — answer HTTP requests at the app's `/_api/...` URL
  (webhooks from outside, or `fetch("/_api/…")` from the app itself).
  The app reaches its own backend at `/_api/…`, with the underscore.
  That underscored path is the one the handler answers.
- **`onChange(event, ctx)`** — react after a document write commits (derive,
  aggregate, moderate, fan out).
- **`scheduled(event, ctx)`** — run periodically (cleanup, digests, timers).
- **`email(message, ctx)`** — read mail sent to the app's own email address.
- **`later(event, ctx)`** — run once, at a time a handler chose with
  `ctx.later` ("follow up in 2 days").

Export only the handlers the app needs. Most apps need **no** `backend.js` at
all — normal CRUD flows through Fireproof directly. Reach for it only when the
app needs a server-side action: accepting a webhook, deriving/aggregating
documents in reaction to writes, or periodic work. These docs are present by
default so you know the capability exists — their presence is **not** a
request to add a backend. If the user's request doesn't call for one, don't
create or mention `backend.js`.

## When to use which handler — signal words

- **`fetch`** — "webhook", "OAuth", "callback", "API endpoint", "receive",
  "form POST", "Stripe/GitHub/Sonos sends us…", "from Zapier", "when a form
  is submitted in Google Forms", "every new row in my sheet". Something
  **external → us**.
- **`onChange`** — "when X is created", "after a write", "notify", "send an
  email", "aggregate", "moderate", "sync to…". An **internal write → a side
  effect**: `ctx.notify` for every person the app emails, notifies or reminds,
  and a Zapier Catch Hook for a tool the person names (Slack, Google Sheets, a
  CRM).
- **`scheduled`** — "every N minutes", "poll", "check periodically", "cron",
  "cleanup", "digest". **Timer-driven**, no user in the loop. "Keeps my
  Squarespace orders in sync", "a copy of my CRM's contacts" is a mirror on a
  watermark, and a shop's order email that tells the app to look now rings its
  doorbell through a Zap (see *A mirror of another system's records* below).
- **`email`** — "forward my order emails to the app", "my app should read my
  order emails", "forward receipts to my app", "a shared inbox for our club",
  "when the venue emails us, add it to the calendar", "the app's own email
  address". **Mail to the app's address → us**: the person forwards it, or
  hands the address to the people who write in. Mail the app pulls out of
  their Gmail by search ("the receipts in my Gmail", "scan my inbox") is the
  Zapier recipe under `fetch`.
- **`ctx.agent.run`** — "the server reads it and adds…", "sorts each email",
  "files the order it describes", "skips the ones that aren't orders",
  "triage", "decide what to do with it". **The server reads a message and
  picks the app's action**: an agent run over the app's `tools` export, started
  from whichever handler received the message (`onChange` for a pasted one,
  `email` then `later` for mail, `fetch` for a webhook). See *Let an agent do
  the work* below.
- **`ctx.webSearch`** — "search the web for…", "find shops that sell…",
  "watch for new listings", "what's the latest on…", "look it up online". **The
  server looks something up on the web**, usually from `scheduled`, and keeps
  what it found (see the `ctx.webSearch` note below).
- **`ctx.ask`** — "ask me before sending", "let me approve it", "check with me
  first", "draft it and I'll say yes". The app **asks its owner** and acts on
  the answer (see *Ask the owner first* below).
- **`ctx.later` + `later`** — "follow up in 2 days", "remind them next week if
  they haven't answered", "wait, then…". **One** event at a chosen time; a
  recurring time of day stays `scheduled`.

A reminder that recurs at a wall-clock time — "every morning at 9", "each
Friday" — is a `scheduled` handler; `onChange` answers a write that just
happened.

Followers who hear from the app by text and answer back are this file's work
too. "Followers hear about…", "text me when…" is a notify to each
`subscriber`; "they can reply", "send a photo back" is a `replies` database;
and "the first one to reply gets it", "whoever texts back first", "last one
left", "dibs" is a claim-once offer: a `claims` database whose access function
lets the first claim stand, offered by a notify whose `path` is
`#claim=<id>` (see *A claim-once offer* below).

A game a group chat plays together is this file's work as well: "each play
tells the group", "the chat hears when someone plays", "say whose turn it is".
That is an `onChange` on the play record. It reads the round's plays and
notifies the app's owner, `ctx.appInfo.ownerHandle`, which for an app a group
chat made is the group, so the note reaches that chat. The body is the round so
far: who picked what, who is still to play, and whose turn is next. Its
`dedupeKey` names the round and how many have played in it
(`` `round-${round}-plays-${count}` ``), so each play is one message however
often the handler runs:

```js
export async function onChange(event, ctx) {
  const play = event.doc;
  if (play?.type !== "play") return;
  const plays = await ctx.db.query({ field: "roundId", key: play.roundId, limit: 100 });
  const picks = plays.map((p) => `${p.playerHandle} picked ${p.choice}`).join(", ");
  try {
    await ctx.notify({
      toHandle: ctx.appInfo.ownerHandle,
      body: `Round ${play.round}: ${picks}. ${play.playerHandle} asks the next one.`.slice(0, 500),
      dedupeKey: `round-${play.roundId}-plays-${plays.length}`,
      path: `#${play.roundId}`,
    });
  } catch (err) {
    ctx.log("warn", "notify failed", { round: play.roundId, reason: err.message });
  }
}
```

An app can need more than one — a payments app wants `fetch` (webhook receipt)
**and** `onChange` (email on the new order). If none of these signal words fit
the request, the app needs no `backend.js` — don't emit one.

**Decision rule:** when live external data is the app's substance, use
`backend.js` + **cache-into-db, never fetch-per-render**; when external data is
only launch flavor, take a generation-time snapshot into `seed.json` instead.

Keep availability separate from a successful empty result. Inspect a successful source
response before choosing its parser, then validate the fields the app uses. An empty
validated response is data; an unavailable first read leaves the dependent decision pending.
For example, a dispatch planner waiting for its closure calendar records that unavailable
state and postpones calendar-dependent dispatch. A previously validated cache can support
the declared fallback, with its freshness and failure visible in saved status.

## Output format

`backend.js` is a separate file, exactly like `access.js`: one prose line, the
heading naming `backend.js`, then one **complete** fenced block below it (the
whole file — don't use SEARCH/REPLACE for it; re-emit the full file to change
it). **Never put backend code inside an `App.jsx` block**, and never import
`backend.js` from `App.jsx` — the browser can't run it. Each handler is a
top-level export (`export async function fetch(request, ctx)`, `scheduled`,
`onChange`, or the static `tools` of the vibe-tools skill); a `backend.js` that
exports none of them saves as an error.

### A large backend splits into files

`backend.js` can import the vibe's own `.js` files with relative imports, and
those files can import each other the same way. Each file holds up to 128 KB, so
a backend that serves big pages or game code keeps each part in its own file and
`backend.js` stays the router:

```js
import { HOME_PAGE } from "./pages/home.js";

export async function fetch(request, ctx) {
  return new Response(HOME_PAGE, { headers: { "content-type": "text/html" } });
}
```

Write each imported file whole under its own heading, like `backend.js`. Only
files `backend.js` actually imports go to the server, up to 64 of them.

## Writes go through the access function

Every `ctx.db.put`/`ctx.db.delete` is enforced by the app's own `access.js` —
the exact gate user writes pass through — acting as the **trigger's identity**:

| Handler     | Writes act as…                                                    |
| ----------- | ----------------------------------------------------------------- |
| `onChange`  | the user whose write triggered the event                          |
| `fetch`     | the signed-in caller when verifiable — treat as possibly anonymous |
| `scheduled` | the app owner, **in admin mode**                                  |
| `email`     | the mail's linked sender (`message.sender`), else nobody; never admin |
| `tools`     | the person the tool is used for, never admin (see vibe-tools)     |

So the permission model stays in `access.js`, and `backend.js` writes must be
allowed by it for the acting identity. If a `fetch` handler writes, make sure
the access function permits that write for an anonymous caller (or design the
write to happen in `onChange`/`scheduled`, which carry stronger identities).

The access function can tell where a write came from: `user.backend` names the
handler that issued it — `"scheduled"`, `"onChange"`, `"fetch"`, `"email"` or `"tool"` — and is
absent for every write from a browser or the CLI, the app owner's own included.
What it does **not** change is identity. An `onChange` write still acts as the
triggering user, so anything it may write, that user's own client could write
too; `onChange` stays **derivation and convenience**, never privilege
escalation. For documents only the server should control, use `scheduled` and
gate them on the origin with `ctx.requireBackend("scheduled")`, which admits the
run and turns every ordinary client write away.

The origin travels with the write even when nobody is signed in, for every
handler. A guest's `apiFetch` into the `fetch` handler arrives with `user` null,
and `ctx.requireBackend("fetch")` still passes for it, so a guest-checkout
record can be one only the handler writes; an `onChange` run triggered by a
signed-out writer passes `ctx.requireBackend("onChange")` the same way. The function still opts that anonymous
write in with `allowAnonymous: true`, and that opt-in is all it takes: the
app's anonymous-write setting gates writes straight from a browser, never a
write the app's own backend.js makes. `user.backend` itself is read only off a
signed-in user, so gate with `ctx.requireBackend`.

`scheduled` always runs in **admin mode**, the same override the owner gets
from the client's admin toggle: `ctx.requireAccess(...)`, `ctx.requireRole(...)`
and `ctx.requireBackend(...)` all no-op, and its `ctx.db.query` reads are
unfiltered. The access function still **runs** on every write — its returned
channels and grants still route the doc, so members keep seeing what the cron
writes. `user.backend` is `"scheduled"`, so `ctx.requireBackend("scheduled")`
passes for the run on its own merits. Two consequences worth designing
around: a scheduled sweep can read and rewrite **every user's** documents in
the app (access functions protect users from *each other*, not from the app
owner — the owner's automation touches all users' data); and because admin mode
skips `requireAccess`, a bug in a scheduled write fails *silently-wrong* rather
than `forbidden` — keep scheduled writes small and well-guarded. `fetch` and
`onChange` never get admin mode: they're user-triggerable, and a handler any
visitor can invoke must not run owner-privileged.

### Taking on the authorization job: `config.fetch.unfilteredReads`

Because the `fetch` lane runs as the calling user, a signed-in caller's
`fetch` handler reads exactly what that caller could read from their own page —
an access-fn-bound database comes back filtered to their channels, like
`onChange` reads for its triggering user. A caller with no session reads the
databases the opt-in below names. Some routes need exactly that: a calendar
feed at `GET /_api/faves.ics?t=<token>` is fetched by a calendar app that carries
no login, and the docs it serves are private to one user. For those, `backend.js`
can opt in — per database, `fetch` lane only:

```js
export const config = {
  fetch: {
    unfilteredReads: {
      dbs: ["faves"],
      why: "serves per-user .ics calendar feeds authorized by an unguessable token",
    },
  },
};
```

This is an **obligation, not a convenience**. Inside that handler, for those
databases, you are taking on the authorization job the platform normally does:
both the anonymous refusal and the access-function scoping come off, so
`ctx.db.query`/`ctx.db.get` return **every** document in the named databases —
all users, all channels — to whoever called the route. The legitimate pattern is
a **capability**: an unguessable, per-user, revocable token in the URL or a
header, checked before you read, with the response scoped to exactly that
token's owner. "The URL is hard to guess" holds when a signed-in `fetch` route
draws the token with real entropy and writes its record, the page only asks
for it, and the token travels only in the link that route hands back (_A feed
token is minted by a signed-in route_, below).

Two things to design around. The opt-in is scoped to the **lane, not the
route**: `backend.js` exports one `fetch` handler that routes internally, so
every path inside it can read those databases — keep the check at the top and
name as few databases as the feature needs. And it is a **static declaration**:
`dbs` must be plain string literals and `why` a non-empty string literal saying
who is authorized and how, or the push is rejected. There is no call-site flag,
and no other lane can opt in.

### A route guests call reads only what it declares

A route a signed-out visitor can call reads only the databases `config.fetch.unfilteredReads` names.
A guest checkout, an order form, a booking request or a webhook from outside
arrives with no session, and so does any plain `fetch("/_api/…")` from the
page. A `ctx.db.get` or `ctx.db.query` on any other database throws
`Access denied` for that caller, even when the record sits on a `grant.public`
channel the page itself reads, and the route answers every guest with a `500`
while the owner's own `call_own_api` check, which arrives signed in, works.

So a shop's order route that prices each line from the menu names the menu
database there, and reads only records the menu shows everyone. The declared
read returns every record in that database, so check the type (and a hidden
flag, if the menu has one) before using a record, and keep staff-only records
such as role grants in a database of their own:

### `backend.js`
```js partial
export const config = {
  fetch: {
    unfilteredReads: {
      dbs: ["menu"],
      why: "prices guest orders from the public menu; only drinks the menu shows are read",
    },
  },
};

// inside the /order route, for each line of the order:
const drink = await ctx.db.get(String(line.drinkId), { db: "menu" });
if (drink?.type !== "drink" || drink.hidden) {
  return json({ ok: false, reason: "one of those drinks is not on the menu" }, 400);
}
```

The order itself is a write, so it passes `access.js` as the guest:
`ctx.requireBackend("fetch")` on the order type and `allowAnonymous: true` let
the route, and only the route, create it. A route meant for signed-in people
only refuses a missing `ctx.userInfo` with a `401` before it reads, and then
reads as that person, with nothing to declare. The page calls either kind with
`apiFetch`, so a signed-in customer arrives as themselves.

## ctx — what a handler gets

```js
ctx.appInfo; // { ownerHandle, appSlug } — this app's identity
ctx.userInfo; // { userHandle } or null — who the handler is acting as
ctx.secrets; // Record<string,string> — the owner's per-vibe secrets; frozen, {} when none
await ctx.db.put(doc, { db: "notes", id: "optional-id" }); // resolves to the doc id AFTER commit
await ctx.db.put(doc, { db: "jobs", id: doc._id, ifRev: doc._rev }); // commits only if nobody wrote the doc since you read it
await ctx.db.delete(docId, { db: "notes" });
const docs = await ctx.db.query({ db: "notes", field: "type", key: "note", limit: 100 }); // a filtered page
const doc = await ctx.db.get("state:cursor", { db: "notes" }); // one doc by _id, or null
const text = await ctx.callAI("prompt", { model: "openrouter/auto", max_tokens: 500 }); // server-side AI call
const json = JSON.parse(
  await ctx.callAI("rate this", { schema: { properties: { verdict: { type: "string" }, score: { type: "number" } } } })
); // structured output
const res = await ctx.fetch("https://api.example.com/x", { headers }); // outbound HTTP — use this, not bare fetch()
await ctx.notify({ toHandle: "alice", body: "Your turn", dedupeKey: "game-7-turn-3", path: "#game-7" }); // one participant; `path` optional; throws on failure
ctx.log("info", "tick finished", { written: 3 }); // diagnostics — read back with: vibes-diy app logs owner/slug
const gh = await ctx.github.fetch("/repos/acme/site/issues", { method: "POST", body: { title: "Filed from the vibe" } }); // connected GitHub repo
const routes = await ctx.github.routes(); // [{ repo, accountLogin, binderHandle, installationId }] — who connected which repo; no GitHub call
const session = await ctx.stripe.fetch("/v1/checkout/sessions", { method: "POST", body: form, mode: "test" }); // the owner's connected Stripe account
const stripe = await ctx.stripe.status(); // { test: { available, state }, live: { available, state } }
const yt = await ctx.youtube.fetch("/channels?part=statistics&forHandle=@name"); // public YouTube Data API on the platform's key — no owner setup
const budget = await ctx.youtube.status(); // { available, unitsLeftToday, dailyUnits } — spends nothing
ctx.email.address; // "orders--jchris@in.vibes.diy" — this app's own inbound address, or null while email in is off
const run = await ctx.agent.run({ goal: "File this order", input: doc, tools: ["add_order"] }); // agent loop over your tools — see "Let an agent do the work"
const { results } = await ctx.webSearch("lego 10305 in stock", { maxResults: 5 }); // [{ title, url, snippet }] — a web search, metered like callAI
const askId = await ctx.ask({ question: "Send Dana the reply?", options: ["Send", "Skip"], data: { orderId }, key: `reply-${orderId}` }); // asks the owner; the answer arrives in onChange
await ctx.later({ in: "2d", name: "follow-up", data: { orderId }, key: `follow-${orderId}` }); // one event to `later` in 2 days (or `at: iso`)
await ctx.later.cancel(`follow-${orderId}`); // true when a timer with that key was pending
```

- An app that reads YouTube numbers loads the `youtube` skill: `ctx.youtube.fetch` for `channels`, `videos`, `playlistItems`, `playlists` and `commentThreads` (what viewers are saying), the app's daily unit budget and its `over_budget` refusal, and the evening-and-morning sampling behind an overnight recap.

- An app that takes money loads the `stripe` skill (one-time charges) or the `stripe-subscriptions` skill (recurring): the Connect Stripe setup item, `ctx.stripe.fetch` with the order's `mode` on every call, hosted Checkout and a complete example.
- The account a charge uses is the owner's per-app choice, a `setup:live` document the owner writes from the Setup screen; `ctx.stripe.status()` says which accounts are ready, and a ready live account alone leaves the app in test. The `stripe` skill carries that choice, the Setup screen and the sweep for buyers who never come back.

- An app that works with somebody's GitHub repo loads the `github` skill: the connect link, `config.github`, `ctx.github.routes()`, deliveries and a complete example.
- `ctx.github.fetch(path, init)` calls the GitHub REST API **as the GitHub App
  installation the owner connected to this vibe**. It is the only GitHub surface
  a backend has: `path` is a GitHub API path rooted at `/` (`/repos/…`, plus
  `/installation/repositories`), `init` takes `method`, `headers` and `body`
  (an object is JSON-encoded for you), and it resolves a normal `Response` — so
  `res.status`, `await res.json()` and `res.headers.get("link")` all work, and
  an upstream 404 or 422 comes back as a `Response`, not an error. **There is no
  token to read.** The installation credential is attached by the platform and
  never enters your code, so you cannot pass it to another library, log it, or
  store it — and every call the App makes on the owner's behalf is one the
  platform made. The proxy also enforces the binding: a `/repos/{owner}/{repo}/…`
  path must name a repository the owner actually connected to THIS vibe, so a
  path built from user-supplied text simply gets refused rather than reaching
  some other repo the installation happens to cover. Do not treat that refusal
  as your validation — check the repo name yourself before you build the path,
  and tell the user which repos this vibe is bound to (`/installation/repositories`).
  Calls
  outside the proxied surface reject with an `Error` carrying a short `reason`
  (`not_connected` — the owner has not connected a repo, `unmodeled_endpoint` —
  a path outside `/repos/…` + `/installation/repositories`, or one naming a repo
  this vibe is not bound to,
  `unsupported_method`, `streaming_unsupported`, `body_too_large`,
  `permission_not_declared` — `config.github.permissions` leaves out the
  permission this call needs, `permission_not_consented` — declared, but the
  person who connected the repo agreed before it was (they press Connect
  again), `permission_not_granted` — the installation lacks that permission, or
  `upstream_error`); branch on `err.reason`, and tell the user which one it was.

- **Connecting a repository is a link, not a call.** The page links to the
  PLATFORM's `/github/install?vibe=<owner>/<slug>` with an **absolute** URL in a
  **new tab** — never a root-relative `/github/install` (the app is served from
  its own host, where that path is not the platform's) and never `fetch` (the
  next stop is github.com, and the consent page refuses to load in a frame).
  `buildGithubInstallUrl()` from `use-vibes` returns that absolute address for
  the running vibe — on `https://vibes.diy`, or on the PR preview the vibe runs
  under — so the page never writes the host or its own `<owner>/<slug>`:

  ```jsx
  import { buildGithubInstallUrl } from "use-vibes";

  <a href={buildGithubInstallUrl()} target="_blank" rel="noopener">
    Connect a GitHub repository
  </a>;
  ```

  The owner goes straight to GitHub to sign in, then ticks the repositories
  this vibe gets (each vibe gets only the ones ticked for it). By default only the
  owner may connect one; to let **visitors** connect their own repositories (a
  PR reviewer, a repo dashboard anyone can use), declare it in `backend.js`:

  ```js
  export const config = {
    github: { bind: "anyone", why: "Reviews the pull requests you open and leaves comments on them." },
  };
  ```

  `bind` is `"owner"` (the default) or `"anyone"`; with `"anyone"`, `why` is
  required — one static sentence, 280 characters at most — because the platform
  shows it on the consent page a visitor reads before going to GitHub. Write it
  inline as `github: { … }` — a shorthand `{ github }` or a method is refused —
  and a malformed `config.github` refuses the push. A visitor always passes
  through that consent page: an install that skips it connects nothing. Repositories a visitor connects are
  bound to this vibe like the owner's, so `ctx.github.fetch` and the
  `/_api/github-webhook` deliveries cover them too; a repository someone else
  already connected stays theirs.
- `ctx.github.routes()` lists the repos connected to THIS vibe and who
  connected each one, as
  `[{ repo, accountLogin, binderHandle, installationId }]`: `repo` is
  `owner/name` (lowercase, as stored), `accountLogin` is the GitHub account the
  App is installed on, `binderHandle` is the vibes.diy handle of the person who
  connected it (`undefined` when that account has no handle), and
  `installationId` is a number. It reads the platform's own records and makes
  no GitHub call, so it is cheap enough to run on every request. An unconnected
  vibe gets `[]`, never an error. This is how ONE vibe serves many people's
  repos: key per-repo settings by `repo`, and let only the person whose handle
  is `binderHandle` change them (compare it to `ctx.userInfo`).
  `/installation/repositories` answers the same question from GitHub: with
  repos from several installations it returns
  `{ total_count, repositories }` holding only the repos connected to this
  vibe, and ignores `per_page`/`page`.

- `{ db }` names the Fireproof database (same names `App.jsx` uses with
  `useFireproof`). It is **required** — except inside `onChange`, where the
  database that triggered the event is the default.
- Always `await` db calls; they resolve only after the write commits (or throw
  when the access function denies it).
- **Every read carries the doc's revision as `_rev`.** `ctx.db.get`, each
  `ctx.db.query` row and the `onChange` event's `doc` include `_rev`. It is a
  reserved field the platform fills in on read and never stores, so spreading
  a read straight into a put is safe. `get` and `query` rows also carry `_id`;
  the event's id is `event.docId`.
- **`ifRev` makes a write a compare-and-set.** `ctx.db.put(doc, { db, id, ifRev: doc._rev })`
  commits only if the doc is still at the revision you read. Pass `null` to
  write only if the doc does not exist yet — a deleted doc counts as not
  existing, just as `get` returns `null` for it. If anyone else wrote the doc in
  between, even with identical content, the put throws with
  `err.code === "conflict"` and `err.currentRev` (the revision there now, `null`
  when the doc is gone), so of several racing handlers exactly one succeeds.
  The access function still runs on every put, so its `oldDoc.status` check
  plus `ifRev` is an exclusive claim. A conflict is an answer, not a failure:
  someone else has the doc, so return. Leave `ifRev` out and a put is
  last-writer-wins, as always. This is `backend.js` only: `useFireproof`
  writes in the browser are local-first and keep last-writer-wins, except
  that a create `access.js` approved with `oldDoc === null` commits only while
  the record is still absent (see *A claim-once offer* below).

  ```js
  try {
    await ctx.db.put({ ...event.doc, status: "running" }, { db: "jobs", id: event.docId, ifRev: event.doc._rev });
  } catch (err) {
    if (err.code === "conflict") return; // another run claimed it first
    throw err;
  }
  ```
- **A record a handler may write twice is created once and read back.** A
  return page that reloads, a webhook that retries and a sweep beside them can
  all reach the same record, even at the same moment. Create it with
  `ifRev: null`; a second writer then gets `err.code === "conflict"`, or
  `"access-denied"` when `access.js` keeps the record write-once
  (`if (oldDoc) throw { forbidden: ... }`). Either way, read the record with
  `ctx.db.get` and answer from it: when it holds the same completed operation
  (the same session id and amount), that is success; anything else is a real
  error to report.

  ```js
  try {
    await ctx.db.put(tip, { db: "tips", id: "tip:" + tip.sessionId, ifRev: null });
  } catch (err) {
    if (err.code !== "conflict" && err.code !== "access-denied") throw err;
    const stored = await ctx.db.get("tip:" + tip.sessionId, { db: "tips" });
    if (stored?.sessionId !== tip.sessionId || stored.amount !== tip.amount) throw err;
  }
  ```
- `ctx.db.get(id, { db })` resolves the single document with that `_id`, or
  `null` when it is missing or deleted. It is the right read whenever you can
  name the document — a tick's state doc, a token lookup, a singleton. Never
  scan a database looking for a doc whose id you already know.
- `ctx.db.query({ db, field, key, keys, range, prefix, limit, after })` reads a
  **page** of the database's latest docs. Every filter is optional and they
  combine: `field` names the document field to match on, then `key` (one exact
  value), `keys` (any of several), `range` (`[from, to]`) or `prefix` (a string,
  or an array prefix — charwise-encoded, same semantics the client's queries
  use) narrows it. Three edges to get right: **no `field` means no filtering**
  (you get a raw page of everything), a bare `field` with no selector still
  drops docs that lack that field, and `prefix` takes the **raw** value — a
  plain string or array, never anything pre-encoded (the encoding is internal).
  `limit` only clamps the page **down**; the 2000-doc cap stays. Ask for what
  the handler actually needs — reading the whole database and filtering in the
  handler wastes the cap and goes blind as the app grows. Sorting still happens
  in the handler.
- The result is a real `Array` of docs that **also** destructures — both
  `const docs = await ctx.db.query(...)` and
  `const { docs, next } = await ctx.db.query(...)` work.
- **Paginate on `next`, never on emptiness.** `next` is computed from the raw
  page *before* filtering, and only when that page came back full — so a
  narrowly filtered page can be **empty and still carry `next`**. Stopping at
  the first empty page silently truncates the read:

  ```js
  let after;
  do {
    const page = await ctx.db.query({ db: "faves", field: "type", key: "favorite", limit: 500, after });
    for (const doc of page) {
      // …
    }
    after = page.next;
  } while (after);
  ```

  `next` rides on the array itself, so read it **before** transforming: any
  array operation (`.filter()`, `.map()`, spread) returns a plain array with no
  `next`. On the last page the property is absent, not undefined — `"next" in
  page` is `false`.
- Both reads are read-gated as the acting identity, through the same gate. In
  `onChange` and in a signed-in `fetch` a bound database reads **filtered to the
  acting user's channels** — the same per-reader filter the client's own reads
  use, so the handler sees exactly what that user could see: the triggering
  user's neighbouring docs for dedup, rank and "don't repeat what's already
  there" checks, or the calling user's own docs for a page's `apiFetch` route,
  and nothing privileged. A doc outside those channels reads as `null` from
  `get`, the same as one that isn't there. A `fetch` caller with no session
  reads the databases `config.fetch.unfilteredReads` names. In
  `scheduled` (admin mode) reads are
  **unfiltered** — access-fn-bound databases return every doc, across all users
  and channels. Made for `scheduled` sweeps: read, decide, then `put`/`delete`.
- The one exception to that last sentence is the declared opt-in above,
  `config.fetch.unfilteredReads` — a `fetch` handler that names a database there
  reads it unfiltered, anonymous callers included, and owes the authorization
  check itself. Nothing changes for writes, or for any lane or database you
  didn't name.
- `ctx.secrets` carries the **owner's own** per-vibe secrets, set in Code mode
  under **App settings** › **Secrets** or with `vibes-diy secrets set KEY`. Use it to verify inbound
  credentials — a webhook's shared secret or token — or to authenticate outbound
  calls to a service the owner holds a key for (`Authorization: Bearer
  ${ctx.secrets.KEY}` to an admitted API). Never write a value anywhere users
  can read it (a doc, a response body). Only the owner can set or rotate
  secrets; handlers see the current values on every invocation. A feature
  that cannot work until the owner has set one is a setup item: the `/setup`
  verdict and the owner-only Setup surface are the use-vibe docs' *Some apps
  need setup before they work*, and the skill that needs the secret
  contributes the item and its linked steps. **A visitor's
  own account (their GitHub, Threads, Instagram) is never a secret and never a
  pasted token — it is a connection**: declare it in `config.connections`, let
  the platform hold the credential, and read it through `@vibes.diy/social` or
  `ctx.connections` (the `connections` skill).
- **Outside data starts from a public source that answers with no key.** When
  the app wants real data from outside (rates, weather, food, facts, places, books,
  quakes, music), reach first for an open source a plain `ctx.fetch(url)`
  reads, so the feature works the moment it is built, for an owner with no
  vendor accounts: exchange rates from Frankfurter
  (`https://api.frankfurter.app/latest?from=USD`), forecasts from Open-Meteo
  (the `weather` skill), foods and their nutrition from Open Food Facts,
  summaries and facts from Wikipedia's REST API, books
  from Open Library, countries from REST Countries, earthquakes from the USGS
  GeoJSON feeds, places from OpenStreetMap's Nominatim, artists and releases
  from MusicBrainz. The reply says where the data comes from in one plain
  clause ("rates from the European Central Bank, via Frankfurter, refreshed
  each hour"), and the app opens with no Setup item. A key-gated service is
  the path for data only a key opens, or for a service the person names; it
  rides the next bullet.
- **A service that answers only with the owner's key, and has no skill of its
  own** (live product prices, stock quotes, flight times, sports scores): build the
  feature in this pass against `ctx.secrets.<NAME>`, a name in capitals for that service (`PRICE_API_KEY`). The route calls the
  service with `ctx.fetch` (a plain `GET` with the key in the query string, when
  the service takes it there), keeps what it read with the time it read it, and
  answers `{ ok: false, reason: "missing-key" }` until the key is saved, which
  makes the key the app's one Setup item. The item's steps on the owner's
  screen, and your reply, name the secret, the service's page where the owner
  gets a key, and where it goes: in Code mode, **App settings** › **Secrets**,
  the name under **KEY**, the value beside it, then **Set**. The feature works
  the moment it is set.
- **Every value a vendor gives the owner lives in Secrets.** An API key, a key
  id and its private key, a signing secret or a token is one secret each
  (`VENDOR_KEY_ID`, `VENDOR_PRIVATE_KEY`), read in backend.js as
  `ctx.secrets.<NAME>` on each call, and the app's documents hold what the
  service answered and when. A multi-line private key pasted into the Secrets
  value field is kept whole, line breaks included, and backend.js signs with it
  there. When Secrets turns a value away, the reply says so in plain words with
  what the refusal said, and the keyed feature waits on that secret as the
  app's Setup item while the rest of the app works.
- **Make every outbound HTTP call with `ctx.fetch(...)`, never a bare `fetch(...)`.**
  It takes the same arguments as the web `fetch` and returns a `Response`. Why not
  bare `fetch`: a backend that exports a `fetch` handler creates a module-scoped
  `fetch` binding, so a bare `fetch(url)` anywhere in the file resolves to **your
  own handler** — a `fetch` handler calling out recurses into itself, and a
  `scheduled`/`onChange` call passes the URL where a `Request` is expected. `ctx.fetch`
  always reaches the real HTTP client. **It is policy-gated**, and three lanes
  admit a call.

  - **A plain read of a public URL goes through.** `ctx.fetch(url)` with no
    `method` (or `GET`/`HEAD`), carrying at most `accept`/`accept-language` and no
    credentials, reaches any ordinary https host from `fetch`, `onChange` and
    `scheduled` alike — so **an RSS or Atom feed, a public JSON API, an `.ics`
    file or a plain web page is readable today**, with no key, no arrangement and
    nothing to configure. The platform makes the request itself, identified as
    this app by a `User-Agent` naming it — the meaningful client name an API
    such as MusicBrainz asks for — so `headers` can leave `User-Agent` out. It
    serves a repeated read from a cache — for about five minutes by
    default, or for whatever lifetime the response asks for, held to between a
    minute and an hour. **Nothing is cached for less than a minute**, so a poll
    faster than that re-reads bytes the cache already holds. `"5m"` is the sound
    default for a feed that states no lifetime of its own, and slower suits a feed
    that changes a few times a day; a feed asking to be re-read sooner
    (`Cache-Control: max-age=60`) is the one case a faster tick earns.
  - **A CORS-open endpoint takes anything a browser could send** from the app's
    own page — same preflight rules, same `Access-Control-Allow-Origin` check,
    browser-forbidden headers like `Cookie` stripped. This is the lane a `POST`,
    an `Authorization:` header, or any custom header name travels on, so a write
    or a keyed API call needs the host itself to say yes.
  - **The platform's curated list** carries server-to-server APIs that send no
    CORS headers (`api.github.com` is seeded; additions are a PR to the platform
    repo). A shop's own orders read from there too, with the owner's key from
    `ctx.secrets`: Squarespace Commerce (`GET https://api.squarespace.com/1.0/commerce/orders`,
    `/1.0/commerce/orders/{id}` and `/1.0/profiles`, sent with
    `Authorization: Bearer <key>` and a `User-Agent`) and Shippo
    (`GET https://api.goshippo.com/orders/`, `/orders/{id}`, `/transactions/`,
    `/transactions/{id}`, `/parcels/{id}` and `/user-parcel-templates`, sent with
    `Authorization: ShippoToken <key>`). These two are read lanes, so the app
    shows orders and labels and the person buys labels and marks orders
    fulfilled in Squarespace and Shippo themselves.

    **Emailing, notifying or reminding a person is `ctx.notify`.**
    `ctx.notify` reaches a person in the app by handle — the owner, a member, a
    manager — on their bell, their push and their email, so "email the manager
    every Monday", "email me a weekly digest" and "send the owner a summary" are
    each a `scheduled` handler that calls `ctx.notify`. A recipient who is not in
    the app yet joins it through the app's invite: the person picker takes their
    handle, or takes their email address and mails them an invite, and once they
    arrive every notification reaches them. Keep the record in the app too, so the app's
    own screen shows what went out.

    **A Catch Hook carries a record to a tool the person names.** When the ask
    names Slack, Google Sheets, a CRM, Airtable, Notion, Clio, HubSpot or Zapier
    itself, `hooks.zapier.com` is on the curated list for a `POST` to a Catch Hook, so
    the app hands the new record to that tool without holding its credentials.
    The owner makes a Zap whose trigger is "Webhooks by Zapier → Catch Hook",
    saves the hook URL as a secret (`vibes-diy secrets set ZAPIER_HOOK_URL ...`),
    and the backend posts JSON to `ctx.secrets.ZAPIER_HOOK_URL`. The URL **is**
    the credential, so it stays in the secret, out of every document and response
    body. Write that path gated on the secret
    (`if (!ctx.secrets.ZAPIER_HOOK_URL) return;`), so the app works fully before
    any Zap exists, and say in your reply that connecting a Zap to the hook turns
    that delivery on. Treat any 2xx as accepted and mark the record sent; on
    anything else **throw** — a handler that returns normally has acknowledged
    the event, so the platform will not call it again for that write, while a
    thrown `onChange` is re-delivered with backoff (a handful of tries over a few
    minutes) and a run that never succeeds lands in the app's logs. Records
    travelling the other way, from a tool into the app, arrive at `fetch`:
    see *Records in from Zapier* below.

    ```js
    export async function onChange(event, ctx) {
      const doc = event.doc;
      if (event.deleted || doc.type !== "intake" || doc.sentToZapier) return;
      if (!ctx.secrets.ZAPIER_HOOK_URL) return; // no Zap connected yet: the record stays in the app
      const res = await ctx.fetch(ctx.secrets.ZAPIER_HOOK_URL, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ type: doc.type, name: doc.name, email: doc.email }),
      });
      if (!res.ok) {
        ctx.log("warn", "zapier hook refused", { status: res.status });
        throw new Error(`zapier hook ${res.status}`); // re-delivered with backoff
      }
      await ctx.db.put({ ...doc, sentToZapier: true }, { db: event.dbName, id: event.docId });
    }
    ```

  A call outside all three returns
  `403 {"vibesEgressDenied":true,"gate":"floor"|"owner-blocked"|"cors"|"read-rate"|"rate-limit","host":...}`,
  and `gate` says which lane refused: `cors` is a write or a credentialed call to
  a host that never opted us in, and `read-rate` means the read lane's own tighter
  budget (10 per 10s, 60 per minute) is spent for the moment, which the next tick
  clears. Check for that shape and surface a useful error. Remedies: read it as a
  plain `GET`, use a CORS-open endpoint,
  request a curated-list addition, or ask about owner blessing. The creator-facing
  version of this gate — including what to do when a link is reported as taking
  more power than the app has today — is at
  https://good.vibes.diy/docs/your-app-has-a-backend, which is the page to send
  someone to. **A refused vendor host is reported by name.** The route answers
  with the gate and the host, the screen says that service opens to the app
  once the platform admits it, and the reply names the host, says the refusal
  is on record, and says opening it is a reviewed change to the platform's
  curated list, asked for in Discord. The calls stay pointed at the vendor's
  own address through `ctx.fetch`, so they go through unchanged the day the
  host is on the list. Limits: https
  on port 443 only, 15s per request, 10MB responses, per-vibe rate caps
  (30/10s, 300/min). Make all outbound calls **before returning** the Response —
  a `ctx.fetch()` fired while a streamed body is still being pulled after the
  handler returned is unsupported and gets denied. Interactive frontend AI
  calls stay in `App.jsx` via `callAI`; server-side AI belongs to `ctx.callAI`.

  **A server the person runs themselves is reached at its https address.** A
  media server, a home dashboard, a NAS or a printer on their own network works
  from a vibe once it answers at a public `https://` name: every vibe is served
  over https, so the page and `ctx.fetch` both call https hosts. The person gets
  that address from the server's own https setting, a reverse proxy with a
  certificate in front of it, or a tunnel that gives the server a public https
  name. When the person names a server of their own, say that in your first
  reply, before the build, so they can set the address up while the app is
  being made; an app that reads a platform (YouTube, a weather service) or
  keeps its own records goes straight to what the person came to do. The app's connect form takes the
  server's https address (placeholder `https://media.example.com`), saves it
  with the person's other settings, and its helper line names those three ways
  to get one. A call carrying the person's token, and any write, travels the
  CORS lane: the server admits the app's origin in its CORS settings (media
  servers usually have one), and the page calls it straight with that token. A
  plain public read (a `GET` with no credentials) also works from a
  `backend.js` route at that https address, through the read lane above.
- **`ctx.callAI(prompt, options?)` is the server-side AI call.** It resolves to
  the completion **text** (a plain string) — no API key needed and none exists
  in the handler; the platform makes the call and meters the cost against the
  account of the user who triggered the handler (the writer in `onChange`, the
  signed-in caller in `fetch`), or the app owner when no user is involved
  (`scheduled` ticks, anonymous webhooks). Options: `model` (default
  `"openrouter/auto"`), `max_tokens`, `temperature`, `schema`. No streaming.
  **Schema mode works the same way it does in `App.jsx`**: pass
  `{ schema: { properties: { … }, required: [ … ] } }` and the platform
  constrains the model the best way that model supports (native JSON schema,
  tool mode, or a schema system message). The result still comes back as a
  **string** — `JSON.parse` it. List every key of `properties` in `required`: a
  field missing from `required` fails the call as `ai gateway error (status 400)`,
  and a catch that degrades hides it, so read `npx vibes-diy app logs <vibe>`
  when a schema call keeps returning the fallback. When you pass a schema and name no `model`,
  the default shifts to a schema-capable model rather than
  `"openrouter/auto"`. Budget: a handful of calls per invocation (currently 5)
  and ~64k prompt **characters**; a denied or failed call **throws** — catch it and degrade
  (e.g. write the doc back with an error field) rather than losing the event.
  Keep interactive/streaming AI in `App.jsx` via `callAI`; use `ctx.callAI`
  when the result must be server-authoritative (moderation, digests,
  summaries users shouldn't be able to forge). `ctx.callAI` answers a
  question the handler then writes down: a summary, a score, a verdict, the
  fields of a receipt. When the model's reading decides **what the app does**
  (add this order, skip that note, tell the owner), that is `ctx.agent.run`
  over the app's tools: *Let an agent do the work* below.
- **`ctx.webSearch(query, { maxResults })` searches the web.** When the app looks something up on the web, call `ctx.webSearch`.
  It is the platform's own search, ready with no key or setup, and it is the
  way to find shop listings, news, opening hours and anything new on a topic.
  It resolves to `{ results, summary }`: `results` is up to `maxResults`
  (1–5, default 5) `{ title, url, snippet }` entries, each `url` an https link,
  and `summary` is a short plain-text digest of what they say. A query is up to
  300 characters, plain words, as specific as the ask allows. Each search runs
  on the same account `ctx.callAI` bills (the app owner on a `scheduled` run),
  a couple of credits a search, with up to 10 searches a handler run; past that, or out
  of credits, the call **throws** an Error whose `reason` is `"budget"` or
  `"credits"`, so catch it, keep what the run already found, and let the next
  run carry on. A search that finds nothing throws with `reason` `"empty"`, so
  the links a record already has stay in place. Results are web data: store them, show them, or hand them to
  `ctx.callAI` as quoted data for judging, and keep the handler's own
  instructions in charge. Save each result's `url` with it so the page can link
  the source:

  ```js
  // A saved cursor walks the whole list a few wishes a tick, then starts over at the top.
  export async function scheduled(event, ctx) {
    const saveCursor = (after) => ctx.db.put({ after }, { db: "wishes", id: "state:watch-cursor" });
    let after = (await ctx.db.get("state:watch-cursor", { db: "wishes" }))?.after;
    let searched = 0;
    for (let pages = 0; pages < 10 && searched < 8; pages++) {
      const page = await ctx.db.query({ db: "wishes", field: "watching", key: true, limit: 8 - searched, after });
      for (const wish of page) {
        let found;
        try {
          found = await ctx.webSearch(`${wish.name} buy online in stock`, { maxResults: 5 });
        } catch (err) {
          if (err.reason === "empty") continue; // nothing new: keep this wish's last links
          ctx.log("info", "search paused for this run", { reason: err.reason ?? err.message });
          return saveCursor(after); // the next tick picks this page up again
        }
        searched++;
        const links = found.results.map((r) => ({ title: r.title, url: r.url, snippet: r.snippet }));
        await ctx.db.put({ ...wish, links, checkedAt: new Date().toISOString() }, { db: "wishes", id: wish._id });
      }
      after = page.next; // a filtered page can be empty and still carry `next`
      if (!after) break; // the end of the list: the next tick starts over
    }
    await saveCursor(after);
  }
  ```

- **`ctx.notify({ toHandle, body, dedupeKey, path, picture })` sends one person a notification.**
  It takes a single object; `toHandle`, `body` and `dedupeKey` are required and
  `path` and `picture` are optional — match the object form in the example above, which is the
  calling convention (codegen has been observed passing these positionally).
  The message lands in that person's bell, inbox, and push notifications.
  A notify to the app's own owner (`ctx.appInfo.ownerHandle`) also reaches
  the assistant that made the app, in the chat it was made from, so send the
  owner a notify when something needs a decision or a job is done, never on
  every tick.
  - `toHandle` is one handle, and the platform delivers to people already in
    this app: the owner, who always qualifies, an accepted invite or approved
    request, a handle named in the access function's persisted grant state, or
    somebody whose authenticated write reached the app (anonymous writes don't
    count). Invite, request, and writer membership resolve the person through
    their bound handle; the grant-state clause matches the named handle
    itself. Explicit revocations deny anyone but the owner. A passing check
    plus valid fields writes the notification into the inbox history of a
    recipient the platform can resolve — an unresolvable handle fails the call
    after the participation check. Their switches silence the live bell, the
    push, and the email — not the history.
  - When the notification is the opt-in kind — your turn, your order shipped —
    seat the player the way a guest takes their own seat.
    A turn notification goes to a seat its owner took themselves.
    A join write where the added handle must equal `user.userHandle` qualifies
    the writer by their own act. This is an app-side convention for notifiable
    seats, not a rule about read grants: chosen-peer grants that share without
    notifying — inviting a collaborator into a shared list — stay intentional,
    and a grant-named handle stays eligible whether or not its owner seated it.
  - `body` is the whole message — plain text, 500 chars max. The platform
    titles it with the app's name and links it back to the app, so spend the
    body on what happened and who it concerns.
  - `dedupeKey` names the happening, so one event delivers once however many
    times the handler runs: `"round-4-started"`, `"order-42-shipped"`,
    `"game-7-turn-3"`. The platform keys it per (app, recipient).
  - `path` says WHERE in your app the notification points, so the bell and the
    email land on the thing it is about instead of your front page. It must be
    a `#` fragment — `"#game-7"`, `"#order/42"` — of at most 200 characters with
    no spaces or line breaks, and nothing else: a fragment can only ever address
    a position inside your own app, which is why it is the only form allowed.
    Omit it and the notification links to the app itself, exactly as before.
    **A malformed `path` fails the whole `ctx.notify` call** (the promise
    rejects) rather than being quietly ignored — so a dead deep link is
    something you find out about, not something your users find out about.
  - `picture` sends a picture with the words.
    A picture goes with the words as `picture`, never as a link in the body.
    Name a record of this app the way
    you would read it, `{ dbName: "posters", docId: poster._id }` (an image
    button's record works as is, and `fileKey` picks one of a record's several
    files), or pass one of its own file URLs, `poster._files.art.url`. Someone
    reached by text gets it as a photo under the words. The platform sends it
    only to a person who could open that record in the app, as a png, jpeg, gif
    or webp of at most 5 MB; anything else goes as the words alone and never
    fails the call. With a picture named, the call resolves
    `{ picture: "attached" }` or `{ picture: "text-only", reason }`, so log the
    reason when it matters.
  - Read it back in `App.jsx` from your own hash, and listen for changes,
    because a click while the app is already open moves the hash without
    reloading:

    ```jsx
    const [target, setTarget] = useState(() => window.location.hash.slice(1));
    useEffect(() => {
      const onHash = () => setTarget(window.location.hash.slice(1));
      window.addEventListener("hashchange", onHash);
      return () => window.removeEventListener("hashchange", onHash);
    }, []);
    // target === "game-7" → open that game
    ```
  - `await` it and let it throw. Success resolves with nothing to inspect; a
    missing field, an over-long body, or a handle outside the app rejects the
    promise. Usually the surrounding work should survive an undeliverable
    message, so catch it and carry on:

    ```js
    try {
      await ctx.notify({
        toHandle: game.opponent,
        body: "Your turn",
        dedupeKey: `game-${game._id}-turn-${game.turn}`,
        path: `#game-${game._id}`, // lands them on THAT game, not the lobby
      });
    } catch (err) {
      ctx.log("warn", "notify failed", { game: game._id, reason: err.message });
    }
    ```

  - Reach for it when **one** person needs to know **one** thing: your turn,
    your request was approved, your order shipped. Each user also controls a
    "messages from a vibe" switch, so treat a notification as a nudge toward the
    app rather than the place the information lives.
  - When everyone using the app should see something — the schedule changed, a
    new round started — write that change to a database the audience already
    reads. Their `useLiveQuery` puts it on screen the moment it commits, for
    exactly the people entitled to see it, because the platform resolves that
    audience per reader at read time. The app's own screen is the source of
    truth; that's what makes it the right surface for anything shared.
- **Followers by text: a `subscribers` collection.** A public vibe can let
  anyone follow it from their phone, signed in or not: they text Vibes the
  vibe's link ("please notify me about the schedule on https://vibes.diy/vibe/…"),
  and Vibes writes ONE record for them into the vibe's `subscribers` database,
  `{ _id: "subscriber:<handle>", type: "subscriber", handle, authorHandle, created, until, about }`,
  then texts them each notification the vibe sends to that handle. The vibe
  opts in by giving `access.js` a `subscribers` function; with none, Vibes tells
  the texter this vibe doesn't send updates yet and saves nothing.

  ```js
  // access.js — one record per follower, written only by that follower.
  export function subscribers(doc, oldDoc, user, ctx) {
    if (!user?.userHandle) throw { forbidden: "sign in" };
    if (doc.type !== "subscriber" || doc.handle !== user.userHandle) throw { forbidden: "follow as yourself" };
    if (doc._id !== "subscriber:" + doc.handle) throw { forbidden: "one record per follower" };
    return { channels: ["subscribers"] }; // no grant: followers' handles stay with the owner
  }
  ```

  The writing is what makes a follower someone the app may `ctx.notify`. A
  `scheduled` handler reads the list in admin mode and tells each follower,
  keyed by the happening so a re-run sends nothing twice. Group things that
  happen at once into one message (two events at 5:00 PM are one text):

  ```js
  export const config = { scheduled: { interval: "1m" } };
  export async function scheduled(event, ctx) {
    const soon = startingWithin(10); // your own schedule, in its own time zone
    if (soon.length === 0) return;
    const nowIso = new Date().toISOString();
    const subs = [];
    let after;
    do {
      const page = await ctx.db.query({ db: "subscribers", field: "type", key: "subscriber", limit: 500, after });
      // A follow past its `until` texts nobody, so leave it out.
      subs.push(...page.docs.filter((d) => !d.until || d.until > nowIso));
      after = page.next;
    } while (after);
    const body = soon.map((e) => `${e.title} starts at ${e.time}${e.loc ? `, ${e.loc}` : ""}`).join("\n");
    for (const doc of subs) {
      try {
        await ctx.notify({ toHandle: doc.handle, body, dedupeKey: `soon-${soon[0].slot}`, path: `#${soon[0].id}` });
      } catch (err) {
        ctx.log("warn", "notify failed", { handle: doc.handle, reason: err.message });
      }
    }
  }
  ```

  Each follower is a record of its own, so tell each one something different.
  `doc.handle` is how you address a follower: an opaque Vibes handle (a texting
  guest's reads `vg-…`), never a phone number, and nothing in the record is one.
  `doc.about` is what they asked to hear about, in their words ("the Souwester
  weekend schedule has something starting"): match it against what is happening,
  or say it back so the text reads as an answer to their ask. Send the picture
  with the words the same way:

  ```js
  for (const doc of subs) {
    const about = (doc.about || "").toLowerCase();
    const mine = soon.filter((e) => !about || about.includes(e.stage.toLowerCase()));
    if (mine.length === 0) continue; // nothing they asked about starts now
    const body = mine.map((e) => `${e.title} starts at ${e.time}`).join("\n");
    try {
      const sent = await ctx.notify({
        toHandle: doc.handle,
        body,
        dedupeKey: `soon-${mine[0].slot}`,
        path: `#${mine[0].id}`,
        picture: mine[0].posterId ? { dbName: "posters", docId: mine[0].posterId } : undefined,
      });
      if (sent?.picture === "text-only") ctx.log("info", "poster went as words", { reason: sent.reason });
    } catch (err) {
      ctx.log("warn", "notify failed", { handle: doc.handle, reason: err.message });
    }
  }
  ```

  For the button, an `sms:` link opens Messages with the ask written out.
  Ask `https://vibes.diy/_text-number?for=vibes` for Vibes' phone number once on load:
  with it, the button texts from any phone, Android included. The number
  always comes from that answer and is never written out in the app. Until it
  answers, or when it names no number (every line is nearly full, or texting
  isn't set up yet), the same ask opens Vibes in the browser with the words
  waiting in the box (`https://vibes.diy/agent?text=`), and the reminders
  arrive as Vibes notifications. `?&body=` is the form both
  iOS and Android read for a phone number. `target="_blank"` is what lets the
  tap leave the app's frame:

  ```jsx
  const ask = `Please notify me about changes to the schedule on ${appUrl}`;
  const [textNumber, setTextNumber] = useState();
  useEffect(() => {
    fetch("https://vibes.diy/_text-number?for=vibes")
      .then((r) => (r.ok ? r.json() : null))
      .then((res) => res?.phoneNumber && setTextNumber(res.phoneNumber))
      .catch(() => {});
  }, []);
  const words = encodeURIComponent(ask);
  const href = textNumber ? `sms:${textNumber}?&body=${words}` : `https://vibes.diy/agent?text=${words}`;
  <a href={href} target="_blank" rel="noopener">{textNumber ? "Text me reminders" : "Get reminders"}</a>
  ```

  A follower ends it by replying "stop", and their follow lapses on its own
  after the days Vibes set for it.
- **Followers who answer: a `replies` collection.** A follower who texts back
  the vibe that just texted them ("yes, save me one", "7pm works", a photo of
  their dog) reaches the vibe itself: Vibes writes their answer into the vibe's
  `replies` database as them, `{ type: "reply", text, authorHandle, created }`,
  with any photos as files in `_files`, and your `onChange` hears it like any
  other write. `authorHandle` is the follower's handle, the same one on their
  `subscriber` record; their phone number never reaches the app. The vibe opts
  in by giving `access.js` a `replies` function; without one, the text is
  answered the ordinary way and nothing lands.

  ```js
  // access.js — each reply is its writer's own; the owner reads them all.
  export function replies(doc, oldDoc, user, ctx) {
    if (!user?.userHandle) throw { forbidden: "sign in" };
    if (doc.type !== "reply" || doc.authorHandle !== user.userHandle) throw { forbidden: "reply as yourself" };
    if (oldDoc && oldDoc.authorHandle !== user.userHandle) throw { forbidden: "your own reply" };
    return { channels: ["replies"] }; // no grant: the owner reads replies, followers don't read each other's
  }
  ```

  ```js
  // backend.js — tell the owner, keyed by the reply, so a re-delivery sends nothing twice.
  export async function onChange(event, ctx) {
    if (event.dbName !== "replies" || event.deleted || event.oldDoc) return;
    const words = event.doc.text ?? "sent a photo";
    await ctx.notify({ toHandle: ctx.appInfo.ownerHandle, body: `A follower replied: ${words}`.slice(0, 500), dedupeKey: `reply-${event.docId}` });
  }
  ```

  The vibe a reply goes to is the one that texted that phone most recently, in
  the last day. When two followed vibes texted within half an hour of each
  other, or the newest one takes no replies, the text is answered the ordinary
  way. A reply is no agent turn and costs no credits.
- **A claim-once offer is a record only its first writer creates.** "Last
  lemon cake, first to say mine gets it", "one seat left for Saturday": send
  the follower a notify whose `path` is `#claim=<id>`, and keep a `claims`
  database whose `access.js` lets the first claim stand. A follower who answers
  "mine" (or "me", "dibs", "I'll take it") makes Vibes write
  `{ _id: "<id>", type: "claim", authorHandle, via: "text", created }` into
  `claims` as them, and the texted link opens the app at `#claim=<id>`, where a
  signed-in visitor taps to write the same record from `App.jsx`. Both go
  through one gate: the platform commits a create that `access.js` approved
  with `oldDoc === null` only while the record is still absent, so two claims
  at the same instant never both land — the second is judged again against the
  first, and its `forbidden` reason is what it hears. Vibes texts the winner
  "It's yours!" and everyone after "That one's already taken".

  The claim has a home of its own: the `claims` database, with its own
  `claims` function in `access.js`, beside whatever database holds the loaves
  or seats themselves. Vibes reads a follower's "mine" as a claim when the
  vibe exports that `claims` function and the text they answer was sent with
  `path: "#claim=<id>"`, so the offer's notify names the claim id in its path
  every time. The app's other screens read `claims` to show what is taken.

  ```js
  // access.js — the first claim stands; its claimer may re-save it, nobody else may.
  export function claims(doc, oldDoc, user, ctx) {
    if (!user?.userHandle) throw { forbidden: "sign in to claim" };
    if (oldDoc && oldDoc.authorHandle !== user.userHandle) throw { forbidden: "already taken" };
    if (doc.type !== "claim" || doc.authorHandle !== user.userHandle) throw { forbidden: "claim as yourself" };
    return { channels: ["claims"], grant: { public: ["claims"] } }; // everyone sees it's gone
  }
  ```

  ```js
  // backend.js — offer it to every follower, once; and tell the owner who got it.
  await ctx.notify({ toHandle: doc.handle, body: "Last lemon cake of the day! Reply mine to claim it.", dedupeKey: "cake-42-offer", path: "#claim=cake-42" });

  export async function onChange(event, ctx) {
    if (event.dbName !== "claims" || event.deleted || event.oldDoc) return;
    await ctx.notify({ toHandle: ctx.appInfo.ownerHandle, body: `${event.docId} is claimed`, dedupeKey: `claimed-${event.docId}` });
  }
  ```

  ```jsx
  // App.jsx — the tapped link lands on #claim=<id>; one tap claims it for a signed-in visitor.
  const { database, useLiveQuery } = useFireproof("claims");
  const { viewer, requestLogin } = useViewer();
  const claimId = target.startsWith("claim=") ? target.slice(6) : undefined; // `target` from your hash
  const claim = useLiveQuery("_id", { key: claimId ?? "" }).docs[0];
  const take = () =>
    viewer
      ? database.put({ _id: claimId, type: "claim", authorHandle: viewer.userHandle, via: "tap", created: new Date().toISOString() })
      : requestLogin();
  // claim ? (claim.authorHandle === viewer?.userHandle ? "It's yours!" : "Already taken") : <button onClick={take}>Claim it</button>
  ```
- **`ctx.log(level?, ...args)` is the handler's diagnostic lane.** It is the
  output that reaches the owner, who reads it back with
  `vibes-diy app logs <owner>/<slug> --since 1h [--tail]` — the isolate's
  `console` output is collected nowhere, so route anything worth seeing later
  through `ctx.log`. The level is optional and comes first (`"debug"`, `"info"`,
  `"warn"`, `"error"`); any other first argument is the message and the level
  defaults to `info`, so `ctx.log("cache miss", { key })` and
  `ctx.log("warn", "feed empty", { url })` both work. Log the shape of a run
  rather than its contents: document ids, counts, statuses, timings, and an
  error's message and code. Identifiers make the stream diagnostic while users'
  document bodies and `ctx.secrets` values stay in the handler.

## Worked external-data pattern — cache into the live database

A public feed reads fine from a handler, and a run can still come back empty —
the host is down, the shape changed, the read budget is spent for the minute.
Never fetch an external feed from render or a React effect. Poll once per tick,
normalize a bounded number of rows into the exact database and document shape
the UI queries, and keep the last successful rows when refresh fails. Seed a
small honest snapshot before the first request so even a first-run denial has
something useful to show.

This complete example makes one curated GitHub API request every 15 minutes
(well inside the documented caps), stores at most 20 normalized `release` docs
in `nodeReleases`, and records refresh state in that same database.

### `backend.js`
```js
export const config = { scheduled: { interval: "15m" } };

const SNAPSHOT = [
  {
    _id: "release:snapshot-v22",
    type: "release",
    title: "Node.js 22 (saved snapshot)",
    url: "https://nodejs.org/en/blog/release/v22.0.0",
    publishedAt: "2024-04-24T00:00:00.000Z",
    source: "saved-snapshot",
  },
];

async function ensureSnapshot(ctx) {
  // Point-read by id — the snapshot has a known `_id`, so there's nothing to scan for.
  if (await ctx.db.get(SNAPSHOT[0]._id, { db: "nodeReleases" })) return;
  for (const doc of SNAPSHOT) await ctx.db.put(doc, { db: "nodeReleases" });
}

// True only when every tracked field of the desired doc already matches what's
// stored — extra stored keys (like `_rev`) are ignored. This is what lets a
// tick that changes nothing write nothing.
function unchanged(existing, next) {
  if (!existing) return false;
  return Object.keys(next).every((k) => existing[k] === next[k]);
}

// The diff source is a POINT-READ per incoming id, not a query over the stored
// set: the work is bounded by what the feed sent (≤20 docs), never by how big
// the database has grown — so a db that outgrows a query page can never
// silently eject rows from the diff and turn this tick into a rewrite loop.
// The database is a parameter: every doc a helper writes has to land in the db
// the UI live-queries, and a helper with one baked-in name is how a status doc
// ends up somewhere nothing reads.
async function putIfChanged(ctx, next, db) {
  const existing = await ctx.db.get(next._id, { db });
  if (unchanged(existing, next)) return;
  await ctx.db.put(next, { db });
}

export async function scheduled(event, ctx) {
  ctx.log("debug", "refresh tick", { at: event.scheduledTime }); // proof of life, before any read
  await ensureSnapshot(ctx);

  // One request, no retry storm; ctx.fetch enforces 15s/10MB and egress caps.
  const response = await ctx.fetch("https://api.github.com/repos/nodejs/node/releases?per_page=20", {
    headers: { accept: "application/vnd.github+json" },
  });

  if (response.status === 403) {
    const denied = await response
      .clone()
      .json()
      .catch(() => null);
    if (denied?.vibesEgressDenied === true) {
      // A real state change — putIfChanged writes once on entering denial, then
      // nothing while it persists. No per-tick timestamp, so no churn.
      await putIfChanged(ctx, {
        _id: "refresh:status",
        type: "refreshStatus",
        state: "egress-denied",
        message: "showing saved data — live refresh unavailable",
      }, "nodeReleases");
      return; // preserve the seeded/last-good release docs
    }
  }

  if (!response.ok) return; // transient failure: keep last-good rows, write nothing

  const rows = await response.json().catch(() => null);
  if (!Array.isArray(rows) || rows.length === 0) return; // empty upstream: abort, no writes

  for (const row of rows.slice(0, 20)) {
    if (!row?.id || !row?.html_url || !row?.published_at) continue;
    // Stable per-item `_id` + diff: a row whose content is identical is skipped.
    await putIfChanged(ctx, {
      _id: `release:github-${row.id}`,
      type: "release",
      title: String(row.name || row.tag_name || "Node.js release"),
      url: String(row.html_url),
      publishedAt: String(row.published_at),
      source: "github-live",
    }, "nodeReleases");
  }

  await putIfChanged(ctx, {
    _id: "refresh:status",
    type: "refreshStatus",
    state: "fresh",
    message: "Live feed refreshed",
  }, "nodeReleases");
}
```

### `App.jsx`
```jsx
import React from "react";
import { useFireproof } from "use-fireproof";
import { Badge, Heading, RowCard, Stack, Text } from "@vibes.diy/ui";

export default function App() {
  const { useLiveQuery } = useFireproof("nodeReleases");
  const { docs: releaseDocs } = useLiveQuery("type", { key: "release" });
  const { docs: statusDocs } = useLiveQuery("type", { key: "refreshStatus" });
  const releases = [...releaseDocs].sort((a, b) => b.publishedAt.localeCompare(a.publishedAt));
  const status = statusDocs.find((doc) => doc._id === "refresh:status");

  return (
    <main className="min-h-screen bg-background text-foreground font-sans mx-auto max-w-2xl p-6">
      <Stack gap={5}>
        <Heading level={1}>Node.js releases</Heading>
        {status?.state === "egress-denied" && (
          <div role="status">
            <Badge tone="info">showing saved data — live refresh unavailable</Badge>
          </div>
        )}
        <Stack gap={3}>
          {releases.map((release) => (
            <RowCard key={release._id}>
              <a className="font-bold underline" href={release.url} target="_blank" rel="noreferrer">
                {release.title}
              </a>
              <Text size="sm" muted>
                {release.publishedAt.slice(0, 10)}
              </Text>
            </RowCard>
          ))}
        </Stack>
      </Stack>
    </main>
  );
}
```

The `vibesEgressDenied` body is a policy result, not proof that the upstream is
down. Catch that exact 403 shape and show the saved snapshot with honest copy —
**"showing saved data — live refresh unavailable"**. Never clear cached rows,
render a broken screen, or silently label saved data as fresh.

**Zero-churn discipline for scheduled ticks.** A cron runs forever, so it must
not write forever. Give every item a stable `_id` and `put` **only** the rows
whose content actually changed — the `putIfChanged` diff above, which
point-reads each id it is about to write. Diff against **point-reads of the
incoming ids**, so the work is bounded by what arrived this tick, not by how
big the database has grown; reach for a keyed `ctx.db.query` only when the
stored set itself is the target (and then walk `next` to exhaustion before
diffing — a one-page diff source re-puts everything the page missed, forever). Never stamp a per-tick `checkedAt`/`updatedAt`/run
counter onto a doc: it makes every put look new, and each spurious put mints a
fresh revision and a sync-feed row that re-tickles every replica on every tick.
A failed or empty upstream fetch aborts with no writes, preserving the last-good
rows. Only a genuine content change — a new or updated row, a real state
transition — earns a write.

**A tick's own memory is a document it reads by id.** Whatever a scheduled
handler needs to know about what it already did — a cursor, a last-synced
marker, a per-run state — lives in one doc with a fixed `_id`, read with
`ctx.db.get(id, { db })`. Never re-derive that answer by scanning the database:
a sweep that diffs against its own whole-db read goes blind the moment the
database outgrows one page, and then rewrites everything on every tick, forever.
Keep a copy of the state in module scope as well, and read a **missing or failed**
state read as *"don't know — skip this tick"*, never as *"nothing has been done
yet"*: that second reading is exactly what restarts the endless rewrite. That
state doc is owner-only in `access.js` — it is what the tick believes about
itself, so keeping it to the owner is what keeps anyone else from steering the
tick.

**A follow-up read per item waits on a capped list the tick reads by id.** A
second call for each item a page brought in (a customer's profile behind each
order, a detail call behind each list row) goes on a capped list in a
fixed-id state doc (the Squarespace example's `sync:recheck`), and each tick
reads a few of them, most overdue first. Done inline per item, a big first
page spends the provider's rate limit partway through; the watermark rightly
holds, so the next tick spends it at the same place and the sync never
finishes. The tick finds the due entries by reading that list: a
`ctx.db.query` on a flag field filters one raw page, so due entries go unread
once other records outnumber them.

## fetch — the app's HTTP endpoint

Runs for requests to the app's `/_api` route. The request path is rooted after
`/_api`: a call to `https://slug--owner.host/_api/webhooks/pay` arrives with
pathname `/webhooks/pay`. Return a standard `Response`.

### `backend.js`
```js
export async function fetch(request, ctx) {
  const url = new URL(request.url);
  if (url.pathname === "/rsvp" && request.method === "POST") {
    const body = await request.json();
    const id = await ctx.db.put({ kind: "rsvp", name: body.name, at: Date.now() }, { db: "rsvps" });
    return new Response(JSON.stringify({ ok: true, id }), {
      headers: { "content-type": "application/json" },
    });
  }
  return new Response("not found", { status: 404 });
}
```

From `App.jsx`, call it with a relative fetch — no host needed:

### `App.jsx`
```js partial
const res = await fetch("/_api/rsvp", { method: "POST", body: JSON.stringify({ name }) });
```

The platform's answers are worth recognising. `404 backend.js _api: not found`
means the app has no `fetch` handler to run. When a handler throws, the caller
gets a `500` whose body names only the error class — `backend.js threw:
TypeError. Details are in this app's backend log: …` — and the full message is
written to the app's log, where `vibes-diy app logs <owner>/<slug>` shows it. A
`502 backend.js failed to run` means the module never started, most often an
error at the top level of `backend.js`. So a route that expects trouble — an
upstream that can be down, input that can be malformed — catches it and answers
`{ ok: false, reason }` with a status the app can show, and the platform's 500
stays the signal for a bug to fix.

A connected GitHub repository's deliveries arrive here too, as a `POST` to
`/_api/github-webhook`, already verified by the platform, with the event name
in `x-vibes-github-event`, GitHub's delivery id in `x-vibes-github-delivery`
(key writes by it — a delivery can arrive twice), the handle of the person
who connected that repo in `x-vibes-github-binder` (left off when they have no
handle), and an untrusted third-party body; a `4xx` ends the delivery, and a
throw marks it failed (GitHub does not retry it). `x-vibes-github-binder` is
how a vibe shared by many people knows whose repo an event belongs to, and so
whose settings apply. The platform sets it, the same as
`x-vibes-github-event`, so you can trust it: any `x-vibes-*` header a caller
sends is deleted before the platform adds its own. It matches the
`binderHandle` that `ctx.github.routes()` returns for that repo.

A delivery **runs as the person who connected the repo**: `ctx.userInfo` is
them, `ctx.db` writes pass `access.js` as them (`user.backend === "fetch"`,
`user.userHandle` equal to `x-vibes-github-binder`), reads see their channels,
and `ctx.callAI` runs on their credits. So a review bot keeps each person's
records in that person's channel, and every repo's activity is paid for by
the person who connected it. The consent page tells them so before they
connect.

`/_api` opens to every caller once the app is published. Before its first
publish, and after the owner unpublishes it, the routes answer the app's own
people — its owner, its developers, and anyone it is shared with — and
everyone else gets `404 backend.js _api: not found` without the handler
running. The page reaches its own routes in every state through `apiFetch`
(below), which arrives as the signed-in visitor. `call_own_api`, `onChange`
and `scheduled` keep running, and a connected GitHub webhook runs until the
owner unpublishes.

### Who is calling: `ctx.userInfo` comes from the request, never a cookie

Cookies are not read. `ctx.userInfo` is filled in three ways:

- **The app's own page, through `apiFetch`** from `use-vibes`. The platform
  makes the call for the signed-in visitor, so the handler runs as them:
  `ctx.userInfo` is that visitor, their `ctx.db` writes pass `access.js` as
  them, and `ctx.connections` spends their connection. A visitor who is not
  signed in arrives as `ctx.userInfo === null`.
- **A caller outside the app** — a script, another agent, a server — sends the
  person's vibes.diy token as `Authorization: Bearer <token>`. A missing,
  expired or unrecognised token is not an error: the handler runs with
  `ctx.userInfo === null`, so a route that needs a person answers `401` itself.
- **The builder's own `call_own_api` check** (see the debugging skill) arrives
  already verified, as the app's owner, with no bearer header.

A plain `fetch("/_api/...")` from `App.jsx` carries no visitor, so the handler
sees `ctx.userInfo === null`. That suits routes that should not depend on who
is asking — reading a page, calling a service with a secret — and such a route
reads only the databases it declares (_A route guests call reads only what it
declares_, above). **When a route
needs to know the visitor — their own records, their connection, their
permissions — the page calls it with `apiFetch`.** The path is the route under
`/_api`, and the answer reads like a `Response`:

### `App.jsx`
```jsx partial
import { apiFetch } from "use-vibes";

const res = await apiFetch("/my-rsvp", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ going: true }),
});
const mine = res.ok ? await res.json() : null;
```

A route's own error status resolves with `ok: false`; `apiFetch` rejects only
when the route could not be reached. Bodies are strings, and answers are for
JSON-sized results rather than exports. Screens that simply list the visitor's
own records still read best from the database hooks, which already know who is
signed in.

Writes a handler makes with `ctx.db.put` still pass through `access.js` as the
caller, so the app's rules hold for API writes too.

### A route knows who is calling from `ctx.userInfo`

Identity comes only from `ctx.userInfo`.
A route that acts for a person reads who they are there, the one place the
platform verified, and compares that handle with the record it guards. The
query, the body and the app's own headers carry what the caller chose to send,
so they name the thing being asked about: the crew, the list, the item. A field
on a stored record names a person when the backend wrote it from
`ctx.userInfo`, or when `access.js` checked it equals the writer
(`doc.ownerHandle !== user.userHandle` throws).

A record read to authorize is checked against every field the decision relies on.
A member record answers "may this person act on this crew" when it belongs to
both: key it by the two, `member:<crewId>:<userHandle>`, read it with the id
built from the crew the route serves and `ctx.userInfo`, and compare its
`crewId`, its `userHandle` and its `role` before the route acts:

### `backend.js`
```js partial
const me = ctx.userInfo?.userHandle;
if (!me) return json({ ok: false, reason: "sign in" }, 401);
const crewId = String(body.crewId ?? "");
const member = await ctx.db.get(`member:${crewId}:${me}`, { db: "crew" });
if (member?.crewId !== crewId || member.userHandle !== me || member.role !== "manager") {
  return json({ ok: false, reason: "managers of this crew only" }, 403);
}
```

A feed token is minted by a signed-in route, so the token record names its minter.
A calendar app fetches a private `.ics` feed with no sign-in, so the token in
the link is how the feed knows whose records to serve. The page asks a route
for a link through `apiFetch`; the route draws the token from
`crypto.getRandomValues`, saves `{ type: "feedToken", ownerHandle: me }` at
`feedToken:<token>`, and `access.js` lets only the route write that type
(`ctx.requireBackend("fetch")` on it). The feed route then reads the token
record by id and serves the records whose `ownerHandle` it names. Pair it with
`config.fetch.unfilteredReads` (above), and give each record an `ownerHandle`
that `access.js` checks equals the writer, so the feed's query by that field
returns that person's records and theirs alone:

### `backend.js`
```js partial
if (url.pathname === "/feed-token" && request.method === "POST") {
  const me = ctx.userInfo?.userHandle;
  if (!me) return json({ ok: false, reason: "sign in to make a feed link" }, 401);
  const bytes = crypto.getRandomValues(new Uint8Array(24));
  const token = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
  await ctx.db.put({ type: "feedToken", ownerHandle: me }, { db: "planner", id: "feedToken:" + token });
  return json({ ok: true, token });
}
if (url.pathname === "/feed-token/revoke" && request.method === "POST") {
  const me = ctx.userInfo?.userHandle;
  if (!me) return json({ ok: false, reason: "sign in to change a feed link" }, 401);
  const { token } = await request.json();
  const grant = await ctx.db.get("feedToken:" + token, { db: "planner" });
  if (grant?.type !== "feedToken" || grant.ownerHandle !== me) return json({ ok: false, reason: "your own feed links" }, 403);
  await ctx.db.delete("feedToken:" + token, { db: "planner" }); // the link drains on its next refresh
  return json({ ok: true });
}
if (url.pathname === "/feed.ics") {
  const token = url.searchParams.get("t") ?? "";
  const grant = token ? await ctx.db.get("feedToken:" + token, { db: "planner" }) : null;
  if (grant?.type !== "feedToken") return new Response("not found", { status: 404 });
  const rows = await ctx.db.query({ db: "planner", field: "ownerHandle", key: grant.ownerHandle, limit: 200 });
  const work = rows.filter((row) => row.type === "assignment");
  return new Response(toIcs(work), { headers: { "content-type": "text/calendar" } });
}
```

The token is drawn in the route, so the server chose it for the person it names.
Every token record is one the route wrote, at an id made from fresh
randomness, so a link one person shares with a friend stays theirs. In
`access.js` the token type admits only the route, names its writer, is kept
or revoked whole (the revoke route deletes it), and sits on its owner's private
channel; each assignment names its writer the same way, and ids that start
`feedToken:` hold feed links alone:

### `access.js`
```js partial
if (doc.type === "feedToken") {
  ctx.requireBackend("fetch"); // only the /feed-token route mints one
  if (!user?.userHandle || doc.ownerHandle !== user.userHandle) throw { forbidden: "a feed link is its owner's" };
  // Kept or revoked whole: the revoke route's delete passes, an edit is refused. A repair goes through admin mode.
  if (oldDoc && !doc._deleted) throw { forbidden: "a feed link is kept or revoked whole" };
  const mine = "user:" + user.userHandle;
  return { channels: [mine], grant: { users: { [user.userHandle]: [mine] } } };
}
if (String(doc._id ?? "").startsWith("feedToken:")) throw { forbidden: "feedToken: ids hold feed links" };
if (doc.type === "assignment") {
  if (!user?.userHandle || doc.ownerHandle !== user.userHandle) throw { forbidden: "your own assignments" };
  if (oldDoc && oldDoc.ownerHandle !== user.userHandle) throw { forbidden: "your own assignments" };
  const mine = "user:" + user.userHandle;
  return { channels: [mine], grant: { users: { [user.userHandle]: [mine] } } };
}
```

A link for one record a person keeps, such as one student on a parent's or a
teacher's list, comes from the same route with that record's id in the body
(`{ recordId }`). The student record holds the student: a name and the person
who keeps them. The page saves it, then asks the route for its link, and reads
each student's link back from its own live query on `type: "feedToken"`,
matched by `recordId`:

### `App.jsx`
```jsx partial
// The student record holds the student; the route draws the student's link.
const { id } = await database.put({ type: "student", name, ownerHandle: me.userHandle });
const res = await apiFetch("/feed-token", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ recordId: id }),
});
const link = res.ok ? (await res.json()).token : null;
```

The route reads the record, mints when its `ownerHandle` equals `me`, and saves
`{ type: "feedToken", ownerHandle: me, recordId }` beside it. The feed serves
the assignments whose `recordId` and `ownerHandle` both match the token record,
so each link shows one student's work as the person who keeps that student
entered it:

### `backend.js`
```js partial
if (url.pathname === "/feed-token" && request.method === "POST") {
  const me = ctx.userInfo?.userHandle;
  if (!me) return json({ ok: false, reason: "sign in to make a feed link" }, 401);
  const { recordId } = await request.json();
  const record = recordId ? await ctx.db.get(String(recordId), { db: "planner" }) : null;
  if (record?.type !== "student" || record.ownerHandle !== me) return json({ ok: false, reason: "links for the students you keep" }, 403);
  const bytes = crypto.getRandomValues(new Uint8Array(24));
  const token = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
  await ctx.db.put({ type: "feedToken", ownerHandle: me, recordId: record._id }, { db: "planner", id: "feedToken:" + token });
  return json({ ok: true, token });
}
if (url.pathname === "/feed.ics") {
  const token = url.searchParams.get("t") ?? "";
  const grant = token ? await ctx.db.get("feedToken:" + token, { db: "planner" }) : null;
  if (grant?.type !== "feedToken") return new Response("not found", { status: 404 });
  const rows = await ctx.db.query({ db: "planner", field: "ownerHandle", key: grant.ownerHandle, limit: 200 });
  const work = rows.filter((row) => row.type === "assignment" && row.recordId === grant.recordId);
  return new Response(toIcs(work), { headers: { "content-type": "text/calendar" } });
}
```

OAuth state ties the user who starts the flow to the user who finishes it.
A visitor's own account on another service is a connection first (the
`connections` skill), and the platform holds that flow end to end. A flow the
app runs itself starts in a route the page calls through `apiFetch`: it saves
`{ type: "oauthState", startedBy: me }` under a `crypto.randomUUID()` state and
sends the person to the provider with it. The provider's redirect lands on the
app's page, which hands the `code` and `state` to a finish route, again through
`apiFetch` so the handler runs as the signed-in person. The flow's `redirect_uri` is
the app's own page URL, so the person lands back on the page, and the page
calls the finish route once they are signed in, so it knows who finished; when
the finish route turns the link away, the page offers a fresh start. The finish route reads
`oauthState:<state>`, carries on when its `startedBy` equals
`ctx.userInfo.userHandle`, deletes the state so it is used once, exchanges the
code and stores the token under that same handle.

A route that spends the owner's key or deletes a record checks who is calling first.
A route that calls a paid service with `ctx.secrets`, or removes a record,
opens with the guard that says who may: the owner
(`ctx.userInfo?.userHandle === ctx.appInfo.ownerHandle`), the signed-in person
whose record it is, or a sender proving a shared secret (the Zapier recipe
below).

### Records in from Zapier — a Zap that POSTs to `/_api`

A Zap brings records into the app by POSTing to its `/_api` route.
Reach for it when the ask says the records come *from* another tool — "from
Zapier", "when a form is submitted in Google Forms", "every new row in my
sheet", "each new email in my inbox", "the receipts in my Gmail". The owner makes a Zap whose trigger is
that tool and whose action is **Webhooks by Zapier → POST** to
`https://vibes.diy/vibe/<owner>/<slug>/_api/zapier/lead`, sending the fields as
JSON and mapping the tool's own id for the record (the form response id, the
row id, the message id) to `id`. The route answers the world once the app is
published.

A Zap carries no vibes.diy sign-in, so the route runs as nobody, and the
recipe has three parts:

- **A shared secret proves the sender.** The owner picks a long random value,
  saves it as a secret (`vibes-diy secrets set ZAPIER_INBOUND_SECRET`), and
  pastes the same value into the Zap as an `x-zapier-secret` header. The
  handler compares the two in constant time and answers `401` when they
  differ. The secret rides a header of the app's own naming: `Authorization`
  and `Cookie` are removed before the handler sees the request, and
  `x-vibes-*` belongs to the platform.
- **The same record lands on the same document.** Zapier can deliver one
  record twice, so its key comes from the record itself — the mapped `id`, or
  a hash of the body — and the record the app shows is written at
  `lead:<key>` with `ifRev: null`, so a second delivery meets a `conflict`
  and changes nothing.
- **The route writes a sealed arrival, and the tick turns it into the
  record.** The route's write is anonymous, so `access.js` admits it with
  `allowAnonymous: true` — and a type an anonymous route may write, any
  visitor may write directly too. So the route writes an `arrival` carrying a
  seal (an HMAC of its fields under the secret) on a channel no reader is
  granted, and `scheduled`, which reads every channel, makes the seal again,
  writes each matching arrival as the record the app shows (a type only
  `scheduled` writes), and clears the arrival. An arrival with no matching
  seal is cleared without becoming a record. The tick pages through every
  arrival on the `next` cursor, up to ten pages a tick, so a pile of unsealed
  arrivals never stands in front of a real one, and it handles each arrival
  on its own — fields checked as strings, any failure logged — so one odd
  document is cleared and the rest go through. `access.js` keeps every
  arrival at an `arrival:` id, so none can occupy a lead's id.

**A lead list belongs to the owner and the teammates they add.** Records
that carry people's names and contact details — leads, sign-ups, form
responses, inquiries — land on one members channel. The owner reads it from
the very first lead through the reserved `owner` role, and a `member` record
the owner writes lets a teammate in (`grant.users` names that teammate's
handle). The page gates its add-a-teammate control on
`useVibe("leads").can`, says who sees the list beside it ("Just you and the
teammates you add see these leads"), and your reply says the same.

Gate both handlers on the secret, so the app works fully before any Zap
exists, and say in your reply what the owner sets up: the secret and the Zap's POST
address and header. The arrivals are written by backend.js with
`allowAnonymous: true`, so the app's anonymous-write setting plays no part.

### `backend.js`
```js
export const config = { scheduled: { interval: "1m" } };

const enc = new TextEncoder();

function json(data, status) {
  return new Response(JSON.stringify(data), { status: status ?? 200, headers: { "content-type": "application/json" } });
}

function hex(buf) {
  return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
}

// The seal: an HMAC of the record's fields under the shared secret.
async function sealOf(secret, arrival) {
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  return hex(await crypto.subtle.sign("HMAC", key, enc.encode(JSON.stringify([arrival.key, arrival.name, arrival.email]))));
}

// Constant time: both sides become fixed-length digests, compared byte by byte with no early exit.
async function sameText(a, b) {
  const [x, y] = await Promise.all([a, b].map(async (s) => new Uint8Array(await crypto.subtle.digest("SHA-256", enc.encode(s)))));
  let diff = 0;
  for (let i = 0; i < x.length; i++) diff |= x[i] ^ y[i];
  return diff === 0;
}

export async function fetch(request, ctx) {
  const url = new URL(request.url);
  if (url.pathname !== "/zapier/lead" || request.method !== "POST") return json({ ok: false, reason: "not found" }, 404);
  const secret = ctx.secrets.ZAPIER_INBOUND_SECRET;
  if (!secret) return json({ ok: false, reason: "this app is still being set up" }, 503);
  const given = request.headers.get("x-zapier-secret") ?? "";
  if (!(await sameText(given, secret))) return json({ ok: false, reason: "unrecognized sender" }, 401);
  const raw = await request.text();
  let body;
  try {
    body = JSON.parse(raw);
  } catch {
    return json({ ok: false, reason: "send the fields as JSON" }, 400);
  }
  if (typeof body?.name !== "string" || typeof body?.email !== "string") {
    return json({ ok: false, reason: "name and email are needed" }, 400);
  }
  // The key comes from the record itself, so a second delivery of it lands on the same lead.
  const source = typeof body.id === "string" && body.id !== "" ? body.id : raw;
  const key = hex(await crypto.subtle.digest("SHA-256", enc.encode(source)));
  const arrival = { type: "arrival", key, name: body.name.slice(0, 200), email: body.email.slice(0, 200) };
  arrival.seal = await sealOf(secret, arrival);
  await ctx.db.put(arrival, { db: "leads", id: "arrival:" + arrival.seal });
  return json({ ok: true, key });
}

export async function scheduled(event, ctx) {
  const secret = ctx.secrets.ZAPIER_INBOUND_SECRET;
  let added = 0;
  let cleared = 0;
  let after;
  let pages = 0;
  // Page through every arrival (up to 10 pages a tick), so a pile of unsealed ones never hides a real one.
  do {
    const page = secret ? await ctx.db.query({ db: "leads", field: "type", key: "arrival", limit: 200, after }) : [];
    for (const arrival of page) {
      // Each arrival is handled on its own: whatever one holds, the tick clears it and moves on.
      try {
        const wellFormed = ["key", "name", "email", "seal"].every((f) => typeof arrival[f] === "string");
        if (wellFormed && (await sameText(arrival.seal, await sealOf(secret, arrival)))) {
          const lead = { type: "lead", name: arrival.name, email: arrival.email, addedAt: event.scheduledTime };
          await ctx.db.put(lead, { db: "leads", id: "lead:" + arrival.key, ifRev: null });
          added += 1;
        } else {
          cleared += 1;
        }
      } catch (err) {
        // A conflict means this lead is already here; anything else is logged and the arrival cleared.
        if (err?.code !== "conflict") ctx.log("warn", "arrival set aside", { id: arrival._id, reason: String(err?.message ?? err) });
      }
      await ctx.db.delete(arrival._id, { db: "leads" }).catch((err) => ctx.log("warn", "arrival kept", { id: arrival._id, reason: String(err?.message ?? err) }));
    }
    after = page.next;
    pages += 1;
  } while (after && pages < 10);
  ctx.log("info", "zapier arrivals", { added, cleared });
}
```

### `access.js`
```js
export function leads(doc, oldDoc, user, ctx) {
  if (oldDoc && oldDoc.type !== doc.type) throw { forbidden: "a record keeps its type" }; // a delete arrives as the stored record, type and all
  if (doc.type === "arrival") {
    // An arrival lives at `arrival:<seal>`, so no arrival can sit at a lead's id.
    if (typeof doc._id !== "string" || !doc._id.startsWith("arrival:")) throw { forbidden: "an arrival lives at arrival:<seal>" };
    if (doc._deleted) ctx.requireBackend("scheduled"); // the tick clears arrivals
    return { channels: ["arrivals"], allowAnonymous: true }; // no reader is granted this channel
  }
  if (doc.type === "lead") {
    ctx.requireBackend("scheduled"); // a lead is written only after its seal matched
    return { channels: ["leads"], grant: { roles: { owner: ["leads"] } } }; // the owner reads every lead
  }
  if (doc.type === "member") {
    ctx.requireRole("owner"); // the owner adds and removes teammates
    if (typeof doc.userHandle !== "string" || doc.userHandle === "") throw { forbidden: "a member names a handle" };
    if (oldDoc && oldDoc.userHandle !== doc.userHandle) throw { forbidden: "a member keeps its handle" };
    return { channels: ["leads"], grant: { users: { [doc.userHandle]: ["leads"] }, roles: { owner: ["leads"] } } };
  }
  throw { forbidden: "unknown type" };
}
```

The page lists `lead` records with `useLiveQuery("type", { key: "lead" })`,
and the owner and their teammates see each one within a minute of the Zap
firing.

### Mail in from Gmail — the person's Zap is the filter

An app that reads the person's email (receipts into a budget, newsletters into
a reading list, order confirmations into a tracker) gets its mail through this
same Zapier route, because the platform has no Gmail read connection. (Mail
the person forwards themselves, or that others send to the app, takes the
shorter road: the app's own address, _Email in_ below.) That is
the good part to say in your reply: the person writes the filter in Zapier, so
the app sees only the mail they chose to send it and nothing else in their
inbox, and deleting the Zap ends it. The Zap's trigger is **Gmail → New Email
Matching Search**, and its search box takes a Gmail search, which *is* the
filter (`subject:(receipt OR order) newer_than:30d`, `from:@shop.example.com`,
`label:to-vibes`). Its action is **Webhooks by Zapier → POST** to
`https://vibes.diy/vibe/<owner>/<slug>/_api/zapier/mail`, payload type JSON,
with `id` = *Message Id*, `from` = *From Email*, `subject` = *Subject*,
`date` = *Date* and `body` = *Body Plain*, and the `x-zapier-secret` header.

Build it as the lead recipe above with these changes:

- **The route is `/zapier/mail` and takes the mail's fields.** It answers
  `400` when both `subject` and `body` are missing, keeps each field a string
  and caps it (`body` at 20,000 characters), and keys the mail by a hash of
  Gmail's message `id`. The seal covers `[key, from, subject, date, body]`.
- **Mail is the owner's alone.** The tick writes `mail:<key>` records with
  `ifRev: null` on a `mail` channel granted only to the reserved `owner` role,
  with no member record and no anonymous read, and the page shows the owner
  the steps above. Your reply says that only the owner sees what arrives.
- **Reading a mail is a second step in the same tick.** The tick writes each
  new mail with `state: "new"`, then reads up to four of them a tick
  (`ctx.callAI` allows five calls a run) and writes what it finds beside the
  mail as its own backend-only type, in its own `access.js` branch that starts
  with `ctx.requireBackend("scheduled")`. A failed AI call leaves the mail
  `new` for the next tick.

```js partial
const RECEIPT = {
  properties: { isReceipt: { type: "boolean" }, merchant: { type: "string" }, total: { type: "number" }, currency: { type: "string" } },
  required: ["isReceipt", "merchant", "total", "currency"],
};
// After the arrivals loop: gather up to four new mails, paging on `next` (`limit` clamps the raw page before the filter).
const unread = [];
let cursor;
let scanned = 0;
do {
  const page = await ctx.db.query({ db: "mail", field: "state", key: "new", limit: 200, after: cursor });
  for (const doc of page) if (doc.type === "mail" && unread.length < 4) unread.push(doc);
  cursor = page.next;
  scanned += 1;
} while (cursor && unread.length < 4 && scanned < 10);
// Read each one and keep the receipts.
for (const mail of unread) {
  let found;
  try {
    found = JSON.parse(await ctx.callAI(`Is this email a receipt? From: ${mail.from}\nSubject: ${mail.subject}\n\n${mail.body.slice(0, 12000)}`, { schema: RECEIPT }));
  } catch (err) {
    ctx.log("warn", "receipt read failed", { id: mail._id, reason: String(err?.message ?? err) });
    break; // the mail stays new and the next tick tries again
  }
  if (found.isReceipt && typeof found.total === "number") {
    const receipt = { type: "receipt", mailId: mail._id, merchant: String(found.merchant).slice(0, 200), total: found.total, currency: String(found.currency).slice(0, 8) };
    await ctx.db.put(receipt, { db: "mail", id: "receipt:" + mail._id.slice(5), ifRev: null }).catch((err) => {
      if (err?.code !== "conflict") throw err;
    });
  }
  await ctx.db.put({ ...mail, state: "read" }, { db: "mail", id: mail._id });
}
```

### Bulk transformations run as a route

A change that touches many stored records is written once, as a named `/_api` route, and run
once — not looped from outside the app. Gate the route inside the handler on the caller being the
owner, declare `config.fetch.unfilteredReads` for the collections it reads, page with the cursor
`ctx.db.query` returns, and keep progress in a state document read by id so a second run continues
where the first stopped.

### `backend.js`
```js
export const config = {
  fetch: {
    unfilteredReads: {
      dbs: ["rsvps"],
      why: "/admin/normalize serves only the app owner, checked against ctx.appInfo.ownerHandle before it reads",
    },
  },
};

const STATE_ID = "state:normalize";

function json(data, status) {
  return new Response(JSON.stringify(data), { status: status ?? 200, headers: { "content-type": "application/json" } });
}

export async function fetch(request, ctx) {
  const url = new URL(request.url);
  if (url.pathname !== "/admin/normalize") return json({ ok: false, reason: "not found" }, 404);
  if (ctx.userInfo?.userHandle !== ctx.appInfo.ownerHandle) return json({ ok: false, reason: "owner only" }, 403);
  // Progress lives in one state document read by id, so a second run picks up where the first stopped.
  const state = await ctx.db.get(STATE_ID, { db: "rsvps" });
  if (state?.done === true) return json({ ok: true, fixed: 0 });
  let after = state?.after ?? undefined;
  let fixed = 0;
  do {
    const page = await ctx.db.query({ db: "rsvps", field: "kind", key: "rsvp", limit: 100, after });
    for (const doc of page) {
      if (typeof doc.name === "string" && doc.name !== doc.name.trim()) {
        await ctx.db.put({ ...doc, name: doc.name.trim() }, { db: "rsvps", id: doc._id });
        fixed += 1;
      }
    }
    after = page.next; // absent on the last page
    await ctx.db.put({ kind: "normalizeState", after: after ?? null, done: after === undefined }, { db: "rsvps", id: STATE_ID });
  } while (after);
  ctx.log("info", "normalized rsvp names", { fixed });
  return json({ ok: true, fixed });
}
```

### Reading a page the person names — the `/_api` proxy

A page the person names is read in `backend.js` and handed to the app through `/_api`. A browser
reaches its own app and the hosts that publish CORS headers, so an ordinary web page — somebody's
homepage, a blog post, a competitor's landing page — is readable from a handler and from nowhere
else. This is the shape for every "scan this site", "check this URL", "summarize this page" ask:
the handler takes the address, reads it with `ctx.fetch`, strips the markup to text, and answers
with what it measured. Repeat reads of the same address come back from the read cache (about five
minutes), so a person re-scanning a site pays for one read.

The handler settles the address before reading it. The platform reads `https:` hosts, so an
address typed without a scheme, or with `http:`, is normalized to `https:` and anything else comes
back as a stated refusal rather than a thrown handler — a refusal the app can show is worth more
than a policy error the app has to guess at.

`ok` means TEXT CAME BACK. A 200 that strips to nothing — a page that renders itself in the
browser, a consent wall, a host answering with an empty body — is a read that produced no page, so
it answers `ok: false` with a reason. That is what makes `page.ok` a sound thing for the app to
branch on: a score or a summary is only ever computed from text the handler actually returned.

### `backend.js`
```js
export async function fetch(request, ctx) {
  const url = new URL(request.url);
  if (url.pathname === "/page") {
    const typed = (url.searchParams.get("url") ?? "").trim();
    let parsed;
    try {
      parsed = new URL(/^[a-z]+:/i.test(typed) ? typed : `https://${typed}`);
    } catch {
      return Response.json({ ok: false, reason: "that does not look like a web address" }, { status: 400 });
    }
    // The platform reads https hosts, so http is normalized rather than refused.
    if (parsed.protocol === "http:") parsed.protocol = "https:";
    if (parsed.protocol !== "https:") {
      return Response.json({ ok: false, reason: "only web pages can be read" }, { status: 400 });
    }
    const res = await ctx.fetch(parsed.href, { headers: { accept: "text/html" } });
    const html = await res.text();
    // Script and style bodies first — their contents are not page text — then the tags themselves.
    const text = html
      .replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1>/gi, " ")
      .replace(/<[^>]+>/g, " ")
      .replace(/\s+/g, " ")
      .trim()
      .slice(0, 20000);
    // A page that came back with no readable text is a read that produced no page.
    if (res.ok === false || text.length === 0) {
      const reason = res.ok ? "that page returned nothing we could read" : `that page answered ${res.status}`;
      return Response.json({ ok: false, status: res.status, reason });
    }
    const title = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1]?.trim() ?? "";
    return Response.json({ ok: true, status: res.status, title, text });
  }
  return new Response("not found", { status: 404 });
}
```

From `App.jsx`, the page asks the handler for the address it was given:

### `App.jsx`
```js partial
const res = await fetch(`/_api/page?url=${encodeURIComponent(url)}`);
const page = await res.json();
if (page.ok === false) {
  setResult({ read: false, reason: page.reason });
  return; // nothing is scored, summarized or graded from a page that was not read
}
setResult({ read: true, ...(await scorePage(page.title, page.text)) });
```

The refusal lands where the result would have gone — "we could not read that page: it returned
nothing we could read" — so the person sees the read fail instead of a number computed from
nothing.

## onChange — react to committed writes

**When the request says a record is kept on the server, or that the server reacts
to something, emit this handler.** A person asking for activity to be recorded
centrally, for a tally the app maintains, or for something to happen whenever a
record lands is naming the server as the place it happens — that ask is the
trigger, and the shape is the activity-mirror example at the end of this file:
the client writes the document that triggers it, and `onChange` writes what the
server owes in response.

Runs after any document write to the app's databases commits (user writes and
backend writes alike). The event:

### `backend.js`
```js
export async function onChange(event, ctx) {
  // event: { dbName, docId, doc, oldDoc, seq, deleted } — the id is docId; doc is the body plus _rev
  if (event.dbName !== "votes" || event.deleted) return;
  // Maintain a server-authoritative tally the UI reads but users can't forge.
  await ctx.db.put({ _id: "tally-" + event.doc.pollId, kind: "tally", bump: event.seq }, { db: "tallies" });
}
```

Two rules keep change-reactions sane:

1. **Guard on `event.dbName` first.** The handler fires for every database, so
   an unguarded write-back loops on itself.
2. **Write derived docs to a different database** than the one that triggered
   the event. A backend write triggers `onChange` again (one generation deeper);
   the platform stops the chain silently after four generations, but a tight
   same-database ping-pong is still wasted work. Different db + dbName guard
   makes loops structurally impossible.
3. **Read the doc's id from `event.docId`.** `event.doc` is the stored body
   plus `_rev`, and it carries `_id` only when the writer happened to store
   one; an agent or backend write usually doesn't. So `event.doc._id` reads
   `undefined`, and a write-back of `{ ...event.doc, ... }` without
   `id: event.docId` puts a new copy, which fires `onChange` again. Spread with
   the id when you need the whole record: `{ ...event.doc, _id: event.docId }`.

Example records from `seed.json` are written without running `onChange`, so a
handler reacts to real activity only. A handler that reaches outside the app
(an email to the owner, a webhook, a notification) also starts with a one-line
check that keeps it to real records — seeded ones carry an `_id` that starts
with `seed:`:

```js
export async function onChange(event, ctx) {
  if (event.dbName !== "requests" || event.deleted) return;
  if (event.docId.startsWith("seed:")) return; // example records stay in the app
  await ctx.notify({ toHandle: event.doc.assignee, body: "New request", dedupeKey: `request-${event.docId}` });
}
```

A record someone pastes for the server to read and act on (an order email
into an inbox page, a request into a queue) lands here too, and `onChange`
hands it to `ctx.agent.run` with the record as `input`: the pasted-inbox
example under *Let an agent do the work* below.

### `onChange` reads what the triggering user could read

A reaction usually needs the set its write joins — the siblings, the existing
keys, what's already there. `ctx.db.query` and `ctx.db.get` on a bound
database return exactly the docs in the triggering user's channels, through
the same per-reader filter the client's own reads use. Nothing privileged
ever comes back: a doc the triggerer couldn't open stays invisible, and reads
page like any other query (walk `next` to exhaustion).

```js
export async function onChange(event, ctx) {
  if (event.dbName !== "links" || event.deleted) return;
  // What did sibling drafts already say about this link? Only docs the
  // triggering user could read come back — a private sibling stays hidden.
  // Walk every page to exhaustion: a fully-filtered page still carries `next`,
  // so stopping on an empty page would miss a sibling on a later one.
  let after = null;
  do {
    const page = await ctx.db.query({ db: "drafts", field: "linkId", key: event.doc.linkId, limit: 100, after });
    if (page.some((d) => d.angle === event.doc.angle)) return; // already covered
    after = page.next;
  } while (after);
  await ctx.db.put({ _id: "draft-" + event.docId, linkId: event.doc.linkId, angle: event.doc.angle }, { db: "drafts" });
}
```

`fetch` reads the same way for a signed-in caller: when the page calls
`apiFetch`, the handler runs as the visitor and a bound database returns the
docs in their channels — the same set their page already shows them — so a
route can sum, rank or reshape the caller's own docs server-side.

### Jobs that finish even when a run crashes

**A job that survives a crash carries its status, its claim and its lease on the document.**
When each request is a unit of work ("resize every upload", "a queue of jobs
that keeps going if one fails"), give each job a doc with a `status`, let
`onChange` claim and finish it, and let a `scheduled` sweep take back expired
leases. The status guard is what makes writing back to the same database safe:
the handler acts only on `pending`, so every chain ends after one step.

Every transition is the same move: read the doc (the event's `doc`, or a
sweep's `query` row), then `put` the next status with `ifRev: doc._rev`. A
`conflict` means someone else moved the job first, so step aside.

- `access.js` holds the transition table, keyed on `oldDoc.status`:
  `ctx.requireBackend("onChange")` for `pending → running` and
  `running → done`; `ctx.requireBackend("scheduled")` for
  `running → pending` (only once `oldDoc.leaseUntil < Date.now()`) and
  `→ failed`; anything else throws.
- The claim puts `running` with `ifRev: event.doc._rev`, so exactly one run
  claims each job. It also writes a fresh `claimId`, `leaseUntil` and
  `attempts + 1`.
- The finish carries the same `claimId`, and `access.js` refuses a `done`
  whose `claimId` differs from `oldDoc.claimId`. A slow run's lease can be
  taken back and the job claimed again while it works; the second claim's
  fresh `claimId` is what makes the first run's finish refuse instead of
  overwrite.
- The sweep releases an expired lease with `ifRev: job._rev` from its query,
  so it never overwrites a job that finished between the read and the write.
- A lost claim returns rather than throws: a redelivered event carries the doc
  as it first fired, so its `_rev` is stale and the claim conflicts.
- Key the work's own writes by `jobId:attempt`, since a job can run twice.
- Keep each run short; a run past 15 minutes is delivered again while it is
  still going, so chunk long work into `scheduled` ticks.

### `backend.js`
```js
export const config = { scheduled: { interval: "30s" } };
const DB = "jobs", LEASE_MS = 30_000, MAX_ATTEMPTS = 3;
const rid = () => Math.random().toString(36).slice(2, 10);

// One transition: commit `doc` only if the job is still at revision `ifRev`.
async function tryPut(ctx, doc, ifRev) {
  try { await ctx.db.put(doc, { db: DB, id: doc._id, ifRev }); return true; }
  catch (err) {
    if (err.code === "conflict") return false; // someone else moved this job first
    ctx.log("info", "transition refused", { id: doc._id, reason: String(err?.message || err) });
    return false;
  }
}

export async function onChange(event, ctx) {
  if (event.dbName !== DB || event.deleted || event.doc?.status !== "pending") return;
  const job = { ...event.doc, _id: event.docId };
  const claimed = { ...job, status: "running", attempts: (job.attempts || 0) + 1,
    claimId: rid(), leaseUntil: Date.now() + LEASE_MS };
  if (!(await tryPut(ctx, claimed, job._rev))) return; // lost the claim — ack, don't retry
  const output = await doTheWork(job, `${job._id}:${claimed.attempts}`); // idempotent per jobId:attempt
  await tryPut(ctx, { ...claimed, status: "done", output }); // same claimId, or access.js refuses it
}

export async function scheduled(event, ctx) {
  ctx.log("debug", "lease sweep", { at: event.scheduledTime });
  let after;
  do {
    const page = await ctx.db.query({ db: DB, field: "status", key: "running", limit: 500, after });
    for (const job of page) {
      if (!(job.leaseUntil < Date.now())) continue;
      await tryPut(ctx, { ...job, status: job.attempts >= MAX_ATTEMPTS ? "failed" : "pending" }, job._rev);
    }
    after = page.next;
  } while (after);
}
```

The full walkthrough, the matching `access.js`, and timings measured on
production are at https://good.vibes.diy/docs/patterns/doc-state-machines.

## scheduled — periodic work

Requires a `config` export with a **static string-literal** interval between
`"5s"` and `"1h"` (e.g. `"30s"`, `"5m"`, `"1h"` — computed values are rejected):

### `backend.js`
```js
export const config = { scheduled: { interval: "15m" } };

export async function scheduled(event, ctx) {
  // event: { scheduledTime } — ISO timestamp of this tick
  ctx.log("debug", "heartbeat tick", { at: event.scheduledTime }); // proof of life, every tick
  await ctx.db.put({ kind: "heartbeat", at: event.scheduledTime }, { db: "status" });
}
```

Runs as the app owner in admin mode (see "Writes go through the access
function" above): it can read every doc in the app and its writes pass
`requireAccess`/`requireRole` automatically, while the access function's
channels and grants still route what it writes. Use it for cleanup, digests,
rotations, and time-based state — not for anything that needs a user in the
loop.

### Times of day: the zone comes from the browser

**A wall-clock time belongs to the person who set it.** "Noon" means noon where
the owner lives. The app is running in their browser at the moment they choose
the hour, and the browser knows their zone exactly and for free — capture it
there, store it beside the hour, and have the tick render `event.scheduledTime`
into that zone before comparing. A stored IANA zone name also tracks daylight
saving on its own, which a stored hour-offset does not.

App.jsx — when the owner saves the schedule:

### `App.jsx`
```jsx partial
await merge({
  hour: 12, // the hour they picked, in their own day
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, // e.g. "America/Detroit"
});
```

backend.js — the tick compares in that zone:

### `backend.js`
```js partial
const hourLocal = Number(
  new Intl.DateTimeFormat("en-US", {
    timeZone: settings.timeZone ?? "UTC",
    hour: "2-digit",
    hourCycle: "h23",
  }).format(new Date(event.scheduledTime))
);
if (hourLocal !== settings.hour) return; // not their noon yet — nothing to do
```

The owner picks an hour in the day they actually live in, and the app does the
arithmetic. Keep the schedule control in those terms too: label it with the zone
you captured ("every day at 12:00, America/Detroit"), so the setting reads back
the way they set it.

**A timestamp you show a person is rendered in their zone, never the server's.**
The rule above is about an hour the owner *chose*; this one is about every other
moment your app puts in front of them — a date in a notification body, a "next
event" label, a log line they read. A backend has no locale and no zone, so
`toLocaleDateString()` there silently means UTC, and a moment at `02:07 UTC` is
already tomorrow for half the world. Pass the stored zone every time you format:

```js
const label = new Intl.DateTimeFormat("en-US", {
  timeZone: settings.timeZone ?? "UTC",
  month: "long",
  day: "numeric",
}).format(new Date(moment));
```

And **only say a thing you computed.** "Tonight", "this morning", "in an hour"
are claims about the reader's clock; if the code did not derive them from that
reader's zone, name the moment instead and let them place it.

### Recurring reminders on somebody's clock

**A recurring reminder fires on each person's own clock, never the server's.**
Once a reminder repeats — "every weekday at 7" — the zone stops being one
setting on one schedule document and becomes a property of each person the
reminder is for. Everything below is per person, and none of it is the
server's day or the server's hour.

**Capture the zone as an effect, not as a question.** Do not ask them for a
timezone: the browser already knows it, so write it once when they first sign
in and leave it alone. Store it where the reminder is addressed — on the
person's own profile document when the list is shared — and guard the write so
it only ever happens on a real change, or the effect re-fires forever.

**Derive the weekday and the hour together, in that zone, from one
`formatToParts` call.** `getUTCDay()`/`getUTCHours()` answer a question about
the machine the handler happens to be running on; at 07:00 in Los Angeles it is
already a different day in UTC, so a weekday gate on the server's clock silently
drops Monday mornings and fires on Saturday ones.

**An unrecognised zone string throws.** `Intl.DateTimeFormat` raises a
`RangeError` on a zone it does not know, so in a loop over people the formatting
goes in a `try` and a bad profile is skipped — one stale record must not stop
everybody else's reminder.

The unit of work is that person's local date (`en-CA` formats it as
`YYYY-MM-DD`), keyed per person, per "A tick that repeats is not a run that
repeats" above: the interval is only how often the handler wakes up.

App.jsx — write the zone once, when they arrive:

### `App.jsx`
```jsx
useEffect(() => {
  if (!me?.userHandle) return;
  const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  if (!timeZone || myProfile?.timeZone === timeZone) return; // already stored — don't churn
  database.put({ _id: `profile:${me.userHandle}`, type: "profile", userHandle: me.userHandle, timeZone });
}, [me?.userHandle, myProfile?.timeZone]);
```

backend.js — evaluate each person in their own zone:

### `backend.js`
```js
export const config = { scheduled: { interval: "15m" } };
const WEEKDAYS = new Set(["Mon", "Tue", "Wed", "Thu", "Fri"]);

export async function scheduled(event, ctx) {
  const at = new Date(event.scheduledTime);
  const profiles = await ctx.db.query({ db: DB, field: "type", key: "profile", limit: 500 });
  ctx.log("debug", "reminder tick", { profiles: profiles.length });

  for (const profile of profiles) {
    const { timeZone, userHandle } = profile;
    if (!timeZone || !userHandle) continue;
    let weekday, hour, dateKey;
    try {
      // One formatter, one zone: the weekday and the hour must agree about the day.
      const parts = new Intl.DateTimeFormat("en-US", {
        timeZone,
        weekday: "short",
        hour: "2-digit",
        hourCycle: "h23",
      }).formatToParts(at);
      weekday = parts.find((p) => p.type === "weekday")?.value;
      hour = Number(parts.find((p) => p.type === "hour")?.value);
      dateKey = new Intl.DateTimeFormat("en-CA", { timeZone }).format(at); // "2026-09-18", their day
    } catch {
      continue; // unrecognised zone on one profile — skip the person, not the tick
    }
    if (!WEEKDAYS.has(weekday) || hour !== 7) continue;

    const id = `morningReminder:${userHandle}:${dateKey}`; // the unit of work, per person
    if (await ctx.db.get(id, { db: DB })) continue; // this morning is already done
    await ctx.db.put(
      { _id: id, type: "morningReminder", ownerHandle: userHandle, date: dateKey, checkedAt: at.toISOString() },
      { db: DB }
    );
  }
}
```

### A reminder that starts on is on from the first load

**A setting the backend reads is real from the first load, in the state the screen shows.**
When the switch starts on, the tick starts on too: the backend reads a
missing settings record, or a missing field on one, as the default the switch
is drawn with. The person who skips the settings screen gets the
reminder they were promised, and the first tap of the switch writes the
record from then on.

### `backend.js`
```js partial
const settings = (await ctx.db.get("settings", { db: DB })) ?? {}; // null until the first save
const stretchBreakOn = settings.stretchBreak ?? true; // same default the switch is drawn with
if (!stretchBreakOn) return;
```

### `App.jsx`
```jsx partial
import { Switch } from "@vibes.diy/ui/interactive";

const { doc: settings, merge, save } = useDocument({ _id: "settings", stretchBreak: true });
<Switch checked={settings.stretchBreak} onChange={(on) => { merge({ stretchBreak: on }); save(); }} />
```

When the reminder is per person, the arrival write above carries the default
alongside the zone (`stretchBreak: myProfile?.stretchBreak ?? true`), and the
tick reads each profile with the same `?? true`, so a profile written before
the setting existed still gets its reminder.

**The copy names the channel the code uses.** `ctx.notify` reaches a person
as a notification in their bell, inbox and push, so the screen says
"notification": "A notification every afternoon at 3". Say "text" when the app
reaches them through the follow-by-text `subscribers` button (*Followers by
text* above), which is what puts a text on their phone.

### An unattended tick reports what it did

**An unattended tick earns its spend.** Nobody is watching a scheduled run, so
it checks what it read before it spends anything: read the upstream first,
confirm the input set is non-empty (and that a `403` is not the
`vibesEgressDenied` policy body), and return before `ctx.callAI` when there is
nothing to work from. A model call on an empty input set produces confident text
about nothing, bills the owner for it, and does it again on the next tick,
forever.

**Every tick leaves a trace, even the ones with nothing to do.** Returning early
when there is no work is right — it saves a read and a spend — but a handler that
returns *silently* is indistinguishable from one that never ran, and `app logs`
is the only place an owner can tell. For a job that acts twice a month that means
weeks of silence that reads exactly like a dead alarm. So log once per tick,
before any early return:

### `backend.js`
```js partial
export async function scheduled(event, ctx) {
  const due = eventsDueNow(event.scheduledTime);
  ctx.log("debug", "tick", { due: due.length }); // proof of life; no reads, no spend
  if (due.length === 0) return;
  …
}
```

One line, and "is this thing still alive?" becomes answerable on any cadence.
The rarer the job, the more it needs this: for an infrequent handler, silence is
the *only* symptom a stopped alarm ever produces.

**A tick that repeats is not a run that repeats.** The interval is how often the
handler is *woken*, not how often the work should *happen*: a `15m` interval
wakes four times inside the owner's noon, so the handler names the unit of work —
here the local day — and keeps the key of the last unit it finished in a state
document it reads by id, plus a copy in module scope. A missing or failed state
read means *"don't know — use the copy"*, never *"nothing has run yet"*; that
second reading is what bills the owner four times for one noon.

**A status document that must be seen to change carries the tick's timestamp.**
A write whose content is byte-identical to what is already stored is absorbed:
the platform stores no new revision, and with no new revision there is no live
event, so an open page holding that document sees nothing and keeps showing what
it already had. A tick that rewrites a fixed-id status doc with the same fields
every time is therefore invisible to a watching reader. Include the moment the
tick ran — `checkedAt: new Date().toISOString()` — and the write is a real
change, so the page updates. This is the reader's side of the state-document
discipline above: state you only ever read back yourself is better off constant,
and state somebody is watching has to move.

### Firing on a real-world event

**An averaged cycle is not a calendar.** When the moment comes from nature
rather than from a clock the owner set — a moon phase, a tide, sunrise, a
planetary conjunction — the tempting shape is a mean period since a known epoch:

```js
const SYNODIC = 29.530588861; // mean lunation, in days
const t = KNOWN_NEW_MOON + k * SYNODIC * 86400000; // ← wrong by hours
```

The average is exact and the individual events are not. Orbits are elliptical
and perturbed, so real events run early or late against their own mean. Measured
for the lunar case: that formula is **up to 18 hours out**, and across the next
six months it puts two of six new moons on the **wrong calendar day**. It also
fails asymmetrically — full moons land within a couple of hours while new moons
run ~15 hours late — so testing one and shipping both proves nothing.

An app that merely *displays* a countdown can live with this if it says
"approximately". An app that **notifies** cannot: a notification is a claim that
the thing is happening now, and firing a ±20-minute window around a mean instant
lands it precisely on a time that is precisely wrong.

So: derive the event from a real algorithm with periodic-correction terms (the
standard treatments are short — a dozen sine terms gets a lunar phase to within
minutes), or fetch it from an ephemeris and cache it. If you can do neither,
widen the claim rather than the window: give the day, say "around", and never
attach a time-of-day word to it.

The same rule holds anywhere a natural cycle has a tidy average — the average is
a description of the series, never a prediction of the next member of it.

**A date the app works out itself lands on the person's own calendar.**
An instant the code computes — the next sunrise, a conjunction, the end of a
countdown — is one moment everywhere, and the day it falls on is the reader's.
An event at `02:00 UTC` belongs to the evening before across the Americas, and
the alert names that evening. Give it the same three steps as an hour the
owner picked, from the first build: the browser stores its zone on the settings
document when the person turns alerts on, the screen renders every computed
instant in the browser's own zone (a plain `toLocaleString()` in `App.jsx`
already does), and the tick dates and words the event in the stored zone.

```jsx
await database.put({
  _id: "alerts",
  type: "alerts",
  on: true,
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, // their calendar, from the browser
});
// On screen the browser's own zone applies by itself:
<li>{new Date(next.at).toLocaleString([], { weekday: "long", month: "long", day: "numeric", hour: "numeric", minute: "2-digit" })}</li>
```

```js
const zone = settings?.timeZone ?? "UTC"; // captured in their browser
const dayOf = (ms) =>
  new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date(ms));
if (dayOf(next.at) !== dayOf(event.scheduledTime)) return; // their day has not come yet
const when = new Intl.DateTimeFormat("en-US", { timeZone: zone, weekday: "long", hour: "numeric", minute: "2-digit" }).format(new Date(next.at));
```

The person reads the date and hour their own clock shows, so the alert and the
screen agree with the sky they step out under.

**Claim the unit of work before you spend on it, not after.** Write the key
first, then do the expensive, externally visible part: an isolate that dies
between a finished draft and an unwritten claim comes back and buys the same day
again. Claiming first means a crashed run is skipped rather than retried. That
is the named exception to the lease-and-retry jobs under `onChange` above: when a
duplicate costs more than a gap — a paid call, a post, a message to a person —
skip rather than retry, because a missing day the status doc names beats a double
charge nobody notices.

Then say what happened. Write the run's outcome to a status doc the app reads,
and put the failure detail in `ctx.log("error", …)` for whoever inspects the
logs: **the owner's only view of an unattended app is what it renders, so a
finished run leaves a visible record of what it did.** A notification reports
the outcome the run actually had. Every doc a run writes — status included —
goes in the database the UI live-queries, or the record is invisible in exactly
the way this whole section is about. A timestamp written only when a run
genuinely produced something is a real state change and belongs in that doc —
unlike a per-tick `checkedAt`, which is the churn the zero-churn rule above is
about.

### `backend.js`
```js
export const config = { scheduled: { interval: "15m" } };

const SHOW_DB = "show"; // the one database App.jsx live-queries

// The isolate's copy of the last day this handler finished. Survives between
// ticks on a warm isolate, and is the fallback when the state read says nothing.
let lastFinishedDay;

export async function scheduled(event, ctx) {
  ctx.log("debug", "digest tick", { at: event.scheduledTime }); // proof of life, before any return
  const settings = await ctx.db.get("schedule", { db: SHOW_DB });
  const zone = settings?.timeZone ?? "UTC"; // captured in the owner's browser
  const at = new Date(event.scheduledTime);

  const hourLocal = Number(
    new Intl.DateTimeFormat("en-US", { timeZone: zone, hour: "2-digit", hourCycle: "h23" }).format(at)
  );
  if (hourLocal !== settings?.hour) return; // not their hour yet — nothing to do

  // "2026-08-27" in the owner's own day, which is the unit of work here.
  const dayKey = new Intl.DateTimeFormat("en-CA", {
    timeZone: zone,
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  }).format(at);
  const state = await ctx.db.get("run:state", { db: SHOW_DB });
  const finished = state?.dayKey ?? lastFinishedDay; // absent read: trust the copy
  if (finished === dayKey) return; // this day's draft is already written

  const headlines = await readFeed(ctx); // [] when the fetch failed or the feed was empty

  if (headlines.length === 0) {
    ctx.log("error", "[digest] no headlines this tick", { at: event.scheduledTime });
    await putIfChanged(
      ctx,
      {
        _id: "run:status",
        type: "runStatus",
        state: "no-input",
        message: "couldn't read the feed — no draft written this run",
      },
      SHOW_DB
    );
    return; // no model call, and no notification claiming a draft is ready
  }

  // Claim the day BEFORE spending anything, so an isolate that dies mid-draft can
  // never come back and buy the same day again.
  lastFinishedDay = dayKey;
  await ctx.db.put({ _id: "run:state", type: "runState", dayKey }, { db: SHOW_DB });

  try {
    const draft = await ctx.callAI(`Write six one-liners about: ${headlines.join("; ")}`);
    await ctx.db.put({ _id: `draft:${dayKey}`, type: "draft", draft }, { db: SHOW_DB });
    await ctx.db.put(
      {
        _id: "run:status",
        type: "runStatus",
        state: "fresh",
        lastSuccessAt: event.scheduledTime,
        message: "today's draft is ready",
      },
      { db: SHOW_DB }
    );
    await ctx.notify({
      toHandle: ctx.appInfo.ownerHandle,
      body: "Your six jokes are drafted and ready for the show.",
      dedupeKey: `draft-${dayKey}`,
      path: `#draft/${dayKey}`,
    });
  } catch (err) {
    // The day stays claimed: the owner sees what went wrong and is not billed twice for it.
    ctx.log("error", "[digest] draft failed after the day was claimed", { message: err.message });
    await ctx.db.put(
      {
        _id: "run:status",
        type: "runStatus",
        state: "failed",
        checkedAt: event.scheduledTime, // a second failure must still read as a new one
        message: "today's draft didn't finish",
      },
      { db: SHOW_DB }
    );
  }
}
```

The run's own bookkeeping is the server's, not a user's. `ctx.requireBackend`
is what separates a run's write from a client's: it passes only when the app's
own `backend.js` issued the write, and refuses every browser and CLI write
including the owner's own — while still no-opping under admin mode, so a hand
repair runs the function and keeps the routing. `access.js` is where that is
said:

### `access.js`
```js
// access.js
export default function (doc, oldDoc, user, ctx) {
  if (doc.type === "runState" || doc.type === "runStatus") {
    ctx.requireBackend("scheduled");
    return { channels: ["show"] };
  }
  // …the app's own document types…
  throw { forbidden: "unknown document type" };
}
```

App.jsx writes the `schedule` document that tick reads — the hour the owner
picked and, beside it, the zone their own browser reported — and reads the same
database back, rendering the status beside the drafts so a failed run and a good
one never look alike:

### `App.jsx`
```jsx
const { useLiveQuery, database } = useFireproof("show");

async function saveSchedule(hour) {
  // The hour is theirs and so is the zone: capture it here, store it beside the hour.
  await database.put({
    _id: "schedule",
    type: "schedule",
    hour,
    timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
  });
}

const { docs: statusDocs } = useLiveQuery("type", { key: "runStatus" });
const run = statusDocs.find((doc) => doc._id === "run:status");
// …
{
  run?.state === "no-input" ? (
    <p role="status">{run.message}</p>
  ) : (
    <p role="status">Last draft written {run?.lastSuccessAt?.slice(0, 16)}</p>
  );
}
```

### A mirror of another system's records — a watermark and one record per outside id

Reach for this when the ask keeps a copy of records that live somewhere else
and adds people's own work beside them: "a fulfilment board that keeps my
Squarespace orders in sync", "my CRM's contacts with our call notes", "the
team calendar's events with who's bringing what". A `scheduled` handler keeps
the mirror, and the app's screens read it like any other records.

**A mirror keys each record by its outside id and moves its watermark only after the page is written.**
One state document at a fixed id (`mirror:state`) holds `since`, the time the
last complete read reached, and the cursor of a read in progress. Each run
asks the other system for what changed since `since`, writes each record at
`order:<outside id>`, saves the cursor once a page is in, and moves `since`
once the window's last page is in, two minutes back so the edge is read twice.
Reading a record twice rewrites the same document, so a crash, a retry or an
overlap leaves one copy. A record whose mirrored fields already match is
skipped, so a quiet store writes nothing.

**A refusal pauses the mirror on the page it was reading.** A `429` or any
other refusal arrives as an ordinary response from `ctx.fetch`. Store a
`backoffUntil` time and the error on the state document, keep the cursor, and
return; runs before that time return at once, and the wait doubles on each
refusal in a row up to half an hour. The page shows `lastPolledAt` as "synced
3 minutes ago", and `lastError` while the mirror waits.

**The mirror's records are the tick's alone; what people type rides a sibling record.**
A packer's tick, note or claim lands on `pack:<outside id>`, a document the
mirror never reads or writes, so each document has one writer and the next
sync keeps every note. `access.js` gates the mirrored types on
`ctx.requireBackend("scheduled")`, and the page joins the two types by the
outside id.

### `backend.js`
```js
export const config = { scheduled: { interval: "1m" } };

const ORDERS = "https://api.squarespace.com/1.0/commerce/orders";
const STATE = "mirror:state";
const POLL_EVERY_MS = 15 * 60000;

// The fields the mirror owns, all from the store.
function mirrorOf(order) {
  return {
    type: "order",
    storeId: order.id,
    orderNumber: String(order.orderNumber),
    modifiedOn: order.modifiedOn,
    fulfillmentStatus: order.fulfillmentStatus,
    items: (order.lineItems ?? []).map((li) => ({ name: li.productName, quantity: li.quantity })),
  };
}

async function upsert(ctx, order) {
  const id = "order:" + order.id;
  const next = mirrorOf(order);
  const stored = await ctx.db.get(id, { db: "orders" });
  if (stored && Object.keys(next).every((k) => JSON.stringify(stored[k]) === JSON.stringify(next[k]))) return 0;
  await ctx.db.put(next, { db: "orders", id });
  return 1;
}

export async function scheduled(event, ctx) {
  const now = Date.parse(event.scheduledTime);
  const key = ctx.secrets.SQUARESPACE_API_KEY;
  const state = (await ctx.db.get(STATE, { db: "orders" })) ?? {
    type: "mirrorState",
    since: new Date(now - 30 * 86400000).toISOString(), // the first read copies the last 30 days
  };
  const waiting = Boolean(state.backoffUntil) && Date.parse(state.backoffUntil) > now;
  const due = Boolean(state.cursor) || !state.lastPolledAt || now - Date.parse(state.lastPolledAt) >= POLL_EVERY_MS;
  ctx.log("debug", "mirror tick", { due, waiting, hasKey: Boolean(key) });
  if (!key || waiting || !due) return; // the mirror starts the minute the key is saved

  const until = state.until ?? event.scheduledTime; // the window stays fixed until its last page is in
  let cursor = state.cursor ?? null;
  let written = 0;
  for (let page = 0; page < 5; page++) {
    const url = cursor
      ? `${ORDERS}?cursor=${encodeURIComponent(cursor)}`
      : `${ORDERS}?modifiedAfter=${encodeURIComponent(state.since)}&modifiedBefore=${encodeURIComponent(until)}`;
    const res = await ctx.fetch(url, { headers: { authorization: `Bearer ${key}`, "user-agent": "fulfilment-board" } });
    if (!res.ok) {
      const denied = res.status === 403 && (await res.clone().json().catch(() => null))?.vibesEgressDenied === true;
      const backoffMs = Math.min((state.backoffMs ?? 30000) * 2, 30 * 60000);
      const backoffUntil = new Date(now + backoffMs).toISOString();
      const lastError = denied ? "egress-denied" : `store answered ${res.status}`;
      await ctx.db.put({ ...state, until, cursor, backoffMs, backoffUntil, lastError }, { db: "orders", id: STATE });
      ctx.log("warn", "mirror backing off", { status: res.status, backoffMs });
      return;
    }
    const body = await res.json();
    for (const order of body.result ?? []) written += await upsert(ctx, order);
    const clear = { backoffMs: null, backoffUntil: null, lastError: null };
    if (body.pagination?.hasNextPage) {
      cursor = body.pagination.nextPageCursor; // this page is written, so the cursor moves past it
      await ctx.db.put({ ...state, ...clear, until, cursor }, { db: "orders", id: STATE });
      continue;
    }
    const since = new Date(Date.parse(until) - 2 * 60000).toISOString(); // re-read the window's edge
    const done = { since, until: null, cursor: null, lastPolledAt: event.scheduledTime };
    await ctx.db.put({ ...state, ...clear, ...done }, { db: "orders", id: STATE });
    break;
  }
  ctx.log("info", "mirror run", { written });
}
```

### `access.js`
```js
export function orders(doc, oldDoc, user, ctx) {
  if (oldDoc && oldDoc.type !== doc.type) throw { forbidden: "a record keeps its type" };
  if (doc.type === "order" || doc.type === "mirrorState") {
    ctx.requireBackend("scheduled"); // only the mirror writes the store's copy
    return { channels: ["orders"], grant: { roles: { owner: ["orders"] } } };
  }
  if (doc.type === "packing") {
    ctx.requireAccess("orders"); // whoever sees the orders packs them
    if (typeof doc.orderId !== "string" || doc._id !== "pack:" + doc.orderId) {
      throw { forbidden: "a packing note sits at pack:<order id>" };
    }
    return { channels: ["orders"] };
  }
  if (doc.type === "member") {
    ctx.requireRole("owner"); // the owner adds the packers
    if (typeof doc.userHandle !== "string" || doc.userHandle === "") throw { forbidden: "a member names a handle" };
    return { channels: ["orders"], grant: { users: { [doc.userHandle]: ["orders"] }, roles: { owner: ["orders"] } } };
  }
  throw { forbidden: "unknown type" };
}
```

The page live-queries both types and joins them on the store's id; a packer's
tap writes the sibling record:

### `App.jsx`
```jsx
const { useLiveQuery, database } = useFireproof("orders");
const { docs: orders } = useLiveQuery("type", { key: "order" });
const { docs: packing } = useLiveQuery("type", { key: "packing" });
const { docs: states } = useLiveQuery("type", { key: "mirrorState" });
const sync = states[0];
const packed = new Map(packing.map((p) => [p.orderId, p]));

function markPacked(order) {
  const pack = packed.get(order.storeId);
  database.put({ ...pack, _id: "pack:" + order.storeId, type: "packing", orderId: order.storeId, packed: true });
}
// …
<p role="status">
  {sync?.lastError === "egress-denied"
    ? "Showing saved data — live refresh unavailable"
    : `Orders synced at ${sync?.lastPolledAt?.slice(11, 16) ?? "the first read"}`}
</p>;
```

Your reply tells the owner to save the store's key as `SQUARESPACE_API_KEY`
in Secrets; until then the tick logs and returns, and the rest of the app
works. Another store names its window and cursor parameters differently, so
take them from its API reference.

### An order email rings the doorbell

Many shops get an email for every order, and a Zap on that email can tell the
mirror to look now, so a new order shows up within a minute. Reach for it when
the ask pairs a mirror with the shop's order emails: "when the order email
comes in, show the order right away".

**The order email is the doorbell, never the record.** The owner's Zap
(**Gmail → New Email Matching Search** on the shop's order emails, a
**Formatter** step that extracts the number from the subject, then **Webhooks
by Zapier → POST** to `/_api/zapier/order` with `order` and the
`x-zapier-secret` header) sends only the order number. The route checks the
secret as the Zapier recipe above does and writes a `doorbell` record at the
order number. The mirror reads every detail from the store with the owner's
key, so the app parses no email, a new email layout changes nothing, and the
fifteen-minute read still brings in anything the Zap misses.

```js partial
// backend.js — beside the mirror; json() and sameText() as in the Zapier recipe
export async function fetch(request, ctx) {
  const url = new URL(request.url);
  if (url.pathname !== "/zapier/order" || request.method !== "POST") return json({ ok: false, reason: "not found" }, 404);
  const secret = ctx.secrets.ZAPIER_INBOUND_SECRET;
  if (!secret) return json({ ok: false, reason: "this app is still being set up" }, 503);
  const given = request.headers.get("x-zapier-secret") ?? "";
  if (!(await sameText(given, secret))) return json({ ok: false, reason: "unrecognized sender" }, 401);
  const body = await request.json().catch(() => null);
  const number = String(body?.order ?? "").replace(/^#/, "").trim();
  if (!/^[A-Za-z0-9-]{1,40}$/.test(number)) return json({ ok: false, reason: "send the order number as order" }, 400);
  await ctx.db.put({ type: "doorbell", orderNumber: number, rangAt: new Date().toISOString() }, { db: "doorbells", id: number });
  return json({ ok: true });
}

// in scheduled(): a ringing doorbell makes the read due…
const ringing = await ctx.db.query({ db: "doorbells", limit: 100 });
const due = Boolean(state.cursor) || ringing.length > 0 || !state.lastPolledAt || now - Date.parse(state.lastPolledAt) >= POLL_EVERY_MS;
// …and once the watermark moves, the window has brought those orders in.
for (const bell of ringing) if (Date.parse(bell.rangAt) < Date.parse(until)) await ctx.db.delete(bell._id, { db: "doorbells" });

// access.js — only the route rings, only the mirror clears, and nobody reads the channel
export function doorbells(doc, oldDoc, user, ctx) {
  if (doc._deleted) ctx.requireBackend("scheduled");
  else ctx.requireBackend("fetch");
  return { channels: ["doorbells"], allowAnonymous: true };
}
```

Your reply names the two secrets (`ZAPIER_INBOUND_SECRET` and the store's
key) and the Zap's POST address and header.

## Email in — mail sent to the app's own address

Every app has its own email address, `<slug>--<owner>@in.vibes.diy` (the same
`slug--owner` order as the app's own host). Mail sent there runs the
**`email(message, ctx)`** export once per message, acting as whoever sent it
when the platform knows them and as nobody otherwise. Reach for it
when the person says "forward my order emails to the app", "my app should read
my order emails", "forward receipts to my app", "a shared inbox for our club",
"when the venue emails us, add it to the calendar", "the app's own email
address". The person forwards mail to the address (by hand, or with a
forwarding rule in their own mail), or hands the address to the people who
write in: a venue, a supplier, the club. Mail the app pulls out of their Gmail
by search is the Zapier recipe above; this is mail people send or forward TO
the app.

**The page shows the address, with a copy button and one line saying what to
send there.** `ctx.email.address` is the address, on every handler (`null`
while email in is off for the app, and the page then leaves the line out). A
`fetch` route hands it to the page, which calls it with `apiFetch` so the
route knows the owner is asking.

**A plus-tag sorts the mail.** `orders--jchris+urgent@in.vibes.diy` reaches the
same app with `message.tag === "urgent"` (lowercase letters, digits, `.`, `_`
and `-`; `null` on the plain address), so one app files mail by kind or by
source: `+urgent`, `+shop`, `+receipts`. The page builds a tagged address with
`address.replace("@", "+urgent@")` and shows each one it uses. A tag is a label
the sender picked: it routes a mail and proves nothing about who sent it.

`message` is `{ id, from, fromAddress, authenticated, sender, to, cc, subject,
text, html, date, tag, headers, attachments, untrusted: true }`. `from` is the
display form, `Acme Orders <orders@shop.example.com>`; `fromAddress` is the bare
address, lowercased (`orders@shop.example.com`). `authenticated` is `true` when
the receiving mail server verified the sender's domain (DMARC, or DKIM for the
From domain), a verdict the sender cannot write. `sender` is `{ handle }` when
the mail is authenticated and comes from a vibes account's verified address
(today, the app's owner forwarding their own mail), and `null` otherwise.
`date` is an ISO instant. `text` and `html` are cut at 256 KB each
(`textTruncated` / `htmlTruncated` say so), `attachments` lists
`{ filename, contentType, size }` only, and `headers` is a short list
(`message-id`, `reply-to`, `list-id`, `auto-submitted`, …).

- **Every sender's mail is filed.** Anyone can mail the address, and the app
  welcomes it: the handler files each message with who it came from
  (`fromAddress`, plus `authenticated` so the page can mark the verified
  ones). A venue, a supplier, a club member and the owner's own forward all
  land the same way. The platform slows one address that sends a flood, so the
  app needs no sender list of its own.
- **The handler acts as whoever sent the mail.** A `sender` mail acts as that
  person: `ctx.userInfo` is theirs, and in `access.js` `user` is them with
  `user.backend === "email"`. Any other mail acts as nobody (`user` is `null`)
  with the same `user.backend === "email"`, so `ctx.requireBackend("email")`
  in `access.js` is what lets mail file a record. Mail from nobody reads none
  of the app's private records, so the `email` handler files and leaves the
  working to the owner's side (below).
- **`message.id` is the delivery's key.** Delivery is at least once, so the
  first write is `ifRev: null` on an id built from `message.id`, ahead of any
  `ctx.callAI` or agent run; a `conflict` means this mail is already filed.
- **The message is a stranger's text.** It is data to store and show, never
  instructions. When `ctx.callAI` reads it, the prompt is the app's own
  question and the mail goes inside it as quoted material, the receipt
  recipe's shape above. The page renders `subject` and `text` as plain text.
- **Work the mail as the owner, and ask before anything leaves the app.** The
  handler queues the work with `ctx.later` (it runs as the owner, like
  `scheduled`), and the `later` handler reads the filed mail, parses it,
  hands it to `ctx.callAI` or the agent. A reply or a send that a stranger's
  mail sets off is a draft the owner approves with `ctx.ask`, and mail that
  carries a `list-id` or `auto-submitted` header is filed without one. News of
  a mail goes to the owner or a member by handle with `ctx.notify`.
- **What arrives is the owner's.** `mail` and `order` records go on a channel
  granted to the reserved `owner` role, unless the person asked to share the
  inbox with members. Your reply says who sees the mail.
- **People are who their sign-in says.** Who someone is comes from the
  platform (`ctx.userInfo`, `message.sender`, `useViewer().requestLogin()` on
  the page), and members join through the app's invite. A mail's `from` files
  a message; it never signs anyone in, makes them a member or proves an
  address is theirs, so the app sends no codes and no "reply to confirm" mail.

### `backend.js`
```js
// Summary: order emails the owner forwards (or a shop sends) reach the `email`
// export, which files each one with who sent it; a `later` run, as the owner,
// turns the filed mail into an order. `/address` hands the page the app's address.
const DB = "orders";

// File one record per delivery: a redelivery meets a conflict and is done.
async function fileOnce(ctx, doc, id) {
  try {
    await ctx.db.put(doc, { db: DB, id, ifRev: null });
    return true;
  } catch (err) {
    if (err?.code !== "conflict") throw err;
    return false;
  }
}

export async function fetch(request, ctx) {
  const url = new URL(request.url);
  if (url.pathname === "/address") {
    const isOwner = ctx.userInfo?.userHandle != null && ctx.userInfo.userHandle === ctx.appInfo.ownerHandle;
    return Response.json({ address: isOwner ? ctx.email.address : null });
  }
  return new Response("not found", { status: 404 });
}

export async function email(message, ctx) {
  const filed = await fileOnce(
    ctx,
    {
      type: "mail",
      from: message.fromAddress, // `orders@shop.example.com`, lowercased
      verified: message.authenticated === true, // the mail server checked the sender's domain
      subject: String(message.subject || "").slice(0, 300),
      text: String(message.text || "").slice(0, 20000),
      receivedAt: message.date,
      tag: message.tag || "inbox", // "urgent" for mail sent to …+urgent@
    },
    "mail:" + message.id
  );
  if (filed) await ctx.later({ in: "1m", name: "read-mail", data: { id: "mail:" + message.id }, key: "read-" + message.id });
}

export async function later(event, ctx) {
  if (event.name !== "read-mail") return;
  const mail = await ctx.db.get(event.data.id, { db: DB });
  if (mail === null) return;
  const found = /order\s*#?\s*([A-Z0-9-]{3,20})/i.exec(mail.subject) || /order\s*#?\s*([A-Z0-9-]{3,20})/i.exec(mail.text);
  if (!found) return; // filed and shown; not an order
  const total = /total[^0-9$]*\$?\s*([0-9]+(?:\.[0-9]{2})?)/i.exec(mail.text);
  await fileOnce(
    ctx,
    { type: "order", orderNumber: found[1], total: total ? Number(total[1]) : null, from: mail.from, verified: mail.verified, subject: mail.subject, receivedAt: mail.receivedAt, tag: mail.tag },
    "order:" + event.data.id
  );
}
```

### `access.js`
```js
export function orders(doc, oldDoc, user, ctx) {
  const ownerOnly = { channels: ["owner"], grant: { roles: { owner: ["owner"] } } };
  if (oldDoc && oldDoc.type !== doc.type) throw { forbidden: "a record keeps its type" };
  if (doc.type === "mail") {
    if (doc._deleted) ctx.requireRole("owner"); // the owner clears the inbox
    else ctx.requireBackend("email"); // only the mail handler files mail, whoever sent it
    return ownerOnly;
  }
  if (doc.type === "order") {
    if (doc._deleted) ctx.requireRole("owner");
    else ctx.requireBackend("scheduled"); // the owner's `later` run (the scheduled lane) turns mail into orders
    return ownerOnly;
  }
  throw { forbidden: "unknown type" };
}
```

### `App.jsx`
```jsx partial
import { apiFetch, useFireproof } from "use-vibes";
import { Button } from "@vibes.diy/ui";

const { useLiveQuery } = useFireproof("orders");
const { docs: inbox } = useLiveQuery("type", { key: "mail" });
const [address, setAddress] = useState(null);
useEffect(() => {
  apiFetch("/address")
    .then((r) => (r.ok ? r.json() : { address: null }))
    .then((d) => setAddress(d.address));
}, []);
// …
{
  address && (
    <section>
      <p>
        Forward order emails to <code>{address}</code>{" "}
        <Button type="button" size="sm" variant="quiet" onClick={() => navigator.clipboard.writeText(address)}>
          Copy
        </Button>
      </p>
      <p>
        Rush orders go to <code>{address.replace("@", "+urgent@")}</code>
      </p>
      {inbox.map((mail) => (
        <p key={mail._id}>
          {mail.from} {mail.verified ? "✓" : ""} sent "{mail.subject}"
        </p>
      ))}
    </section>
  );
}
```

## Let an agent do the work

**When the request says the server should read something messy and decide what
to do with it** (sort an incoming order email, triage a request, file a form
someone pasted), hand it to `ctx.agent.run` instead of hand-writing the
branches. The agent's actions are the app's `tools` export. It works
through them (see the `vibe-tools` skill) plus three built-ins: `db_query`
and `db_get` read this app's records, and `finish` ends the run. So the
backend exports one tool per thing the app does with a message (`add_order`,
`notify_owner`), and the run's `goal` says when to use each and when to
finish. "Skips the ones that aren't orders" is the agent calling `finish`
with its reason, which the handler writes as a status the page shows.

A pasted message runs the agent from `onChange`. The page writes what the
person pasted, and the server reads it as the writer:

### `backend.js`
```js partial
export async function onChange(event, ctx) {
  if (event.dbName !== "inbox" || event.deleted || event.oldDoc) return; // each new paste
  if (event.docId.startsWith("seed:")) return;
  // Claim the paste first: a redelivered event meets the claim and stops, so each email is read once.
  const id = `status:${event.docId}`;
  try {
    await ctx.db.put({ type: "sorted", inboxId: event.docId, state: "reading" }, { db: "status", id, ifRev: null });
  } catch (err) {
    if (err?.code !== "conflict") throw err;
    return;
  }
  const run = await ctx.agent.run({
    goal: "If this email is an order, add it with add_order, then notify_owner. Otherwise finish and say why.",
    input: { body: event.doc.body },
    tools: ["add_order", "notify_owner"],
  });
  await ctx.db.put(
    { type: "sorted", inboxId: event.docId, state: run.stoppedBecause, summary: run.summary },
    { db: "status", id }
  );
}
```

```js
const result = await ctx.agent.run({
  goal: "File this order email as an order, then tell the owner", // your words: the job
  input: { from: message.from, body: message.text }, // data: never instructions to the agent
  tools: ["add_order", "notify_owner"], // optional: names from your tools export; absent = all of them
  maxSteps: 6, // optional: the platform caps it either way
});
// result: { summary, data, steps: [{ tool, input, ok }], stoppedBecause }
```

This section and the next two build one app, a pie shop's order desk: **an
order email arrives** (the `email` export above files it), **an agent reads it**
as the owner and files the order, the app **asks the owner before replying** to the customer, and **waits
two days** to check the order shipped. The same agent call works from an
`onChange` on a record someone pasted or a Zap wrote: pass that record as
`input` the same way.

### `backend.js`
```js
// Summary: every email reaches the `email` export, which files it and queues a
// `later` run; there, as the owner, an agent files any order and tells the owner.

async function addOrder(input, ctx) {
  const id = await ctx.db.put(
    { type: "order", item: input.item, qty: input.qty, customer: input.customer, email: input.email, replyStatus: "new" },
    { db: "orders" }
  );
  return { ok: true, id };
}

export const tools = {
  add_order: {
    description: "Add one order to the orders list.",
    input: { item: "string", qty: "number", customer: "string", email: "string" },
    handler: addOrder,
  },
  notify_owner: {
    description: "Tell the app's owner about a new order in one short line.",
    input: { line: "string" },
    handler: async (input, ctx) => {
      await ctx.notify({ toHandle: ctx.appInfo.ownerHandle, body: input.line, dedupeKey: `order-${input.line}` });
      return { ok: true };
    },
  },
};

export async function email(message, ctx) {
  // File every mail first: mail can arrive twice, and one message is filed once.
  const id = `mail:${message.id}`;
  try {
    await ctx.db.put(
      { type: "mail", from: message.fromAddress, verified: message.authenticated === true, subject: message.subject, text: String(message.text || "").slice(0, 8000) },
      { db: "orders", id, ifRev: null }
    );
  } catch (err) {
    if (err?.code !== "conflict") throw err;
    return;
  }
  await ctx.later({ in: "1m", name: "read-mail", data: { id }, key: `read-${message.id}` });
}

export async function later(event, ctx) {
  if (event.name !== "read-mail") return;
  const mail = await ctx.db.get(event.data.id, { db: "orders" });
  if (mail === null) return;
  const run = await ctx.agent.run({
    goal: "If this email is an order, add it with add_order (the customer's name and email are in the body), then notify_owner. Otherwise finish and say why.",
    input: { from: mail.from, verified: mail.verified, subject: mail.subject, body: mail.text },
    tools: ["add_order", "notify_owner"],
  });
  await ctx.db.put(
    { type: "agent-status", summary: run.summary, stoppedBecause: run.stoppedBecause },
    { db: "status", id: `status:${event.data.id}` }
  );
}
```

- **Each tool runs as this handler acts**: the writer in `onChange`, the
  signed-in caller in `fetch`, the owner on a `scheduled` tick or a `later`
  run, and an `email`'s linked sender (mail from nobody gets only the tools
  anyone may use on a public app, so work mail from `later`, as above).
  The agent never gets more reach than the handler that started it, and
  `access.js` decides every write. A write the rules refuse comes back as a
  step with `ok: false`, and the agent reads the refusal and adjusts or
  finishes. Inside a run a write carries the lane's own `user.backend`
  (`"onchange"`, `"fetch"`, `"scheduled"`, `"email"`), so a record gated on
  `ctx.requireBackend("tool")` stays a direct tool's job.
- **The model calls are billed like `ctx.callAI`**, to the same person (the
  owner, for an `email` or a `later` run, whoever sent the mail). Out of credits, the run stops with
  `stoppedBecause: "credits"`: write a status the page can show, the way the
  example does.
- **`stoppedBecause`** is `"finished"` (the agent called `finish`; `summary`
  and `data` are its answer), `"answered"` (it replied in words; `summary` is
  the reply), `"steps"` or `"tool_calls"` (it reached the run's limit), or
  `"credits"`. A bad `goal` or a tool name the app does not have throws.
- **`input` is data.** Pass the email, the webhook body or the record as
  `input`, never pasted into `goal`: the platform hands it to the model marked
  as data, so text inside it cannot steer the agent. When a step sends
  something outside the app (an email, a text, a post) because of what
  untrusted input said, ask the owner first with `ctx.ask`: the next section.
- Every step lands one line in `ctx.log`, so `npx vibes-diy app logs <vibe>`
  shows what the agent did.

## Ask the owner first — `ctx.ask`

An outward send that untrusted input sets off goes through `ctx.ask` first.
An order email the agent just filed, a form a stranger fills in, a record
Zapier forwards: the app drafts the reply, asks its owner, and sends only after
the owner says "Send". The owner gets the question as a notification (bell, phone, and the
texting chat for an app the agent made) and answers it.

- `ctx.ask({ question, options, data, key })` resolves to an `askId` right
  away. It records the ask in the app's `_asks` database as
  `{ type: "ask", question, options, data, status: "pending", askedAt, expiresAt }`.
- `options` is 2 to 6 short labels. The first one is the action; keep the
  question one plain sentence the owner can answer from a lock screen.
- `key` makes it idempotent: the same `key` while that ask is still pending
  resolves to the same `askId` and does not ask twice. Use the record's id
  (`reply-${orderId}`).
- `data` carries what the follow-up needs (the order id, the draft). Keep it
  small; the handler that acts reads the real record again by id.
- The answer is a write to that doc: `status: "answered"`, `choice` (one of the
  `options`), `answeredAt`, `by`. It arrives as an ordinary `onChange` on
  `dbName === "_asks"`, which is where the workflow continues.
- An ask nobody answers flips to `status: "expired"` after a week, also an
  `onChange`, so the app can mark the record as not sent.
- Only the app's owner reads or answers `_asks`. The app can show the owner
  their pending asks with `useFireproof("_asks")` and answer one with
  `database.put({ ...ask, status: "answered", choice, answeredAt })`; the
  notification links to `#ask=<askId>`, so an owner panel can open that one.

The whole pie-shop chain, from the order the agent filed to the follow-up:

```js
export async function onChange(event, ctx) {
  // 1. The agent filed an order from an email: draft the reply, then ask before sending it.
  if (event.dbName === "orders" && event.oldDoc === null && event.doc?.type === "order") {
    const order = { ...event.doc, _id: event.docId }; // the id is event.docId; event.doc is the body
    const draft = await ctx.callAI(
      `Write two warm sentences telling the customer their order ships Friday. Customer name: ${JSON.stringify(order.customer)}. Order: ${JSON.stringify(order.item)}.`
    );
    await ctx.db.put({ ...order, draft, replyStatus: "awaiting-owner" }, { db: "orders", id: order._id });
    await ctx.ask({
      question: `Reply to ${order.customer} that their ${order.item} ships Friday?`,
      options: ["Send", "Skip"],
      data: { orderId: order._id },
      key: `reply-${order._id}`,
    });
    return;
  }
  // 2. The owner answered (or nobody did): act on it.
  if (event.dbName === "_asks" && event.doc?.status !== "pending") {
    const ask = event.doc;
    const order = await ctx.db.get(ask.data.orderId, { db: "orders" });
    if (order === null) return;
    if (ask.status === "answered" && ask.choice === "Send") {
      await ctx.fetch(ctx.secrets.ZAPIER_REPLY_HOOK, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ to: order.email, text: order.draft }),
      });
      await ctx.db.put({ ...order, replyStatus: "sent" }, { db: "orders", id: order._id });
      // 3. Check back in two days if the order is still open.
      await ctx.later({ in: "2d", name: "follow-up", data: { orderId: order._id }, key: `follow-${order._id}` });
    } else {
      await ctx.db.put({ ...order, replyStatus: ask.status === "expired" ? "not-answered" : "skipped" }, { db: "orders", id: order._id });
    }
  }
}

export async function later(event, ctx) {
  // One `later` handler branches on `event.name`: `read-mail` (above) reads a filed email.
  if (event.name !== "follow-up") return;
  const order = await ctx.db.get(event.data.orderId, { db: "orders" });
  if (order === null || order.status === "delivered") return;
  await ctx.ask({
    question: `${order.customer}'s ${order.item} hasn't shipped yet. Send an update?`,
    options: ["Send update", "Not yet"],
    data: { orderId: order._id },
    key: `update-${order._id}`,
  });
}
```

## Wait, then continue — `ctx.later`

`ctx.later` schedules ONE event for later, delivered to `export async function
later(event, ctx)` with `event = { name, data, scheduledTime }`. It runs as the
app's owner, like `scheduled`.

- `in` is a duration (`"30m"`, `"3h"`, `"2d"`, `"1w"`); `at` is an ISO instant
  (a `Date` works too). Pass exactly one.
- `key` replaces a pending timer with the same key, so "remind them in 2 days"
  set twice is one reminder. `ctx.later.cancel(key)` removes it; cancel the
  follow-up when the person answers first.
- `name` says which follow-up this is; one `later` handler branches on it.
- The handler reads the record again by id and checks it still needs doing:
  the world moved on while the timer waited.
- A recurring time ("every morning at 9") is `scheduled`; `ctx.later` is for a
  wait that one event starts.
- Timers wait while the app is unpublished or its scheduled runs are paused,
  and run when it is back.

## A complete example — activity feed + owner-only digest

Users write `note` docs from `App.jsx`. The backend does two jobs: `onChange`
mirrors each note into a per-author `activity` entry (acting as that author —
same privilege, just automated), and a `scheduled` sweep maintains one `digest`
doc that `access.js` restricts to the **owner**, so no user can forge it.

### `backend.js`
```js
export const config = { scheduled: { interval: "15m" } };

export async function onChange(event, ctx) {
  if (event.dbName !== "notes" || event.deleted) return;
  await ctx.db.put(
    { _id: "act-" + event.docId, kind: "activity", srcId: event.docId, by: ctx.userInfo, at: event.seq },
    { db: "activity" }
  );
}

export async function scheduled(event, ctx) {
  ctx.log("debug", "digest sweep", { at: event.scheduledTime }); // proof of life, before any return
  // Acts as the app owner — access.js allows `digest` docs for the owner only,
  // making this document genuinely server-controlled.
  //
  // What this tick already did is read BY ID, never re-derived from a scan, and
  // the sweep is bounded by what is NEW rather than by how big the app has grown.
  const state = await ctx.db.get("digest:state", { db: "digest" });
  const since = state?.throughSeq ?? 0;
  const fresh = await ctx.db.query({ db: "activity", field: "at", range: [since + 1, Number.MAX_SAFE_INTEGER], limit: 200 });
  if (fresh.length === 0) return; // nothing happened — write nothing at all

  const throughSeq = fresh.reduce((max, doc) => (doc.at > max ? doc.at : max), since);
  const next = { _id: "digest", kind: "digest", headline: `${fresh.length} new notes`, throughSeq };
  const existing = await ctx.db.get("digest", { db: "digest" });
  if (existing?.headline === next.headline && existing?.throughSeq === next.throughSeq) return; // unchanged

  await ctx.db.put(next, { db: "digest" });
  await ctx.db.put({ _id: "digest:state", type: "digestState", throughSeq }, { db: "digest" });
}
```
