# closedui: the chat agent's UI tongue

> **Status (1.0 HTML lane):** the old line-command grammar tabled below is retired — agents now write plain HTML with closedui classes (`HTML_LANE_DOC` + the kit SKILL.md); this page is kept as the historical grammar record. The living law for interactive posts is the **marriage law** — one interaction per section, each plate its section's climax, honesty always (see the kit SKILL.md and `docs/posting.md`).

The chat agent answers in two tongues: plain markdown, and **closedui** —
fenced ` ```closedui ` blocks of line commands the server renders into
the radar's own components when the reply lands. The agent never writes
HTML. There is no sanitizer to trick: the parser builds every tag from
escaped primitives, and a malformed block can at worst render as escaped
plain text.

## The grammar

One command per line; `|` separates fields. Unknown lines are skipped.

| command | shape | renders as |
|---|---|---|
| `hero <kicker> \| <title> \| <sub>` | a missing title draws nothing (never a bare strap) | a display-size headline band — the opener of a composed page |
| `row` … `end` / `grid` … `end` | layout containers: children lay side by side (wrap) / as an even card grid; nest to depth 3; hold stats, links, cards, bars, lists | composed dashboards, not paragraphs |
| `card <title> \| <tone>` … `end` | wraps following nodes; tone: ok · info · warn · err stripes the top | a boxed section |
| `stat <label> \| <value> \| <n,n,n> \| <tone>` | consecutive = one row | a stat plate; spark in field 3, tone in field 4 (tints the value); a value starting `+`/`-` shows a delta |
| `badge <text> \| <tone>` | tones: ok · info · warn · err | a tone chip |
| `kv <key> \| <value>` | consecutive = one plate | a key/value plate |
| `link <title> \| <url> \| <note> \| <badge> \| <img>` | consecutive = one grid; the 5th field is a `/media/…` photo (shape-gated, lazy) | a link card — the default way to list items, hubs, sources |
| `table sort` + `cols <a \| b>` + `row <x \| y>` | inside a table, `row` is a table row — the layout container never steals it | a data table; numeric cells right-align; `sort` = the reader clicks headers (trusted-engine JS, presentation-only) |
| `bars` + `bar <label> \| <0-100> \| <sub-label>` | values clamped | a ranked bar list with sub-labels |
| `chart <title> \| <n,n,n>` | the ONLY series allowed is one the context carries | a big trend line with a filled area (gradient) over an honest axis: 4 gridlines + a min/mid/max scale |
| `chart <title>` + `series <name> \| <n,n,n>` + `labels <l1,l2,…>` + `end` | up to 4 series on ONE shared scale; labels render only when their count equals the series length | a multi-line chart with a legend, per-point dots and an x-axis — comparisons, honest |
| `parts <title>` + `part <label> \| <n>` + … | 2–8 parts, zeros dropped; shows raw value + share % + total | a share-of-whole stacked bar |
| `callout <text> \| <tone>` | | a highlighted note; links ride |
| `progress <label> \| <0-100> \| <note>` | clamped | a labeled progress bar |
| `tabs` + `tab <label>` … `end` per tab | up to 6 tabs | tabbed sections — the trusted engine builds the tabbar; WITHOUT JS the sections stack with headings (the degrade is the contract) |
| `more <title>` … `end` | | a collapsed detail (native `<details>`, zero JS) |
| `list` + `item <text>` | | a list; `[label](url)` links render |
| `steps` + `step <text> \| <when> \| <done\|current\|todo>` | | a timeline with time markers + state dots |
| `ask <question>` | max 4 | a suggested follow-up button |
| `choice <question>` + `opt <text>` one per line | up to 6 opts, consecutive = one form | ask-back chips — the reader's pick returns as their next message |
| `input <label> \| <placeholder>` | one line, maxlength 2000 | a typed ask-back form |

The kit-0.8 set — the chart walls compile CLIENT-side (the vendored
engine turns their grammar text into svg when the page loads; without
JS the grammar shows as text — never a fake chart), the rest render
server-side like every word above:

| command | notes | renders as |
|---|---|---|
| `sequence` + `msg <from> \| <to> \| <note> \| <dashed>` | the engine draws the arrows; a note can't fake one (escaped) | a message-exchange diagram |
| `states` + `move <from> \| <to> \| <label>` | `*` = start/end | a state-machine diagram |
| `er` + `rel <a> \| <b> \| <cardinality> \| <label>` | the cardinality carries a digit, `-` or `:` (like `1-n`) — `many` refuses | an entity-relation diagram |
| `gantt` + `task <name> \| <Nd> \| <after <name>>` | ≤12 tasks, 1–365 d; a bad duration skips its line, never the chart | a schedule bar |
| `flowmap LR` + `hop <a> \| <b>` | drop `LR` for top-down | a dependency flow |
| `radar` + `axis <label> \| <0-100>` | 3–8 axes; fewer degrades honestly to a list | a radar chart |
| `quadrant <x-label> \| <y-label>` + `pt <0-1> \| <0-1> \| <label>` | coords clamp to 0–1 | a quadranted scatter |
| `dots <rows>` + `point <label> \| <±n>` | labels may carry spaces; negatives sink | a dot wall |
| `mindmap` + `node <label> \| <depth>` | depth 0 = root; indentation IS the tree | a mind map |
| `job <name> \| <running\|done\|failed> \| <why>` | the engine reads the state; a failed job owes its why | a live-status plate |
| `tool <name> \| <state> \| <result>` | state: running · done · failed | a tool-call card |
| `meter <label> \| <0-100>` / `radial <0-100> \| <label>` | pure CSS fills (`--pct` / `--value`), no script | progress bars + rings |
| `countdown <ISO-8601> \| <label>` | one interval ticks every countdown on the page | a live countdown |
| `hover <label> \| <body> \| <url>` | the body rides in-page, revealed on hover/focus | a hovercard |
| `chip <text>` | consecutive = one chip row | a chip run |
| `avatars <AL> \| <KJ>` | initials, six max | an avatar stack |
| `tree` + `node <label> \| <depth>` | native `<details>`, zero JS | a collapsible tree |
| `timeline` / `feed` + `post <when> \| <text>` | same dress, two names | dot-and-connector lines |
| `diff` + `add <line>` / `del <line>` / `keep <line>` | | an ins/del block |
| `carousel` + `item <text>` | | a scroll strip |
| `toggles` + `opt <label> \| <on>` | the engine flips aria-pressed | press-to-flip buttons |
| `approval <name> \| <prompt>` + `opt <choice> \| <label>` | max 4; the engine locks the choices and reports them | an approval gate |
| `empty <message>` | | the honest empty |
| `mockup <caption> \| <text>` | | a terminal figure |

Impossible data renders NOTHING — a starved radar degrades to a plain
list, a skipped line never poisons its wall. Feed real numbers only.

Cells and items may carry markdown links `[label](url)` — they render as
anchors when the url passes the shape check (a site path, or http(s));
anything hostile (`javascript:`, quotes, spaces) stays escaped literal
text.

## The laws

- **urls and numbers come only from context.** The RADAR block's
  `trend:` line (cooked per day, from the db) is the only series — the
  agent never invents one, and a sparkline with fewer than two
  parseable numbers draws nothing at all.
- **the merge law.** Consecutive same-kind lines form ONE plate, opened
  on the first line, closed on the flush.
- **caps.** 6 blocks per chat reply · 16 on the landing flavor (the
  composed edition IS the page) · 120 lines per block · 8 links per
  grid · 4 asks · 6 opts per choice · 6 stats · 24 rows · 16 items ·
  24 spark points · strings capped char-safe at every field. A block
  past the cap falls back to escaped plain text — never dropped
  silently, never raw.
- **markdown keeps its place.** Prose between ui fences renders where
  it sat — a composed page interleaves headings and blocks in the
  order the writer wrote them.
- **render once.** The tongue renders when the reply lands; the stored
  turn is finished bytes.

## The ask-back loop (v5)

`choice` and `input` render native forms POSTing `/chat` aimed at the
dock (`aria-controls="chat-dock"`); every chip is a submit button
carrying its own text as `q`. No JS. The flavor decides where the
answer lands: **in chat**, the form carries hidden `thread` + `ctx` —
the pick continues the reader's thread; **on a page** (the landing
closer, an answer), it posts bare and opens the dock fresh. Either
way the pick rides the same wire as a typed message: one POST, one
cooked reply, one poll — the conversation continues without the
reader touching the keyboard.

## For machines

Same grammar, one example — "what moved today?" replies with a stat row
(the trend spark), a link grid of the latest items, and follow-up asks:

````
```closedui
stat cooked items | +94 | 12,15,9,22,31,18,26
link Baidu CEOs warn of AI hype gap | /u/baidu-warns-c32da5 | SCMP · today | hype
link DGX Spark cluster kit | /u/dgx-spark-kit-f453c3 | NVIDIA · today | hardware
ask go deeper on the hype gap
ask what should i read first?
```
````

The chat endpoint is POST /chat (form-encoded `q`, optional `thread`,
`ctx`, `trail`); polls read GET /partials/chat/{thread}. See [auth](/docs/auth)
— there is nothing to authenticate to.

## Where the tongue speaks

Every agent surface renders through the same parser: chat replies, the
`/a/` answers, item bodies, hub abouts and the weekly deep dives — and
the landing: on a baked day the day's edition IS the whole page,
composed by the landing composer in one closedui document (hero →
rundown → numbers → topics → choice closer), rendered at the landing
flavor's cap. One shared canonical example (`TONGUE_DOC`) teaches all
the prompts — the HTML lane prompt (`HTML_LANE_DOC`) is the spec the writers learn.

## Images

Item photos ride the ingest-adjacent `mrsn images` pass: it fetches each
article through an SSRF boundary (http(s) only, hosts resolving to
anything but globally-routable addresses die, every redirect hop
re-runs the guard), byte-scans `og:image` out of the head, re-fetches it
through the same boundary, sniffs the REAL type from magic bytes (the
server's word is ignored), caps at 5 MiB and stamps `og_path`. The
`/media/{name}.{ext}` route serves the dir shape-gated (lowercase
`[a-z0-9_-]`, one dot) — traversal is dead by construction. The RADAR
context carries the stamped paths; the 5th `link` field is the only way
a photo reaches a card, and a hostile one just drops the photo.

## The trusted-engine law (v4)

Tabs and table sort want a hand, and the hand is OURS: the parser emits
plain stacked sections / a static table, and mrsn-owned
`closedui-chat.js` (SRI'd in base.html, class-bound) builds the
tabbar and wires header sorts. The agent NEVER writes JS — it writes
tongue lines; the engine upgrades them. Without the script the shapes
degrade to stacked sections and a static table: nothing breaks, nothing
hides. The vendored kit bytes (`ui.css`, `ui.js`) stay pinned — this
lane is mrsn's own. The engine also silences a DEAD poll: a serve
restart clears in-memory chat threads, so a poll for a gone thread
bakes a `.chatdead` note (200, never a 404 the kit's poll loop would
swallow) and the engine stops that thread's stale 15s loop.

The dock answers in TWO postures. On the stream lane (the dock's own
`[data-stream="raw"]` region — the kit's native answer stream) the
send POSTs with `Accept: text/event-stream` and the reply rides back
as frames: a status line (what the reply is reading), the raw text
deltas painted live, `done` — then ONE bake refresh swaps the rendered
reply in over the raw draft. The reader's own message lands optimistically
at submit (textContent — data, never markup); the chips pour their ask
into the input and fire one submit, because the stream lane serializes
`FormData(form)` alone and a submitter's `name=value` never rides it.
On the pjax lane (an askbar POST opened the dock; the cook has no
stream view) the typing bubble carries `data-cook` — NEVER
`data-stream`, the kit's engine would arm it and bind the poll form —
and the engine polls the progress endpoint every second, ticking the
count OVER the stream (the raw text never renders); when the cook
lands, one FRESH poll submit bakes the full reply. The poll form
carries `no-cache` (the kit's GET cache would repaint the stale cooking
fragment forever — a done submit that never lands) and `chatpoll`
instead of `poll` (the kit's 15s loop stacks an interval per swap); the
engine's own slow fallback covers a dead progress lane. Page links also
swap in place: any internal link (a dock reply, the ticker, a crumb)
fetches its target and swaps `<main id=main>`'s content — title,
history and the thread's ctx ride along — while the shell (one header,
one ticker) never duplicates. The engine intercepts in the CAPTURE
phase so the kit's own region-scoped anchor swap (the dock carries
`role=region`) never replaces a region with a whole fetched page;
external links open a new tab, machine lanes (`/partials/`, `/static/`,
xml/txt/json/md) and hash jumps keep native behaviour, and a fetch miss
falls back to normal navigation. `popstate` swaps too, so back returns
the page the url names.

## The front page (v8)

The daily broadcast composes the LANDING, and the landing IS the
broadcast — TWO bands only, in fixed order, the page ends at the
rundown; nothing renders under the edition (no river, no listing):

1. `hero` — the lead: kicker, the day's biggest signal as a headline,
   one sourced clause, and a photo (the lead row's own, or borrowed
   from the highest-scored photo'd row — the engine finishes the borrow
   when the composer skips it: `digest::with_hero_photo`).
2. `rank` lines — the rundown: at most FIVE, the day's essential
   stories, consecutive lines rendering as one ruled index; the row is
   a DIV, only the TITLE carries the anchor (a note's md link must
   never nest an anchor), and the paint numbers the rows (CSS counter,
   decimal-leading-zero) — the engine emits no ordinals. Every link is
   a REAL source url: an https://… the composer's one web pass actually
   surfaced, or the carried row's own url — never a /u/ path (the
   compose context carries each row's url, not its /u/ path).

The `pull` band, the folio line and the raw-news surface are all gone
(v8): no pull-line, no `no. day · composed by · the mine` signature,
no kindpills, no statplates, no sweepband, no leadplate, no
trendstrip, no hub grid, and no news river — the feed ends ONCE, at
the rundown, and the site-wide askbar below it IS the one ask-back;
the composer writes no closer. On a not-yet-baked day the landing is
the honest line alone (the lede + a composing notice; the agent off
means no line at all) — never a half edition (ready-before-switch).

Chat furniture never lands: `grid`, `link`, `card`, `row`, `table`,
`tabs`, `list`, `stat`, `chart`, `ink`, `choice` and `pull` are the
CHAT grammar; the composer's prompt bans them for the landing, and the
output gate (`digest::front_ok`) enforces the shape structurally — a
dirty draft (one recompose with a rejection notice, then serve-anyway
with a loud journal) never leaves the front unleadable. Cells carry
`**bold**` → `<strong>` (`strongify`, escaped first, an odd marker
count stays literal). The diet law is 80-120 words; the composer's
context carries the day's top rows with url + photo hints and nothing
it may invent. The /u/ deep read is baked-only (v8): a composed section
rides its page with cited sources, but a visit never arms a cook — no
pulse, no check-now plate; the `i` fragment lane and the deep-read
composer are gone (the ask flow's own cook lanes are untouched).

## Composed pages (v9)

A composed page is ONE document in three tongues, and the /u/ page IS
the composition when a bake exists (title + lede stay header chrome;
the deep-read section stands down — it would double-render the same
story):

1. **markdown prose** — the spine. Comrak renders it (raw HTML
   escaped); headings, lists, links, emphasis all ride.
2. **```closedui fences** — the FULL grammar above at page scale.
   The chat cap (6 blocks) lifts to a page-scale fuse (128): it is a
   runaway guard for a looping model, not a portion size. Every
   command is legal here, `hero` and `pull` included.
3. **```html fences** — the bespoke layout tongue: free HTML5 +
   inline SVG + one scoped `<style>` per fence, through the sanitize
   gate (`core/sanitize.rs`). The gate is structural: scripts, event
   handlers, style attributes, non-site links and non-`/media/`
   images die by construction; the CSS scanner REJECTS `url()`,
   `@import`, `position:fixed` and friends — a dirty draft is refused
   whole and the writer recomposes, never serves. The chat law
   "NEVER write raw HTML" applies to chat; in a composed page raw
   HTML rides only inside ```html fences.

The same document is the same grammar for every writer: the owner
bakes by hand (`just compose <slug> <file>`), the fleet bakes through
`mrsn compose <slug> --agent` (the compose pass carries COMPOSE_SYS +
the tongue doc; three unbaked items per `mrsn agent` run). The bake
stores the finished bytes (`composed` DATA table, one row per item,
rebake replaces) and the document — the rebuild truth. Serving never
re-parses. `mrsn agent` composes now, so every agent-written post
lands as a composed page; `mrsn compose --agent` upgrades a single
item on demand.
