# Mote card

The language in brief; everything here compiles today. The whole of it is in `docs/` of the Mote
repository and at https://motelang.com: start at docs/README.md (a map, and a "how do I…" index). Each
section names its page. Every component, live with its source: https://playground.motelang.com

```mote
// docs: whole
shape Todo
  id: string
  title: string
  done: bool
state todos: Todo[] = [] persist
state draft = ""
derive left = todos.filter(t => !t.done).length
action add
  if draft.trim() == "" return
  todos.push({id: uid(), title: draft, done: false})
  draft = ""
column gap=8 padding=16
  row gap=8
    input value=draft placeholder="What next?" submit=add
    button "Add" press=add
  for t in todos key=t.id
    row gap=8 align-items=center
      input type=checkbox checked=t.done
      text t.title color=(t.done ? "dim" : "fg")
      button "×" press={todos.remove(t)}
  text `${left} left` color=dim
```

Three rules: only an `action` or a `{…}` handler writes state (a `fn` is pure) · a call that can fail
meets `else` or `?` at once · in markup a space ends a value: anything with an operator goes in parentheses.

## Commands → docs/cli.md
```text
mote dev app.mote       serve it, reload on save        mote check app.mote [--json]   what is wrong, and the fix
mote test app.mote      run its `test` blocks (the back end's rules, hooks, fns, jobs): no browser  docs/testing.md
mote build app.mote     dist/: installable, offline     mote build app.mote --single   one HTML file (opens from file://)
                        a battery (zip img pdf syntax re sql charts …) is a file, assets/<name>.<hash>.wasm, fetched at its first call; --single holds them inside
mote serve dist         serve a built directory         mote card                      this card
mote editor vscode      set an editor up (cursor neovim helix …; `mote lsp` is its server)          docs/editor-plugin.md
mote tree app.mote      the syntax tree as written, with where each part starts and ends (--json)
```
In a terminal `mote check` shows the line and underlines what is wrong; `--json` says `end_line` `end_col` too.
A file is an app: declarations and markup. Blocks are indented with spaces. `// comment`: the lines right
above a declaration (a field too) are its documentation, shown on hover.
Beside the entry: `public/` ships whole · `assets/` ships what is named · `icon.svg` is the app's icon.

## Declarations → docs/language.md
```text
state n = 0                          a value the page shows; `persist` keeps it in localStorage
state todos: Todo[] = [] persist     an empty list or `none` needs its type
derive left = todos.filter(t => !t.done).length        follows what it reads; cannot be assigned · `derive row: json = got?.row` with a type
action add  /  action set(v: string)                   statements; may write state
  `assume` + a block of assignments in an action: done at once, taken back if the action fails after it (a `server fn` says no);
    `+=` by as much, `=` only if nothing wrote since · model writes need none: they show at once         reactivity.md#assume
fn total(xs: number[]) = xs.length                     pure; or `fn f(a: T): R` with a block · `T?` params at the end may be left out (none)
wasm fn sum(xs: number[]): number                      experimental: it and the plain fns it calls as one WebAssembly module
                                     (numbers bools shapes lists; same answers as JavaScript, which runs until it is ready) language.md#wasm-fn
shape Todo                           `field: type` lines indented under it
component Badge(label: string, tone: string?)          declarations and markup indented under it
use "./parts.mote"                   that file's declarations · `use "pkg:name/file.mote"` with mote.toml (the program's, first, from any file)
wants fn usageMay(): bool            in a package: a fn the program is to declare (H166 at its entry, with the line) · `= expr`: a default it may replace
                                     a name is declared once in the whole program (H022 names both places)
app "Todos" accent=#0a84ff           title and accent · scheme=dark (or light) · lang="de" (<html lang> with no words) · toasts="top right" · agents=off
                                     edges=cover (under a phone's notch and home bar: padding-bottom="max(16px, env(safe-area-inset-bottom))")
                                     render=ahead (the back end sends each page drawn, with its data: back-end.md#a-page-drawn-ahead; with no back end of its own, `mote build` writes `/` and each written-out route drawn, as files)
                                     writes=confirmed (a model's writes from the page wait) · timeout=30000 (ms a call may take; unsaid: no limit)
                                     policy=strict connect="https://api.x.com wss://relay.x.com" (a Content-Security-Policy made from the build: scripts and styles by hash,
                                     no unsafe-inline, no unsafe-eval; and HSTS, Referrer-Policy, COOP, Permissions-Policy) · update=ask (a new build waits:
                                     on app.update(u: {build: string, forced: bool}) · app.check() · app.update()) · app.build() the build's hash, the SHA-256 of
                                     dist/build.txt · the same source and compiler give the same dist/: mote build app.mote --check dist → docs/delivery.md
                                     installed: id="mail" scope="/" share="text links image/* .eml" handles="mailto" opens=".eml"
                                     shortcuts="New: #/compose; Inbox: #/inbox" · on app.handed(h: {how, title, text, url, files: picked[]})
app "Shop" "Cabinets drawn by you"   a second string is the description · a shared link fills itself in (title, Open Graph, Twitter):
                                     share.png (or .jpg, og.png) beside the entry or in public/ is the picture, else the icon (small card)
                                     image="cover.png" (or an address; never SVG: H169) · url="https://shop.example" for a page no back end
                                     serves; a back end writes whole addresses from Host (MOTE_PROXY: the proxy's; MOTE_URL)   markup.md
```

## Types and logic → docs/language.md
```text
string number bool none bytes json · T[] · T? · a shape's name · {x: number} · image sheet video sound font
```
Inferred except parameters, shape fields, and an empty or `none` first value. Structural. `json`
fits anything, unchecked. No unions: `T?` is the one "or", and must be settled before `.` or
arithmetic: `x?.f` · `x ?? d` · `if x …` · `if x == none return` (or `fail("…")?`, `continue`, `break`:
the rest of the block knows it is there). `find() pop() at()` give `T?`.
```text
let x = e · x = e, += -= *= /= · if c … else if … else … · `if c stmt else stmt` on one line · match x (arms indented)
a block declares a name once (a second `let x`, or one of a parameter: H022; `x = e` changes it); an inner block may hide an outer name
for x in xs · for x, i in xs · while c · return e · break · continue · x => e · (a, b) => e · c ? a : b · a ?? b · a?.b
& | ^ ~ << >> >>> (32-bit; tighter than == and <, looser than + -: `x & 1 == 0` is `(x & 1) == 0`) · 0xff
== and != are strict · none (no null, undefined) · `text ${e}` · r"\d+" raw · [a, ...b] · {k: v, k, ...o}
writes: assign state, or change it in place (push pop shift unshift splice sort reverse fill remove(x), t.done = true)
built in: uid() now() log(x) toast("Saved") (three show, the rest wait) copy(text) go("/path") back() forward() time.clock(now()) time.date(now())
          share() the share sheet with this page (its route's title, description, address) · share({title, text, url, files}) ·
          gives "shared" "cancelled" "copied" "shown": no sheet, the link is copied and a toast says so; never fails   data.md
          focus("id") (the caret stays; focus("id", true) selects) · scroll("id", "end") · close()
          by id these (and el.focus el.scrollTo el.select) wait for what the action itself just made appear; `drawn()` waits
          for the page to show what was written (then read el.rect …) · el.from() {id, row, data}: where the event being
          handled happened (row: its `for` row's key) · el.at(x, y) the same at a point · el.row("list", key) that row's element
          scroll("msg-42", {inside: "list", block: "center", behavior: "instant"}) brings it into view (start center end nearest)
plus JavaScript's own methods, and Math JSON Date Number String Object Array (there is no `new`)
words   words "en" + lines `hello = "Hello, {name}!"`, `items = {zero: "…", one: "{n} item", other: "{n} items"}` (the first is the
        source; a later language's missing keys show the first's: H251) · words "de" from "./de.words" · t("hello", {name}) checked
        against the keys and their {names} (H248) · words.lang words.langs words.choose("de") (kept; <html lang> follows) · screen.lang
fmt     fmt.number(n, {lang, digits, exact, compact, grouping}) · fmt.currency(n, "EUR", {sign: "code"}) · fmt.percent(0.25)
        fmt.list(xs, {type: "or"}) · fmt.plural(n, {one: "{n} file", other: "{n} files"}) · in words.lang unless lang: said → docs/words.md
time    time.clock(at, {zone: "Asia/Tokyo", lang: "de", hours: 24}) · time.date(at, {zone, lang, style: "long"}) (short medium
        long full numeric month weekday iso) · time.words(at, {from: tick}) "in 20 minutes", "yesterday" · time.zone() · time.zones()
        let p = time.parts(at, zone?) {year, month, day, hour, minute, second, weekday, offset} · time.of({...p, day: p.day + 1, hour: 9}, zone?)
        time.add(at, {days: 1}, zone?) · time.startOf(at, "week", {zone, first: 1}) · time.endOf · time.stamp(at) "2026-11-12T14:22" ·
        time.read(stamp)? · time.weekStart(lang?) · on the back end the zone is said (there is no reader)   → docs/language.md#time
        time.next({hour: 9, minute: 0, weekday?}, zone?, from?): the next moment a clock there reads so, right across a change of the clocks
```

