Skip to content
Back to skills

Apps

ASecurity

Build and iterate on schema-backed Swarm Apps with live models, named queries, custom actions, and json-render interfaces using the app-upsert, app-get, app-list, and app-patch tools.

  • 1,156 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added November 9, 2026
ai-agentstypescriptgoshellsqlnodeexpressawsgitapidatabase

Works with

  • cursor
  • vscode
  • cli
  • api
  • mcp

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned November 27, 2026

npx -y skills add desplega-ai/agent-swarm --skill apps --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Apps?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Apps
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/desplega-ai-apps/badge)](https://www.skillsdirectory.com/skills/desplega-ai-apps)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: apps
description: Build and iterate on schema-backed Swarm Apps with live models, named queries, custom actions, and json-render interfaces using the app-upsert, app-get, app-list, and app-patch tools.
---

# Swarm Apps

Swarm Apps are persistent, agent-authored internal applications: a schema-backed row store, named queries, custom script/task actions, and a validated json-render interface served at `/apps/<id>`. Use an app when people need to view and change live records; use `create_page` for a static snapshot.

**When to use a sheet or board instead:** a tracker or grid people keep editing, with no queries or actions, is a sheet. A plan, diagram or map to think through is a board. Both are editable agent-fs files; see the `boards-and-sheets` skill. To show one inside an app, use the `ObjectEmbed` component (section "Embed a sheet or board"). To fill a sheet from CSV, Parquet or xlsx files on the drive, use `data-query` with `sheet` (the `data` skill).

> **Capability gate**: app tools are available when the server's `CAPABILITIES` includes `pages` (for example `CAPABILITIES=core,task-pool,pages`). There is no separate `apps` capability. If these tools are absent from your MCP list, this is why.

## Tools and iteration loop

| Tool | Use it for |
|---|---|
| `app-list` | Discover apps by id, name, description, and timestamps. Definitions are omitted. |
| `app-catalog` | Ask what a page may contain: no args lists every component (one line, child slots) and action type; `{ component }` returns its props schema (`prop` drills into one); `{ action }` an action step's params; `{ topic: "expressions" }` the binding reference (`$state` roots, route params, `$param`, `$template`, repeat, `watch`, `OnEnter.everyMs`, visibility). Read it instead of guessing props or reading dashboard source. |
| `app-get` | Read a definition. `{ outline: true }` returns the tree without props (pages with params and `{ nodeId: [type, childIds] }`, model columns, queries, actions); `{ path }` returns one subtree (`pages.main.elements.title` or `/pages/main/elements/title`). Read the whole app only when you need all of it; the whole read also returns `sourcesPath`, the app's agent-fs sources folder. |
| `app-upsert` | Create an app, or replace an existing app's entire definition when you intentionally have the full desired state. |
| `app-patch-node` | Edit one page or reusable-element node: `props` merges one level (`null` deletes a prop), `set` replaces node keys, `remove` deletes the node and its subtree, `create: { parentId, index?, node }` adds one. Prefer this for UI iteration. |
| `app-patch` | Make a focused change to actions, queries, models, page params or settings while preserving everything not mentioned. `ops` takes JSON-pointer `add`/`replace`/`remove`/`test` ops instead of a merge patch. |
| `app-query` | Run one declared named query and return its rows. Use this when an agent or saved script needs to consume app data rather than render the app UI. |
| `app-rows-list` | List rows with typed equality filters, sorting, and a limit. Returns `{ rows, total }`. |
| `app-row-get` | Read a row by `rowId`. Returns `{ row }`. |
| `app-row-create` | Create a row from `values`. Returns `{ row }`. |
| `app-rows-create` | Create 1 to 500 rows from a `rows: values[]` array, within 10 MiB. Returns `{ rows }`. |
| `app-row-patch` | Patch a row by `rowId` with `values`. Returns `{ row }`. |
| `app-row-delete` | Delete a row by `rowId`. Returns `{ ok: true }`. |
| `app-rows-delete` | Delete matching rows with a non-empty `equals` filter. Returns `{ deleted }`. |
| `app-action-run` | Run a declared script, task, or sync action with `{ appId, action, input? }`. Agents can invoke it through MCP only. |
| `app-action-status` | Read or wait on the run an action returned: `{ appId, runId, waitSeconds? }`. A script run settles when it and every run its script launched have finished. |
| `app-history` | List definition snapshots and their compact model/column digests before choosing a restore point. |
| `app-diff` | Show a unified definition diff; defaults to newest snapshot → CURRENT. |
| `app-rollback` | Restore a snapshot through the normal schema-migration engine. |

For every edit: `app-get { outline: true }` -> `app-get { path }` for the node you change -> `app-patch-node` (UI) or `app-patch` (actions, queries, models) -> if rejected, fix every returned `issues[]` entry (`path` + `message`) and retry. A missing node returns the `closest` node ids. Validation happens before storage, so a rejected update leaves the saved app unchanged. `dryRun: true` validates and reports `changed` without storing. Writes return a compact summary (`changed` paths, `issues`, `warnings`, `versionCreated`); pass `includeApp: true` only when you need the stored app back. Use `app-upsert` only to create an app or to replace a definition you hold whole; never with a partial definition.

Keep what you need to rebuild or extend an app in its agent-fs sources folder, `sourcesPath` from `app-get` (`shared/app:<id>/src/` by default): the generator that builds the definition, backing-script drafts, and a `NOTES.md` with the decisions, data sources and control numbers a follow-up must keep. On a follow-up edit, read `NOTES.md` first, then update it with what you changed. `app-get` lists the files there when agent-fs is set up. The server never writes this folder.

When refreshing row data, write only the diff: read the current rows with `app-rows-list`, then `app-row-patch` the changed rows, `app-rows-create` the new ones, and `app-row-delete` the removed ones. Do not delete every row and recreate it, or recreate the model: a large rewrite can be interrupted partway and leave the app half-populated.

`app-patch` can also change `name`; omit `description` to preserve it or pass `description: null` to clear it.

### Reading an app's callable surface

One `app-get` returns everything needed to drive an app you did not write: `definition.queries` are runnable with `app-query` (supply every `$param` the query references), and `definition.actions` are invocable with `app-action-run` or `POST /api/apps/<id>/actions/<name>` (a `script` action runs its script, a `task` action spawns a task, a `sync` action refreshes sources). Read the query parameters and action arguments from the definition before invocation. Do not guess parameter names.

### Verified action caller

Script actions receive `caller` as a reserved, server-stamped argument. The server overwrites `caller` from definition defaults and request input.

```typescript
type AppActionCaller = {
  kind: "user" | "agent" | "operator" | "guest";
  id: string | null;
  name?: string;
  pageId?: string;
};
```

The caller identifies the authenticated user or agent. Operator and guest callers have `id: null`. A signed page session adds `pageId`.
With the swarm key, a registered `X-Agent-ID` produces an agent caller and `agent:<id>` row provenance. Missing or unknown agent IDs remain operator callers.
Task actions include the same caller as server-verified JSON in the task prompt. Script execution still uses the saved script owner's bindings.

### Verified action caller

Script actions receive `caller` as a reserved, server-stamped argument. The server overwrites `caller` from definition defaults and request input.

```typescript
type AppActionCaller = {
  kind: "user" | "agent" | "operator" | "guest";
  id: string | null;
  name?: string;
  pageId?: string;
};
```

The caller identifies the authenticated user or agent. Operator and guest callers have `id: null`. A signed page session adds `pageId`.
With the swarm key, a registered `X-Agent-ID` produces an agent caller and `agent:<id>` row provenance. Missing or unknown agent IDs remain operator callers.
Task actions include the same caller as server-verified JSON in the task prompt. Script execution still uses the saved script owner's bindings.

## Safe schema evolution and rollback

Prefer **hiding** a column over deleting it. A hidden column's values stay on every existing row, so an unhide or rollback can make it visible again. Hiding is metadata-only: hidden columns cannot be used in queries, page bindings, `app.mutate` values, or new row writes, and `required` is ignored while hidden. Row GETs still expose the historical value for backward compatibility.

Do not reuse a hidden column name. The name remains held until you either unhide it or explicitly purge its stored values. To permanently remove a column, delete its declaration with `null` and include `{ "columnName": { "purge": true } }` in the same `migration` object. That is deliberately one-shot and irreversible for row data.

Schema-changing writes can carry this sibling `migration` object:

```json
{
  "migration": {
    "priority": { "from": "flag", "map": { "urgent": "high", "watch": "low" }, "else": "none" },
    "status": { "from": "flag", "map": { "watch": "watching", "done": "done" }, "else": "open" },
    "oldColumn": { "purge": true },
    "count": { "coerce": true, "else": 0 },
    "owner": { "set": "unassigned" }
  }
}
```

Use `set` to backfill a changed column, `from` with optional `map`/`else` to derive it from one existing (including hidden) column, `coerce` for a kind change, and `purge` only for explicit destruction. Non-purge directives target a column changed in that same write. The server fails loudly before writing when a lossy change needs a directive: inspect every returned `issues[]` item, including its per-value row counts, then choose an explicit policy and retry. Never guess a migration just to get a 200.

**Source lifecycle** rides the same engine with the same all-or-nothing guarantees. Free: adding a source, adding a NEW column with a `source` binding, binding an existing column that holds zero values, changing a binding's `field`/`transform`, and changing a source's `args`/`config`/`connection`/`scriptId` (window changes churn staleness on the next pass — expect `stale` flips when narrowing). Rejected with a path-bearing issue: changing `joinKey` (immutable — remove the source and add it again), changing `connector` while the source owns rows (row count in the message), and binding an existing column that already holds values (purge it — or add a fresh column — and bind that instead; a sync pass would otherwise overwrite the data). Removing a source **detaches** its rows: values survive as ordinary columns, the `source`/`syncedAt`/`stale` envelope is stripped, and the report counts them in `detachedRows`. A patch removing a source must drop its column bindings in the same call — a dangling `source.of` is rejected before anything is written.

Sync never adopts rows it does not own: a pulled record whose join key matches an unowned row creates a second, source-owned row. Adding a source over a join-key column that already holds values therefore duplicates those records on the first pass — and remove-source → re-add duplicates for the same reason, because detached rows keep their values. To convert a hand-maintained model into a synced one, purge the old rows first or use a fresh join-key column.

For example, split a legacy `flag` into `priority` and `status` without losing data in one patch: add the two columns, map both from `flag`, update every affected query/page binding, then hide `flag`.

```json
{
  "appId": "<app-id>",
  "definition": {
    "models": {
      "ticket": {
        "columns": {
          "priority": { "kind": "enum", "enum": ["none", "low", "high"] },
          "status": { "kind": "enum", "enum": ["open", "watching", "done"] },
          "flag": { "kind": "string", "hidden": true }
        }
      }
    }
  },
  "migration": {
    "priority": { "from": "flag", "map": { "urgent": "high", "watch": "low" }, "else": "none" },
    "status": { "from": "flag", "map": { "watch": "watching", "done": "done" }, "else": "open" }
  }
}
```

Every schema migration returns `{ scanned, backfilled, coerced, mapped, elsed, purgedValues, idxRebuilt, detachedRows, orphanFields }`. Read `orphanFields`: it reports extra row fields that predate or no longer appear in the definition; they are preserved until an explicit purge. `schemaVersion` is server-managed: never set it in an input patch or try to use it as application data.

Every successful definition write snapshots the previous definition. Use `app-history` to select a version, `app-diff({ appId, from: <version> })` to inspect it against CURRENT, then `app-rollback({ appId, version: <version>, migration? })` to restore it. Rollback is a forward migration over live rows, not row-level time travel: it creates a new pre-rollback snapshot and may reject a lossy restore with the same migration directives and counts. A rejected rollback changes nothing.

### Per-user configuration

`userConfig` declares up to 20 typed settings in the versioned definition; its values are deliberately stored outside the definition, separately for each user (and the operator dashboard). Each field is `{ "kind": "string" | "number" | "boolean" | "date" | "enum", "default"?: ..., "enum"?: [...], "label"?: "..." }`. Defaults follow column rules, including enum membership; `required` is not allowed. A missing or obsolete stored value reads as its default, or `null` when no default is declared.

Use `{ "$state": "/user/<field>" }` on a page for the read-only current-user binding; the field must be declared and the path cannot continue below it. Pure and bound reusable elements cannot bind `/user` directly — pass the value through an element prop from the consuming page. An agent acting on an owned user-requested task reads and edits that requester's preferences. `userConfig` schema changes are always migration-compatible and appear in migration reports; no migration directives are needed. Rollback restores the historical schema but never alters saved per-user values, so values can resurface when a field returns.

### Theming

An optional top-level `"theme"` sets the preset the dashboard applies to the app's rendered canvas: a lowercase slug validated by shape only. The preset catalog ships with the dashboard and lives in `src/themes/presets.ts` and `src/themes/classics.ts`. Update this list and the `app-upsert` tool description when it changes. Current ids: `hive` (the stock look), the accent/field presets `meadow`, `iris`, `rose`, `cobalt`, `ember`, `carbon`, `paper` (the warm editorial paper look), and the classic editor/platform presets `github`, `vscode`, `material`, `solarized`, `tokyo`, `monokai`, `gruvbox`, `catppuccin`. Action and destructive tones are never themed; status tones are themed ONLY by the classic presets (their identity includes a status palette: hue semantics stay fixed, success reads green and error reads red everywhere). An id the viewer's dashboard build does not know degrades to the dashboard's own theme, so unknown slugs are safe but pointless. Omit `theme` to inherit whatever theme the viewer runs; `"hive"` is an explicit reset to the stock look even inside a themed dashboard.

Viewers can override the preset per app from the app's settings drawer; the override rides the reserved `$theme` key of the user-config values (accepted on every app, even without a declared `userConfig` schema, and never visible at `/user/...`). A present override always beats the definition's `theme` — even an unrecognized one, which degrades to the dashboard theme — so treat `theme` as the app's default styling, not a guarantee.

An optional top-level `"icon"` sets the app's icon on the dashboard Apps page. It takes one of three shapes:

- `{ "type": "lucide", "icon": "<kebab-case lucide name>", "color": "#RRGGBB" }` (`color` optional). The dashboard looks the name up in its curated icon catalog and shows a generic grid icon for an unknown name.
- `{ "type": "url", "url": "https://..." }`: an https image link, at most 2048 characters, no credentials.
- `{ "type": "agent-fs", "path": "/apps/<appId>/icon.png" }`: an image on the swarm's agent-fs drive. Add both `orgId` and `driveId` for another drive; never just one.

The server validates shape only. The dashboard shows the grid glyph while an image loads, when it fails to load, and when the viewer has no agent-fs connected, so omitting `icon` is always safe. `app-patch` replaces `icon` whole, so switching shapes leaves no keys from the old one.


Distinguish the two rollback 400s. A lossy-migration 400 is fixable: copy the required `migration` entries from the message and retry. A target-snapshot validation 400 explicitly says that directives cannot repair that historical definition; use `app-history` and choose a different version.

When a schema patch reports stale page/query bindings, repair them in that same patch. Page elements are atomic: replace the complete `pages.<page>.elements.<id>` declaration, removing any reference to a hidden or deleted column, instead of sending only the changed nested prop. This is also the repair move for older apps whose stored page already references an undeclared column; full-definition validation otherwise blocks every patch.

## Definition reference

```json
{
  "models": {
    "modelName": {
      "columns": {
        "externalId": { "kind": "string" },
        "title": { "kind": "string" }
      }
    }
  },
  "queries": { "queryName": { "model": "modelName" } },
  "actions": { "actionName": { "kind": "task", "prompt": "Review the current rows and report" } },
  "pages": {
    "main": {
      "root": "root",
      "elements": { "root": { "type": "Container", "props": {} } }
    }
  },
  "defaultPage": "main",
  "theme": "ember"
}
```

Optional top-level `layout: "sidebar"` turns on the app shell (see Pages, routes, and page trees). Without it every page renders on the plain canvas, exactly as before.

Model, reusable-element, element-prop, query, action, column, page, and page-param names start with a lowercase letter, contain only letters, numbers, or underscores, and are at most 40 characters. A definition has 0-50 models, at most 100 actions, and at most 20 reusable elements; each declared model has 1-200 columns. Operators can change the model, column and action caps per swarm (`APPS_MAX_MODELS`, `APPS_MAX_COLUMNS_PER_MODEL`, `APPS_MAX_ACTIONS`, 1-1000 each); the save error names the current cap. Zero-model apps are valid for pure UI utilities as long as their pages and reusable elements validate.

### Reusable elements

Top-level `elements` are versioned inside the app definition and can be reused from the app's own pages or, when explicitly exported, from another app. They are private by default. Each entry declares a `mode`, optional typed `props`, one `root`, and a flat `elements` node map using the same validated tree vocabulary as a page:

```json
{
  "elements": {
    "statCard": {
      "mode": "pure",
      "export": true,
      "props": {
        "label": { "kind": "string", "required": true },
        "value": { "kind": "number", "default": 0 }
      },
      "root": "card",
      "elements": {
        "card": { "type": "Card", "props": {}, "children": ["label", "slot"] },
        "label": { "type": "Metric", "props": { "label": { "$state": "/props/label" }, "value": { "$state": "/props/value" } } },
        "slot": { "type": "ElementSlot", "props": {} }
      }
    }
  }
}
```

- `pure` elements may read only their declared `/props/<name>` state; `$item` and `$index` are also legal inside repeated nodes. They cannot invoke any action step. A pure tree may contain at most one leaf `ElementSlot` where consumer children are inserted.
- `bound` elements may additionally read the defining app's declared queries and actions and use its models. Those references are validated against the defining app, including hidden-column rules. Reusable elements cannot read `/app` directly, including private elements nested in an exported tree; pass app-wide state through a declared prop from the consuming page. Exported bound elements cannot use `app.navigate`; private bound elements may navigate within their defining app.
- Prop kinds are `string`, `number`, `boolean`, `date`, or `enum`. An enum prop requires a non-empty `enum: ["value", ...]` values array. A literal default and each literal consumer value must match the kind and, for enums, be one of those values. A required prop without a default must be supplied.

Reference an element with an `ElementRef` node. Omit `app` for same-app reuse; cross-app references name the defining app id and require `export: true`. `instanceKey` is optional. Consumer `children` are accepted only when the target has an `ElementSlot`:

```json
{
  "type": "ElementRef",
  "props": {
    "app": "<defining-app-id>",
    "element": "statCard",
    "props": { "label": "Open issues", "value": 12 },
    "instanceKey": "openIssues"
  },
  "children": ["details"]
}
```

Element references float to the defining app's current definition. `app` and `element` must be literal strings; dynamic references are not supported. The server rejects reference cycles and expansion deeper than five, missing/private targets, invalid props, and a breaking write to an exported element that other apps reference. Removing or unexporting an exported element, changing its mode, removing a declared prop, changing a prop kind, or adding a required prop without a default is breaking; publish the new contract under a new element name. If consumers are abandoned intentionally, retry the PUT, PATCH, or rollback with `"forceElementBreak": ["elementName"]`. The named consumers will then render an error once element rendering is available; deleting an entire app is deliberately not compatibility-gated.

### Models

Each column is `{ "kind": ..., "required"?: boolean, "default"?: ..., "index"?: boolean, "enum"?: string[], "hidden"?: boolean }`.

| `kind` | Values and indexing |
|---|---|
| `string` | String value; set `index: true` only when equality lookups need it. |
| `number` | Finite number; never indexed. |
| `boolean` | Boolean; set `index: true` only when equality lookups need it. |
| `date` | ISO-8601 string; never indexed. |
| `enum` | String from the non-empty unique `enum` list; always indexed, without `index: true`. |
| `json` | Any JSON value (object, array, nested) up to 256 KB serialized by default (`APPS_JSON_COLUMN_MAX_BYTES`); never indexed, and a named query cannot `filter` or `sort` on it. Not allowed for `userConfig` fields or element props. |

`default` must match the column kind (and be one of the enum values). `required: true` rejects missing/null values unless a default supplies the value. `id`, `createdAt`, `updatedAt`, `createdBy`, `updatedBy` — and the sync envelope `source`, `syncedAt`, `stale` — are system columns and reserved names. An app created before the sync envelope that declared ordinary columns with these names surfaces `definitionError` after upgrade until they are renamed: patch in a fresh column with a `{from}` migration directive, then purge the old one. Rows always expose `id`/`createdAt`/`updatedAt`; `createdBy`/`updatedBy` record the acting principal (`user:<id>`, `agent:<id>`, `operator`, or `sync:<source>` for engine writes) and are system-managed on every row write.

### Sources and sync

A model may declare up to 4 named `sources` — one-way inbound projections of an external system into its rows. The `script` connector is THE way to bring external data in (GitHub, Linear, any API): a saved script owns the fetch, its auth placeholders, and its paging. `swarm-tasks` is the one native connector, projecting this swarm's own task pool (`config`: `status`/`tags` comma-lists, `agentId`, `assetKey` namespace prefix, `limit` up to 200 — default 100, `includeHeartbeat`). Synced rows are readable by EVERY principal with `app.use` on the app; an unscoped `swarm-tasks` source publishes task prompts (truncated, secret-scrubbed) to all of them, so scope it with `config.assetKey`/`config.agentId` unless that exposure is intended. A user-invoked sync only ever pulls the invoking user's own requested tasks. Script sources run with their run-as identity's credentials — an agent-owned script runs as its owner and only the owner may wire it; an owner-less catalog (global) script runs as the LEAD, so only the lead or the operator can wire or alter such a source (stored references stay valid with their args and connection pinned).

```json
{
  "models": {
    "issue": {
      "columns": {
        "issueKey": { "kind": "string" },
        "title": { "kind": "string", "source": { "of": "gh", "field": "title" } },
        "openedAt": { "kind": "date", "source": { "of": "gh", "field": "created_at", "transform": "date-parse" } },
        "note": { "kind": "string" }
      },
      "sources": {
        "gh": { "connector": "script", "scriptId": "<script-uuid>", "joinKey": "issueKey", "args": { "repo": "owner/name" }, "connection": "github" }
      }
    }
  }
}
```

- **Join key**: each source names a `joinKey` — an owned, non-hidden `string` column carrying the external identity. It must not be `required`, must not declare a `default`, and cannot itself be source-bound. A row belongs to at most ONE source (`row.source`).
- **Column bindings**: `{ "of": "<sourceName>", "field": "user.login", "transform"? }` projects a (dotted-path) field of the pulled record into the column on every pass. Transforms and their required column kinds: `slug`/`lower`/`upper` → `string`, `cents` → `number` (×100, rounded), `date-parse` → `date` (ISO). A failed transform nulls that one column and warns; it never fails the pass.
- **Read-only contract**: source-bound columns and the join key reject every direct write (row create/patch/bulk) with a path-bearing issue — mutate them via the source or a sync refresh. Owned columns on the same model stay writable. Every `required` owned column on a sourced model must declare a `default`, because sync-created rows cannot supply it.
- **Provenance**: synced rows carry `source` (owner), `syncedAt` (last confirmed presence — sortable), and `stale` (true when a complete pull no longer returned the record; clears on reappearance). `syncedAt` advances on every confirmed row WITHOUT touching `updatedAt`; `updatedAt` moves only when projected data actually changed.
- **`connection`** (optional, script sources): names a connections-system slug the source depends on. It buys write-time validation plus a preflight before every pull; it does not by itself gate egress. Credentials resolve for the sync run-as identity — the script's owner when it has one, else the lead agent — so global connections always work and agent-scoped ones need matching script ownership. The slug is injected into the script's args as `connection`, letting one generic script serve N connections.

**The canonical sync-script contract** (every sync script, always):

```ts
export default async function run(args, ctx) {
  // args = { ...source.args, app: { id }, model: "<model>", source: "<sourceName>", connection?: "<slug>" }
  const records = [{ key: "42", fields: { title: "…", created_at: "…" } }];
  return { records, complete: true }; // or return the bare array — a bare array IS a complete snapshot
}
```

Return `Array<{ key, fields }>` or `{ records, complete? }`. `key` is the external identity the engine joins on `joinKey` (numbers are coerced to strings); `fields` is the bag bindings project from. Return `complete: false` whenever the pull window may have missed records — a paged fetch, a hit `limit`, or client-side filtering of a full page. An incomplete pull skips the stale sweep, so rows outside a narrow window are not falsely marked stale; compute `complete` BEFORE any client-side filtering. Hard cap 500 records per pull (over-cap pulls truncate and count as incomplete). An invalid return shape, thrown error, or non-zero exit fails the pass with zero row churn.

The seeded catalog script `github-issues-pull` is the worked example (placeholder auth via `[REDACTED:GITHUB_TOKEN]`, PR filtering, `complete` computed before filtering). For scheduled refreshes, point a `targetType: "script"` schedule at the seeded `app-sync-run` with `scriptArgs: { "appId": "<id>", "model"?, "source"? }`.

**Three refresh doors, one engine**: `POST /api/apps/<id>/sync` (body `{ "model"?, "source"? }`), a `sync` action kind, and the `app-sync` MCP tool (`ctx.swarm.app_sync` from scripts). `{model?, source?}` fans out to every matching (model × source) pair; each pass reports `{ pulled, created, updated, refreshed, unchanged, markedStale, warnings }`. A pair already syncing in this API process short-circuits with `alreadyRunning: true` instead of pulling twice. Each pair's last-pass status (`lastFinishedAt`, counts, `error?`) comes back as `syncStatus` — keyed `"<model>:<source>"` — on `GET /api/apps/<id>` and in `app-get` data, so UI and agents can render "last synced / last error" without extra calls.

### Freshness and the refresh button

Freshness renders with the existing column kinds — no special components. Give the table `{ "key": "syncedAt", "kind": "date" }` and `{ "key": "stale", "kind": "badge", "tones": { "true": "warning" } }` columns, declare a `sync` action, and wire a Button to it:

```json
{
  "actions": { "refresh": { "kind": "sync" } },
  "pages": {
    "main": {
      "root": "root",
      "elements": {
        "root": { "type": "Container", "props": {}, "children": ["refreshBtn", "issuesTable"] },
        "refreshBtn": {
          "type": "Button",
          "props": { "label": "Refresh" },
          "on": { "press": [{ "action": "app.action", "params": { "name": "refresh" } }] }
        },
        "issuesTable": {
          "type": "Table",
          "props": {
            "data": { "$state": "/queries/allIssues/data" },
            "columns": [
              { "key": "title", "label": "Issue" },
              { "key": "syncedAt", "label": "Synced", "kind": "date" },
              { "key": "stale", "label": "Stale", "kind": "badge", "tones": { "true": "warning" } }
            ]
          }
        }
      }
    }
  }
}
```

A `sync` action answers the script-action state shape (`/actions/refresh` → `running` → `ok`/`error`, result under `result.passes`), so the page's queries refetch when it completes. Use `app-query` to READ rows (named queries may filter on `stale`/`source` and sort by `syncedAt`); use `app-sync` to REFRESH sources; never poll a sync door in a loop — schedule it or give people the button.

### Queries

A named query is:

```json
{
  "model": "idea",
  "filter": { "status": "open" },
  "sort": { "column": "createdAt", "dir": "desc" },
  "limit": 100
}
```

`filter` is a strict AND of equality checks. A filter may target a declared model column or a system column (`id`, `createdAt`, `updatedAt`, `createdBy`, `updatedBy`, and on synced models `source`, `syncedAt`, `stale`) — filtering on `id` is the universal way to select one row for a detail view, and `{ "stale": true }` selects rows a complete pull stopped confirming. A literal value must match the column's kind; date filters compare the stored raw ISO string, not parsed instants. Omit `limit` for the default 200 rows, or set an integer from 1 through 1000. `sort.column` is a non-`json` model column, `createdAt`, `updatedAt`, or `syncedAt`; `dir` is `asc` or `desc`. Query runtime state is `{ data, loading, error }` under `/queries/<queryName>`.

A filter value may instead be exactly `{ "$param": "<name>" }`. At execution, the caller supplies that name and the server coerces its value to the filtered column's kind before equality matching:

```json
{
  "queries": {
    "issueDetail": { "model": "issue", "filter": { "issueId": { "$param": "issueId" } }, "limit": 1 }
  }
}
```

The placeholder object must contain only `$param`. Missing caller values fail loudly rather than returning unfiltered rows: HTTP reports 400 and `app-query` returns a tool error listing every missing name. Supplying a param name the query does not reference is also an error. The app UI supplies current declared route params automatically. Direct calls use `app-query({ appId, query: "issueDetail", params: { issueId: 42 } })` or `ctx.swarm.app_query({ appId, query: "issueDetail", params: { issueId: 42 } })`.

### Custom actions

Actions are optional (maximum 20) and are invoked from the page with the `app.action` runtime action.

```json
{
  "actions": {
    "recalculate": {
      "kind": "script",
      "scriptId": "00000000-0000-4000-8000-000000000000",
      "args": { "mode": "fast" }
    },
    "triage": {
      "kind": "task",
      "prompt": "Triage this idea and report a recommendation"
    }
  }
}
```

| Kind | Contract |
|---|---|
| `script` | `scriptId` must identify an existing script; optional `args` are defaults. Invocation input overrides same-named defaults, and the runtime also supplies `app: { id }`. |
| `task` | `prompt` must be non-empty; omit `agentId` to use default (lead) assignment. Only set `agentId` to a real agent UUID. Invocation `input` is included as context for the task prompt. Spawned tasks carry asset key `shared/app:<appId>/action:<name>/`, so a `swarm-tasks` source with `config.assetKey: "shared/app:<appId>/"` pulls back the tasks this app spawned. |
| `sync` | Optional `model` and `source` narrow which (model × source) pairs refresh; omitting both syncs every pair the app declares. At least one pair must exist. Answers the script-kind state shape with per-pass results under `result.passes`. |

- Invocation state lands at `/actions/<name>` as `{ status, result?, error?, taskId?, taskStatus? }`, where `status` is `"running"`, `"ok"`, or `"error"`.

Use a task action named Tackle when a person should hand one issue row to the swarm. Pass the complete current row under `input.issue`; `{ "$row": "" }` resolves to the whole row and that context lands in the task prompt.

```json
{
  "actions": {
    "tackle": { "kind": "task", "prompt": "Tackle this issue. Inspect the supplied issue context, do the work, and report the outcome." }
  },
  "pages": {
    "main": {
      "root": "issuesTable",
      "elements": {
        "issuesTable": {
          "type": "Table",
          "props": {
            "data": { "$state": "/queries/allIssues/data" },
            "columns": [{ "key": "title", "label": "Issue" }],
            "rowActions": [{
              "label": "Tackle",
              "actions": [{
                "action": "app.action",
                "params": { "name": "tackle", "input": { "issue": { "$row": "" } } }
              }]
            }]
          }
        }
      }
    }
  },
  "defaultPage": "main"
}
```

For direct MCP calls, `app-query` accepts `{ appId, query, params? }` and returns rows from that declared named query; every supplied param must be referenced by a `$param` filter in that query. Use it when an agent needs to read app state without scraping the UI.

Saved scripts use the generated SDK name `ctx.swarm.app_query({ appId, query, params? })`. Use `app_query` in scripts or workflows that turn current app rows into reports, digests, or follow-up work. Saved scripts also get generated per-app types automatically: each app contributes an `App_<Name>` namespace with one row interface per model (enum columns as literal unions) and a typed `app_query` overload per named query, all visible via `script-query-types`. A script is typechecked against only the apps it names (literal app id or `App_<Name>`). Types are budgeted at 1 MiB per app and 4 MiB for all the apps one script names. An app past a budget loses its types (calls still work, untyped): `app-upsert` and `app-patch` warn when the app is over the per-app budget, and `script-upsert` warns for each untyped app the script names. Scripts can create, list, get, patch, and delete rows with the seven row tools. Actions remain REST/MCP-only and have no script SDK method.

### Pages, routes, and page trees

`pages` is a map of independently validated page trees and `defaultPage` must name one entry. Each page may also declare a display `title` and typed route `params`. On every non-default page the runtime automatically renders breadcrumbs (`<default page title> › <current page title>`, first crumb navigates back) — including in chromeless embeds — so a detail page does NOT need its own back button; give pages good `title`s instead. This complete pattern connects a table row to a typed detail route and its parameterized query:

```json
{
  "models": {
    "issue": {
      "columns": {
        "issueId": { "kind": "number" },
        "title": { "kind": "string" },
        "status": { "kind": "string" }
      }
    }
  },
  "queries": {
    "allIssues": { "model": "issue" },
    "issueDetail": {
      "model": "issue",
      "filter": { "issueId": { "$param": "issueId" } },
      "limit": 1
    }
  },
  "pages": {
    "issues": {
      "title": "Issues",
      "root": "issuesTable",
      "elements": {
        "issuesTable": {
          "type": "Table",
          "props": {
            "data": { "$state": "/queries/allIssues/data" },
            "columns": [
              { "key": "title", "label": "Issue" },
              { "key": "status", "label": "Status", "kind": "badge" }
            ],
            "rowActions": [{
              "label": "Open",
              "actions": [{
                "action": "app.navigate",
                "params": {
                  "page": "detail",
                  "params": { "issueId": { "$row": "issueId" } }
                }
              }]
            }]
          }
        }
      }
    },
    "detail": {
      "title": "Issue detail",
      "params": { "issueId": { "kind": "number", "required": true } },
      "root": "detail",
      "elements": {
        "detail": {
          "type": "DetailList",
          "props": {
            "data": { "$state": "/queries/issueDetail/data/0" },
            "fields": [{ "key": "title", "label": "Issue" }]
          }
        }
      }
    }
  },
  "defaultPage": "issues"
}
```

Drawer variant: declare a route param on the containing page, set the Drawer `props.param` to that literal param name, and use the same `app.navigate` shape targeting that page with the row id assigned to the Drawer's param. The Drawer then opens from route state without a separate action contract.

App shell (`layout: "sidebar"` at the top level of the definition): every page renders inside a left sidebar that lists the app's pages and a sticky page header. Per page:

- `title`: the sidebar label and the header heading (defaults to the page name).
- `icon`: one catalog icon name (the list under Component catalog) before the sidebar label; unknown names are rejected.
- `description`: one line under the header title (at most 280 characters).
- `headerActions`: the key of one element of this page, rendered in the header's actions slot (right side), e.g. a Refresh `Button` with `on.press: [{ "action": "app.refresh" }]` or a row `Stack` of buttons. It is a second root: it must exist in the page's `elements` and must NOT also be reachable from `root`. It shares the page's state and actions.
- `nav: false`: leave the page out of the sidebar. Pages with a `required` param never list (they cannot open without it); open them with `app.navigate`.

The sidebar lists pages in definition order and marks the current one. Below 768px it folds into a menu button at the left of the header. Crumbs back to the default page show in the header only on pages the sidebar does not list. The shell renders in every view mode: inside the bordered canvas (default view, under the dashboard header that names the app), under the slim bar in `?mode=full`, and as the whole viewport in `?mode=chromeless`, where the sidebar also shows the app name (it is the only navigation inside an iframe). `headerActions` and `nav` without `layout: "sidebar"` are rejected; `icon` and `description` are accepted and unused.

```json
{
  "layout": "sidebar",
  "defaultPage": "overview",
  "pages": {
    "overview": {
      "title": "Overview",
      "icon": "activity",
      "description": "Deploys and spend, last 14 days.",
      "headerActions": "refresh",
      "root": "root",
      "elements": {
        "root": { "type": "Stack", "props": {}, "children": ["spend"] },
        "spend": {
          "type": "Chart",
          "props": {
            "kind": "area",
            "data": { "$state": "/queries/days/data" },
            "loading": { "$state": "/queries/days/loading" },
            "x": "date",
            "xType": "time",
            "format": "currency",
            "series": [{ "key": "spend", "label": "Spend" }]
          }
        },
        "refresh": {
          "type": "Button",
          "props": { "label": "Refresh", "icon": "refresh-cw", "variant": "outline", "size": "sm" },
          "on": { "press": [{ "action": "app.refresh" }] }
        }
      }
    },
    "settings": { "title": "Settings", "icon": "pencil", "root": "root", "elements": { "root": { "type": "Text", "props": { "content": "…" } } } }
  }
}
```

Param `kind` is `string` by default, or `number` / `boolean`; `required` defaults to false. The names `mode`, `apiUrl`, `apiKey`, `email`, and `name` are reserved. `/apps/<id>` renders `defaultPage`; `/apps/<id>/p/<page>?issueId=42` is the shareable deep link for another page. Browser navigation is client-side, so app state and polled data stay warm across page changes.

Within each page, `root` names one entry in its non-empty `elements` map. Elements are a flat, single-parent tree: ids are map keys, `children` contains ids (not nested elements), all elements must be reachable from `root`, and cycles, missing children, or shared children are invalid. Element and Form/UI ids are page-local. Element keys are `type`, `props`, `children`, `on`, `visible`, `repeat`, and `watch`; only components with a `default` child slot accept `children` (Stack, Grid, Split, Tabs, Accordion, Container, Card, Section, Drawer, Dialog, and Svg). `watch` maps state paths to an action step or chain. A page may also declare `state`: page-local values read and written at `/local/<name>` (see Low-level primitives).

## Component catalog

Props reject unknown keys. A `{"$state":"..."}` binding may replace a literal prop value at any depth.

Icons: every `icon` prop (and the `Icon` block) takes one name from a curated lucide set: `plus`, `refresh-cw`, `search`, `filter`, `download`, `upload`, `external-link`, `copy`, `check`, `x`, `trash-2`, `pencil`, `eye`, `calendar`, `clock`, `user`, `users`, `bot`, `git-pull-request`, `git-branch`, `github`, `slack`, `mail`, `link`, `file-text`, `folder`, `database`, `zap`, `sparkles`, `flag`, `star`, `tag`, `alert-triangle`, `info`, `circle-check`, `trending-up`, `trending-down`, `dollar-sign`, `activity`, `rocket`. Any other name is rejected.

Tones: Badge, Metric and Progress `tone` take `neutral`, `success`, `active`, `error`, `info`, `pending`, `warning`, or `paused`.

Components: `Stack`, `Grid`, `Split`, `Divider`, `Tabs`, `Accordion`, `Container`, `Card`, `Heading`, `Text`, `Markdown`, `SearchInput`, `Select`, `NumberInput`, `Chips`, `Button`, `Metric`, `Chart`, `Alert`, `Badge`, `Icon`, `Progress`, `EmptyState`, `CopyButton`, `Kbd`, `Skeleton`, `Spinner`, `AvatarStack`, `Section`, `Table`, `Form`, `OnEnter`, `Drawer`, `Dialog`, `DetailList`, `CardGrid`, `Kanban`, `Calendar`, `ContributionGraph`, `Tree`, `Files`, `File`, `DateRange`, `Timeline`, `LogStream`, `SchemaForm`, `Approval`, `SessionThread`, `PageFrame`, `Input`, `Svg`, `Rect`, `Line`, `Path`, `Circle`, `SvgText`. Read a component's props, required props, enums and child slots with `app-catalog { component: "<Name>" }` (`prop` drills into one prop); it serves the same schema the server validates against. The notes below cover behavior the schema does not show.

Table details:

- `columns[]`: `{ key, label?, kind?, tones?: {value: badgeTone}, width?: number, pinned?: "left" or "right", align?: "start" or "end", truncate?: "end" or "middle", icon?, tooltip?: "<row field>", hint?: string, popover?: { title?, fields, trigger? }, href?: "<row field>", linkLabel?: "<template>", max?: number, format?: "<template>", currency?: "<ISO 4217>", onChange?: chain, filter?: "values" or "text" or false, muted?: string[] }`. `kind` is `text`, `string`, `enum`, `number`, `boolean`, `date`, `badge`, `status`, `user`, `agent`, `relative`, `duration`, `progress`, `copy`, `switch`, `checkbox`, `link`, `json`, `currency`, or `percent`; `string` and `enum` render as text, and `json` renders a truncated single-line `JSON.stringify` preview. `currency` shows a number as money in the column's `currency` (an uppercase ISO 4217 code, default `USD`): `1234.5` is `$1,234.50`. `percent` reads a ratio: `0.42` is `42%`. Both right-align and show a non-numeric value as is. Pin id/actions columns so they survive horizontal scroll on narrow viewports.
  - `status`: lifecycle values (`pending`, `in_progress`, `running`, `completed`, `failed`, `cancelled`, `paused`, `reviewing`, ...) render the dashboard status chip with its icon; other values use `tones` like `badge`.
  - `user` / `agent`: avatar plus name. `relative` (and `date`): smart time, exact time on hover. `duration`: milliseconds as `1m 23s`. `progress`: a bar against `max` (default 100). `copy`: the value plus a copy button. `link`: a smart link (see Smart links, tooltips and popovers below); any other http(s) URL opens in a new tab and other values render as text.
  - `switch` / `checkbox`: a toggle or a checkbox bound to a boolean column. `onChange` runs with `$row` = the row with this column already set to the new value, e.g. `[{ "action": "app.mutate", "params": { "model": "m", "op": "update", "rowId": { "$row": "id" }, "values": { "enabled": { "$row": "enabled" } } } }]`. Without `onChange` the control is read-only. Each toggle is a model write, so to pick rows for a bulk action use `selectable` (below), not a boolean column.
  - Numbers, durations and progress right-align by default. `truncate: "middle"` keeps both ends of ids and paths. `icon` shows in the header; `tooltip` names a row field shown in a styled tooltip on the cell (when the cell is plain text that gets cut off, the tooltip shows its full text without any config).
  - `format`: a `{{field}}` template that combines several row fields into one cell, e.g. `"{{name}} ({{status}})"`. Placeholder names match `[\w.]+` (letters, digits, `_` and `.`; no hyphens or spaces). Each placeholder reads that row field as-is (a dotted name such as `{{owner.name}}` is a literal column name, not a nested path); a missing or null field becomes an empty string and an object or array becomes a JSON preview cut to 120 characters. The whole cell is capped at 500 characters. A templated column ignores `kind`, shows the same text in the phone list, and sorts by the composed text. `search` and `filters` still read the column's `key`.
  - `muted: ["none", "no"]`: those cell values (matched case-insensitively) render as a quiet `—` instead of a pill or text, for columns that are mostly `none` / `no`. The value stays in the data, in the filter list, as a hover title and for screen readers; the phone list leaves it out. Not applied to `switch` / `checkbox` cells.
- `selectable` + `id`: a leading pinned checkbox column. The header checkbox selects every row left after `search` / `filters` (checked, unchecked or indeterminate; clicking it again clears those rows), and shift-click selects a range in the order shown. The selection is client state at `{ "$state": "/ui/<id>/selected" }`, an array of row ids (the `rowId` field, default `id`, as strings). It is never a model write and is not shared with other viewers. `id` is a literal like `SearchInput.id`, and the validator requires it with `selectable` or `bulkActions`. Selected rows that disappear from the data drop out of the selection.
- `bulkActions[]`: `{ label, variant?, icon?, confirm?, actions }`, the `rowActions` shape without `placement`; a non-empty list implies `selectable`. A bar under the table shows `N selected`, the buttons and Clear while the selection is non-empty. Chains have no `$row`; pass the ids with `{ "$state": "/ui/<id>/selected" }`, e.g. `{ "action": "app.action", "params": { "name": "enqueue", "input": { "prs": { "$state": "/ui/prTable/selected" } } } }`. Confirm rules match `rowActions`; the dialog always adds the selection size (`Applies to 3 selected rows.`). The selection is locked while the chain runs. It clears (only the rows the chain acted on) once every step succeeded, waiting for a task-backed `app.action` to finish; a failed `app.mutate` or a failed task stops the chain and keeps the selection for a retry.
- `filterable: true` + `id`: built-in column filters. Each filterable column gets a filter button in its header: `badge`, `status`, `enum`, `boolean`, `user` and `agent` columns open a checkbox list of the distinct values with row counts (the counts follow the other active filters, so a second tick shows what it adds); a column with no kind (or `text` / `string`) opens a contains-text field; numbers, dates, links and `format` columns get none. `columns[].filter` overrides per column: `"values"` or `"text"` (works without `filterable`, and is how a `format` column opts in), or `false` to opt out. Active filters show as removable pills above the table with Clear all. The state is client state at `{ "$state": "/ui/<id>/filters" }`, an object with one entry per column (`/ui/<id>/filters/<column>`): a string array for a list, a string for text; other elements can read it. It composes with `search` and `filters`: a row must pass all three. Below 768px the header menus become one Filters button above the card list. `id` is required (the validator checks it).
- `clearState`: state paths the Table's Clear filters button and the pills' Clear all also reset, e.g. `["/ui/prSearch/value"]` for the `SearchInput` feeding `search`. Only `/ui/<id>/...` paths of controls on the page. Without it, those controls keep their value and the no-match state only offers Clear filters for the built-in filters.
- Loading and errors: the first load (no rows yet) shows a skeleton shaped like the table, with its header labels. `loading` (`/queries/<name>/loading`) is the first load only. Bind `refreshing` to `{ "$state": "/queries/<name>/fetching" }` (true during any fetch, including the 5s poll and `app.refresh`) and a refetch with rows showing runs a slim bar along the top edge, on phones too, and never dims, covers or blanks a row. A failed query shows the error callout with a Retry button; `onRetry` is the chain it runs (default `[{ "action": "app.refresh" }]`, which re-runs every query on the page). With rows already loaded the callout sits above the stale rows; with none, it is the whole state (no empty message). A search or filter that hides every row shows "No rows match" with a Clear filters button; with header filters the table stays in place (header and open filter input included) and the button sits under it.
- Smart links, tooltips and popovers (Table, DetailList, CardGrid, Markdown):
  - A `link` cell (Table `kind: "link"`, DetailList and CardGrid `kind: "link"`) shows a chip with an icon and a short label when its value is a GitHub PR, issue, commit or repo URL (`agent-swarm#2605`, `agent-swarm@a1b2c3d`, `owner/repo`), the GitHub shorthand `owner/repo#N` or `owner/repo@sha`, a dashboard task, agent, session, app, page or workflow URL (shown by its name once the dashboard knows it, else `Task 1f6feea0`), or an agent-fs file. GitHub links open in a new tab; dashboard links stay in the app. Any other http(s) URL is a plain external link, and any other value is text. Only `github.com` links are GitHub links.
  - `href: "<row field>"` (Table column, DetailList or CardGrid field) takes the URL from another row field, so a cell can show one field and link with another: `{ "key": "number", "label": "PR", "format": "{{repo}}#{{number}}", "href": "url" }` shows `agent-swarm#2605` as a PR chip. With `href` the cell's own text (or `format`) is the label. `linkLabel: "<template>"` (same `{{field}}` rules as `format`) sets the label instead, e.g. `"Lead review"` on a `kind: "link"` column.
  - `hint: "<text>"` on a column adds a header tooltip. A header cut off by the column width also shows its full label in the tooltip, with no config.
  - `popover: { title?: "<template>", fields: [...], trigger?: "hover" | "click" }` on a Table column opens a popover from the cell that lists up to 12 fields of the row, in the DetailList field shape (`{ key, label?, kind?, tones?, href?, linkLabel? }`, any DetailList kind). It opens on hover or keyboard focus by default and lets the pointer move into it; `trigger: "click"` toggles it from the cell; on a cell with its own controls (link, copy, switch) it opens from a separate Details button beside the content. In the phone list, link columns render as chips under the row and each popover column gets a Details button that opens on tap. Use it for detail that does not fit a column, such as a merge reason or CI status. `key` and `href` must name model columns.
- `onRowClick`: action chain with `$row` / `$rowIndex`, run when a row is clicked (or Enter on a focused cell). Pair it with `app.navigate` that sets a Drawer param, and bind `selectedId` to `{ "$state": "/route/params/<param>" }` so the open row stays highlighted. `rowId` names the id field (default `id`).
- Phones (below 768px): the table renders as a card list. `mobileFields: { title, subtitle?, meta?: string or string[], status? }` picks the columns; by default the first text column is the title and the first `status`/`badge` column the chip. `mobile: "scroll"` keeps the grid; it is the default when the table has `rowActions` but no `onRowClick`. With `selectable`, each phone card gets a checkbox beside it and a Select all row sits above the list. An editable `checkbox` / `switch` column (one with `onChange`) becomes a real control beside the card, not a line of text.
- `emptyState: { icon?, title, body? }` replaces the plain empty message. A search or filter that hides every row shows its own "No rows match" state.
- `pagination`: boolean; defaults to auto-enabling past 200 rows (set `false` to force one scroll region). `density: "compact"` tightens row height for dense readouts.
- `rowActions[]`: `{ label, variant?, icon?, placement?: "inline" or "menu", confirm?, actions }`. `placement: "menu"` moves the action into the row's More menu. Variants add `destructive-outline` to the Button variants. `destructive` and `destructive-outline` confirm by default; customize with `{ "title": ..., "description": ..., "confirmLabel": ... }`, or use a bare `confirm` string as the dialog description (use `confirm: false` only for a reversible action).
- `search`: optional string; case-insensitive substring matching across the listed string and number columns. Bind a SearchInput value for client-side search.
- `filters`: optional record of per-column string, number, boolean, null, or array values. An array means "the cell is one of these" (what a `multiple` Chips or Select writes). Null, empty strings, empty arrays, or absent values disable one filter. Bind Select or Chips values for client-side filters.

Kanban details:

- One card per `data` row, grouped by the row's `columnField` value. `columns[]` are plain strings or `{ id, label? }`, in display order; rows matching no column are hidden.
- `cardFields[]` uses the DetailList field shape (`{ key, label?, kind?, tones? }`, same kinds) for extra lines under the title.
- `onMove` is an action chain run when a card is dropped in another column. `$row` is the moved row with `columnField` already set to the new column: `[{ "action": "app.mutate", "params": { "model": "deal", "op": "update", "rowId": { "$row": "id" }, "values": { "stage": { "$row": "stage" } } } }]`. Without `onMove`, cards cannot be dragged.
- `onCardClick` is an action chain with `$row`; pair it with `app.navigate` and a `Drawer` to open a card.

Calendar details:

- `startField` / `endField` hold ISO dates, ISO datetimes, or epoch ms. An event shows on every day from start to end; without `endField` it shows on its start day.
- Each Calendar keeps its own visible month (prev/next controls in its header). `onSelect` is an action chain with `$row`, run when an event is clicked.

ContributionGraph details:

- Buckets `data` rows by the calendar day of `dateField` over the trailing `days`. Each row counts 1, or adds its numeric `countField` when set.

Tree details:

- `nodes` is a doc-shaped value: `{ root: string | string[], elements: { <key>: { type, children?: string[] } } }`, the json-render flat element map. Usually bind it to a json column: `{ "$state": "/queries/<name>/data/0/<column>" }`. A malformed or absent value renders an empty state; a `children` key missing from `elements` shows as `key — ?`. Outlines are cut at 2,000 rows with a notice; branches deeper than 32 levels keep a disabled chevron.
- Each row shows `key — type`. Clicking a row writes its key to `/ui/<id>/value`, and the row bound to that path renders selected; read the selection with `{ "$state": "/ui/<id>/value" }`. The Tree never writes `null`: when the selected key leaves the doc (a refetch, an edit) the stored key stays and no row renders selected. Selection and collapse are keyed by node key, so a key reachable through two parents selects and collapses in both places.
- Rows scroll inside `maxHeight` (default `480px`). Set `fill: true` inside a `fill` Stack or Split pane to grow to that height instead and scroll within it (ignores `maxHeight`).

Files and File details:

- Both read agent-fs as the viewer, with the viewer's own agent-fs key (the one Comb saves in their browser), from the swarm's default drive (`agent_fs.comb` in `/status`). There is no `drive` prop yet. The swarm key never reaches agent-fs, and the viewer sees only what their drive membership allows; an app cannot widen it.
- A viewer who has not connected agent-fs sees a "Connect agent-fs" card that opens Comb's connect flow. In a `?mode=chromeless` iframe the card links to the app in the dashboard instead, because the iframe has no saved key.
- `path` is absolute. A literal path must not contain `..`; bind it with `$state` to follow a route param. A folder that does not exist yet lists as empty (`emptyMessage`).
- `Files` sorts folders first. `mode: "browser"` opens subfolders in place, with crumbs that never go above `path`, and reopens on the folder holding `selectedPath`. A file click (in list mode, any row) runs `onSelect` with `$row` = `{ path, name, type, size, modifiedAt }`; `type` is `file` or `directory`, and a folder's `path` ends with `/`. Usually: `[{ "action": "app.navigate", "params": { "page": "docs", "params": { "file": { "$row": "path" } } } }]`, plus `"selectedPath": { "$state": "/route/params/file" }`.
- `File` renders Markdown with raw HTML shown as text, images as `<img>` (SVG too, so its scripts never run), PDFs in the browser's viewer, video and audio in a player, CSV as a table, and text files (HTML as source) as lines. Other types show Download and "Open in agent-fs". An empty `path` shows "No file selected".
- List and view: a `Split` with `Files` in the left pane and `File` with `"path": { "$state": "/route/params/file" }` in the right; declare `file` in the page's `params`.
- `upload: true` adds an Upload button and a drop zone over the list. Files upload with the viewer's key into the folder on screen (the opened subfolder in browser mode), create-only: a taken name asks Keep both or Skip. The list refreshes when a file lands. agent-fs's own upload limit applies.
- Scripts: an `app.action` script runs as its owner agent, so `ctx.fs` `/afs` reads that agent's default drive, not the viewer's. It sees the same files only when the agent's default drive is the swarm's comb drive.

DateRange and Timeline details:

- `DateRange` writes inclusive `YYYY-MM-DD` dates (the viewer's local calendar) to `/ui/<id>/from` and `/ui/<id>/to`, and the active preset to `/ui/<id>/preset`. On first load it writes `defaultPreset` unless the state already holds a range. Bind query params with `{ "$state": "/ui/<id>/from" }` so the query refetches when the range changes. `7d` is today and the six days before it; `mtd` starts on the 1st. `custom` opens two date inputs in a popover; Apply needs both dates, from not after to. `id` must match `[A-Za-z0-9_-]+`, and `defaultPreset` must be one of `presets`.
- `Timeline` reads `timeField` as an ISO date or epoch ms (rows that do not parse are left out), sorts newest first and groups under day headings: Today, Yesterday, then the date. Each event shows `titleField`, the time, `descriptionField` (two lines at most) and a `statusField` pill (`tones` maps value to tone; lifecycle values get the status chip). `icon` replaces the marker dot. `onSelect` runs with `$row` (the row) and `$rowIndex` (its index in `data`); without it events are not clickable.

LogStream details — logs as a tail, not a table:

- One monospace line per entry, newest first: `HH:mm:ss.SSS`, a 3 px severity bar (text like `WARN` or an OTel number), the service, the body on one line. Click a line to expand the full body, `attributesField` and `resourceField` (objects or JSON strings) and a trace link that runs `onTrace` with `$row`.
- Virtualized and memoized: 50k entries scroll smoothly, and a refresh re-renders only the lines it adds. Set `keyField` to a unique id so expanded lines stay open across refreshes and a refetched entry is reused, not redrawn.
- `maxRows` (default 10,000, at most 100,000) keeps the newest entries; the oldest past it drop with a notice at the bottom. Keep the source query bounded too (a `limit` or a `since` window).
- Live tail: refresh the source with `OnEnter.everyMs` (and a `since` cursor in the action) and set `follow: true`. The newest entry stays in view; once the viewer scrolls down, new entries show an "N new" pill instead of moving the view.
- Pair it with a severity histogram (`Chart` kind `bar`, stacked per severity) on top and facets (`Chips` or `Select` over service and severity) beside it.

```json
{ "type": "LogStream", "props": {
  "data": { "$state": "/actions/tail/result/logs" },
  "loading": { "$state": "/actions/tail/running" },
  "timeField": "timestamp", "bodyField": "body", "severityField": "severity_text",
  "serviceField": "service.name", "attributesField": "attributes", "traceField": "traceId", "keyField": "cursor",
  "follow": true, "fill": true,
  "onTrace": [{ "action": "app.navigate", "params": { "page": "trace", "params": { "traceId": { "$row": "traceId" } } } }]
} }
```

Form details:

- `schema` is a JSON schema object held in state (usually `{ "$state": ... }`). Each entry of `properties` becomes one control: `type: "boolean"` a switch, `enum` of strings a select, `type: "number"` or `"integer"` a number input, anything else a text input. `description` is the tooltip. Fields seed from `value[key]`, else the property `default`. At most 100 fields and 200 enum options render. `id` must match `[A-Za-z0-9_-]+`. Rebinding `schema` resets the form.
- Typing updates `/ui/<id>/value` with the draft object; switches and selects commit at once and text and number inputs commit on blur. Each commit runs `onChange` with `$form` = the draft.
- Nested document editing: bind `baseDoc` to a doc-shaped value (`{ root, elements }`) and `nodeKey` to an element key, such as a Tree's `{ "$state": "/ui/<tree>/value" }`. The form then edits `baseDoc.elements[nodeKey].props`, and `/ui/<id>/value` holds the whole doc with the edit merged in, so one `app.mutate` with `values: { <jsonColumn>: { "$state": "/ui/<id>/value" } }` persists it. Props the schema does not list are kept. Edits the query has not returned yet stay applied, so two quick edits on different nodes both survive. A `nodeKey` that is not a key of `elements` falls back to plain mode, and a `baseDoc` over 5,000 elements is not editable. Typing writes `/ui/<id>/value` on every keystroke, before the commit on blur, so another component's `app.mutate` that reads that path can persist half-typed text; persist from the SchemaForm's own `onChange`.

Approval details (human-in-the-loop):

- `requestId` names one approval request, usually the id an `app.action` script returned: `{ "$state": "/actions/<name>/result/requestId" }`. An empty value renders nothing, so the element can sit on the page before the request exists.
- While the request is pending, the card shows its questions with the dashboard's answer flow and polls every 5s; polling stops once it resolves. The viewer answers with their own credential, so the server records them and enforces the approvers list and RBAC.
- A viewer whose role cannot answer, or whose answer the server refuses (not an approver), sees a read-only card with an "Open in dashboard" link. If the request was answered or expired meanwhile, the card refetches and shows that state instead of an error. With an `all` or `{ min: N }` policy, an answer that does not resolve it shows "Your answer is recorded".
- `showResolved: false` shows only the outcome line after resolution, not the answers. `compact: true` drops the card chrome.
- `onResolved` is an action chain run once, when the page sees the request leave `pending`. Its params may read `{ "$chain": "status" }` (`approved`, `rejected`, `timeout`, `cancelled`), `{ "$chain": "responses" }` (answers keyed by question id; `{ "$chain": "responses/<questionId>" }` reads one), and `{ "$chain": "resolvedBy" }`. A request that was already resolved when the page loaded does not run it, so a reload never repeats the follow-up. Use `onResolved`, not `on.resolved`: the validator rejects the latter.

In-session wait: the follow-up runs in the viewer's browser, so if they close the tab before the answer, nothing continues. The script behind the action creates the request detached and returns its id:

```ts
export default async function run(args, ctx) {
  const res: any = await ctx.swarm.request_humanInput({
    title: `Deploy ${args.service}?`,
    questions: [{ id: "go", type: "approval", label: "Ship it to production?" }],
    detached: true,
  });
  return { requestId: res?.data?.requestId ?? res?.requestId };
}
```

```json
{
  "askBtn": { "type": "Button", "props": { "label": "Request deploy", "busyWith": "requestDeploy" },
    "on": { "press": { "action": "app.action", "params": { "name": "requestDeploy", "input": { "service": "api" } } } } },
  "approve": {
    "type": "Approval",
    "props": {
      "requestId": { "$state": "/actions/requestDeploy/result/requestId" },
      "onResolved": [
        { "action": "app.action", "params": { "name": "applyDecision",
          "input": { "status": { "$chain": "status" }, "responses": { "$chain": "responses" } } } },
        { "action": "ui.toast", "params": { "message": "Decision applied", "tone": "success" } }
      ]
    }
  }
}
```

Durable wait: when the follow-up must run even if nobody watches the page, put it in a workflow whose human-in-the-loop node waits server-side, and use `Approval` only to answer. A script action starts the run with `ctx.swarm.workflow_trigger({ id, triggerData, wait: false })` and returns `runId`. The request appears once the run reaches its human-in-the-loop node, so a second script action (pressed from the page, or retried) finds it and returns its id: `ctx.swarm.db_query({ sql: "SELECT id FROM approval_requests WHERE \"workflowRunId\" = $1 AND status = 'pending' ORDER BY \"createdAt\" DESC, id LIMIT 1", params: [args.runId] })`, then `{ requestId: res.data.rows[0]?.[0] }`. Bind `Approval.requestId` to that action's result. The workflow resumes on the answer whether or not the page is open.

SessionThread details — a chat on an app page, one session per viewer and `sessionKey`:

- `sessionKey` names the session, a plain token (`^[A-Za-z0-9_-]{1,128}$`): a literal such as `"main"`, or a `$state` binding to a token such as a route param or row id (`{ "$state": "/route/params/itemId" }`) for one session per item. No row stores the session: the server keys every task the thread's `app.action` creates as `task:app:<appId>:<sessionKey>:user:<viewer>`, and the thread shows the viewer's newest session with that key. A page can only write sessions of its own app.
- `scope` is `"user"` (the default): each viewer has their own session per key. The viewer needs an identity; with none picked the composer is disabled. `scope: "shared"` (one session everyone on the page writes to) comes in a follow-up PR: the validator rejects it today. The planned design adds an everyone:write session share on the root when the server creates it.
- It renders the same conversation as the dashboard's "Session about this page" panel: the session turn timeline (each person message with the sender's name, the swarm's replies with a live Queued / Working status, worker steps, approvals) and the shared composer. A person bubble shows the `message` of an app-action input instead of the whole agent prompt, cut at 4,000 characters. The mic is off. Without `attachments` a message is text only.
- Sending a message takes one of three routes:
  1. No session yet → run `onDispatch` with `$form = { message }` and `$chain = { leafTaskId: null, newTaskId: null }`. Its `app.action` creates the session's root task.
  2. A task in the session is not finished → the composer steers the newest such task, on any agent, with `source: "app-page"`. It offers Queue, and Interrupt where the harness supports it. The server promotes a steer it cannot deliver into a follow-up task (source `ui`), and a toast says so.
  3. Every task is finished (completed, failed, cancelled, superseded, skipped, or draft) → run `onDispatch` again with `$chain.leafTaskId` set to the newest task id, so `"parentTaskId": { "$chain": "leafTaskId" }` chains the new task under it. The follow-up keeps the session's key.
- Each `app.action` step of `onDispatch` is sent with the session (`{ key, scope }`) and with `followUp: false` unless the step sets `followUp` itself, so the Lead adds no review task to the chain and each message stays one task. A Lead review that is in the chain anyway (a steer the server promoted to a task) is never steered or chained under.
- "New session" (shown once a session exists) starts over: the next message creates a new root, and the thread shows only sessions created after the current one. Nothing is deleted; older sessions stay in the dashboard's Sessions list.
- While the session loads, the composer is disabled with a loading notice. A session whose chain cannot be found blocks sending. After a send, the composer stays busy until the new task shows up, for at most 30 seconds.
- `attachments: { dir, accept?, maxFiles?, maxBytes? }` lets a message carry files. Both composers then get the attach button, a drop zone, image paste and removable chips (thumbnails for images), as in Sessions. `accept` takes extensions (`".png"`) or MIME types (`"application/pdf"`, `"image/*"`), default the dashboard composer's list; `maxFiles` defaults to 10 per message, `maxBytes` to 50 MB per file; a literal limit must be a positive integer. A refused file gets an error line for its type, size or the count. On send, the files upload create-only with the viewer's own agent-fs key to `<dir>/<timestamp>-<id>-<n>-<name>` (like a Form file field), then `onDispatch` runs with `$form = { message, attachments: [{ path, name, mimeType, size }] }` (`attachments: []` when none). If any upload fails nothing is sent, and the text and files stay in the box. A message with files always goes as a follow-up, never a steer; while a turn runs the box steers and takes no files, as in Sessions. A person bubble shows the `attachments` of its app-action input as chips that open the file. `dir` is literal or bound (`{ "$join": [["/projects/", { "$state": "/route/params/projectId" }, "/attachments"], ""] }`); a literal must be an absolute path without `..`. The viewer needs agent-fs connected with write access to `dir`. While the viewer's browser has no agent-fs key, the thread itself shows the steps to connect above the composer, with a Connect Files button that opens Comb's connect flow (hidden in a `?mode=chromeless` iframe), so an app needs no connect hint of its own.
- Without `fill` the thread is 420 px tall; `fill: true` fills a `fill`-aware parent, and keeps at least 420 px on a phone, where a `Split` or `Grid` stacks its panes. Inside an element instance, `id` is namespaced per instance, so two instances keep separate drafts.

```json
{ "type": "SessionThread", "props": {
  "id": "chat",
  "sessionKey": { "$state": "/route/params/screenId" },
  "onDispatch": [{ "action": "app.action", "params": {
    "name": "editScreen", "input": { "$form": "" }, "parentTaskId": { "$chain": "leafTaskId" } } }]
} }
```

PageFrame details — a live swarm Page inside the app, for a preview pane next to a `SessionThread`:

- It renders the body `/pages/<pageId>` shows: an HTML page in a sandboxed iframe (scripts, forms and popups; never top navigation), a JSON page inline. The viewer can click and scroll it.
- It checks the page every 3 s and reloads by itself when the page's `updatedAt` moves: a new version, a restore, a theme switch. A reload resets scroll and any state inside the page.
- `pageId` is a page id (32 hex characters), usually bound: `{ "$state": "/queries/project/data/0/pageId" }`. A literal slug is rejected; an empty id shows "No page selected".
- The viewer needs read access to the page: an authed page launches a page session for them, a password page asks for its password.
- `device: "mobile"` centers a 390 px wide frame, so the page's own media queries see a phone. A JSON page follows the dashboard viewport instead. Switch devices with two `PageFrame`s in `Tabs`, or bind `device` to a `Select`.

```json
{ "type": "PageFrame", "props": {
  "pageId": { "$state": "/queries/project/data/0/pageId" },
  "device": { "$state": "/ui/device/value" },
  "fill": true
} }
```

#### Pages inside an app (`appContext`)

An HTML page in an app `PageFrame` talks to the app through `window.appContext`. Outside an app (a page opened on its own, or embedded by another page) it is `null`, so one page serves both.

- **App side**, on the `PageFrame`: `params` (scalars, usually bound) reach the page as its query string and as `appContext.params`; a change reloads the frame. `actions` lists the app actions the page may run (script actions only; task actions stay on app buttons). `expose` lists the app state paths the page may read (`/app/<name>`, `/ui/<id>/...`). `id` plus `on.message` receive the page's messages: each one is stored at `/ui/<id>/message` (`{ name, data, seq }`) before the chain runs. The frame also follows the app's theme preset, not the dashboard's.
- **Page side**: `await appContext.ready` (rejects after 5 s with no app), then read `appContext.route` (`{ page, params }`), `.params`, `.theme` (`{ mode, preset }`) and `.state` (keyed by exposed path). `appContext.on("change" | "route" | "params" | "theme" | "state", fn)` returns an unsubscribe. `await appContext.action(name, input)` returns `{ status: "ok", result }` or `{ status: "error", error }`. `appContext.navigate(page, params)` opens another page of this app. `appContext.emit(name, data)` runs `on.message`.
- **Security**: the page holds no credential. The app runs each action with its own `app.action` step as the viewer, so the server's `app.use` gate and the script's `caller` checks apply. A page never gets more than the viewer: an action outside `actions` and a path outside `expose` are refused, and navigation stays inside this app. The frame answers only its own iframe on the API origin, and caps requests at 20 per second and 64 KiB each.
- JSON pages render inline and get no `appContext`. Keep one static page per view and feed it with `params` and `appContext.action`, instead of writing a page per viewer.

### Example: Page inside an app

The trace page draws a waterfall for `?traceId=`, loads spans through `traceDetail`, and asks the app to open a span: `appContext.emit("open", { spanId })`.

```json
{
  "models": {},
  "defaultPage": "trace",
  "state": { "window": "1h" },
  "actions": { "traceDetail": { "kind": "script", "scriptId": "00000000-0000-4000-8000-000000000001" } },
  "pages": {
    "trace": {
      "title": "Trace",
      "params": { "traceId": { "kind": "string" } },
      "root": "frame",
      "elements": {
        "frame": {
          "type": "PageFrame",
          "props": {
            "id": "waterfall",
            "pageId": "8b8077e8b7a94dfc89c88636889a46ac",
            "params": { "traceId": { "$state": "/route/params/traceId" } },
            "actions": ["traceDetail"],
            "expose": ["/app/window"],
            "fill": true
          },
          "on": {
            "message": [
              { "action": "ui.set", "params": { "path": "/app/window", "value": { "$state": "/ui/waterfall/message/data/window" } } }
            ]
          }
        }
      }
    }
  }
}
```

In the page:

```js
const ctx = window.appContext;
if (ctx) {
  await ctx.ready;
  const { result } = await ctx.action("traceDetail", { traceId: ctx.params.traceId });
  draw(result.spans, ctx.theme.mode);
  ctx.on("state", (state) => redraw(state["/app/window"]));
}
```

Form details:

- `fields[]`: `{ name, label?, kind?, options?: string[], placeholder?, required? }`; `kind` is `string`, `text`, `number`, `boolean`, `date`, `enum`, or `file`, and enum fields need `options`.
- `kind: "file"` adds `dir`, `accept` (e.g. `[".pdf", "image/*"]`), `multiple` and `source`: `"upload"` (default) chooses local files, `"pick"` opens a browser of `dir` (or `/`) to attach a file that already exists in agent-fs, `"both"` offers both. `dir` is an absolute agent-fs folder, required unless `source` is `"pick"`. Files use the viewer's own agent-fs key on the swarm's default drive, like `Files`.
- On submit, chosen files upload first, create-only, to `<dir>/<timestamp>-<id>-<n>-<sanitized name>`: a random id per submit and a counter across all fields, so two fields or two submits never write the same path; then the chain runs. `$form.<name>` is the stored path, or an array of paths with `multiple: true`. An upload failure (the error shows agent-fs's text, e.g. its size limit) stops the chain and keeps the form's values. Without an agent-fs connection the field shows a "Connect agent-fs" card, and a required file field disables submit.
- Values live at `/forms/<formId>/<fieldName>`. `onSubmit` is an action chain.
- The submit button shows a pending spinner while the chain runs, and `app.mutate` failures in the chain render inline under the fields (not the page banner) — no extra wiring needed.

Drawer details:

- `param` must name a param declared on the containing page. The drawer is open exactly when `/route/params/<param>` has a non-empty value, so its open state survives refresh and is shareable. Its children mount only while open; closing it clears that param with history replacement.
- `actions[]`: `{ label, variant?, icon?, confirm?, actions }`, rendered as buttons in a sticky footer under the scrolling body. Confirmation follows Table `rowActions`: destructive variants confirm by default, and a chain with an `app.mutate` delete always confirms. Chains have no `$row`; address the open record with `{ "$state": "/route/params/<param>" }`, for example `{ "action": "app.mutate", "params": { "model": "order", "op": "delete", "rowId": { "$state": "/route/params/panel" } } }`. Prev/next record navigation is not available.
- `presentation: "split"` renders the Drawer as an inline right pane beside the page instead of a sheet over it. The page canvas shrinks while it is open; the pane has a draggable left edge (arrow keys, Shift for big steps, Home/End for the min/max, double-click or Enter to reset) and the viewer's width is kept per app in the browser. `size` sets its starting width (360/480/640/800px). Opening, closing, refresh and shared links work exactly as for the sheet. Below 768px it falls back to the sheet. At most one split Drawer per page; `side` does not apply.

List + detail recipe (a row click opens the record beside the table):

```json
"params": { "issue": { "kind": "string" } },
"elements": {
  "root": { "type": "Stack", "props": {}, "children": ["table", "issue"] },
  "table": { "type": "Table", "props": {
    "data": { "$state": "/queries/issues/data" },
    "columns": [{ "key": "title" }, { "key": "status", "kind": "status" }],
    "selectedId": { "$state": "/route/params/issue" },
    "onRowClick": [{ "action": "app.navigate", "params": { "page": "main", "params": { "issue": { "$row": "id" } } } }] } },
  "issue": { "type": "Drawer", "props": { "param": "issue", "presentation": "split", "size": "md", "title": "Issue" },
    "children": ["issueDetail"] },
  "issueDetail": { "type": "DetailList", "props": { "data": { "$state": "/queries/issue/data/0" }, "fields": [{ "key": "title" }] } }
}
```

DetailList details:

- `fields[]`: `{ key, label?, kind?, tones? }`. Kinds reuse Table formatting (`text`, `string`, `number`, `boolean`, `date`, `badge`, `enum`) and the Table cell renderers (`status`: lifecycle chip or `tones` pill; `user`: avatar plus name; `relative`: smart time, exact on hover; `copy`: value plus copy button; `link`: a smart link from the value, or from the row field named by `href`, with `linkLabel` as an optional label template), and add `code` for a monospace block and `json` for a collapsible JSON tree (objects, or a string holding JSON). `currency` and `percent` (with `currency?: "<ISO 4217>"`) format numbers like the Table kinds. Bind `data` to one record, commonly `/queries/<detailQuery>/data/0`.

Motion details:

- Every `Stack` fades its direct children in and lifts them 4px over 200ms on first paint, staggered 30ms (capped at the 10th child). It never replays on the 5s data poll. A Stack nested inside another one does not add its own entrance. `motion: "fade"` drops the lift; `motion: "none"` turns it off. Viewers with reduced motion get a 150ms fade.

CardGrid details — the visual counterpart to Table for record browsers (projects, documents, media):

- `titleKey` (required) picks the row field shown as the card title (an object value shows a JSON preview; titles are capped at 500 characters).
- `imageKey` (optional) picks a row field holding an absolute http(s) image URL and adds an image tile to every card. When it is set, a non-URL value, a missing value, or a failed load shows a placeholder tile. Omit it for text-only cards with no tile.
- `fields[]`: `{ key, kind?, tones?, href?, linkLabel? }`. `kind` is `text`, `string`, `enum`, `number`, `boolean`, `date`, `badge` (with `tones`), `link` (a smart link, with `href` / `linkLabel`), or `json` (no `label`, no `format`). A field with no `kind` whose value is an object renders like `json`. They render as an unlabeled `·`-joined meta line under the title, e.g. a `date` field for "created" and a `text` field for the author.
- `columns`: same responsive shorthand as `Grid.columns` (default `{ "base": 1, "sm": 2, "md": 3 }`).
- `onClick`: an action chain with `$row` / `$rowIndex`, run when a card is clicked or activated with Enter or Space. Commonly `app.navigate` into a detail page, the CardGrid equivalent of Table's `onRowClick`.
- Bind `data` / `loading` / `error` to a named query like Table. Loading shows skeleton cards, an error shows a callout, and no rows shows `emptyMessage`.
- It renders 200 cards at a time with a Show more button below the grid that reveals the next 200.

Shortcut details:

- `Button.shortcut` and `SearchInput.shortcut` are one key. Letters and digits match without Shift; symbols such as `/` and `?` match as typed. They do nothing while focus is in a text field, while Ctrl, Cmd, or Alt is held, or while a dialog or menu is open (unless the control is inside it, such as a Button in an open Drawer).

## Layout & interactivity

For a multi-page app that should feel like a product (a sidebar of pages, a sticky title bar with actions), set `layout: "sidebar"` (see Pages, routes, and page trees) instead of building navigation out of Tabs or button rows. Pair `Metric` tiles (with `sparkline`) in a `Grid` with `Chart`s inside `Card`s for dashboards.

Use `Stack` as the primary page and section layout; `Container` is the legacy two-prop primitive retained for existing pages. Stack supports vertical or horizontal flow, shared spacing, alignment, justification, wrapping, and padding; row Stacks (filter bars, button rows) should set `collapseBelow: "sm"|"md"|"lg"` so they stack vertically on phones. Use `Grid` for responsive card or metric strips: a bare column count is responsive shorthand (1 column on phones, 2 from `sm`, the count from `md` up), or pin breakpoints explicitly with `{ "base": 1, "md": 2, "lg": 3 }`. `Grid` and `Split` also accept `padding` on the shared spacing scale.

`Stack` and `Split` size to their content by default, so a page scrolls as a whole. Set `fill: true` to make one grow to fill the remaining height of a `fill`-aware parent (another `fill` Stack or Split) instead; chain it from the page root down through every container on the path to the element that should scroll, and that element scrolls within whatever height is left while the page itself does not. A non-`fill` sibling (a toolbar, a header) keeps its natural height and the `fill` sibling absorbs the rest. A `fill` Split stretches both panes to the full row height, so nesting a `fill` Split inside one pane of another `fill` Split is the way to build a three-or-more column viewport-height layout (`ratio` is only ever two panes).

`Split` and `Tabs` children are positional. For Split, `children[0]` is the first pane, `children[1]` is the second, and extra children append inside the second pane. Below `collapseBelow`, panes stack; `reverse` changes only that narrow-layout stacking order. For Tabs, `children[i]` is the body for `tabs[i]`; keep both arrays in the same order and with the same count. Inactive tab children stay mounted but hidden, so Tables keep polling. Use `Divider` to separate sections and `Markdown` for richer explanatory content.

SearchInput, Select, NumberInput, Chips, and Tree are client-side controls: each needs a literal `id` and writes state under `/ui/<id>/value` (Tree writes the clicked node key; a `selectable` Table writes its selected row ids to `/ui/<id>/selected`); Tabs writes its active key to `/ui/<id>/tab`. Bind those values into a Table's `search` and `filters` props. This filters already-polled rows locally; it does not alter or re-run the named query.

```json
{
  "filters": { "type": "Stack", "props": { "gap": "sm" }, "children": ["query", "status"] },
  "query": { "type": "SearchInput", "props": { "id": "ideaSearch", "placeholder": "Search ideas" } },
  "status": { "type": "Select", "props": { "id": "ideaStatus", "options": ["open", "done"] } },
  "ideas": {
    "type": "Table",
    "props": {
      "data": { "$state": "/queries/allIdeas/data" },
      "columns": [{ "key": "title" }, { "key": "status" }],
      "search": { "$state": "/ui/ideaSearch/value" },
      "filters": { "status": { "$state": "/ui/ideaStatus/value" } }
    }
  }
}
```

`visible` accepts a boolean, a `$state` truthiness binding, comparisons, and logical groups. Put exactly one comparison key in each condition object. The renderer evaluates the first matching key in fixed priority order (`eq`, `neq`, `gt`, `gte`, `lt`, `lte`; otherwise truthiness), so additional comparison keys in the same object are ignored. Use `$and` / `$or` arrays to combine conditions. `not` is a negation FLAG inside a condition object (`"not": true`), never a wrapper around one — `{ "not": { "$state": … } }` is invalid and the validator rejects it. The absent-record pattern (e.g. an alert when a detail query matched nothing) is `{ "$state": "/queries/<q>/data/0/id", "not": true }`:

```json
[
  { "$state": "/route/params/issueId", "gt": 0 },
  {
    "$and": [
      { "$state": "/route/page", "eq": "detail" },
      { "$state": "/route/params/panel", "neq": "hidden" }
    ]
  }
]
```

## Bindings, sentinels, and action chains

Use this exact query binding shape; do not invent `$query`, `$item`, or template strings:

```json
{
  "data": { "$state": "/queries/allIdeas/data" },
  "loading": { "$state": "/queries/allIdeas/loading" },
  "error": { "$state": "/queries/allIdeas/error" }
}
```

Valid `$state` roots are:

- `/queries/<declaredQuery>/...`
- `/forms/<formId>/...`, where a `Form` element has that literal `props.id`
- `/ui/<id>/...`, where a SearchInput, Select, Chips, or Tabs element has that literal `props.id` (SearchInput, Select, and Chips use `/value`; Tabs uses `/tab`; Select also writes its typed search to `/search`)
- `/actions/<declaredAction>/...`
- `/route` (the whole `{ page, params }`), `/route/params` (all params), or `/route/page` for the active page name
- `/route/params/<declaredParam>` for a param declared on the current page
- `/local/<name>/...`, where the current page declares `<name>` in its `state`

`/route` is mirrored as `{ page, params }`. Only declared params appear. Values are coerced by their declared kind: `number` becomes a number when possible; boolean strings `true`/`1` become true; failed number coercion remains the raw string.

Only inside action-chain `params` (`on.<event>`, `Table.rowActions[].actions`, `Table.bulkActions[].actions`, `Form.onSubmit`, or a component chain prop such as `Approval.onResolved` or `SessionThread.onDispatch`) these scoped sentinels are valid, recursively inside objects and arrays:

| Sentinel | Resolves to |
|---|---|
| `{ "$row": "id" }` | Current Table row's `id`; another column name selects that field. |
| `{ "$row": "" }` | Entire current Table row. |
| `{ "$rowIndex": true }` | Current Table row index. |
| `{ "$form": "title" }` | One current Form value. |
| `{ "$form": "" }` | All current Form values. |
| `{ "$state": "/queries/allIdeas/data" }` | Current value at a valid app state path, including action state such as `/actions/refreshIssues/status`. |
| `{ "$chain": "leafTaskId" }` | One chain-scope value, published by the component that runs the chain: a task chain (`SessionThread`) carries `leafTaskId` and `newTaskId`; `Approval.onResolved` carries `status`, `responses` and `resolvedBy`; `Form.onSubmit` carries `createdRowId` (the row its newest `app.mutate` create step made). The component publishes every key, `null` when it has no value yet; a `null` key resolves to nothing and its param is dropped (a `parentTaskId` bound to a `null` `leafTaskId` creates a root task). Where no chain scope is published (Table), or the key is not one the scope carries (a typo), the sentinel is left in place and the action fails instead of silently dropping the parent. An empty string is not "no parent": a `$state` slot meaning "no parent yet" must hold `null`. |
| `{ "$chain": "" }` | The whole chain scope. |

Each sentinel object must contain exactly the single key shown.

An action-chain step is `{ "action": "<type>", "params": {...} }`. Available action types:

- `app.mutate`: `{ model, op, rowId?, values?, formId? }`, where `op` is `"create"`, `"update"`, or `"delete"`. `update`/`delete` require `rowId` (usually `{ "$row": "id" }`, or `{ "$state": "/route/params/<param>" }` in a Drawer footer); literal `values` keys must be model columns. Successful mutation refetches all queries on that model. In a `Form.onSubmit` chain, steps after a `create` read the new row's id as `{ "$chain": "createdRowId" }`, e.g. to navigate to the new row (not `$state`: the renderer resolves a chain's `$state` reads when the form renders, before the row exists).
- `app.refresh`: `{ query? }`; omit `query` to refetch all, or name a declared query.
- `app.action`: `{ name, input?, parentTaskId?, followUp? }`; `name` must be declared in definition `actions`. For a task-kind row action, pass whole-row context with `input: { issue: { "$row": "" } }`. `parentTaskId` chains the created task under an existing one for task-kind actions (typically `{ "$chain": "leafTaskId" }`; a literal or `$state` task id also works); a script or sync action rejects it with 400. `followUp: false` creates the task with no Lead follow-up (the review task the Lead adds when a worker task finishes); script and sync actions ignore it. A task an action creates is attributed to the viewer's identity. `session: { key, scope? }` keys a task-kind action's task into the viewer's `SessionThread` session for that key; the server builds the key, never the page. SessionThread sets it on its own `onDispatch` steps (replacing any value there). Any other chain can set it to start a session: `key` is a literal plain token (validated like `sessionKey`) or a binding; a key that does not resolve to a token fails the step instead of creating a task outside the session, `scope: "shared"` is rejected, and a session step defaults to `followUp: false`. Example, a create form that sends the idea as the chat's first message:

```json
"onSubmit": [
  { "action": "app.mutate", "params": { "model": "project", "op": "create", "values": { "name": { "$form": "name" } } } },
  { "action": "app.action", "params": { "name": "build", "input": { "message": { "$form": "idea" } }, "session": { "key": { "$chain": "createdRowId" } } } },
  { "action": "app.navigate", "params": { "page": "studio", "params": { "projectId": { "$chain": "createdRowId" } } } }
]
```

The `studio` page's `SessionThread` with `"sessionKey": { "$state": "/route/params/projectId" }` then shows the idea as its first message and the running task, with no second send.
- `app.navigate`: `{ page, params? }`; `page` must be declared, supplied keys must be params of the target page, and every required target param must be supplied. `params` replace the current route params wholesale and may contain action sentinels. Navigation pushes history, so browser Back returns to the previous page/params; only `mode` is preserved automatically.
- `ui.toast`: `{ message, description?, tone?, undo? }`, where `tone` is `"success"`, `"error"`, `"info"` (default), or `"warning"`. `undo: { label?, actions }` adds an Undo button (default label `Undo`) that runs `actions` as a chain; its steps are validated like any chain. Put it after the step it confirms, e.g. a row delete followed by `{ "action": "ui.toast", "params": { "message": "Order deleted", "undo": { "actions": [{ "action": "app.mutate", "params": { "model": "order", "op": "create", "values": { "title": { "$row": "title" } } } }] } } }`. Undo params resolve `$state` when Undo is pressed; `$row` / `$form` resolve when the toast is shown.
- `swarm.sdk`: `{ sdk, args? }`; invokes a catalog-supported Swarm browser SDK method with the viewer's bearer.
- `swarm.call`: `{ method, endpoint: "/api/...", body? }`, where `method` is `"GET"`, `"POST"`, `"PUT"`, `"DELETE"`, or `"PATCH"`; raw authenticated API call.

A failed step halts its chain: when `app.action`, `app.mutate`, `swarm.sdk` or `swarm.call` fails (a thrown error, a script action that returns `ok: false`, a non-2xx `swarm.call`), the steps after it do not run and the error shows as an error toast. A step's `onError` (`{ set }` or `{ action }`) runs first, and the chain still halts. So a `ui.toast` after a write is a real success message. A `Form`'s failed `app.mutate` shows inline under the fields instead of a toast. A task-backed `app.action` succeeds once the task is created; the task's own failure shows in the page banner and does not halt the chain. A Table bulk action reads each step's own outcome, as before.

## Low-level primitives

Compose custom widgets (a code input, a timeline, a Gantt chart) from page-local state, a bindable `Input`, three `ui.*` steps, expressions, and `Svg` shapes. No custom component needed.

**Page state.** `pages.<page>.state` maps names to initial JSON values. The page reads them at `{ "$state": "/local/<name>/..." }` and only this root is writable. Each page has its own `/local`, even when two pages declare the same name. The values are seeded on first render and survive navigation; patching `pages.<page>.state.<name>` replaces that entry. Reusable elements cannot read or write `/local`.

**App state.** The definition's top-level `state` maps names to initial JSON values shared by every page: read `{ "$state": "/app/<name>" }`, write with `ui.set` (`/app/<name>/...`) or bind a `Select`/`Input` through `$bindState`. Use it for one time window that every page follows. It is seeded once and survives navigation between the app's pages; a reload starts from the initial values.

**Input.** `value: { "$bindState": "/local/<name>/..." }` binds two-way; inside a `repeat` over a `/local` list, `{ "$bindItem": "" }` binds the item itself (`"field"` binds a field of it). `$bindState` and `$bindItem` are valid only on `Input.value`. Event chains are props, run by the Input:

- `onInput`: after every edit; `{ "$chain": "value" }` is the new text.
- `onPaste`: instead of the browser paste; `{ "$chain": "text" }` is the clipboard text.
- `onKeyDown:<Key>`: instead of that key's default. Keys: `Backspace`, `Delete`, `Enter`, `Escape`, `Tab`, `ArrowLeft`, `ArrowRight`, `ArrowUp`, `ArrowDown`, `Home`, `End`.

`$state` reads inside these chains resolve at render time. To read the newest value, use `$chain`, or put the chain in a `watch`.

**`watch` rules.** A `watch` skips the value it sees on first render: it only fires on a later change, so it never loads data on page open. Any state write while a `watch` chain runs cancels the steps after it, and `app.action` always writes (`/actions/<name>`), so a `watch` chain runs at most one `app.action` or `ui.set`, and it must be the last step. Put multi-step loads in `OnEnter` instead.

**Live data.** `OnEnter.everyMs` (1000 or more) re-runs the chain on an interval while the tab is visible; a tick is skipped while any earlier run (a tick or a `deps` change) is still going. Bind it to a toggle (`{ "$if": [{ "$state": "/local/live" }, 2000, null] }`) for a pausable live tail.

**Realtime.** An open app page holds one realtime socket (the same one pages use). A row write (UI, `app-row-*` tools, a sync pass) refreshes every query over that model on every open page within about 250 ms, with no polling needed; polling stays as the fallback. `/presence/peers` lists the other people on the same app page (`[{ id, name, avatar? }]`), `/presence/names` their names and `/presence/count` how many: `{ "type": "AvatarStack", "props": { "users": { "$state": "/presence/names" } } }`. Viewers need `app.use`. Script query results and action results are not pushed: refresh those with `OnEnter.everyMs`.

**`OnEnter`: load on open.** An `OnEnter` element renders nothing. It runs its `on.enter` chain on mount, then again each time its resolved `deps` value changes. Its steps always run to the end (no `watch` cancel). Use `deps: { "$state": "/route" }` to re-run it when the page or a route param changes; omit `deps` to run it once per mount. Put it anywhere in the page tree.

**Steps.**

- `ui.set`: `{ path, value }` writes `value` to a `/local/...` path. A literal path must name declared state; `path` may be an expression, e.g. `{ "$join": [["/local/otp", { "$index": true }], "/"] }`.
- `ui.focus`: `{ id, index? }` focuses the `Input` with that literal `id` on this page. Inside a `repeat`, `index` picks the item. A missing target is a no-op.
- `ui.when`: `{ value, eq? }` continues the chain only when `value` equals `eq` (or is truthy without `eq`); otherwise the rest of the chain is skipped quietly.

**Expressions.** An object with one operator key and an operand array, valid in any prop or action param. Operands are literals or bindings (`$state`, `$item`, `$index`, `$chain`, another expression):

| Operator | Operands | Result |
|---|---|---|
| `$add`, `$mul`, `$min`, `$max` | 1 or more numbers | sum, product, minimum, maximum |
| `$sub`, `$div` | exactly 2 numbers | difference, quotient |
| `$split` | text, separator (default `""`), optional limit | array of strings |
| `$join` | array, separator (default `""`) | text |
| `$length` | 1 value | length of a text or array (`0` for null) |
| `$eq`, `$neq` | exactly 2 values | `true`/`false`. Strict, except a number equals its numeric string (`"5"` and `5`) |
| `$not` | 1 value | `true` when the value is falsy |
| `$if` | condition, then, optional else | `then` when the condition is truthy, else `else` (or no value) |

`{ "$eq": [{ "$state": "/actions/load/status" }, "running"] }` is a busy flag for a `loading` prop. A non-numeric operand, or a division by zero, yields no value and the attribute is left out.

**Svg.** `Svg` draws in `width` x `height` user units. Shape attributes (`x`, `y`, `width`, `height`, `x1`..`y2`, `cx`, `cy`, `r`, `d`) accept expressions, so a bar is `x = 100 + (start - min) * scale`. A nested `Svg` is a group: put `repeat` on it to draw its shapes once per item. Colors are palette tokens (`chart-1`..`chart-5`, `primary`, `success`, `warning`, `error`, `info`, `muted`, `foreground`, `background`, `border`, `none`). The validator rejects unknown attributes, raw colors, a `Path.d` with anything but path commands and numbers, shapes outside an Svg, and non-shape Svg children.

### Example: Load on enter

The page loads its data on open and when the `traceId` param changes, runs two actions in a row, and shows a spinner while the first one runs. The edit form is prefilled from the loaded row.

```json
{
  "models": {},
  "defaultPage": "trace",
  "actions": {
    "traceDetail": { "kind": "task", "prompt": "Load the trace" },
    "traceLogs": { "kind": "task", "prompt": "Load its logs" }
  },
  "pages": {
    "trace": {
      "title": "Trace",
      "params": { "traceId": { "kind": "string" } },
      "root": "main",
      "elements": {
        "main": { "type": "Stack", "props": { "direction": "column" }, "children": ["enter", "busy", "edit"] },
        "enter": {
          "type": "OnEnter",
          "props": { "deps": { "$state": "/route" } },
          "on": {
            "enter": [
              { "action": "app.action", "params": { "name": "traceDetail", "input": { "traceId": { "$state": "/route/params/traceId" } } } },
              { "action": "app.action", "params": { "name": "traceLogs", "input": { "traceId": { "$state": "/route/params/traceId" } } } }
            ]
          }
        },
        "busy": {
          "type": "Text",
          "props": { "content": { "$if": [{ "$eq": [{ "$state": "/actions/traceDetail/status" }, "running"] }, "Loading…", "Loaded"] } }
        },
        "edit": {
          "type": "Form",
          "props": {
            "id": "note",
            "fields": [{ "name": "traceId", "label": "Trace id" }],
            "initialValues": { "traceId": { "$state": "/route/params/traceId" } },
            "resetKey": { "$state": "/route/params/traceId" },
            "onSubmit": []
          }
        }
      }
    }
  }
}
```

### Example: Shared window and action-fed chart

Every page follows `/app/window`. The chart reads a script action's result, so it can draw any window; it reloads when the window changes and every 30 s.

```json
{
  "models": {},
  "defaultPage": "overview",
  "state": { "window": "1h" },
  "actions": { "red": { "kind": "task", "prompt": "Replace with a script action that returns { rows: [{ t, p95 }] }" } },
  "pages": {
    "overview": {
      "title": "Overview",
      "root": "main",
      "elements": {
        "main": { "type": "Stack", "props": { "direction": "column" }, "children": ["window", "load", "chart"] },
        "window": {
          "type": "Tabs",
          "props": { "id": "w", "tabs": [{ "key": "1h", "label": "1h" }, { "key": "24h", "label": "24h" }] },
          "watch": { "/ui/w/tab": [{ "action": "ui.set", "params": { "path": "/app/window", "value": { "$state": "/ui/w/tab" } } }] }
        },
        "load": {
          "type": "OnEnter",
          "props": { "deps": { "$state": "/app/window" }, "everyMs": 30000 },
          "on": { "enter": [{ "action": "app.action", "params": { "name": "red", "input": { "window": { "$state": "/app/window" } } } }] }
        },
        "chart": {
          "type": "Chart",
          "props": {
            "kind": "line",
            "x": "t",
            "xType": "time",
            "series": [{ "key": "p95", "label": "p95 ms" }],
            "data": { "$state": "/actions/red/result/rows" },
            "loading": { "$eq": [{ "$state": "/actions/red/status" }, "running"] }
          }
        }
      }
    }
  }
}
```

### Example: 6-cell code input

Typing advances to the next cell, Backspace clears the cell and moves back, pasting a 6-character code fills every cell, and the `watch` submits once all 6 are filled. Replace the `ui.toast` step with an `app.action` to verify the code server-side.

```json
{
  "models": {},
  "defaultPage": "verify",
  "pages": {
    "verify": {
      "title": "Verify",
      "state": { "otp": ["", "", "", "", "", ""], "code": "" },
      "root": "root",
      "elements": {
        "root": {
          "type": "Stack",
          "props": { "gap": "md", "padding": "md" },
          "children": ["heading", "cells", "submitted"],
          "watch": {
            "/local/otp": [
              { "action": "ui.when", "params": { "value": { "$length": [{ "$join": [{ "$state": "/local/otp" }, ""] }] }, "eq": 6 } },
              { "action": "ui.toast", "params": { "message": "Code submitted", "tone": "success" } },
              { "action": "ui.set", "params": { "path": "/local/code", "value": { "$join": [{ "$state": "/local/otp" }, ""] } } }
            ]
          }
        },
        "heading": { "type": "Heading", "props": { "text": "Enter the 6-digit code", "level": "h2" } },
        "cells": {
          "type": "Stack",
          "props": { "direction": "row", "gap": "sm" },
          "repeat": { "statePath": "/local/otp" },
          "children": ["cell"]
        },
        "cell": {
          "type": "Input",
          "props": {
            "id": "otp",
            "value": { "$bindItem": "" },
            "size": "cell",
            "maxLength": 1,
            "inputMode": "numeric",
            "autoComplete": "one-time-code",
            "selectOnFocus": true,
            "onInput": [
              { "action": "ui.when", "params": { "value": { "$length": [{ "$chain": "value" }] }, "eq": 1 } },
              { "action": "ui.focus", "params": { "id": "otp", "index": { "$min": [{ "$add": [{ "$index": true }, 1] }, 5] } } }
            ],
            "onKeyDown:Backspace": [
              { "action": "ui.set", "params": { "path": { "$join": [["/local/otp", { "$index": true }], "/"] }, "value": "" } },
              { "action": "ui.focus", "params": { "id": "otp", "index": { "$max": [{ "$sub": [{ "$index": true }, 1] }, 0] } } }
            ],
            "onPaste": [
              { "action": "ui.when", "params": { "value": { "$length": [{ "$chain": "text" }] }, "eq": 6 } },
              { "action": "ui.set", "params": { "path": "/local/otp", "value": { "$split": [{ "$chain": "text" }, ""] } } },
              { "action": "ui.focus", "params": { "id": "otp", "index": 5 } }
            ]
          }
        },
        "submitted": {
          "type": "Text",
          "props": { "content": { "$state": "/local/code" }, "tone": "muted" },
          "visible": { "$state": "/local/code" }
        }
      }
    }
  }
}
```

### Example: Gantt timeline

Each task is a bar at `x = 100 + (start - min) * scale`, `width = days * scale`, one row per item of a repeated list; the dashed line marks day 12. Bind `repeat.statePath` to `/queries/<q>/data` to draw rows from a query instead.

```json
{
  "models": {},
  "defaultPage": "plan",
  "pages": {
    "plan": {
      "title": "Plan",
      "state": {
        "axis": { "min": 3, "scale": 24 },
        "tasks": [
          { "name": "Research", "start": 3, "days": 4 },
          { "name": "Design", "start": 6, "days": 5 },
          { "name": "Build", "start": 10, "days": 8 },
          { "name": "QA", "start": 16, "days": 4 },
          { "name": "Launch", "start": 20, "days": 2 }
        ]
      },
      "root": "card",
      "elements": {
        "card": { "type": "Card", "props": { "title": "Launch plan", "description": "Days 3-22" }, "children": ["chart"] },
        "chart": {
          "type": "Svg",
          "props": { "width": 640, "height": 200, "label": "Gantt chart of the launch plan" },
          "children": ["axis", "today", "rows"]
        },
        "axis": { "type": "Line", "props": { "x1": 100, "y1": 190, "x2": 632, "y2": 190, "stroke": "border" } },
        "today": {
          "type": "Line",
          "props": {
            "x1": { "$add": [100, { "$mul": [{ "$sub": [12, { "$state": "/local/axis/min" }] }, { "$state": "/local/axis/scale" }] }] },
            "y1": 8,
            "x2": { "$add": [100, { "$mul": [{ "$sub": [12, { "$state": "/local/axis/min" }] }, { "$state": "/local/axis/scale" }] }] },
            "y2": 190,
            "stroke": "error",
            "dashed": true
          }
        },
        "rows": { "type": "Svg", "props": {}, "repeat": { "statePath": "/local/tasks" }, "children": ["label", "bar"] },
        "label": {
          "type": "SvgText",
          "props": {
            "x": 0,
            "y": { "$add": [26, { "$mul": [{ "$index": true }, 34] }] },
            "text": { "$item": "name" },
            "size": 13
          }
        },
        "bar": {
          "type": "Rect",
          "props": {
            "x": { "$add": [100, { "$mul": [{ "$sub": [{ "$item": "start" }, { "$state": "/local/axis/min" }] }, { "$state": "/local/axis/scale" }] }] },
            "y": { "$add": [14, { "$mul": [{ "$index": true }, 34] }] },
            "width": { "$mul": [{ "$item": "days" }, { "$state": "/local/axis/scale" }] },
            "height": 24,
            "rx": 4,
            "fill": "chart-2",
            "title": { "$item": "name" }
          }
        }
      }
    }
  }
}
```

## Patch semantics

`app-patch.definition` is RFC 7396 JSON Merge Patch applied to the stored definition:

- omitted keys stay unchanged;
- object keys merge recursively;
- arrays and scalar values replace;
- `null` deletes a key;
- reusable-element disambiguation: a patch value for `elements.<name>` containing ONLY the `elements` key merges node-by-node; any other key present (`mode`, `root`, `props`, or `export`) makes it a full element replace — restate every field you want kept. In that node-by-node form, `elements.<name>.elements.<id>: null` deletes one node. Literal null nodes are rejected in a full element replace so they cannot be mistaken for deletions.
- otherwise every supplied `pages.<page>.elements.<id>`, `pages.<page>.params.<param>`, `actions.<name>`, `models.<name>.columns.<col>`, and `models.<name>.sources.<src>` value is atomic and replaces that complete declaration; `null` deletes it (deleting a source detaches its rows — see the source lifecycle above).

`pages.<page>: null` deletes a page, except the current `defaultPage` cannot be deleted. `root`, `title`, and top-level `defaultPage` use ordinary merge semantics. A top-level `page` patch is rejected with guidance to patch `pages.<name>` instead.

Because elements, param declarations, actions, and columns are atomic, include the complete desired object when changing one. For example, changing only a Table's `emptyMessage` with a merge patch requires sending its full `{ "type": "Table", "props": ... }` element; `app-patch-node { page, nodeId, props: { emptyMessage } }` or one `ops` entry (`{ "op": "replace", "path": "/pages/main/elements/table/props/emptyMessage", "value": "..." }`) changes just that prop. A `test` op makes the patch conditional: when it fails, nothing is stored and the issue names `ops[<i>]`. The merged result is validated as a whole; on failure, read `issues[]`, correct the paths, and retry without assuming anything was written.

```json
{
  "appId": "<app-id>",
  "description": null,
  "definition": {
    "models": {
      "idea": {
        "columns": {
          "priority": { "kind": "enum", "enum": ["low", "high"], "default": "low" }
        }
      }
    },
    "queries": { "openIdeas": null },
    "pages": {
      "main": {
        "elements": {
          "title": { "type": "Heading", "props": { "text": "Prioritized ideas", "level": "h1" } }
        }
      }
    }
  }
}
```

## Worked example: ideas tracker

Create this with `app-upsert`:

```json
{
  "name": "Ideas Tracker",
  "description": "Collect and manage product ideas",
  "definition": {
    "models": {
      "idea": {
        "columns": {
          "title": { "kind": "string", "required": true },
          "status": { "kind": "enum", "enum": ["open", "done"], "default": "open" }
        }
      }
    },
    "queries": {
      "allIdeas": { "model": "idea", "sort": { "column": "createdAt", "dir": "desc" } }
    },
    "actions": {
      "triage": { "kind": "task", "prompt": "Review current ideas and recommend the next one to pursue" }
    },
    "pages": {
      "main": {
        "root": "root",
        "elements": {
          "root": {
            "type": "Container",
            "props": { "direction": "column", "gap": "lg" },
            "children": ["heading", "formCard", "ideasCard", "triage"]
          },
          "heading": { "type": "Heading", "props": { "text": "Ideas", "level": "h1" } },
          "formCard": {
            "type": "Card",
            "props": { "title": "Add an idea" },
            "children": ["ideaForm"]
          },
          "ideaForm": {
            "type": "Form",
            "props": {
              "id": "newIdea",
              "fields": [{ "name": "title", "label": "Title", "required": true }],
              "submitLabel": "Add",
              "onSubmit": [{
                "action": "app.mutate",
                "params": { "model": "idea", "op": "create", "values": { "$form": "" } }
              }]
            }
          },
          "ideasCard": {
            "type": "Card",
            "props": { "title": "All ideas" },
            "children": ["ideasTable"]
          },
          "ideasTable": {
            "type": "Table",
            "props": {
              "data": { "$state": "/queries/allIdeas/data" },
              "loading": { "$state": "/queries/allIdeas/loading" },
              "error": { "$state": "/queries/allIdeas/error" },
              "columns": [
                { "key": "title", "label": "Title" },
                { "key": "status", "label": "Status", "kind": "badge", "tones": { "open": "info", "done": "success" } }
              ],
              "rowActions": [{
                "label": "Delete",
                "variant": "destructive-outline",
                "actions": [{ "action": "app.mutate", "params": { "model": "idea", "op": "delete", "rowId": { "$row": "id" } } }]
              }]
            }
          },
          "triage": {
            "type": "Button",
            "props": { "label": "Ask swarm to triage", "variant": "secondary" },
            "on": { "press": [{ "action": "app.action", "params": { "name": "triage" } }] }
          }
        }
      }
    },
    "defaultPage": "main"
  }
}
```

The tool returns `{ appId, url: "/apps/<id>" }`. Open that URL to verify the live UI, then continue with the read-patch-validate loop above.

## Embed a sheet or board

`{ "type": "ObjectEmbed", "props": { "objectId": "<object id>" } }` shows a live, editable sheet or board (see the `boards-and-sheets` skill). Optional props: `height` (160-1200), `readOnly`, and for sheets `tab` and `range`. To show the same object on an HTML page instead, use the page snippet, where `${APP_URL}` is the dashboard origin:

```html
<script type="module" src="${APP_URL}/embed/v1/swarm-object.js"></script>
<swarm-object object-id="<object id>"></swarm-object>
```

## View and screenshot a live app

- An app renders at `<dashboard>/apps/<id>`. Two view modes are set by query string: `?mode=full` (full-viewport overlay with a slim header) and `?mode=chromeless` (only the rendered page, the embed surface). `app.navigate` keeps only `?mode`.
- Logged-in browser: run `agent-swarm ui-dev --app <id>` in the background and wait for its `UI_DEV_READY {json}` line. It needs no repo checkout; when you change dashboard code, `bun run ui:dev --app <id>` from an agent-swarm checkout does the same with hot reload. Open its `url` with agent-browser, Playwright or qa-use: the dashboard is already connected as a fixed user, with no /setup redirect and no "Who are you?" dialog. It acts with your swarm key, so in prod do not click actions or submit forms unless the task asks. Do not seed localStorage or write a one-off browser script. Runbook: `runbooks/app-and-page-dev.md`.
- Apps scroll inside an inner canvas, so a full-page screenshot captures only the viewport. Scroll the canvas or raise the viewport height. For mobile, set a 375px-wide viewport before the screenshot.
- App definitions: `GET /api/apps` and `GET /api/apps/<id>` with the API key as Bearer.
- Follow-up edit to a live app: list in the brief the control numbers the edit must not move, and assert them from the backing script before publishing. Take a signed-in screenshot of each changed selector at 1440px wide, save the shots to agent-fs, critique, and repeat at least 3 times. If the backing script caches results, bump its version or force a fresh run so the shots show new data.


### Rows from agents and scripts

Every row tool requires `appId` and `model`. Scripts use underscore names, such as `ctx.swarm.app_row_create` and `ctx.swarm.app_rows_list`.
Results use the usual `data` wrapper, so scripts read `res?.data ?? res`. Rows contain system fields and declared columns at the top level.
Writes record `agent:<agentId>` in `createdBy` and `updatedBy`. Source projections and join keys remain read-only. Each row input must fit within 1 MiB.

`app-rows-list` accepts `equals`, `sort: "<column>:asc|desc"`, and `limit` from 1 to 1000 (default 200).
Equality filters accept declared columns and system columns. Filter values must match the column kind and use strict equality.
`app-rows-delete` requires at least one equality filter and accepts a limit from 1 to 1000 (default 1000).

`app-action-run` returns the REST action body under `data`. Script actions run with the script owner's identity and receive the verified invoking agent as `caller`.
Scripts and extensions cannot invoke `app-action-run`.

#### Async refresh: wait on the run, not on rows

A script or task action returns `run: { id, state, settled, runs, failures?, next? }`. For a script action, the run tree is the action's own run plus every run its script launched with `ctx.swarm.script_launchRun` or called with `ctx.swarm.script_run`. The tree settles when none of them is running; `state` is `failed` when any of them failed, and `failures` names the first three. Runs that a launched background run starts itself are not in the tree: keep them nested (`script_run`) so the background run stays running until they finish, and let it fail when they fail.

- Launch background work from the action script itself, before it returns, so the launched run joins the tree.
- Wait with `app-action-run { waitSeconds: 25 }`. While `run.settled` is false, call `app-action-status { appId, runId: run.id, waitSeconds: 25 }` (REST: `GET /api/apps/<id>/action-runs/<runId>?waitSeconds=25`).
- Never write sleep loops against a progress `meta` row: the run tree is the done signal.

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.