Motus

For agents

A skill that writes Motus well.

This repository ships a Claude Code skill at .claude/skills/motus/SKILL.md: a short, precise brief on the language, the Jai side of an entry, and the mistakes worth avoiding. With it, an agent writes templates that compile the first time, and checks them before it says it is done.

What it covers

Its description, which Claude Code reads to decide when to load it:

Write, check and wire Motus templates (.mot) in Jaiweb — components, styles, regions, routes, forms, queries — and mount them as entries from Jai controllers. Use when creating or editing any .mot file, a page or entry, a component's styles, or the Jai code (controllers, @Call/@Action/@Enter) that a template calls.

361 lines. It points to the sources of truth (the modules' headers, the tests, Argoshot) rather than repeating them, and sets the workflow: write, motus check, motus fmt, build.

  • Workflow
  • The language
  • · Components
  • · Behavior: no application JavaScript
  • · Styles (three levels)
  • · Regions, loading, motion
  • · Entries: routes, calls, actions
  • The Jai side
  • · Effects at once, in a controller (lanes)
  • Gotchas

Use it in another repository

A skill is a folder. Claude Code finds the ones under .claude/skills/ of the repository it works in, and loads one when a task matches its description: here, any .mot file, an entry, a component's styles, or the Jai a template calls.

  1. Copy the folder into the other repository's skills.

    shell
    # from the other repository's root; JAIWEB is where this repository is
    mkdir -p .claude/skills
    cp -R "$JAIWEB/.claude/skills/motus" .claude/skills/
    # Claude Code loads it when a task matches its description (a .mot file, an entry...)
  2. Keep its paths true. It sends the agent to sdk/Motus/module.jai, sdk/Motus_Flows/entries.jai, the Motus tests, examples/argoshot and tools/motus/motus. In a repository that vendors Jaiweb at its root they resolve as they are; elsewhere, edit those lines to where Jaiweb is.

  3. Ask for the work. “Add a usage page to the dashboard entry, with the last 30 days as a chart”: the agent reads the skill, writes the .mot and its controller, runs motus check and motus fmt, then builds.

The skill, as it is · 361 lines
---
name: motus
description: Write, check and wire Motus templates (.mot) in Jaiweb — components, styles, regions, routes, forms, queries — and mount them as entries from Jai controllers. Use when creating or editing any .mot file, a page or entry, a component's styles, or the Jai code (controllers, @Call/@Action/@Enter) that a template calls.
---

# Motus

Motus is Jaiweb's template language: HTML plus a few elements and expressions, compiled against Jai types
(a typo or a wrong type is a build error), rendered by a small VM natively, in WebAssembly, or at the edge.
Templates are `.mot` files; the build turns `views/foo.mot` into the constant `TEMPLATE_views_foo`.

Source of truth when in doubt — read these, they are short and precise:
- `sdk/Motus/module.jai` (header): the language, styles, edge pages.
- `sdk/Motus_Flows/entries.jai` (header): entries, calls, actions, routes, `@Enter`, live regions.
- `sdk/Motus/tests/test.jai`: one passing example of nearly every feature.
- `examples/argoshot/` (`app.jai`, `views/*.mot`): a complete product on entries. A product: native, it
  links its modules (`build.jai`: `build_app(..., link = .["Screenshots", "Products", ..., "Marketing"])`),
  their rows its own; its code `#import`s them (`#import "Screenshots";`) and calls their public procedures
  directly (`Screenshots.account()`, `(answer, failed)` as anywhere: how_to/101_modules), and a module's
  own page, if it has one, comes as a template constant (`<NAME>_TEMPLATE`).
  `examples/argoshot/test.sh` runs it end to end.

## Workflow

1. Write or edit the `.mot` (and the Jai controller it calls).
2. `tools/motus/motus check <files or dirs>` — the compiler's errors with file:line:column, no build needed.
3. `tools/motus/motus fmt -w <files>` — the repo's formatting (CI runs `fmt --check`).
4. Build the app (`jai build.jai`) and run its tests. Template type errors are build errors.

(`tools/motus/motus lsp` is the language server the VS Code extension in `editors/vscode` uses.)

## The language

```xml
<output product.name>                          <!-- escaped text -->
<output body_html>                             <!-- a member noted @Html in Jai: inserted as HTML -->
<let total (price * qty)> ... </let>           <!-- a binding for its children only -->
<let o {a: 1, b: "two"}><output o.b></let>     <!-- object and array literals: {..}, [..] -->
<if (stock > 0)>In stock<elsif backorder>Soon<else>Sold out</if>
<for p, i in products> <output i>: <output p.name> </for>
<for n in 1..3><output n></for>
<match status><case "ACTIVE">on</case><case "DRAFT">draft</case><default>off</default></match>
<a href=(base + "/keys") class=(if active then "on" else null)>  <!-- computed attributes; null/false: left out -->
```

- Jai's operators: `== != < <= > >= && || ! + - * / %`. In a tag, outside parentheses, a `>` ends the
  tag: put a comparison with `>` or `>=` in parentheses, `<if (a > b)>` (the compiler refuses the slip
  `<if a > b>`). `+` adds numbers or joins text. Inline condition: `(if a then b else c)`.
- Functions are called: `<output money(price, "brl")>`, `default(a, b)`, `number(n, 2)`: `uppercase
  lowercase trim length default join truncate first last money date plural paragraphs where number
  percent url css`. No pipes, no filters. Their formats are `Presentation`'s procedures (product code
  calls the same: `money` is always `$1,234.56` / `R$ 1.234,56`).