## A call that can fail → docs/language.md
Everything that leaves the page can fail, and none says async or await: the compiler waits for it.
```text
x else fallback          the fallback on failure; `else err => …` gets the message
x?                       pass the failure on: in a fn, the fn can now fail; in an action, the action stops · `c ? a()? : b()?`
pending(a) failed(a) failure(a)      of an action or a resource: `button "Save" press=save disabled=pending(save)`
pending(row)                         a model's row with a write the back end has not answered: opacity=(pending(m) ? 0.5 : 1)
let xs: Post[] = net.get(url)?       json takes the type its `let` gives it
fail("out of stock")?                a failure made on purpose: failure(action) has the words; only a fault is logged
fail("out of stock", {kind: "stock", data: {sku}})?   with a kind and data · a failure in text is its words, and also:
err.kind err.id err.data err.where err.words (under `else err =>`) · failure(save)?.kind …   kind: offline signin refused
                                     invalid toobig full (no room on the device) memory (img) limited (429: err.data.retryAfter, seconds) timeout
                                     taken (a key or a unique value another row has: err.data {model, fields}; add set put atomic
                                     auth.create, SQLite and Postgres, and in the page) fault said, or the program's own · id: the call's, as the back end's log has it
x else err => (err.kind == "taken" ? none : err?)   err? in the handler: the failure passed on as it came (kind, data; a fault
                                     stays a fault); fail(err)? makes a "said" of its words · back-end.md#a-create-that-loses-taken
on failure(f)            + a block, top level: every failure nothing else heard (an action's nobody reads with failure(a), a
                         resource's with no else, a live value's, an uncaught error); f: Failure {words, kind, id, data, where, at}
                         f.at: where a fault of the page's own code was written ("app.mote:12"), as its back end says (`app … faults=off`)
```
extern js "./glue.js"    + lines `fn confetti(count: number): none`: the file's exports, typed; every call waits and can fail, and what
                         comes back is checked against its type · `off` after the file: also in a worker · a `server fn` runs it in Bun
                         · `el: element` hands a ref (the file hears `mote:gone` when it leaves) · extern script "https://…" integrity="…"
                         another site's script in the head · a LAST RESORT (a battery, the kit, an extension, net.* to an HTTP API, proc.run come
                         first); build and check list each as "outside what is checked" · docs/js.md
Only actions, fns, handlers, tasks and resources can wait. A binding or a `=>` cannot: use a resource.
But `x => upload(x)` (nothing but a call of an action that waits) begins it and gives none: for callbacks (forEach, a handler
given to a json value). `wait(p)?` waits for a promise a json value holds: `let t = wait(widget.value()) else ""` (widget: json).

## Markup → docs/markup.md
```text
tag text? name=value…                children indented. Text is a string, a template, or a name.
tags    view box row column grid text image link icon, HTML's own (button input h1 ul li …), Components
value   "string" · 12 · 12px 50% 1fr · #0a84ff · center · t.title · draft.trim() · (any expression) · {a handler}
style   any CSS property by name; a bare number is px (not on flex opacity z-index line-height font-weight …)
roles   fg bg dim card line accent danger ok warn follow light and dark; computed: color=(done ? "dim" : "fg")
attrs   HTML's own: class for id href type placeholder aria-* data-*; a lone word is a boolean: `input autofocus` · `AdminPanel trusted` (a bool prop)
bind    `input value=draft`, `input type=checkbox checked=t.done` write back when the value is state
states  hover · active · focus · disabled · checked · phone · tablet · desktop · dark · light · still: a child line of styles
          button "Save" background=accent
            hover opacity=0.8                    a value may be worked out: hover background=skin.hover
        mark a parent `group`; then `in hover opacity=1` on a child styles it while the parent is hovered
control if c / else if c / else · for t in todos key=t.id · for t, i in xs · match x · let p = e · let xs: string[] = row.data.xs ?? []
long    for r in rows key=r.id virtual (measured) · virtual=32 (every row 32px: a million rows) · sticky=r.head (a group's head stays)
        only the rows in view are drawn, in the nearest box that scrolls (give it a height); across in a `row`; lanes in a grid;
        the row at the top stays put; a row's own state goes when it is scrolled away (keep it by key); find-in-page sees drawn rows
        a model's rows: `live xs = T.find(f, {order: "at desc", window: 200}) else []` + `for x in xs key=x?.id virtual=36` (below)
        scroll("list", {row: key}) · {index: n} · el.inView("list", key) · el.shown("list") {first, last, count}   markup.md#long-lists
try     + what may fail to draw, then `else err` + what stands there instead (err: a Failure; `again` builds it once more):
        catches a throw while built or updated, a derive's failure, a resource's or live value's with no else; not a handler's
routes  route "/planet/:id" (id is in scope) · route "*" · link "About" href="/about" · go("/about") (a whole address leaves the page) · route.path
        a program with `route` blocks, or that reads route.path or calls go/back, routes in the page: there href="/x" is
        in-app (#/x), but for a whole address, `download`, `target=`, and /file/…
        route.origin · route.url · route.link("/join/abc") the whole address of a path, for someone else to open
        route "/pricing" title="Pricing" description="…" image="p.png": the tab follows it; the back end answers /pricing
        with its own tags (strings written out: H172) · a page no back end serves: the app's (routes are after #)
        route.query("q") (reactive, or none) · route.setQuery({q: text, page: none}) (no new history entry)
        app "X" routes=paths: /planet/mars with the History API (back, forward, scroll put back, href="#id" scrolls); the
        host answers every path with the page (back end, mote dev/serve do; a build writes 404.html) · base="/shop/" below a
        path · from file:// routes stay after # · root unsaved=(dirty) (or the words): beforeunload, and in-app moves ask
        with routes=paths (else H355): route.fragment what stands after # (reactive) · route.setFragment("x") ("": none; no new
        entry) · route.takeFragment() read and taken out of the address and the history before any other script of the page
        runs, handed over once: for a secret another site hands over with go("https://there.example/#…")   markup.md#the-fragment
        lines=2 (two lines, then an ellipsis) · -webkit-line-clamp=3 (a browser's own property) · on a style a word that
        names a fn or an action is CSS's word (flex-wrap=wrap) · preload=none decoding=async fetchpriority=low inputmode=numeric
        enterkeyhint=send · an attribute whose value is none is not written · a popover is its element's next sibling
other   image "hero.jpg" (assets/) · icon "camera" size=20 · `icon glyph` for a value, its names written `icon("camera")` where they are made (only those ship) · popover and tip under an element · dialog open=flag · row glass
        net.online: a reactive bool, false with no network (not asked of a page on localhost) or while the line to the back end is down (it reopens itself);
        a call that finds nobody there fails (`else`, failure(action)) and logs nothing            → docs/back-end.md
window  screen.visible (in front) · screen.focused (has the keyboard) · screen.idle(60000) (nobody at it): reactive bools
        screen.awake(true)? keeps the screen on (taken again whenever the page is seen) · screen.awake(false)?
        screen.filesOver (files held over the window; a file let go outside a `drop=` never leaves the page) ·
        pastefiles=attach: a paste that carries files, in a field inside too; the field keeps the words
page    root density=density zoom=zoom var-brand=brand motion="less"    values of the whole page, from state, at the top of any file:
          a CSS property styles the root · var-brand is --brand, read as color="var(--brand)" (var-accent re-colours a role) ·
          any other name is asked about by a child line in any file: `in root[density=compact] padding=2`, `in root[contrast] …`
          motion: "less" | "full" | "system"; the system's wish for less motion is honoured unsaid; `still …` lines, screen.still
          root lang=locale dir=rtl translate=no: HTML's own on the root; <html lang> is root lang= while said, else words.lang, else app lang=
          root title=(n > 0 ? `(${n}) Inbox` : "") badge=n · in an action: title("…") ("" is the app's own) · badge(0) clears
          root description=(page.blurb): what the page says of itself; with render=ahead it and the title are in the head of the page sent
        close() in a handler or action closes the popover or dialog the reader is in · close("id") that one
```
Components: `Badge label=t.title`; a `T?` prop may be left out; an event's name is a handler (`Go press=save`,
inside `button press=press`); a prop the component assigns is written back (`Switch on=dark`); anything that is
not a prop goes on its first element (the first inside it, if that one is a `form display=contents`); children go where it writes `slot`.
`slot "bar.tools" row=r` is a place any file may draw in: `fill "bar.tools"(row: Row)` + markup, at the top of a
file (a component with no name: props from what the slot gives; every fill is drawn, in `use` order).

## Events → docs/events.md
```text
press input change submit focus blur key keyup dblclick contextmenu scroll drop paste pastefiles wheel pinch resized contents seen
seen={if it.visible more()} seen-margin=600: into view and out of it, {visible, ratio}; the margin counts as in view
pointer events hand {x, y, …, id, type, primary}: `id` tells two fingers apart · pinch={zoom = it.scale} hands {scale, x, y, done}
pointerdown pointerup pointermove pointercancel pointerenter pointerleave · dropped over (things carried from a `drag=`)
pointerdown= with pointermove= keeps the pointer, and each press gets exactly one pointerup or pointercancel (a touch taken
  to scroll, the page hidden, the element gone): end the drag on both. Say touch-action=none on what a finger drags
wheel={x += it.dx} wheels="x": only that way of the wheel ("y": up and down), the other is the page's · screen.keyboard: px of the window under a keyboard
swipe={x = it.tx + it.dx} swipes="y": one finger along it, {dx, dy, vx, vy, phase: "start" "move" "end" "cancel", tx, ty, width,
  height, type}; swipes= "x" (unsaid) "y" "left" "right" "up" "down" or none. Presses inside still work, the page scrolls the other way
press: the innermost thing pressed hears it (a button in a `row press=` does not press the row); presses= hears all
press=add · press=remove(t.id) · press={n += 1; open = false}        an action, a call, or a block
input/change hand over the field's value (a checkbox: its bool) · key: the key's name · pointer*: {x, y, …}
in a block, `it` is what was handed over: `input={draft = it.trim()}` · `pointerdown={at = it.x}`
`change=set` with `action set(on: bool)` · `key=k keys="mod+s tab"` takes those chords for itself
typed in a field inside it, `key=` hears only Escape and the chords with a modifier named in keys= (mod+k)
shortcut "mod+k" openSearch · shortcut "mod+1" pick(1) · shortcut "escape" {open = false} (or statements indented under it)
  a line at the top of any file, in a component, under an `if` or a route (live while that is shown): heard wherever the
  keyboard is, and when it is nowhere; the chords are `keys=`'s ("mod+z mod+shift+z": several). While a field has the caret
  only Escape is heard, unless the line ends in `fields`: shortcut "mod+s" save fields. An element whose `keys=` names the
  chord hears it instead. Under a dialog or a popover: heard while that is open, before the page's own line for the chord
keys.shift keys.alt keys.ctrl keys.meta keys.mod (⌘ or Ctrl): held now; pointer events say them too
`row drag=t.id kind="todo"` is carried; `row dropped=move(t.id) takes="todo"` receives {value, kind, x, y, …};
  child lines `dragging …` and `over …` (`over top …`) style them meanwhile
state box: element? = none, then `ref=box`: el.width(box) el.scrollTo(box, top) el.focus(box) el.rect(box) {x, y, width, height}
  el.transform(box) {tx, ty, sx, sy}: its translate and scale now, mid-transition too
  every el.… also takes an id (another component's field: el.select("composer", 0)) · el.rect(row, list): its place in the list
a field's caret: el.selection(box) {start, end, text} · el.select(box, start, end?) · el.replace(box, start, end, words)
                 (as typing: undo, input=, the bound state) · el.caret(box, at?) {x, y, height} in the window
```

## When things run → docs/reactivity.md
```text
resource posts: Post[] = net.get(`/api?tag=${tag}`) else []
                       loaded in the background, again when the state its call reads changes;
                       `else` is its value until then and on failure. pending(posts) failure(posts) refresh(posts)
task                   statements that run when the page opens; `task load` is also an action: load()
every 1000 / after 500 statements on a timer
watch active           statements that run after a value changes (never at the start); may not write what it watches
                       task, every, after, watch under an `if` or a route start and stop with it
```
A binding re-runs when state it read changes; nothing else re-renders. A fn that loops and uses only its
parameters runs in a worker when an action calls it (`main fn` keeps it on the page, `off fn` sends it).
`action preview newest` (or `task load newest`): called again while it waits, the earlier run ends at its wait:
nothing after it is done, no `else`, no failure; its worker or call is stopped. What it wrote before the wait stays.
Said once: `fns main` (or `off`, `auto`) at the top of a file, before its first fn, for the plain fns below it ·
mote.toml: `fns = "main"` at its top for the project's own files, and `[fns]` + `engine = "main"` for a package.