- The app's procedures are functions too: any top-level procedure of a `.jai` the template `<load>`s or a
  module it `<import>`s, by its bare name: `<import Presentation>` then `<output when(k.created_at)>`.
  Arguments in order (trailing defaults allowed); whole numbers, floats, bools and text in, one of them
  out; Motus's own names win; overloaded or polymorphic ones are not callable. They run at once as the
  page renders, at origin: no effects in them, and an edge part cannot call one. Prefer this to
  pre-formatting values in a controller only for the template.
- `can("orders.read")`: whether the viewer has a permission (decided at the edge for edge pages).

### Components

```xml
<defcomp Card | product: Product, highlight: bool = false, footer: html = "" |>
  <article class=(if highlight then "card hot" else "card")>
    <h3><output product.name></h3>
    <children />                    <!-- what the caller put inside <Card>...</Card> -->
    <output footer>
  </article>
</defcomp>

<Card product=p highlight=p.sold_out><p>body</p><@footer><small>fine print</small></@footer></Card>
```

Prop types: `string int number bool html`, a Jai type by name (`Product`, `Logs.One`), lists `[] T`.
`<@name>…</@name>` fills an `html` prop. A `<defcomp>` is visible in its enclosing scope (local ones
too); a layout library (`views/layout.mot`) holds shared components.

**A component needs more than one call site** (owner's rule). A section used in one place stays
inline in its route, however long: no single-use components or `#expand` macros for "structure".

**Components from modules.** `<import Stripe_Card>` makes the module's `.mot` files' components available
(framework, sdk ... layers, or the app's `modules/`), as `<load>` would; the editor tools find them so
too. Such a file holds components and root styles only. Framework components carry no scoped styles:
they document their classes and take `class=`, so the app's CSS decides their look.

### Behavior: no application JavaScript

An app writes no `.js` of its own (owner's goal: Argoshot ships none). Motus's attributes, which the
browser runtime (`/_jaiweb/client.js`) carries out:

```xml
<form method="get" region="pg" submit-on="change">    <!-- sent as it is filled: a choice made -->
  <input type="search" name="q" submit-on="input">     <!-- ... as it is typed (250 ms after the last key) -->
</form>
<form call=Keys.revoke(id = k.id) confirm="Revoke this key?">   <!-- asked first (a form's or a button's) -->
<button type="button" copy=k.access_key>Copy</button>          <!-- to the clipboard; .jw-copied a moment -->
```

- A GET form sent this way replaces the address without a history step; a newer GET navigation cancels
  an older one still on its way. After a navigation, a field takes the server's value only where the
  server's HTML changed it (a preset, a mode's choices) and the person has not touched it meanwhile;
  the focused field is never overwritten. A new `[autofocus]` element gets the focus.
- State lives in the URL and the server renders the whole form from it: what shows, which choices,
  summaries. No hidden fields packed by script, no client copies of server rules.
- **State variables** (docs/motus-reactivity.md): a route's query parameter that a control binds is one. `<input bind=q>`
  (`bind=params.q` under `|params: T|`) shows it and writes the URL's `q` as it changes, with no form: what reads only it is
  redrawn in the browser by compiled code, no request; what origin draws from it is asked for alone; `motus graph <file>`
  shows each field's plan. Checkbox `bind=` a bool; radio `bind=s value="x"`; `<select bind=s>` (its options' `value=`, or
  their text as written). `value=` is only ever shown. A GET form is plain HTML: its fields are state only when bound.
- **Page state**: `<state open = false>...</state>` (`<state tab: string = "a">`), scoped as a `<let>`, the browser's alone (a
  tab, a disclosure, a selection): kept by its key across every morph; in a `<for>` one for each row, keyed by the row's `id`
  (else `key=`). Only browser parts read it (origin reading it is a build error).