## A back end → docs/back-end.md
```mote
// docs: whole
state job = "door"
state price = 0
fn priceOf(job: string): number = job == "door" ? 4175 : 0
server fn quote(job: string): number requires anyone
  if priceOf(job) == 0 fail("no such job")?
  return priceOf(job)
action ask
  price = quote(job)?
button "Quote" press=ask
text `${price} ${failure(ask) ?? ""}`
```
`server fn` runs on Bun; the page calls it by name, as a call that waits and can fail. Its parameters need
types (they are checked on arrival). It cannot read the page's state (a `derive` written out whole, `derive most = 50`, it can). A fn only it uses is not in the page.
`requires` says who may call it (below: `anyone`, `signedIn`, a rule).
It has sql, fs, net, proc, tcp, ws, env("KEY"), route.origin (where the caller reached it), crypto.hash, re, search, syntax. `mote build` writes server/main.js:
`bun dist/server/main.js --port 4870`. `mote dev` runs both. Also: auth.signUp/signIn/signOut/me/changePassword(old, new)
and `requires signedIn` · `server live fn` with `live x = f(a) else []` and `changed("f", a)` · `emit` and
`on name(e: {…})` · notify.send(userId, {title, body, url}, {data, only: "desk" | "phone" | [device ids], tag, silent, renotify}?)
· in the page notify.enable() notify.disable() notify.devices() [{id, kind, here}] notify.kind() notify.inbox() notify.read(id) ·
`on notified(n: {title: string, data: {…}})` · `on notify.opened(n: {url: string, data: json, action: string})`: a notification was pressed (action: its button's id, or "").
`on push.received(p: {data: {sealed: string}})` in the service worker, no page open: db, crypto, notify.show, server fns; nothing shown → "Something new".
```text
auth.find(email)? {id, email}? · auth.setPassword(userId, password, {keepSessions})? · auth.signInAs(userId)? ·
auth.signOutAll(userId)?   in a `server fn` only, and unchecked: that fn checks who may (a token kept hashed, a role)
auth.create(email)? {id, email}: an account with no password (no sign-in by one until `setPassword`) · auth.setEmail(userId, email)? ·
auth.create()? an account with no address either (email "", `me.email` none in a rule; any number of them) · auth.setEmail(userId, none)? ·
auth.limit(key)? first in a sign-in fn of the program's own: its tries counted as auth.signIn's are, in the same buckets ·
auth.verified(userId)? bool: the address was shown to be theirs, which only the program says: auth.setVerified(userId, yes?)?
use "pkg:google/google.mote" · GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET · GoogleButton (or press=googleSignIn): Continue with Google, into the
  same accounts and sessions; by Google's `sub`; `fn googleMay(who: OidcWho): bool` (false or fail) says who may not → docs/google.md
use "pkg:passkey/passkey.mote" · press=passkeyAdd press=passkeySignIn · passkeyCheck (a second factor) · passkeyList()? [{id, name, aaguid, backup…}] ·
  the program may say: fn passkeyMax(user: string): number (how many an account) · fn passkeyPrf(): bool · fn passkeyAttestation(): string
  (checked: packed, tpm, android-key, fido-u2f, apple) · fn passkeyRoots(aaguid: string): string[] (PEM or folders) ·
  fn passkeyMay(about: PasskeyAbout): bool (about.attested, about.attestation {fmt, trust, root, …}, backup) ·
  security keys only: about.attested && !about.backup · use "pkg:passkey/metadata.mote": passkeyMdsLoad(blob, root)?
  passkeyMdsRoots(aaguid)? (the FIDO Metadata Service's BLOB, checked up to the root the program pins)       second-factor.md#passkeys
page: passkey.create(options)? {id, clientData, attestation, transports, authenticator, aaguid, attachment, prf {enabled, first?, second?}} ·
  passkey.get(options)? {id, clientData, authenticator, signature, userHandle, attachment, prf {first?, second?}} · passkey.supported() ·
  passkey.prfSupported()? · options are WebAuthn's, binary as base64url or bytes; no `server fn` needed (challenge, rp, user.id default) ·
  extensions: {prf: {eval: {first: salt}}} or {prf: {evalByCredential: {[id]: {first}}}}: prf.first is 32 secret bytes, the same for the same
  passkey and salt, not enumerable (never sent, logged or kept by accident)                                 second-factor.md#a-key-from-a-passkey-the-prf-extension
auth.list({search, after, limit})? {rows: [{id, email, made, sessions}], total, next} · auth.sessions(userId)? {who, sessions, actedAs, actingAs}: likewise
models.list()? · models.of(name).find(f, o)? (past the rules) · models.of(name).as(me).set(key, changes)? (under them): a model named as the program
  runs, rows as json; get one find count has search searchCount add set del · app.info()? {name, build, started, data, snapshots, settings…} · app.access()?
  all the back end's alone (H160, H161): who may is the `requires` of the fn that says them                 models.md#models-chosen-at-run-time
rule member(channel: id) = exists(Member, {channel: channel, who: me})   a named test, in the language of a model's rules;
rule admin = exists(Member, {who: me, role: "admin"})                    it may name other rules (never itself) and `signedIn`
rule staff = me.email in setting.list("SHOP_ADMINS")     `me.email` (lower case) · `setting("KEY")` its text · `setting.list` after `in`
  (split at commas, trimmed): read once as the back end starts (a change is a restart); never `secret()` (H163)   back-end.md#a-rule-that-reads-a-setting
  model Message … read if member(channel)                a model's line names it with its fields: as if written there
server fn purge(channel: id): number requires admin && member(channel)   `requires` a test of rules, `signedIn`, && || ! ( ),
  over the fn's own parameters (id string number bool; `o.channel` of a shape): asked after the arguments are checked, before
  the body, and at every run of a `live` value; one answer a rule and its values in a call · nobody signed in: 401 `signin`
  (a test that reads `me` asks for a session) · the rule says no: 403 `refused`, "you may not do that"
server fn status(): string requires anyone     open to the internet, and says so · server route GET "/x/:id"(req) requires
  member(id) · a `server fn` with no `requires` where people sign in is warned of (H134; `mote check --strict`: an error)
  · so is a rule that can never pass, or passes for anyone: `kind == "a" && kind == "b"`, `kind in []` (H162)
server fn search(q: string): Hit[] requires anyone limit 5 per minute    also per second hour day · by me | ip | a parameter
  (unsaid: who is signed in, else the address) · over it: 429 `limited`, `retry-after` · kept by each process · on a route too
  auth.signIn signUp changePassword are limited with nothing written: 10 a minute an email, 30 an address (MOTE_AUTH_LIMIT)
  the address is the socket's; behind a proxy say MOTE_PROXY=1 (how many): then the last of X-Forwarded-For, never a caller's own
check(value, Shape)?     json held to a shape (a model's row, [T], {f: T}) as it runs: the value typed, or "invalid" with where:
                        "events[3].amount: a number was wanted, and there is \"12\"" · {extra: "keep" | "drop" | "refuse"}
schema(Shape)           its JSON Schema, written out when compiled ($defs; {strict: true}: all required, no others)
net.lookup(host, "TXT")? a name's records of one kind (back end): A AAAA CNAME NS PTR TXT texts, MX {exchange, priority},
                        SRV {name, port, priority, weight}, CAA {critical, tag, value} · none is [] · {timeout: 5000, servers}
                        · no answer: "offline" · a test: given dns "example.com TXT" answers {records: […]}
net.send("GET", url, {to: {path: "in/a.mp4", resume: true}})?   the answer written to a file as it arrives (back end): a.written,
                        a.size; resume asks for the rest (Range) · body: {file: "out/x.csv", from, length}: a file or a part, read as sent
lock("export", {for: 60000})   + a block: one run at a time of every back end at the database; one that finds it held is "busy"
net.pace("api.x.com", {per: 1000, max: 10}) · net.breaker("api.x.com", {after: 5, rest: 30000})   in `server start`: requests
                        wait their turn; after 5 failures running the host is "offline" at once for 30 s · net.health()
req.form({file, files})? a form's body at a route (multipart or urlencoded): {fields, files: [{field, name, type, data}]};
                        a file past `file` bytes, or more than `files` (100), is "toobig"; the whole is held to MOTE_MAX_BODY
webhook.check(req, "stripe", secret("WH"))?   the body (json), once its signature is the service's: over the bytes sent, in
                        constant time, its moment within {tolerance: 300} s; else "refused" (a 400) · schemes: stripe standard (svix
                        resend clerk …) github shopify slack twilio paddle discord token … or {hmac, over, header, timestamp}
webhook.once(event.id)  + a block: done the first time that id is seen, the id kept in the block's own turn (a redelivery is
                        answered and skips it) · queue a `job fn` there for the slow part · req.url: the address as the caller wrote it
secret("PAY_KEY")       a setting the back end does not start without (it names every one missing) and its log never shows
                        (`[secret]`); not returned by a `server fn`, emitted, kept in a row or said in `fail` (H136, one fn deep)
                        env("KEY") is a plain setting: "" if unset, written as it is
auth.as(userId, {look: false, minutes: 10})?   in a `server fn` whose `requires` says who may (H137): the caller is taken for
  that person (`me`, rules, rows, pages) in this app, their own session kept · unsaid: only to look (every write refused: models,
  files, notify.send, passwords) for 30 minutes · auth.actor()? {id, email}? the real person · never while acting:
  changePassword, setPassword on them, signOutAll, signing in, acting again · auth.asEnd()? ends it (a page may) · page:
  auth.acting {as, by, look, until}? and a banner of the runtime's own, with End · logged: began, ended, expired, each refusal
a call with the session's cookie, and the open line, are taken from the app's own origin (MOTE_ORIGINS adds some): else 403 ·
  the page is in no other site's frame (MOTE_FRAME) · the line: 500 live values a page, 50 messages a second, 1 MB each (MOTE_LIVE_*)
MOTE_ACCOUNTS=/srv/accounts on several apps: one set of accounts and sessions, one id a person (`me`), each app its
own rows; MOTE_COOKIE_DOMAIN=.example.com if they are on sibling subdomains                             back-end.md
proc.run(["git", "status"], {cwd, env, input, timeout, max})?   {code, out, err, cut}; a list, never a shell's line
let run = proc.start(["bun", "test"])?   run.line() (none at the end) · run.stop() · run.done()? · run.pid
let c = tcp.open(host, 5432, {tls, servername, ca, pin, cert, key, verify, timeout, proxy, pool})?   c.read(n, ms?)? exactly n ·
  c.readUntil("\r\n")? · c.line()? · c.readSome()? · c.write(data)? · c.startTls({…})? · c.end() half · c.close() ·
  fails refused lookup reset timeout tls closed toobig · TLS checked (chain and name) unless verify: false · closed at the stop ·
  tcp.take(name, {size, idle, wait})? an idle one, or none (room held: tcp.open(…, {pool: name})) · c.give() · c.keep(k, v) c.kept(k)
server listen smtp(c) port=env("SMTP_PORT") cert= key= tls? timeout= max= maxIp= refuse= limit 20 per minute by ip + a block:
  each connection a socket (closed as the block ends) · c.remote c.local {address, port} · c.startTls() as the server ·
  c.line(ms, max) c.readUntil(end, ms, max) c.readSome(ms, max): toobig, the rest let go · c.stopping, reads fail "stopping"   back-end.md#accepting-connections-server-listen
let w = ws.open("wss://…", {headers, protocols, reconnect: true})?   w.send(data)? · w.next(ms)? {text, bytes, binary, reopened} ·
  w.ping()? ms · w.close(4000, "why") · w.state · w.protocol · both in `mote check --access` CONNECTIONS IT MAY OPEN       back-end.md#connections-of-its-own
let repo = fs.folder(env("REPO"))?       repo.path · repo.text(p) bytes write append del list entries exists info move mkdir
  a path cannot leave its folder (.., absolute, a link out) · fs.append/exists/info/entries/move/mkdir: the data folder
MOTE_SQL=file:/srv/shop/shared on several apps: one database for their models (declared once, in a package both `use`),
  their files and their accounts; a write in one is in the other's `live` lists; `readonly Price, Staff`: this app only
  reads them · hooks run where the write was made                                   back-end.md#several-apps-one-database
MOTE_SQL=postgres://…?sslmode=require on several back ends of one program: models, jobs, answered calls, leases in Postgres;
  writes one turn at a time of all of them; `live` by LISTEN/NOTIFY · behind a pooler (port 6543, ?pooler=transaction):
  MOTE_SQL_DIRECT for LISTEN, else polled · accounts, sessions, limit counts, notify's inbox and devices there too ·
  calls' rooms across back ends (MOTE_CALL_BEAT) · no fulltext yet  back-end.md#models-in-postgres
mote migrate app.mote --to postgres --data data [--dry-run] [--replace]   an app's SQLite data into MOTE_SQL's Postgres (back
  end stopped): schema as the back end makes it, rows in batches a second run goes on from, each table summed on both sides
  · logs, facts and the push key (vapid.json → mote_vapid) too · files/ to MOTE_FILES's store when set, after the rows        back-end.md#moving-an-app-from-sqlite-to-postgres
MOTE_FILES=s3://bucket/folder?endpoint=https://<acct>.r2.cloudflarestorage.com + MOTE_FILES_KEY_ID, MOTE_FILES_SECRET: a model's
  files in R2/S3, not on disk; streamed both ways, Range; rules as before · a file no row knows is kept and counted, never
  swept (MOTE_FILES_SWEEP_UNKNOWN=1 to) · a container's disk: back-end.md#containers-with-an-ephemeral-disk
mote check --disk: what the back end keeps on its own disk · MOTE_DISK=ephemeral|kept: said as it starts (unset: under Postgres) ·
  MOTE_VAPID (a secret): the push key; with Postgres it is one row, mote_vapid, for every back end
MOTE_BACKUP="backups?every=1h&keep=30": snapshots of every database, the stored files and vapid.json (WAL; several processes),
  a folder a time; `mote restore <snapshot> <data folder>` puts one back (back end stopped)        back-end.md#snapshots
server start            + a block: once, when the back end is up (nobody is signed in)
server every 60000      + a block: on a timer, one run at a time · `server every 60000 once`: in one back end of several
server at "03:00"       + a block: each day at that time (UTC; `zone="Europe/Paris"`), `"mon,thu 18:30"`: those days; once
                        however many back ends; a moment it was down for is made up at start if under an hour late (MOTE_AT_LATE)
detach work(id)         the call goes on after this one answers, as who called; a failure is logged; lost if the back end stops
job fn welcome(who: id) retries=5 timeout=300000 unique as me    + a block: work done later, at least once, across restarts.
                        welcome(id) queues it (cannot fail, gives the job's id) · welcome.in(60000, id) · welcome.at(when, id)
                        a job may run more than once: make it safe to · fails: again after 1 s, 4 s, 16 s … then kept as failed
                        queued inside `atomic`: only if the block is kept · only the back end queues one (a page: H142) ·
                        jobs.list({name, state})? jobs.cancel(id)? jobs.retry(id)? · MOTE_JOBS=4 at once (0: none here)
server on jobFailed(j)  + a block: a job given up on; j: {id, name, args, tries, words, kind}       back-end.md#later-job-fn
server stop             + a block: once, when it is asked to stop (SIGTERM): after the calls in flight, before the databases close
app "Shop" usage=on     · use "pkg:usage/usage.mote" · `fn usageMay(): bool` (it `wants` it) · UsagePanel on an admin route: who is active, what is used, what fails, kept in the
                        app's own database · track("checkout", {plan}): a measure of one's own (nothing with usage off) · usage="signed in" → docs/usage.md
                        web: visitors, visits (30 min gap, midnight), pageviews, bounces (1 screen, < 10 s, no goal), sources, utm_, country, browser, device,
                        speed (LCP CLS INP TTFB), now · UsageOverview UsagePages UsageSources UsageCountries UsageDevices UsageNow UsageGoals UsageVitals
                        `fn usageGoals(): string[] = ["checkout", "/thanks"]` · paths=full (unsaid: /job/:id) · geo=city|off (unsaid: country) · vitals=10|all|off
                        country: MOTE_GEO_HEADER=cf-ipcountry (with MOTE_PROXY) · MOTE_GEO_DB=ranges.csv (start_ip,end_ip,CC) · else the time zone · never the IP
                        no lasting id unless visitors=kept (a year) · DNT/GPC: nothing, page nor back end · bots dropped (USAGE_BOTS=keep; tests: USAGE_AUTOMATION=count)
                        a visitor who signs in or up is joined to the account (one person, one visit) · several apps, one panel: no usage=on on the keeper;
                        usageTake(batch, "planner") · every question `…, app?` and component app="planner" · fn usageGoalsFor(app: string): string[]
                        the page keeps the open line (/live) and sends on it (posts with none; sendBeacon as it goes) · kinds here, gone: who is here now,
                        exact (UsageHere, a row a tab; a line back within 30 s is the same tab) · autocapture=on: click, change (never a value), rage, dead
                        by data-mote name · inside `private`: named private · no positions kept
log Events               + fields, `keep 7 days` (or `keep 2 GB`), `capture` (POST /capture, MOTE_CAPTURE_KEYS; PostHog's /batch/ too): an append-only
                        durable log; every log and fact has id at name who session app props · Events.append(row)? appendAll(rows)? read(offset)?
                        since(t)? last()? rewind("store", 0)? stats()? · server on Events(batch) as store: a consumer, its own place, at least once
                        · in Postgres with the models (MOTE_SQL=postgres://…): one log for every back end, in order, no gaps
fact Event               + fields, order app, name, at · partition month · keep 400 days · rollup daily by name, day count, uniq(who): an analytics
                        table, SQLite, Postgres with the models, or ClickHouse (MOTE_ANALYTICS=clickhouse://…) · Event.dialect() · Event.addAll(rows)? trend funnel retention paths stickiness
                        lifecycle frequency people rows ({last: "30 days", every, by: "props.plan", measure: "p95", of, where, steps, within})
                        alias(visitor, person) forget(who) sql("…?", [v]) · use "pkg:usage/analytics.mote": AnalyticsPanel, flags, experiments → docs/analytics.md
use "pkg:admin/admin.mote" · `rule admin = …` · AdminPanel on a route: people (sessions, sign out everywhere, see what they see), every model's rows (search, open,
                        follow references; changed only as the model's rules let that admin), jobs, health, access, a log · AdminPeople AdminData AdminJobs … alone → docs/admin.md
server on usage(batch)  + a block: the events themselves, every 5 s: {name, kind, at, user?, anon?, session, route?, ms?, ok?, failKind?, props, path?, title?,
                        referrer?, utm?, client?: UsageClient {ua, brands, lang, zone, screen, viewport, dpr, webdriver, country?, region?, city?, geoFrom}}
server on failure(f)    + a block: every fault the back end had (call, route, live, start, every, detach);
                        f: {where, words, stack, at?, kind, call?, user?, id}; one that fails itself is logged, no more
                        a stack reads by .mote lines: `place (app.mote:12:3)`, the runtime's frames folded (server/main.js.map)
log.info("order placed", {order: o.id})  log.warn log.error log.debug · log(x) is log.info · on the back end one line of JSON
                        on stdout: time level msg fields + call, user, id (the call's: sent by the page in x-mote-call, given
                        back in the answer) or block; a line per call (status ok said fault refused invalid, ms) and per route
                        hit · MOTE_LOG=debug|info|warn|error|off · what secret("KEY") gave (6+ characters) is written [secret]
a fault tells the page only `name could not be done (id …)`: the rest is in the log under that id (mote dev shows it)
GET /healthz 200 while up · GET /readyz 200 once it takes calls, 503 once stopping · SIGTERM: readyz 503, no new connections,
                        calls in flight finish (MOTE_STOP_MS, 10 s), pages are told and come back within MOTE_BYE_MS (1 s), exit 0
a call is answered once: the back end remembers each caller's ids and answers for 10 min (MOTE_ONCE_MS; a page's model write
  also in the database, with the write) · so the page sends a call that got no answer again, twice (0.3 s, 1.2 s), then fails
  as offline ("could not reach the server"); a call has no time limit unless `app … timeout=` says one · another client: send `x-mote-call: <its own id>` and reuse it to retry
net.* from the back end with no `timeout` gives up after 30 s (MOTE_NET_TIMEOUT; `timeout: 0` none; net.stream: until it begins)
it serves the built app: hashed assets/ immutable for a year, the rest no-cache, an etag on the page (304), .gz to who takes
                        gzip, Range, nosniff · mote build also writes dist/Dockerfile and dist/.env.example (never served)
server fn thumb(picture: bytes, w: number): bytes    bytes cross as they are; a call is 16 MB at most (MOTE_MAX_BODY)
files.keep(data, name)? files.bytes(f)? files.path(f)?   what a model's `file` field keeps → docs/models.md#files
files.derive(f, "thumb", bytes)?   a picture kept beside a file: `f.url + "/thumb"`, for whoever may read the row · `f.url + "?download=Q3.pdf"`
server fn take(k: Kitchen): string requires peer        only another back end may call it; to anyone else it is a 404
extern server fn take(k: Kitchen): string at env("SHOP_URL")   declared where it is called: no body · timeout=60000 · as me
  called like any fn of the back end (never by a page); signed with MOTE_PEER_SECRET (same on both; `new,old` to change it);
  the answer is checked against the type; the other's `fail` words pass through · `at to` with a `to: string` parameter: the caller's address
  failing: err.kind is the other's own / said · offline · timeout · invalid · fault (err.id: the id both logs have the call under)
data styles: Style[] from "./styles.json"   a JSON file beside it, read as it is built: the value written out, for the page and the back end; typed if said   data.md
api Harbor from "./harbor.json" only ["listBoats", "getBoat"]   an OpenAPI 3 file kept beside it, read as it is built: a typed fn a
  listed operation (harborListBoats(options), harborGetBoat(boatId)) and only the shapes they reach, one harborCall (HARBOR_API,
  retries on a GET, Retry-After, kinds, the file's error words) · lines: base "…" · auth bearer secret("K") (basic, header "x", query "x")
  · header "x-version" "1" · mote api expand app.mote: the Mote it is made into → docs/services.md#a-service-with-an-openapi-file
mote check app.mote --against ../shop/app.mote   the models both keep (MOTE_SQL) and each extern, against that program (or, externs only, its dist/server/api.json)
dist/server/api.json: calls, externs, models, shapes, events, routes, rules, env, secrets · `mote build --api`: + openapi.json, client.ts
mote check app.mote --access [Name] [--json]   who may do what: each model operation, call, route and room with its rule and
  who that admits in words (`[not tested here: role]`), then "Worth a look": a page write past a `server fn`, a secret field
  read by many, membership alone on a write, a fn with no `requires`; facts, exit 0             back-end.md#who-may-do-what
server route POST "/hooks/:token"(req)   + a block: an address for another service; no session assumed
  req.params.token req.query("n") req.header("x-key") req.text()? req.json()? req.bytes()? req.method req.path
  return {status: 201, json: {ok: true}}   or text: / bytes: / headers: {…}; nothing returned is a 204
  GET HEAD POST PUT PATCH DELETE OPTIONS · a GET route answers HEAD: its status and headers, no body (req.method == "HEAD")
  · answers are cache-control: no-store unless the route says · cors="*" | "https://app.example" | [origins] |
  setting.list("APP_ORIGINS") | {origins, headers, expose, maxAge, credentials} last on the line: allow-origin on every
  answer, the OPTIONS preflight written; from another origin the cookie is nobody's unless credentials (H356)   back-end.md#head
  body=4096 (after requires/limit, before or after cors=; on a server fn too): the most bytes it may be sent, in place of
  MOTE_MAX_BODY, more or less; 413 before the route runs (content-length), or as it arrives (H480)
  · an address no route and no file is: the page, in a program with one; 404 in a back end with no page (no markup)
```
zip and img work in a server fn too: an export packed where the data is (returned as bytes, or served by a route), a thumbnail.
A plain fn is the back end's when only server fns call it (or nothing does yet); called by the page, it is the page's too.
use "pkg:mail/parse.mote": mailParse(reader)? {headers, from, to, subject, date, parts [{path, type, charset, name, id, start, end, text}], text, html, problems}
  · mailPiece/mailSave/mailBody(r, part) a body decoded a piece at a time · pkg:mail/mbox.mote mailMboxNext(r)? {start, from, bodyAt, end, data}
  · pkg:mail/server.mote: smtpServe(c) in a `server listen` block; the program's smtpRecipient(s, to) and smtpMessage(m) (m.path: the body, spooled) say accept/refuse/defer
    · smtpOpen(m)? reads it · fn smtpSpool() "file" | "sealed" (fn smtpSpoolKey(): json) | "memory" (up to SIZE, else 552)
  · pkg:mail/auth.mote (back end): mailDkimVerify(r)? mailDkimSign(r, {domain, selector, key})? mailSpf(ip, from, helo)? mailDmarc(r, spf, dkim)? mailArcVerify(r)?
  · pkg:mail/deliver.mote (back end): mailDeliver(from, to, path)? [{to, status: delivered|deferred|bounced, code, host, tls}] MX, STARTTLS, MTA-STS
    · mailQueue(from, to, path)? tried again by a job fn; fn mailDelivered(q, results) · mailDsnRead(r)? a bounce read
  · pkg:mail/address.mote mailAddrValid mailAddrSame mailDomainAscii (Punycode) mailOrgDomain (the Public Suffix List)   page, off fn, back end → docs/mail-library.md
Mail is net.send to a mail service's API from a `server fn` (a `job fn`, so that it is not lost), its key a secret() → docs/back-end.md#sending-mail
A route that changes things must not trust the cookie alone (a GET never changes anything) → docs/back-end.md#routes
Never put what a page sent into a command or a path unchecked → docs/back-end.md#what-this-lets-a-program-do

## Models → docs/models.md
```mote
// docs: whole
model Room
  name: string unique
  owner: id = me
  read anyone
  add if me != none
  change, remove if owner == me
local model Draft
  room: string unique
  text: string = ""
live rooms: Room[] = Room.find({}, {order: "name"}) else []
resource drafts: Draft[] = Draft.find({}) else []
action make(name: string)
  let r = Room.add({name})?
  Draft.add({room: r.id})?
for r in rooms key=r.id
  text `${r.name} ${drafts.find(d => d.room == r.id)?.text ?? ""}`
button "Make" press=make("den")
```
`model T` is kept on the back end, `local model T` in this browser's SQLite; each is a type and a table.
Fields: `id: id` (the key, made for you) · `= default`, `= now`, `= me` (who is signed in; never the page's
to give) · `T?` · `Other cascade` (a reference, kept as its key) · `unique` `hidden` `key` `was oldName`;
lines `unique a, b` · `index a, b` · `check test else "why"`.
```text
T.get(key) T.one(f) T.find(f, {order: "at desc", limit, last, after, with: ["from"]}) T.count(f) T.has(f)
T.add(row) T.addAll(rows) T.set(key, changes) T.setAll(f, changes) T.del(key or f)     each waits: `?` or `else`
a filter: {room: id, state: ["a", "b"], note: none, at: after(t), n: between(1, 9), name: startsWith("ab")}
  {room: id, any: [{thread: none}, {shown: true}]}: one of several filters, with the fields beside them
T.take(f, changes, {order: "due"}): the first row f finds, changed, or none; two callers never get the same row
T.put(row, {n: inc(1)}): the row there (its key, or a `unique` set it gives, `= me` counted) changed, else `row` added: an add or a
  change to the rules, hooks and pages; one turn · inc(n) in any change: `n = n + ?` (numbers; H164) · a page's put waits
T.count(f, {by: ["kind"]}) [{kind, count}] · T.sum(f, "total" or [fields], {by, order: "total desc", limit}) · T.min T.max:
  one statement, GROUP BY; 1000 groups unless `limit` (10000); the back end's alone (H165; `T.as(me)` under the rules)
migrate "name" + a block: the back end's statements, run once for a database as it starts, after the schema's steps, all or none
atomic + a block: its operations are one (on the back end nothing else waits in it: no net, proc, detach; queue a `job fn`)
  writes take turns (a block is one turn); on the back end a read never waits for one: it sees the last state
  kept, one moment per read, its own call's writes, and inside `atomic` the block's own
rules (model only): read / add / change / remove / write + `anyone` or `if test`; no rule = closed to the page
  a test: fields, me, values, == != && || !, `x in [..]`, `exists(Other, {field: value})`; `change if a then b`
  a reference one step on: `exists(Member, {workspace: channel.workspace, who: me})`, `channel.owner == me`
  `change text, edited if from == me`: only those fields, for the page; several such lines, each its own test
a page's find gives 1000 rows unless it says `limit` (10000 at most); a filter's list holds 1000 values at most
full-text: line `index text, title fulltext` (string fields, not hidden/private) · T.search(words, f, {order: "rank" | "at desc",
  limit, after, snippet: {field, around, mark}}) → rows + `rank` `snippet` · T.searchCount(words, f); reads, under the `read` rule
  words: `a b` both · `"a b"` phrase · `-a` not · `ab*` prefix; nothing else is syntax · r.snippet.split(mark): every second piece a hit
in a page, T.add / T.set / T.del of a `model` show at once: the row the page expects (key made here, = now, = me, defaults) goes in
  its `live` values, the call gives it back and the action goes on; the answer's row takes its place (same key, same node);
  refused: taken back, and the `else` beside it runs, else failure(action) has it, else `on failure` · what the action did after
  that line is not undone · offline: kept (pending), sent in order when the line is back; 200 writes, 5 min at most
  `confirmed T.add(row)?` this one waits · `confirmed`, a line of a model: all its writes wait · `app … writes=confirmed`: all
  wait by themselves: addAll setAll take, del by filter, a `file` given, a write in a `fn` passed on with `?`, a row the action
  goes on to use where a `server before` hook may change it, a row the page holds in no `live` value (set, del)
`live x = T.find(…) else []` is kept current, no `changed` (a write sends the row, not the list). In a `server fn`: no rules, unless `T.as(me).find(…)`
`live xs = T.find(f, {order: "at desc", window: 200})`: T?[] as long as the count, the rows of the windows a `for … virtual` over it draws, none elsewhere; kept by key as rows come and go
`resource` over a `local model`'s find follows the page's writes, in every tab
hooks: server before / after T.add(m) · T.change(was, now) · T.remove(was); a `before` may change the row or fail
  `caller.page` in a hook: the page asked for this write (or `T.as(me)` did), not the back end's own code
  a write: defaults → before hook → types, checks → the rule → references, unique → kept → after hook
  a model with no rule is the back end's alone (a queue of one's own: `model Task` + `Task.take(…)`; for work later, a `job fn`)
a file: `photo: file` in a model · `Photo.add({photo: files.upload(picked)?})?` · `image p.photo.url` · files.progress
  several at once: let up = files.sending() · files.upload(f, {into: up})? · up.sent (0..1) up.state · up.cancel()
  served through its row (the `read` rule decides, 404 otherwise); gone with the row; 100 MB (MOTE_MAX_FILE)
`who: Member = me private`: whose the row is, given only to that person's page (none to others; a filter on it finds only one's own).
`hidden` fields never reach the page: not by the model's operations, not in the rows a `server fn` returns
schema.lock (keep it): safe changes are applied when the back end starts / the page opens; a removed field
  needs `dropped field` or `mote migrate --drop T.field`; a rename is `was`
```

## The standard library → docs/README.md#namespaces
```text
net     net.get(url) net.post(url, body) net.put net.del net.text net.bytes     JSON in, json out      data.md
        net.send("POST", url, {headers, body, timeout})?  any status: {status, ok, url, location, headers, text, json, bytes}
          redirect: "follow" | "manual" | "error" · max: bytes · back end: public: true refuses addresses that are not
          public at every step (a person's URL, fetched safely) · allow: ["wiki.corp"] · net.lookup(host)? · net.public(address)
        let s = net.stream("POST", url, {…})?  s.status · s.chunk()? · s.event()? {event, data, id} · s.rest()? · s.stop()
db      db.get(k) db.set(k, v) db.del(k) db.keys() db.all()                     IndexedDB              data.md
        db.persist()? asks the browser to keep the site's data · db.persisted()? · db.room()? {used, left} · a full disk: err.kind == "full"
sql     sql.open("shop") sql.run(d, "select … where n > ?", [5]) sql.batch      SQLite                 data.md
fs      fs.text(p) fs.bytes(p) fs.write(p, data) fs.list(dir) fs.pick("image/*") fs.pickMany fs.save(data, name)  data.md
        fs.pick("image/*", {camera: "back"}) a phone's camera · fs.pickMany("image/*", {read: false})? picked[]: {name, size, type} unread, fs.bytes(f)? when wanted
        fs.append fs.exists fs.info fs.entries fs.move fs.mkdir · fs.open(path or picked)? a reader: r.read(n) readUntil(end) line()
        find(end) seek(at) readAt(at, n) r.at r.size close() · fs.writer(path, {append})? w.write(data)? w.close()? (an off fn: in place)
        · fs.writer(path, {seal: key})? / fs.open(file, {seal: key})? sealed: AES-256-GCM in 64 KiB chunks, key 32 bytes or crypto.aes.key
clip    clipboard.text() clipboard.image() clipboard.put(text or picture) · `paste=` hears a paste     data.md
store   store.get(k) store.set(k, v) store.remove(k)                            localStorage           data.md
crypto  crypto.hash(data, "sha512"?) crypto.random(n) crypto.argon2id(password, salt)                   data.md
        crypto.argon2id(pw, salt, {memory, time, parallelism, length, bytes: true})? bytes · crypto.randomBytes(n) bytes
        a page's own keys (raw bytes; page, `off fn` and `server fn` alike):                                 data.md#keys-of-the-pages-own
        crypto.aes.seal(key32, nonce12, data, {aad})? ciphertext then tag (AES-256-GCM; a nonce never twice) · crypto.aes.open(…)?
        crypto.aes.key(raw)? a key nothing reads back (db.set keeps it) · crypto.x25519.keyPair(seed?)? {private, public} ·
        crypto.x25519.shared(private, public)? · crypto.ed25519.keyPair(seed?)? · .sign(private, data)? · .verify(public, data, sig)?
        crypto.mlkem768.keyPair(seed?)? {decaps, encaps, seed} · .encaps(encapsKey)? {ciphertext, shared} · .decaps(decapsKey, ct)?
        crypto.pow(prefix, {bits: 18})? 16 bytes that give prefix + them a SHA-256 of 18 zero bits · crypto.hash(d, "sha3-256")
        ("sha3-512" "shake128" "shake256" {length} "blake2b" {length, key}) · an old browser: kind "unsupported" (x25519, ed25519)
        crypto.hash(data, "md5") (a protocol's, never security) · crypto.pbkdf2(pw, salt, {iterations, length})? bytes ·
        crypto.hkdf(key, {salt, info, length})? · crypto.hkdf(key, {info, as: "aes"})? an AES key never bytes · as: "hkdf" ·
        crypto.hkdf.key(raw)? material nothing reads back · key bytes into persist/store/db/log/toast/fail/text/server fn: H460 ·
        crypto.reveal(x) x, meant to be seen (a recovery key shown once) ·
        back end: crypto.seal(secret("KEY"), data, {aad})? (AES-256-GCM) · crypto.open(…)? · crypto.encrypt(publicKey, data, {alg: "RSA-OAEP-256"})? · crypto.decrypt(privateKey, data, {alg})?
        crypto.hmac(key, data, "sha256"?)?.hex() · crypto.equal(a, b) (a secret is never compared with ==) · crypto.crc32(data)
        back end: crypto.sign(privateKey, data, {alg})? bytes · crypto.verify(publicKey, data, signature, {alg})? bool ·
        alg "RS256" "ES256" "EdDSA", a key PEM or JWK · crypto.jwt.verify(token, jwks, {aud, iss, leeway})? its payload,
        checked (signature, exp, nbf, aud, iss; never alg none or HS*) · crypto.jwt.read(token)? {header, payload, …}: unchecked
        crypto.cert(pem or der)? read whole: {subject, issuer, tbs, signature, sigAlg, ca, pathLen, keyUsage, altNames, aaguid, …} ·
        crypto.cert.chain(leaf, intermediates, roots, {at})? {root, rootSubject, path}: signatures, dates, CAs (no revocation)
zip     zip.gzip(data) zip.gunzip(b) zip.pack([{name, data}]) zip.unpack(b)                             data.md
        zip.entries(f)? (zip64 too) · zip.open(f, name)? a reader, inflated as read · zip.gunzipStream(r)? · tar.entries(r)? t.next()?
csv     csv.read(data)? string[][] · csv.records(data, Row, {delimiter, header, decimal, dates})? Row[] ·
        csv.open(file, Row)? r.next()? (rows, none at the end) · csv.write(rows, {delimiter, bom})  text   tables.md
xlsx    xlsx.sheets(b)? xlsx.rows(b, {sheet})? xlsx.records(b, Row)? xlsx.read(b)? (kinds, formulas, merges) ·
        xlsx.write([{name, rows, columns: [{key, title, format: "currency"}], filter: true}])? bytes   tables.md
bytes   bytes("text") bytes.new(n) bytes.of([72, 105]) bytes.join([a, b]) bytes.hex(s) bytes.base64(s)
        b[i] b[i] = v b.slice() b.set(other, at) b.read(at, "u32") b.write(at, "u32", v) b.text() b.hex() b.url()  language.md
        b.text("windows-1251")? any WHATWG label ("unsupported": none such; the CJK sets by a battery, alike everywhere)
        bytes.find(b, "\r\n", from?) (-1: nowhere) · let w = bytes.buffer(): w.add(data) w.byte(n) w.put("i32be", n) w.length w.bytes()
img     img.decode(b) img.decode(b, {fit: 2560}) img.info(b) img.png(p) img.jpeg(p, 85) img.tiff img.resize img.fit img.crop img.blur …  media.md
paint   paint.new(w, h) paint.line paint.shape paint.text paint.image, shown by `canvas layers=stack`  media.md
scan    scan.read(picture) codes as {format, text}[] · `camera on=live scan=found` · cam.shot()        media.md
vid     vid.open(b) vid.frame vid.export(clips) · aud.open(b) · `reel clips=clips at=time playing=on`  media.md
draw    `surface draw=chart` with fn chart(g: pen, size: {width: number, height: number, time: number})
        draw.clear draw.rect draw.circle draw.line draw.path draw.text draw.image draw.measure("words", {size})
        draw.picture(w, h, chart) an `image` · `surface gl`, gl.draw · gl.filter(picture, fs)        drawing.md
3D      `canvas boxes=list view="iso"` boxes in space · `canvas scene=world camera=eye` with three.*   drawing.md, scene.md
        three.box sphere cylinder plane · three.extrude([[x, y], …], height, {holes}) an outline pushed up  scene.md
        a picture on a material: three.material({color, map: address | bytes | picture, mapSize: [w, h] of the scene per copy
        (unsaid: one copy a face), mapOffset: [u, v], mapTurn: 90, tint: true}) · three.mesh(geometry, material, {grain: "x" | "y" | "z"
        (the picture's up; z), sides: material (a box's four thin faces, an extrusion's sides), faces: "x"}) · the same words on a box
        of boxes= · input hears {phase: "materials", loaded, of, failed, ready} and, past 128 pictures, {phase: "limit"}  scene.md#pictures-on-materials-map
url     url.encode(text) url.decode(text)? · url.parse(text)? {scheme, host, port, path, query, hash} · url.build({host, path,
        query: {q: "oak door"}}) · url.query("a=1&b=x+y") a record · url.form({…}); page and back end   language.md#addresses
re      re.test(text, r"\d+") re.find(…)?.named?.year re.all re.at re.replace(text, p, "$1" or m => …) re.split re.check re.escape   text.md
        flags last: "i" "m" "s" "u" "y"; \p{L} \p{sc=Greek} \u{1F600} imply "u"; linear time: no \1, (?=, (?<=
search  search.index([{id, text}] or [{id, fields: {subject, body}}]) a segment · search.find(segs or s, "oak door \"a phrase\" pre* subject:x",
        {limit, prefix, all, weights: {subject: 3}, removed}) [{id, score, matches: [{field, words}]}] · search.merge([a, b], {removed})
        search.open([a, b]) a searcher (loaded once) · search.add(s, seg) remove(s, ids) close(s) count · search.marks(text, q) [{from, to}]  text.md#search
html    html.clean(text, {images: "block"|"proxy"|"allow", proxy: "/img?u={url}", cid, styles})? {html, images, links, removed, trackers} · html.text(text)?   text.md
        htmlframe html=letter images="block" link=open cleaned=seen: cleaned, in a frame where nothing runs (policy=strict too)
syntax  syntax.parse(text, "js") syntax.tokens syntax.lines; "markdown" is a document, ready to draw   text.md
        a language of your own: let g = syntax.grammar(rules)? · syntax.parse(text, g)? is its whole tree · or `grammar Calc from "./calc.grammar"`, checked at the build
font    font.open(bytes) font.layout(f, "words", {size}) font.outline font.use(f, "Name")              text.md
pdf     pdf.make([pdf.heading("Invoice"), pdf.text("…"), pdf.table(rows), pdf.image(b)], {title, footer})  pdf.md
        pdf.read(b) (each page's text) pdf.words pdf.info pdf.fields pdf.fill(b, {Name: "Ada"}) pdf.merge([a, b]) pdf.stamp
screen  screen.phone screen.dark screen.width · scheme("dark" | "light" | "auto") · screen.print()   markup.md
notify  notify.ask() notify.show("Title", "A line", {actions: [{id, title}], data, url, tag}?) · notify.allowed() "granted" "denied" "default" · push.subscribe(key)   data.md
speech  speech.listen() speech.say(text) · mic.list()                                                 media.md
mic     state rec: recording? = none · rec = mic.record({levels: true})? · rec.level rec.time rec.state (reactive)
        rec.pause() rec.resume() rec.cancel() · rec.stop()? {bytes, type, length, peaks} · mic.meter()? {level, stop()}
player  `audio src=url playing=on at=time rate=1 volume=1 duration=length ended=done` (video too; preload="none")
        playing and at are written back to state (every frame while it plays); a new `at` seeks; duration is only written
sound   sound.play("ping" | bytes | url, {volume, loop, id}) {played, why: "" | "gesture" | "unsupported"} · sound.stop(id?)
        tones: ping pop ring error join leave · sound.ready (false until the page was pressed) · sound.error     media.md
rtc     state call: call? = none · call = rtc.join(room, {audio: true, video: true, name, levels: true})?   calls.md
        call.peers call.me: {id, user, name, audio, video, screen, level, speaking, state, verified, error, fingerprints} · `video of=p` (`screen`)
        rtc.join(room, {verify: key})?: each connection proved with a key the back end lacks · {relay: true}: only through TURN
        call.ring(accounts, {url}) call.rings: {user, state: ringing answered declined missed offline, at} · rtc.rings() rtc.decline(id)
        with notify: rung on their devices too, Answer and Decline · on rtc.answer(r: {id, room, from, name}) joins
        call.mute(on)? call.camera(on)? call.share(on)? call.use({mic})? call.send(data) call.leave() · rtc.devices()?
        `server call(room: string): bool` says who may join (none declared: nobody) · `on rtc.message(m: {from, data})`
        models in Postgres: members on different back ends share rooms and rings          calls.md#more-than-one-process
```
Most of these leave the page, so they wait and can fail: `else` or `?`. Not store, paint, draw, three, re,
screen, `bytes("text")` and crypto.random.

## The kit → docs/kit.md
Components that come with Mote; a page carries only those it uses, and they follow the colour roles.
```text
Button "Save" press=save variant="outline" size="sm" · Badge · Card title="…" · Label · Separator
Input value=name · Textarea value=bio · Checkbox "I agree" checked=ok · Switch on=wifi · Slider value=n
Switch value=row.on change=set (also Checkbox, Toggle): driven, shows `value`, tells `change`, writes nothing back
Select value=fruit options=["Apple", "Pear"] · Radio · Tabs value=tab options=[…] · Combobox · Pagination
Carousel api=car with CarouselContent, CarouselItem: car.index read and set, follows the finger, kept through resizes and slides that come and go
Drawer open=open snapPoints=["64px", 0.86] modal=false: a sheet that stays on the page at its peek (modal unsaid: over it)
Dialog open=asking title="…" · Sheet open=menu · Alert · Progress value=40 · Avatar · Skeleton · Spinner
Menu with MenuItem "Rename" press=rename, and Popover: written under the element that opens them
LineChart data=rows x="day" y="visitors" scale="time" zoom · BarChart … config=[{key, label}] stacked · PieChart value= name= donut
Chart data=rows x="day" + children Line y="a" · Bar y="b" axis="right" · Rule y=100 label="target" · Band lower= upper=
  ScatterChart HeatMap BoxPlot CandlestickChart SankeyChart TreemapChart GanttChart Sparkline …  a million points; range= picked= group=  charts.md
Highlight text=code lang="ts" · CodeBlock code=… · Markdown text=answer streaming=busy
editor value=source lang="ts" · terminal output=out input=typed · flow edges=edges     (docs/widgets.md)
richtext value=doc edit=ops picture=file · richtext.html(doc) richtext.text(doc) .from .quote .apply   kit/richtext.md
        several at once: richtext log=entries send=post (sealed units a server numbers; H500) · richtext.copy(doc)
        .edit(copy, ops) .take(copy, entries) .snapshot(copy) .transform(mine, theirs); page, worker, back end
```

## For agents and tests → docs/agents.md, docs/testing.md
```text
test "a muted person cannot post"       + a block, in any file: the back end's own tests, run by `mote test app.mote [words] [--json]`
  as "ada@example.com" · as none        who the lines that follow are run as (an account is made); each test: a fresh back end and database
  let c = Channel.add({name: "x"})?     a model's operation and a `server fn` go through the rules and `requires`, as a page's would
  trusted + a block                     its lines are the back end's own code, past the rules: to arrange, and to look
  expect Message.count({}) == 1         expect <yes or no> · expect (a + b) == c · expect post(…) fails · fails "words" · fails kind "signin"
  clock "2026-03-01T09:00" · clock +1 day    the back end's one clock; moved on, `server every` and `server at` blocks run in order
  run jobs · queued(welcome)            jobs that are due are run · those waiting
  given net "https://mail.example/*" answers {status: 200, json: {…}} · sent(net) sent(notify) sent(emit) sent(proc)
  given env "KEEP_DAYS" is "30" · given secret "PAY_KEY" is "sk-test"    that test's back end starts with it (H167)
test "a note is added" page             a test of the page too: its back end listens, and `page` is a browser at it (Chrome on the machine)
  page.type("New note", "Milk") · page.press("Add") · tap hover key check pick hold swipe drag pinch scroll    real input; back when the page is at rest
  page.see("Milk") · expect page.has("Milk") · page.read() · page.changed() · page.path() · page.title() · page.errors()
  page.open("/about") · go reload back · size(390, 844, {touch: true}) · scheme("dark") · shot("p.png") · page.eval(js)
  as "ada@…" signs the browser in too · clock +5 seconds moves the page's timers with the back end's · `page` elsewhere: H336
                                        nothing leaves the process: a request nothing was said of fails the test
```
Every control carries `data-mote`: the action its press runs (`[data-mote="add"]`) or the state a field writes
(`[data-mote="draft"]`). A built app has agent.json and llms.txt; `agents.mote` adds your notes.
In the page, `mote`: `await mote.read()` the page as lines of text (`#4 button Add`), `mote.press(4 | "add" | {name, text})`,
`type` `check` `pick` `key` `hold` `swipe` `drag` `scroll` `go` `see`: each comes back with the page at rest and `{settled, changed}`;
`mote.clock.hold()` / `.advance(ms)` the page's timers in hand. `mote drive --out f.mjs`: the same with real input, for tests (no sleeps).   agents.md

## Refused, with the fix in the message
```text
className onClick htmlFor style=…    class · press · for · the property itself
null undefined                       none
xs.sort() in a binding or derive     toSorted(), or sort in an action
text Hello                           text "Hello"
text a ?? b                          text (a ?? b): a space ends a value
xs.contains(x) s.len() xs.append(x)  includes · .length · push
any boolean String                   json · bool · string
```