- **Events** on any element: `on:click=(open = !open, page = page + 1)` writes state when it happens, computed in the browser;
  `on:click=Cart.add(sku = p.sku)` posts an action (signed where the page is drawn). On the element that triggers (a bound
  control, an event's): `debounce=300` (ms; 150 while typing, else 0), `throttle=200`, `edge="leading"`, `requests="latest"`
  (cancel the one before: parts' default) | `"first"` (ignore while one goes: actions' default) | `"queue"` | `"all"`.
- **Typed forms**: `<form buyer: Buyer call=Box.pay(buyer, event = e.code)>` (the action's argument `buyer: Buyer`; posted as
  `buyer.name`), `<form Buyer call=X.y>` (the action takes `Buyer` itself; its state `it`), `= n.draft` a starting value
  (origin's), `note := n.draft` (its type the action's). `<field buyer.name label="Name" autocomplete="name" />` draws a label
  and its control from the member's type (text, number, yes/no, an enum's select, `@Multiline` textarea, `@Hidden`; other
  attributes go to the control); `<fields />` the members not placed, `<fields after=buyer.name />` / `before=`. Each member is
  a page state (`<output buyer.name>` drawn as typed); the action's notes are the checks, browser and origin; `@Private` never
  drawn nor sent; forgotten once the action took it. Labels are the template's (Jai's notes hold no text with spaces).
- **Edge pages**: a request parameter a control binds (the mount's `params` struct) is a state variable too; it is drawn in the
  browser inside the edge part, the rest of what it reaches is the page again (the edge's).
- Dialogs: HTML's own `popover` / `<dialog>` with `popovertarget`, not script.

**A component's script** (only for what HTML and the attributes above cannot do: a third party's
widget, Stripe's card): a `<script>` with no attributes right inside a `<defcomp>` is the component's
behavior. It is not drawn where the component is; the build bundles every such script (an entry's
library's into one cached `/_mot/js/<hash>.js`, as its stylesheet), and the runtime runs it once for
each outermost element of the component as it appears (first load, navigation, fill, live update),
with `element` bound to it. The component's outermost elements carry `data-jw-c="<Name>"`; give it one
outermost element and pass what the script needs as attributes of it (`data-key=key`).

```xml
<defcomp Stripe_Card | key: string, secret: string, class: string = "" |>   <!-- sdk/Stripe_Card/card.mot -->
  <div class=(...) data-key=key data-secret=secret> ... </div>
  <script> const form = element.closest("form"); ... </script>
</defcomp>
```

A `<script src=...>` stays where it is written; a store's template has no scripts at all.

### Styles (three levels)

```xml
<style>                                    <!-- ROOT: a file's top-level <style>: every element's -->
  :root { --ink: #16212a }
  body { font: 16px/1.5 system-ui; color: var(--ink) }
</style>

<defcomp Meter | pct: int, tone: string |>
  <style>                                  <!-- SCOPED: the component's direct child: its own elements only -->
    .bar {
      width: calc(var(pct) * 1%);          /* var(prop): a Motus value, becomes a CSS variable */
      background: var(tone, gray);
      transition: width .3s;               /* changes from live updates animate */
      &:hover { opacity: .8 }              /* nesting; & is the outer selector */
      .full & { background: red }
      @media (max-width: 600px) { display: none }
    }
    .dot { translate: calc(var(pointer.x) * 1px) 0 }   /* the browser's: pointer.x/y, scroll.x/y,
                                                          scroll.progress (0-1), viewport.width/height */
  </style>
  <div class="bar" style="height: 6px"></div>         <!-- INLINE: one node -->
</defcomp>
```

- A `var(name)` without `--` reads the component's props; `--name` stays plain CSS. Values are sanitized
  (`css()`). Root styles read only the browser's values.
- An entry links its CSS: one stylesheet for the whole library (cached for every page of the app) plus one
  for the template's own components. `motus_render` pages get an inline `<style>`.
- Styles go at `<styles />` or the end of `<head>`; a fragment with no `<head>` gets none.
- Scoping adds an attribute to each selector's last part, so a scoped rule beats a root rule of the same
  selector. Keep shared classes root; scope only what is the component's alone (and move its `@media`
  rules with it).

### Regions, loading, motion

```xml
<region id="preview" transition="fade">     <!-- a part kept/replaced alone on navigation and actions -->
  <loading><Spinner label="Rendering…" /></loading>   <!-- shown at once while a request that changes it goes -->
  ...
</region>
<region live id="recent">...</region>        <!-- re-rendered and pushed when the rows it read change -->
<form method="get" action=(base + "/play") region="preview">...</form>
```

Transitions: `fade slide rise scale` (view transitions; reduced motion respected). A first render whose
regions wait on calls streams the frame first, then each region (`<template jw-fill>`) the moment its own
calls answer: the calls a render asks for run at once (each a lane of a `for parallel`, in the page's own
flow), so the slowest holds back only its own region. Keep the frame free of calls (a call outside every region turns
streaming off for the page). `motus_mount(..., whole = true)`: never streamed.

### Entries: routes, calls, actions

```xml
<!-- views/app.mot, mounted at /app -->
<let g Account.current(path = path)>
  <if g.redirect><redirect to=g.redirect /></if>
  <App title=route.title>
    <routes transition="fade">
      <route "/" title="Overview">...</route>
      <route "/logs/:id" params=Logs.One title=("Log #" + id) can="logs.read" else="/app">
        <let log Logs.one(id = id)><output log.text></let>
      </route>
      <route "/keys" title="API keys"><@actions><a href=(base + "/keys/new")>New</a></@actions>
        <form call=Keys.save(id = k.id)>
          <input name="name"><button>Save</button>
        </form>
      </route>
      <route "*"><Not_Found /></route>
    </routes>
  </App>
</let>
```

- The template reads `Motus_Request`: `base` (where the entry is: prefix links with it), `root`, `path`,
  `query`, `signed_in`, `notice`, `error` (an action's answer).
- `route.title` (any attribute of the matching route, or its `<@name>` HTML) is readable anywhere, so the
  frame is written once. `<routes whole>`: full pages, no in-place navigation. `<redirect to=…/>`,
  `<status code=404 />`.
- `<form call=X.y(fixed args)>` posts to its own page with the action and the fixed arguments signed in the
  URL; the rest of the input comes from the fields, checked by the action's notes (`@Required`,
  `@MaxLength(n)`), which also become the inputs' HTML attributes. `optimistic="remove"` /
  `optimistic="add" into="list"` show the change before the answer. `<form call=Room.read(upto = last) seen>` is sent
  once by itself when it comes into view while the tab is seen (a read marker), its redirect not followed; never
  `hidden` (it takes no room anyway). Who has the app's pages open: `presence()` (Flows) in a live view's render, which
  renders again when that changes.
- Queries (Jaiweb models, one index range): `<let items query Part where category == c order by number after
  :cursor limit 24>`. In an edge page a query is origin's, its rows baked into the frame, unless it says
  `edge` (`<let items edge query Part ...>`): then its rows are fetched at the edge, cached apart. A query
  reading the request must say `edge`. `<let items edge lazy query Part ...>` reads nothing where it is
  bound: only where the render first uses its rows (a branch not taken never fetches them), a part of its
  own at the edge, its region drawn by the rows' shape until they come. Refine it before it is read, one
  query of both: `<let newest lazy query items order by number desc limit 1 single>`.
- A query inside a `<for>` over another query's rows, reading the row, is an include: `<for o in orders><let
  lines query Order_Line where order_number == o.number limit 2>`. It is read with its collection, once per
  row, in the same part (one trip, no cascade). The collection needs a limit (at most 100); one level deep.
- A query reads all its model's public columns. `<let items fields query Part ...>` reads only the columns
  the template uses (followed into components' props and includes); `fields(name, price)` reads those named
  and refuses a template reading others. The columns are part of the cache key: opt in where it pays.
- A model's member noted `@Private` (a password's hash) is never read by a template nor fetched by its
  queries. A record is never written whole into a page: output, attributes, a form's arguments and an edge
  wrapper's props take values (`m.id`, not `m`).
- Except for debugging: `<debug><output m></debug>` writes a record or a list whole (its members, never the
  `@Private` ones), drawn only for the product's staff (`JAIWEB_PAGE_DEBUG`: `team`, the default, a user of
  the realm's own organization; `anyone` on a developer's machine; `off`). Never at the edge nor cached: in
  an edge page a staff's request goes to origin, the page whole, `no-store`.

## The Jai side

```jai
routes :: () {
    motus_mount("/app", TEMPLATE_views_app, .[Account, Keys, Logs], TEMPLATE_views_layout);
    motus_mount("/orgs/:org", TEMPLATE_views_orgs, .[Orgs, Billing], TEMPLATE_views_layout);
    motus_mount("/", TEMPLATE_views_site, .[Site]);   // last: every other path
} @Handler

render_view :: () { motus_render_view(routes); } @Job   // live regions
setup :: () { register_job(render_view); }

Keys :: struct {
    list :: () -> (keys: [] Api_Key = .[]) { ... } @Call            // a read, called from the template
    save :: (p: struct { id: int; name: string; @Required @MaxLength(60) }) -> (done: Motus_Done = .{}) {
        ...
        return .{notice = "Saved."};          // or .{error = "..."}, or .{redirect = "/app/keys"} (as written)
    } @Action @Permission(keys.manage)
}

Orgs :: struct {
    At :: struct { org: int; }               // the mount's :org
    enter :: (p: At) -> (done: Motus_Done = .{}) {   // once per request, before every call and action
        if !enter_org(p.org)  return .{error = "No such organization."};   // 404
        return .{};
    } @Enter @Async
}
// a call or action that needs the mount's params: motus_mounted(Orgs.At).org

Panel :: struct {                            // motus_mount("/app", ...): who may be in, said once
    enter :: () -> (done: Motus_Done = .{}) {   // no params: a mount without :params
        if !signed_in()  return .{redirect = "/login"};
        plan := current_plan();
        if !plan.active  return .{redirect = "/start"};
        return .{};
    } @Enter @Async
    // every call and action below: no sign-in check of its own (enter ran first)
}
```

- **Access to a whole area is the entry's `@Enter`**: signed in, a plan, staff, the organization entered.
  It runs before every render, call and action of the mount, each request. Never repeat
  `if !signed_in() return .{redirect = ...}` at the top of each call (one forgotten is a hole); a call
  that needs more (a permission) says `@Permission(x)`.
- One `@Enter` per entry; it takes the mount's `:params` as a struct, or nothing (else a build error).
- `@Call` and `@Action` are `@Async` already (do not write both). `@Enter` still says `@Async`. `@Permission(x)` needs an `@Async` procedure: a call or action is one; on a call, a refusal is the page's 401/403.
- A call renders only: code that writes on a read checks `reads_only()` first.
- Templates rendered to a string (emails, invoices, fragments): `program, err := motus_program(TEMPLATE_x,
  X_View, TEMPLATE_layout); html, err2 := motus_render(*program, *view);`.
- An entry reads models with queries of its own: `motus_mount("/parts", TEMPLATE_views_parts, .[Catalog],
  TEMPLATE_views_shell, models = .[type_info(Part)], params = Parts_Query)` (`params`: a struct of its query
  string's parameters, read by name). A query said `edge` makes the page one made in two places, cached at
  the edge by read set; nothing else says so. See the catalog example.
- Caching follows what the render did: a page that read only public data is `public` and kept at the edge
  until a write to what it read purges it; one that read who asks (a `@Session` model or member, a cookie, a
  varying header), wrote, or set a cookie is `private`. A model noted `@Session` is whoever's signed in.

### Effects at once, in a controller (lanes)

A page's calls already run at once (each a lane). Inside one call or action, several slow effects
(other services, app calls) go at once with a block of lanes (Flows/lanes.jai; the long form,
with every option and what the build refuses: `how_to/060_parallel` to `how_to/063_timeouts_and_retries`):

```jai
price, stock, eta, reviews: string;                 // declared before: a lane is a statement
for parallel() {
    price = Prices.get(id);                         // each statement a lane, started at once
    { stock = Stock.of(id); eta = Stock.eta(stock); }   // { }: steps in order, in one lane
    reviews = Reviews.top(id);
}                                                   // past the block: every lane finished
for parallel(ids)  quotes[it_index] = Quotes.of(it);    // a lane per item: write its own slot
won := -1;
for first(*won) { a = Mirror_A.get(k); b = Mirror_B.get(k); }   // first to finish wins, rest cancelled
r: Lanes_Result;
for parallel(timeout_ms = 300, result = *r) { ... }  // deadline; failures reported, not fatal
for with_effects(.{timeout_ms = 800, retries = 2, backoff = .{initial_ms = 100}}) { rate = fx(c); }
```

- The build refuses: a lane reading or writing what another lane writes; every lane of a
  `for parallel(items)` writing one variable; a declaration as a lane; a transaction in a lane (or a
  block in a transaction); in `for first`, effects that tell the world (External, Respond, Push).
- Without `result = *r` a lane's failure fails the flow; a deadline's cancelled lanes just stop.
- Retries: only failures that surely did not happen, unless the driver is `idempotent` or the block
  says `retry_uncertain = true`.

## Gotchas

- `remove` is a Jai reserved word: name actions `erase`, `remove_item`…
- `@Async` procedures have no `_async` suffix (`find`, `error`, `redirect`, `respond`). A local named like
  one (`error := ...`, `profile := profile()`) shadows it; and a leftover bare `if error` after renaming
  the local still compiles (the procedure is truthy). Rename every use.
- A controller struct must not share its name with a module's namespace (`Campaigns`, `Products`…) that
  `#import "<Name>"` gives (its `api.jai`, `modules/<Name>/api.jai`, written by the build).
- The platform's business apps are all modules (`framework/Crm`, `Email`, `Sms`, `Whatsapp_Cloud`, `Support`,
  `Campaigns`, `Analytics`, `Storefront`, `Marketing`, and the commerce ones): code `#import`s them,
  never `#load`s an `api.jai`; products link them. The channels are also platform apps
  (`modules/Jaiweb_Channel_<Name>` builds each). Email's namespace is
  `Email_App` (`API_NAME` in its `module.jai`); its, Sms' and Whatsapp_Cloud's types bring the channel
  answers (`Mail_Channel_Answer`...): don't `#load` `Stack/*_channel_types.jai` beside the import.
- A seller's site using Marketing `#import`s it and `#load`s `framework/Marketing/touches.jai` and its
  `site.jai` (`marketing_touch()`, the consent banner's answer). A product linking it calls
  `Marketing.connect()` once (no catalogue install tells a linked module it is there: Argoshot's staff claim).
- `#import "<Module>"` gives a linked module's public types and constants by their own names, for the
  templates too; the module itself, for what is no API (its routes, its page's procedures), is
  `<Name>__linked`. `motus check` warns that a module's component is not defined unless its `.mot` is given too.
- Comparisons are words; `<`/`>` in an expression would end the tag.
- Action redirects are used as written (absolute paths), not relative to the entry.
- Scoped styles add `data-m-<hash>` attributes to the component's elements; tests matching exact markup
  must expect them.