# Open App Definition: the authoring guide and the specification 0.2 > Open App Definition is an open format that describes a whole app as one JSON file. You ask an AI assistant for an app in plain words, the assistant writes the file, and a host runs it: in a browser, inside a chat, or as tools that an AI agent can call. This file holds, in this order, the authoring guide (every topic, then its example apps) and every chapter of the specification 0.2, as they stand in the project's repository, then the list of the repository's example apps. --- # Writing your first app An Open App Definition (OAD) app is one JSON document, its definition. It names the values the app keeps (state), the things it can do (actions), what happens on its own (rules and flows), what it needs from outside (capabilities) and the permissions it asks for (grants). Screens and agents are views of the same app: a screen shows state and runs actions, and an agent calls the same actions as tools. A host loads the definition, asks a person for the permissions, keeps the state and runs the app. Logic is short expressions inside the JSON, never a program. ## The smallest app This app counts glasses of water. It is complete: it passes `oad validate` and runs. ```json example=water { "oad": "0.2", "id": "com.example.water", "version": "1.0.0", "meta": { "name": "Water today", "description": "Counts the glasses of water you drink today against a daily goal." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "state": { "goal": { "type": "integer", "initial": 8, "description": "Glasses to drink each day." }, "glasses": { "type": "integer", "initial": 0, "description": "Glasses drunk on the day in countedOn." }, "countedOn": { "type": "date", "initial": "=env.today", "description": "The day the count belongs to." }, "today": { "type": "integer", "derive": "state.countedOn == env.today ? state.glasses : 0", "description": "Glasses drunk today." } }, "actions": { "drink": { "description": "Count one more glass of water today.", "steps": [ { "set": "state.glasses", "to": "=state.today + 1" }, { "set": "state.countedOn", "to": "=env.today" } ] } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "Water today", "body": { "control": "core:stack", "children": [ { "control": "core:progress", "props": { "label": "Glasses today", "value": "=state.today", "max": "=state.goal" } }, { "control": "core:text", "props": { "value": "=`${state.today} of ${state.goal} glasses`" } }, { "control": "core:button", "props": { "label": "I drank a glass", "emphasis": "high" }, "on": { "press": { "run": "drink" } } } ] } } } } } } ``` What each part does: - `oad` (`"0.2"`), `id` (reverse-DNS, lowercase, two segments or more), `version` and `meta` (with `name` and `description`) are required. - `uses` names the core catalog under the alias `core`, which every `core:` name needs. - `state` holds the values: `goal`, `glasses` and `countedOn` are stored and start at their `initial`; `today` is derived, worked out again when what it reads changes. - `actions` holds what the app can do: `drink` has a `description` (required) and `steps` that write state. - `surfaces.visual` is the screen: `start` names the first view, whose `body` is a tree of nodes, each a `control` with `props`. The button's `on.press` runs the action. An app with one view and no `navigation`, like this one, is drawn as one card headed by the view's `title`, with no app bar; any other app is a page (see `views`). **The `=` rule.** In a prop, a step's `to`, a `with` or an `initial`, a string that starts with `=` is an expression and any other string is text: `"=state.today"` is a number, `"state.today"` is the words "state.today". Fields that are always expressions (`derive`, `when`, `if`, `allow`, `where`, `becomes`, a `require` entry's `that`) take no `=`. An input field's `default` is neither: a plain value, never an expression. ## A list you can add to and change Most apps keep a list. This one is a shopping list a household shares: add a thing, tick it off, take it off. ```json example=groceries { "oad": "0.2", "id": "com.example.groceries", "version": "1.0.0", "meta": { "name": "Groceries", "description": "A shopping list the whole household shares: add what to buy, tick it off, take it off." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "types": { "Item": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "bought": { "type": "boolean" } }, "required": ["id", "name", "bought"], "additionalProperties": false } }, "state": { "items": { "type": "Item[]", "initial": [], "scope": "shared", "conflict": "merge", "key": "id", "description": "Everything on the household's list, bought or not." }, "bought": { "type": "integer", "derive": "state.items.count(i, i.bought)", "description": "How many things are ticked off." } }, "actions": { "addItem": { "description": "Put something on the shopping list.", "input": { "name": { "type": "string", "description": "What to buy, such as milk." } }, "require": [ { "that": "size(trim(input.name)) > 0", "message": "Say what to buy." } ], "steps": [ { "append": "state.items", "value": { "id": "=uuid()", "name": "=trim(input.name)", "bought": false } } ] }, "tick": { "description": "Tick something off as bought, or untick it.", "input": { "id": { "type": "string", "description": "Which item, by its id." } }, "steps": [ { "patch": "state.items", "where": "item.id == input.id", "with": { "bought": "=!item.bought" } } ] }, "removeItem": { "description": "Take something off the list.", "input": { "id": { "type": "string", "description": "Which item, by its id." } }, "confirm": { "message": "=`${state.items.find(i, i.id == input.id).name} is taken off the list for everyone.`" }, "steps": [ { "remove": "state.items", "where": "item.id == input.id" } ] }, "clearBought": { "description": "Take everything ticked off the list, after a shop.", "confirm": { "message": "=`Everything ticked off (${state.bought}) is taken off the list for everyone.`" }, "steps": [ { "remove": "state.items", "where": "item.bought" } ] } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "Groceries", "state": { "name": { "type": "string?", "description": "What is being typed." } }, "body": { "control": "core:stack", "children": [ { "control": "core:form", "props": { "submitLabel": "Add" }, "on": { "submit": [ { "run": "addItem", "with": { "name": "=default(view.name, '')" } }, { "set": "view.name", "to": null } ] }, "children": [ { "control": "core:textInput", "props": { "label": "Add to the list", "required": true }, "bind": { "value": "view.name" } } ] }, { "control": "core:list", "props": { "label": "Shopping list", "items": "=state.items", "empty": "The list is empty." }, "slots": { "item": { "control": "core:stack", "props": { "direction": "horizontal" }, "children": [ { "control": "core:text", "props": { "value": "=item.bought ? `${item.name} (bought)` : item.name" } }, { "control": "core:button", "props": { "label": "=item.bought ? 'Undo' : 'Bought'", "icon": "check" }, "on": { "press": { "run": "tick", "with": { "id": "=item.id" } } } }, { "control": "core:button", "props": { "label": "Remove", "destructive": true, "emphasis": "low" }, "on": { "press": { "run": "removeItem", "with": { "id": "=item.id" } } } } ] } } }, { "control": "core:button", "when": "state.bought > 0", "props": { "label": "Clear ticked off", "emphasis": "low" }, "on": { "press": { "run": "clearBought" } } } ] } } } } } } ``` What is new here: - `types` declares a record, `Item`; `state.items` is a list of them, `Item[]`. With `"additionalProperties": false` the check reports a misspelt field. - `"scope": "shared"` makes one list for everyone, and `conflict` with `key` keeps both of two things added at once. Without the three, each person keeps a list of their own. - `addItem` reads `input.name`; its `require` refuses an empty name, in words the person reads. `uuid()` gives the record an id. - `patch` and `remove` change every element for which `where` is true, with `item` the element: `tick` changes one row, `clearBought` removes all those ticked off. - `removeItem` asks first (`confirm`), in words that name the item, since a question is read on its own. The words may read the `input` and any state. - What is typed lives in view state, `view.name`: `bind` ties the input to it, `required` keeps the form from sending it empty, and `submit` runs the action, then clears it. - A `core:list` draws its `item` slot for each element of `items`, with `item` that element. A button in a row keeps a short label, since the row says which item it is for, and passes `item.id` to its action. ## Fields of a record A record type under `types` is JSON Schema, field by field. Everywhere else a `type` (of a state entry, an input field, a view's input or state) is a short name such as `date`, `string?` or `Item[]`, and the two do not mix: `{ "type": "date" }` inside a record is `schema.invalid`. A number, an enum, a date, a field that may be `null` (still in `required`), a list of dates and a list of other records: ```json quiet=groceries#/types/Chore { "type": "object", "properties": { "id": { "type": "string" }, "minutes": { "type": "number", "minimum": 0 }, "size": { "type": "string", "enum": ["small", "big"] }, "due": { "type": "string", "format": "date" }, "doneAt": { "type": ["string", "null"], "format": "date-time" }, "doneOn": { "type": "array", "items": { "type": "string", "format": "date" } }, "needs": { "type": "array", "items": { "$ref": "#/types/Item" } } }, "required": ["id", "minutes", "size", "due", "doneAt", "doneOn", "needs"], "additionalProperties": false } ``` A derived entry's `type` is a short name too, such as `Item?` or `string[]` (see `state`). ## Controls The controls a first app uses most; `controls` has every prop of each. | Control | Must be given | Often given | Raises | | --- | --- | --- | --- | | `core:stack` | nothing | `children`, `direction`, `gap` | | | `core:text` | `value` | `style` | | | `core:button` | `label` | `emphasis`, `icon`, `destructive` | `press` | | `core:form` | nothing | `children`, `submitLabel`, `cancelLabel` | `submit`, `cancel` | | `core:textInput` | `label` | `value` (bindable), `required`, `multiline` | `change` (`event.value`) | | `core:numberInput` | `label` | `value` (bindable), `min`, `max` | `change` (`event.value`) | | `core:dateInput` | `label` | `value` (bindable), `mode`, `min` | `change` (`event.value`) | | `core:choice` | `options`, `label` | `value` (bindable), `required` | `change` (`event.value`) | | `core:toggle` | `label` | `value` (bindable) | `change` (`event.value`) | | `core:list` | `items`, slot `item` | `itemKey`, `empty` | `select` (`event.item`, `event.index`), `move` | | `core:table` | `items`, `columns`, `label` | `itemKey`, `empty` | `select` (`event.item`, `event.index`, `event.selected`), `sort`, `page` | | `core:chart` | `kind`, `items`, `category`, `series`, `label` | `format` | `select` (`event.item`, `event.series`, `event.selected`) | | `core:stat` | `label`, `value` | `format` | | | `core:badge` | `label` | `tone` | | | `core:alert` | `title` | `message`, `tone` | `dismiss` | - `core:choice`: `options` are maps with `value` and `label`, such as `state.items.map(i, {value: i.id, label: i.name})`; the bound value is the picked `value`. - `core:dateInput` gives `YYYY-MM-DD` (mode `date`), a UTC datetime such as `2026-11-24T09:00:00Z` (`datetime`) or `HH:MM` on a 24-hour clock (`time`). - A `core:list` draws its slot for each element, a few words and buttons; a `core:table` shows `columns`, sorts and pages, and picking a row raises `select` with `event.item`, to open it in a view of its own (see `views`). Both tell elements apart by `itemKey`: `id` unless you name another field. - In a `core:chart`, `category` and each series' `field` name fields of the elements of `items`; they are not labels. - Money: `"format": "currency"` on a `core:stat`, a table column or a `core:numberInput`; in text, `formatNumber(12.5, {style: 'currency'})`. Each uses the person's currency when the host knows it, a plain number when not (see `controls`). ## Working with lists | Expression (each is `true`) | What it shows | | --- | --- | | `[3, 1, 2].filter(n, n > 1) == [3, 2]` | `filter` keeps the elements for which the body is `true`. | | `[3, 1, 2].count(n, n > 1) == 2`, `[3, 1, 2].exists(n, n > 2)` | `count` says how many pass, `exists` whether any does. | | `[3, 1, 2].find(n, n > 1) == 3`, `[3, 1, 2].find(n, n > 5) == null` | `find` gives the first that passes, or `null`. | | `[{n: 'b'}, {n: 'a'}].sortBy(x, x.n) == [{n: 'a'}, {n: 'b'}]` | `sortBy` puts the smallest key first. | | `['a', 'b'].map(s, {value: s, label: upper(s)}) == [{value: 'a', label: 'A'}, {value: 'b', label: 'B'}]` | `map` makes a new list, here of maps, such as the options of a choice. | | `default({a: 1}.b, 0) == 0`, `has({a: 1}.a)` | `default` gives its second value when the first is missing or `null`; `has` says whether a member is there. | In each macro the first argument names the element, as you choose; `expressions` has every function. ## Where to start Each example is a whole app, read by its name with the guide tool or `oad guide --example `; one close to the request is the fastest start. | Example | What it shows | Nearest start for | Read too | | --- | --- | --- | --- | | `groceries` | The list above | A list several people use | `people` | | `reading` | A table whose row opens one book, which a form changes | A list with a view for one record | `views` | | `plants` | A reminder per plant, permissions asked when needed | Reminders, or work done by itself at a time | `rules`, `capabilities` | | `timeoff` | Roles, a flow, a section for approvers | Records that move through stages and are decided by someone | `people`, `flows` | | `weather` | A web service and its sample document | Something read from the web | `capabilities`, `sample-data` | | `gift` | The app `jar` inside it as a part | An app that uses another whole app | `parts` | A time of day has no type: keep it as text `HH:MM`, as a `time` input gives it. To act at that time every day, schedule a wake whose rule schedules the next (see `rules`). A `sample-data.json` beside the definition is used without being named (see `sample-data`). ## Keys and names `meta` may also hold `icon`, `tags`, `authors` and `license`. `parts` covers the keys `parts` and `exports`; no topic covers `code` yet. Names of things (state entries, actions, views, fields) start with a lowercase letter and hold only letters and digits, such as `countedOn`: no spaces, dashes or underscores. Type names start with a capital letter. Unknown keys are an error everywhere. ## How to work Write the whole definition in one file, from the closest example. Check it and look at it with the tools you were given or, at a terminal, `oad validate`, `oad look` and `oad run`, and fix every error and warning (see `mistakes`); a new app the tools refused for its checks is kept unfinished, to mend with small patches. Look after every change; when several people use the app, look as each kind of person; when it does something by a time, move the look's clock. Change one thing at a time; `changing` shows how to edit an app in use. ## Rules of thumb - **Put logic in actions, not in views.** A handler is usually one `run`, perhaps then a `navigate`, so an agent can do the same. - **Describe, and handle what can fail.** `description` is required on actions, rules, flows and capabilities, `reason` on grant requests: the person reads them. Give a `call` that may fail an `onError` (see `actions`). ## Mistakes every newcomer makes | Mistake | What you see | Fix | | --- | --- | --- | | A prop meant as an expression without its `=`: `"value": "state.today"` | The words "state.today" on the screen, and no diagnostic | Write `"=state.today"`. | | A `=` in a field that is always an expression, such as `"derive": "=state.glasses"` | `expression.syntax` | Drop the `=`. | | Joining text and a number with `+` | `expression.typeMismatch` | Use a template: ``"=`${state.today} glasses`"``. | | A key the format does not have, or a missing `description` | `schema.invalid` | Use the keys of this guide; describe every action. | | A `core:` control with no `uses.catalogs` entry for `core` | `contract.unknown` | Add the `uses` block of the smallest app. | | A state entry that does not exist, often a typo | `reference.unknownState` | Use the name declared under `state`. | | Calling a capability with no grant request for its scope | `grant.uncovered` | Add a grant request (`capabilities`). | | Writing a shared list straight from a screen | `write.sharedDirect` | Run an action that writes it. | | Reading an optional input that was left out, such as `input.note` | `expression.error` when the action runs | Give the field a plain `default`, or read it with `default(input.note, '')`. | | An expression as an input field's `default`: `"=env.today"` | `value.typeMismatch` | Type `date?` with `"default": null`, and `default(input.day, env.today)` in the step. | | `uuid()` or `random()` in a `derive`, a guard or a prop | `expression.effectNotAllowed` | Call them in a step, and store the result. | ## Next - `state`, `expressions`, `actions`, `views`, `controls` and `mistakes` for each part in full; the table of examples names the other topics. - `languages` for an app not in English, or in several languages. --- # State State is every value the app keeps or works out. Each entry has a name, a `type` and a `description`, and is one of three kinds: | Kind | Written as | Its value | Who writes it | | --- | --- | --- | --- | | Stored | `initial`, or no kind key at all | Starts at `initial` (or `null`) and keeps what steps write | Actions, and screens through bindings | | Derived | `derive`: an expression, no `=` | Worked out again whenever what it reads changes | Nobody: it is read-only | | Sourced | `source`: a capability operation | What the operation last returned, `null` before the first read | Nobody: the host reads it | The weather example has all three: ```json example=weather#/state { "city": { "type": "string", "initial": "Lisbon", "description": "The city whose weather is shown." }, "forecast": { "type": "core:HttpResponse", "sensitive": false, "description": "The weather service's answer for the city.", "source": { "call": "weather.get", "with": { "path": "/v1/forecast", "query": { "city": "=state.city" } }, "refresh": { "every": "PT1H" } } }, "found": { "type": "boolean", "derive": "state.forecast != null && state.forecast.status == 200", "description": "Whether the service knew the city." }, "days": { "type": "Day[]", "derive": "state.found ? default(state.forecast.body.days, []) : []", "description": "The forecast for the next days." } } ``` Expressions read an entry as `state.city`. When an action sets `city`, the host reads the forecast again (its `with` changed), and `found` and `days` follow. ## Where a value lives: `scope` A stored entry has a `scope`. Choose it first: it decides who sees the value. | `scope` | One value for | Who may write it | Use it for | | --- | --- | --- | --- | | `user` (the default) | Each person, on all their devices | That person's actions and screens | A personal list, a person's settings | | `shared` | The whole app, everyone using it | Actions only, never a screen directly | A team's records, settings everyone sees | | `session` | One visit on one device; gone when it ends | Actions and screens | Something about this visit only | | `device` | Each person on each device | Actions and screens | A preference for one device | `conflict` says what happens when two people change the value at once, or a device comes back online with changes. `lastWrite` (the default) keeps the later write. `merge` with `key` matches list elements by that field, so two people adding different requests both keep theirs. `reject` refuses a write based on a value that changed meanwhile (`state.conflict`). Use `merge` with `"key": "id"` for a shared list of records. ## Types Every entry states its `type`, a derived one too (`schema.invalid` without it). A `type` is a short name, or a JSON Schema object written in place. | Type | Values | | --- | --- | | `string`, `number`, `integer`, `boolean` | As in JSON. | | `date` | A string `YYYY-MM-DD`, such as `"2026-11-13"`. | | `datetime` | A string such as `"2026-11-13T09:00:00Z"`. | | `duration` | An ISO 8601 duration string, such as `"P1D"` or `"PT30M"`. | | `any` | Anything. | | `Book` | A type declared under `types`. Type names start with a capital letter. | | `core:HttpResponse` | A type of the core catalog, through its alias. | | `Book[]`, `string?`, `Book[]?` | A list, a value that may be `null`, both (list mark first). | A derived entry's value must fit its `type`: the check reports a `derive` whose value it knows does not (`expression.typeMismatch`). Declare a record's shape under `types` and refer to it by name. Inside a record type each field is JSON Schema, not a short name: `start` shows the common fields, among them a date, a field that may be `null`, a list of dates and a list of records. A derived entry takes a short name, `?` when it may be missing and `[]` for a list: ```json quiet=groceries#/state { "items": { "type": "Item[]", "initial": [], "scope": "shared", "conflict": "merge", "key": "id", "description": "The list." }, "bought": { "type": "integer", "derive": "state.items.count(i, i.bought)", "description": "Ticked off." }, "next": { "type": "Item?", "derive": "state.items.find(i, !i.bought)", "description": "First to buy." }, "names": { "type": "string[]", "derive": "state.items.map(i, i.name)", "description": "The names." }, "toBuy": { "type": "Item[]", "derive": "state.items.filter(i, !i.bought)", "description": "Still to buy." } } ``` A short name in a record type is `schema.invalid`: ```json wrong=groceries#/types/Item/properties/addedOn expect=schema.invalid { "type": "date" } ``` Only these schema keywords are allowed: `type`, `properties`, `required`, `additionalProperties`, `items`, `minItems`, `maxItems`, `uniqueItems`, `enum`, `const`, `oneOf`, `format` (`date`, `date-time`, `duration`, `uri`), `minimum`, `maximum`, `minLength`, `maxLength`, `pattern`, `default`, `description`, `title` and `$ref`. Anything else is `schema.invalid`. Write `"additionalProperties": false` on record types. The check then knows every field, and a misspelt field in an expression is an error (`expression.unknownMember`) instead of a `null` at run time. A value that does not fit its type is refused when it is written (`state.invalidValue`). A literal that does not fit is reported by the check (`value.typeMismatch`). ## Stored entries and `initial` `initial` is the value a stored entry starts with. It is worked out once, when the app is installed, and may read only `env`: `"initial": "=env.today"` is the install day, and stays that day. (A view's own state is worked out each time the view opens, and its `initial` may read more: see `views`.) Without `initial` the entry starts as `null`, so give its type a `?`. Keep `initial` small: a definition holds no one's data, and it may be shared. ## Derived entries A derived entry is a formula. Use one for anything you can work out from other values, rather than storing a copy that can fall out of step: | `derive` | Gives | | --- | --- | | `state.books.count(b, b.status == 'toRead')` | How many books are not started. | | `state.books.filter(b, b.status == 'read').map(b, b.title)` | The titles read. | | `size(state.books) == 0 ? 'Empty' : 'Has books'` | Text that depends on the list. | - Nothing writes a derived entry: a step that tries is `state.readonly`. - Derived entries must not read each other in a circle (`state.cycle`). - A `derive` that reads `user` has one value for each person: `state.requests.filter(r, r.personId == user.person.id)` is "my requests". - A `derive` that reads `env.now` or `env.today` is worked out again as time passes: while the app is open, the host moves `env.now` on at least once a minute, and `env.today` when the day changes. - A `derive` that fails, such as one reading a member of `null`, gives `null`. Guard it with `default` or a comparison with `null`. ## Sourced entries A sourced entry reads an operation of a capability: a web service, a record collection, the directory. The operation must only read (its effect is `read`), and a grant request must cover it (see `capabilities`). - `call` names it as `.`, such as `weather.get`. - `with` is the operation's input; expressions in it are followed, and a change reads again. - `when` is an optional expression: the entry is read only while it holds. - `refresh` says when to read again: `every` (a duration) and `on` (a list of `open`, `change`, and capability events). `on` is `["open", "change"]` when left out. - `pages` (1 to 50) follows the pages of an operation that has them, such as `core:records` `list`. The value is `null` until the first read succeeds, whatever the `type` says, and a failed read keeps the last value. Guard what reads it, as `found` does above. The `body` of a `core:HttpResponse` is `any`: nothing under it is checked, so a misspelt field is not reported and reads as missing: ```json quiet=weather#/state/days/derive "state.found ? default(state.forecast.body.dayz, []) : []" ``` To have the fields checked, derive an entry of a named type from the body, as `days` is a `Day[]`: what reads `state.days` is then checked against `Day`. With `"additionalProperties": false` on `Day`, a misspelt field is reported too, but an answer whose days carry any other field no longer fits, and `days` is `null`. Keep only the declared fields, and the answer fits when the service adds one: ```json quiet=weather#/state/days/derive "state.found ? default(state.forecast.body.days, []).map(d, {date: d.date, high: d.high, low: d.low, summary: d.summary}) : []" ``` The `body` is the service's JSON as it is. A service that answers with a bare list gives a list: ```json quiet=weather#/state/days/derive "state.found ? default(state.forecast.body, []) : []" ``` `sources.` tells the screen what is going on: | Expression | Means | | --- | --- | | `sources.forecast.status == 'loading'` | A read is under way. `status` is `idle`, `loading`, `ready` or `error`. | | `sources.forecast.status == 'error'` | The last read failed. | | `default(sources.forecast.error.message, '')` | Why it failed, when it did. | | `sources.forecast.updatedAt != null` | Whether a read ever succeeded. | A source on a scope of `high` sensitivity, such as every `core:http` read, must say whether its value is `sensitive`: whether what the app keeps from the answer is private. It changes where the value may go (see below), not the permission the source needs. Without it the check warns: ```json wrong=weather#/state/forecast expect=state.sensitivityUnstated { "type": "core:HttpResponse", "description": "The weather service's answer for the city.", "source": { "call": "weather.get", "with": { "path": "/v1/forecast", "query": { "city": "=state.city" } } } } ``` ## Keeping values private - `"sensitive": true` keeps the value out of the activity log and off the agent surface (unless the agent surface names it). A derived entry that reads a sensitive one is sensitive too, unless it says `"sensitive": false`. - `"internal": true` keeps an entry off the agent surface and out of exports altogether. Use it for helpers that exist only for the screen, such as the screen title in the reading list example. ## Next - `expressions` to write `derive`, `when` and the rest. - `actions` for the steps that write stored state. - `views` for bindings that write state from a screen. - `capabilities` for what a source can read. --- # Expressions Expressions are short formulas, like a spreadsheet's: they read values and compute a new one, and they never change anything. The syntax is close to JavaScript's, but several JavaScript habits are errors here (see "Habits that break" below). ## Where the `=` goes There are two kinds of places, and the `=` is the difference: | Place | How to write it | Fields | | --- | --- | --- | | Always an expression | No `=`: `"derive": "state.goal - state.saved"` | `derive`, `allow`, `where`, `becomes`, a node's or a section's `when`, an `if` (rule, step or transition), a `require` entry's `that`, a step's `each`, a node's `each.in`, a source's `when` | | A value that may hold expressions | `=` before an expression, anything else is literal: `"value": "=state.goal"`, `"label": "Save"` | props, a view's `title`, a section's `label`, `to`, `value`, `with`, `return`, `initial`, `message`, `once`, `orElse`, `config` | In a value, objects and lists are walked, so `{ "id": "=item.id", "status": "read" }` mixes an expression and a literal. A literal text that must start with `=` is written with two: `"==x"` is the text that starts with one `=`. An input field's `default` is in neither row: it is a plain value, never an expression. ```json wrong=timeoff#/actions/askForTimeOff/input/from/default expect=value.typeMismatch "=env.today" ``` For "today when left out", let the field be `null` and read it in the step with `default`: ```json patch=reading consent=no [ { "op": "add", "path": "/actions/addBook/input/addedOn", "value": { "type": "date?", "description": "The day it went on the list; today when left out.", "default": null } }, { "op": "replace", "path": "/actions/addBook/steps/1/value/addedOn", "value": "=default(input.addedOn, env.today)" } ] ``` ## Values There are six kinds of value: `null`, booleans, numbers, strings, lists and maps (JSON objects). There is one number kind; an integer is a number with no fraction. Dates, datetimes and durations are strings (`"2026-11-13"`). Strings are written in single or double quotes; inside a JSON string, single quotes are easier: `"=state.city == 'Lisbon'"`. A template is written in backticks, with `${...}` around each expression: ``"=`${state.today} of ${state.goal} glasses`"``. A template turns any value into text; it is the way to join text and numbers. ## Operators | Expression | Gives | | --- | --- | | `state.toRead + state.finished`, `-state.toRead` | Arithmetic: `+`, `-`, `*`, `/`, `%`, and `-` before a number. `/` is exact: `7 / 2` is `3.5`. | | `state.toRead == 0 && state.finished > 0` | Comparison and logic: `==`, `!=`, `<`, `<=`, `>`, `>=`, `&&`, `\|\|`, `!`. | | `state.toRead > 0 ? 'Keep reading' : 'All done'` | Choose one of two values. | | `'read' in ['read', 'reading']` | Whether a list holds a value, or a map a key. | | `state.books[0].title` | A list element (from 0) and a member. | | `{id: 'a', count: state.toRead}` | A map; a bare key is the key's name. | | `{toRead: 'To read', reading: 'Reading', read: 'Read'}[state.books[0].status]` | A map read by a key: a stored code in words. A key it lacks fails, so wrap it in `default`. | | `` `${state.toRead} to read` `` | A template. | `==` compares whole values, lists and maps included, and never fails. `<` and its kind compare two numbers or two strings, nothing else: compare a field that may be `null` with `null` first. A date compares in time order with a date, so a record's date compares with `env.today` as it is (`state.books.filter(b, b.addedOn < env.today)`); against a datetime it compares as text, so take the datetime's date with `toDate` first. Each of these is `true`: ```expr true '2026-11-20' < '2026-11-24' {main: 'Main', side: 'Side'}['main'] == 'Main' default({main: 'Main'}['dessert'], 'dessert') == 'dessert' ``` ## What an expression can read Each place sees certain names (roots). The ones you use most: | Root | Holds | Where | | --- | --- | --- | | `state` | Every state entry. | Almost everywhere; not in a stored entry's `initial`. | | `sources` | The status of each sourced entry. | Where `state` is, but in no `initial`. | | `grants` | For each grant request, `held` and `declined`. | As `sources`. | | `user` | Who is acting: `id`, `name`, `kind`, `roles`, `person`. | Where `state` is. | | `env` | `today`, `now`, `timezone`, `locale`, `currency`, `online`. | Everywhere. | | `input` | The action's input. | An action's `allow`, `require` and steps. | | `event` | What happened: a control event's payload, a rule's trigger. | Handlers, rules and flow transitions. | | `view` | The view's input and view state. | A view's props, `when`, handlers and view state `initial` (input only). | | `item`, `index` | The current element and its position. | A slot, a node's `each`, a step's `each`, `where` and `with` of `remove` and `patch`. | | `error` | `code` and `message` of a failed step. | `onError` steps and `orElse`. | A name that is not a root at that place is `expression.unknownRoot`. A stored entry's `initial` sees only `env`; a view state entry's `initial` sees `env`, `state`, `user` and the view's input; a grant request's `where` sees only `input` and `env`. ## Functions Every function can be called as a function or as a method of its first argument: `size(state.books)` is `state.books.size()`. The exceptions are `can`, `canSend`, `has`, `default` and `let`, which are only written as calls, and the list macros, which are only written as methods. | Expression | Gives | | --- | --- | | `size(state.books)` | Elements of a list, keys of a map, characters of a string. | | `sum([1, 2, 3])`, `avg([1, 2])`, `min([3, 1])`, `max(state.toRead, 1)` | Totals and extremes; `avg`, `min` and `max` of an empty list are `null`. | | `first(state.books)`, `last(state.books)` | An end of a list, or `null`. | | `slice(state.books, 0, 5)`, `reverse(state.books)` | Part of a list (or string), and a list reversed. | | `contains(['a', 'b'], 'a')`, `indexOf('hello', 'l')` | Whether a list or string holds a value, and where (`-1` when not). | | `distinct(['a', 'a', 'b'])`, `flatten([[1], [2, 3]])` | Without repeats; one level of lists joined. | | `keys({b: 1, a: 2})`, `values({a: 1})`, `entries({a: 1})` | A map's keys, values, or pairs as maps with `key` and `value`, in key order. | | `merge({a: 1}, {b: 2})`, `compact({a: 1, b: null})` | Two maps joined; a map without its `null` members. | | `range(3)`, `enumerate(state.books)` | `[0, 1, 2]`; each element as a map with `index` and `value`. | | `trim(' x ')`, `lower('A')`, `upper('a')` | Text cleaned up. | | `split('a,b', ',')`, `join(['a', 'b'], ', ')`, `replace('a-b', '-', ' ')` | Text taken apart and put together. | | `substring('hello', 0, 2)`, `startsWith('hello', 'he')`, `endsWith('hello', 'lo')` | Parts of text. Text cannot be indexed with `[0]`. | | `padStart('7', 2, '0')`, `matches('AB12', '^[A-Z]{2}[0-9]{2}$')` | Padding; a pattern test (no lookaround or backreferences). | | `round(2.345, 2)`, `floor(2.7)`, `ceil(2.1)`, `abs(-1)` | Rounding (`round` rounds halves away from zero). | | `int('42')`, `number('4.5')`, `string(42)`, `bool('true')`, `type(state.books)` | Conversions, and a value's kind as text. | | `formatNumber(12.5, {style: 'currency'})` | A number for people: `style` is `decimal`, `percent`, `currency` or `compact`, with `digits`. Money is in `env.currency`, the person's currency, or the option `currency`. | | `` `${state.toRead} ${plural(state.toRead, {one: 'book', other: 'books'})}` `` | The right word for a count. | The formatting functions give text for people to read. Never compare, parse or store what they return. `env.currency` is `null` on a host that does not know the person's currency. Money is then shown with two decimals and no symbol, so the same expression works either way; do not name a currency the person did not name: ```expr true formatNumber(12.5, {style: 'currency'}) == '12.50' ``` ## Dates and times A date is a string `YYYY-MM-DD`, a datetime a UTC string such as `"2026-11-13T09:00:00Z"`, a duration a string such as `"PT1H"` (see `state`). There is no function for the present: read `env.now` (a datetime) and `env.today` (the date in the person's time zone). | Expression | Gives | | --- | --- | | `addDays(env.today, 7)`, `addMonths(env.today, 1)` | A date some days or months later (a negative count goes back). On a datetime, `addDays` adds whole days of 24 hours. | | `addDuration(env.now, 'PT1H')` | A datetime a duration later: one hour from now. It takes a datetime, not a date. | | `daysBetween(env.today, '2026-12-25')`, `durationBetween(env.now, '2026-12-25T00:00:00Z')` | Whole days from one date to another; seconds from one datetime to another. | | `seconds('PT30M')` | A duration in seconds; one with years or months fails. | | `datePart(env.today, 'weekday')`, `startOf(env.today, 'month')`, `toDate(env.now)` | A part (`year`, `month`, `day`, `weekday` from 1 for Monday, `hour`, `minute`, `second`); the start of a `day`, `week`, `month` or `year`; the date of a datetime. | | `atTime(env.today, '09:00')`, `dateIn(env.now, 'Asia/Tokyo')` | The datetime at a time of day in the person's time zone; the date in a time zone. | | `formatDate(env.today, 'long')`, `relativeTime(env.now)` | A date for people (`short`, `medium`, `long`, `time`); "3 days ago". | Each of these is `true`: ```expr true addDays('2026-11-24T09:00:00Z', 1) == '2026-11-25T09:00:00Z' addDuration('2026-11-24T09:00:00Z', 'PT1H') == '2026-11-24T10:00:00Z' daysBetween('2026-11-24', '2026-12-25') == 31 atTime('2026-11-24', '09:00', 'UTC') == '2026-11-24T09:00:00Z' ``` Dates in their usual form compare in time order with `<` and `>`. Apart from `atTime` and `dateIn`, these functions work in UTC. To act at a later time, schedule a wake (see `rules`). ## List macros A macro walks a list, naming each element with a name you choose. In `state.books.map(b, b.title)` the list is `state.books`, the first argument names each element, and the body after it is worked out for each element. | Expression | Gives | | --- | --- | | `state.books.map(b, b.title)` | A new list of the body for each element. | | `state.books.filter(b, b.status == 'read')` | The elements for which the body is `true`. | | `state.books.find(b, b.status == 'reading')` | The first such element, or `null` when there is none. | | `state.books.exists(b, b.author == '')`, `state.books.all(b, b.title != '')` | Whether some, or every, element passes. | | `state.books.count(b, b.status == 'toRead')` | How many pass. | | `state.books.sortBy(b, b.title)` | Sorted by the key, smallest first; `reverse` it for largest first. | | `state.books.groupBy(b, b.status)`, `state.books.indexBy(b, b.id)` | A map from each key to its elements, or to one element. | | `state.books.sumBy(b, size(b.title))`, `state.books.minBy(b, b.addedOn)`, `state.books.maxBy(b, b.addedOn)` | A total; the element with the smallest or largest key. | | `state.books.distinctBy(b, b.author)` | The first element for each key. | `find` gives the element it found even when that is `0`, `false` or empty text. An element that is itself `null` cannot be told from none found: test with `exists`. To count a run, such as days in a row, find where it breaks: with `range` and `find`, the first position that does not continue the run is its length, and `default` covers a run longer than the range. Each of these is `true`: ```expr true [0, 1].find(n, n == 0) == 0 [true, false].find(b, !b) == false ['a', ''].find(s, s == '') == '' [1, 2].find(n, n > 5) == null -(2 + 3) == -5 let(done, ['2026-11-24', '2026-11-23', '2026-11-21'], default(range(366).find(i, !(addDays('2026-11-24', -i) in done)), 366)) == 2 ``` The last is a streak: the days in a row, back from 2026-11-24, that are in the list. Three more macros are written as calls: | Expression | Gives | | --- | --- | | `default(first(state.books).title, 'No books')` | The first value, unless reading it fails for a missing member or gives `null`. | | `has(state.books[0].title)` | Whether every step of the path is there. | | `let(open, state.books.filter(b, b.status != 'read'), size(open) == 0 ? 'All read' : first(open).title)` | Names a value once, to use it in the body. | ## Questions `can` is `true` when an action would accept that input now (its input checks, `allow` and `require` pass); `canSend` when a flow would take that event, for that element, now. Use them to show a button only to someone who can use it (see `views`): ```expr example=timeoff#/actions/approve/steps canSend('approval', 'approve', input.id) can('askForTimeOff', {from: env.today, to: env.today}) ``` The names are literals in quotes. Both are allowed in views and steps, never in a `derive` or a guard (`expression.effectNotAllowed`). ## Habits that break **No truthiness.** Conditions must be booleans. `!state.books` and `state.books && size(state.books) > 0` are errors; compare instead: ```json wrong=reading#/surfaces/visual/views/home/body/children/1/when expect=expression.typeMismatch "state.books" ``` Write `size(state.books) > 0`, `state.city != null`, `state.city != ''`. **`+` does not convert.** `+` adds two numbers, joins two strings or joins two lists. Text and a number together is an error (`expression.typeMismatch`): write ``"=`To read: ${state.toRead}`"``, not ``"='To read: ' + state.toRead"``. **No methods of other languages.** A list has no members: `state.books.length` is an error (`expression.typeMismatch`). Use `size(state.books)`. **No functions of your own.** For logic written once and read in several places, use a derived state entry when it takes no input, and a code module when it does (see `code`). **A missing member fails.** Reading a member that is not there, or a member of `null`, fails with `missing`. An action's optional input field that the caller left out is missing, not `null`. Read such a value with `default(input.author, '')` or test it with `has(input.author)`, or give the field a plain `default` in the action's input. A failure in a `derive` gives `null`; in a guard, `false`; in a step, it fails the action. **`uuid()` and `random()` only in steps.** A value worked out again must come out the same, so these are allowed only in a step, such as a `let` step whose result you store: ```json wrong=reading#/state/toRead/derive expect=expression.effectNotAllowed "size(uuid())" ``` **Patterns are escaped twice.** A pattern in `matches` is a string inside a JSON string, so each backslash in it is written four times in the file. Classes such as `[0-9]` need no backslash, so prefer them. ## Size Each expression has a fixed budget of work, far above ordinary ones. A `filter` inside a `map` over the same long list works on every pair of elements: build a lookup once with `indexBy` and `let`. ## Next - `state` for `derive` and sources. - `actions` for expressions in guards and steps. - `views` for props, `when` and bindings. - `mistakes` for the diagnostics expressions produce. --- # Actions and steps An action is a named thing the app can do. It is the only way to change shared state or to reach outside the app, and every surface uses the same actions: a button runs one, an agent calls one as a tool. So a guard written on the action holds for everyone. ## An action ```json example=reading#/actions/addBook { "description": "Put a book on your list, to read later.", "input": { "title": { "type": "string", "description": "The book's title." }, "author": { "type": "string", "description": "Who wrote it.", "default": "" } }, "output": "string", "require": [ { "that": "size(trim(input.title)) > 0", "message": "Give the book a title." } ], "steps": [ { "let": "id", "to": "=uuid()" }, { "append": "state.books", "value": { "id": "=id", "title": "=trim(input.title)", "author": "=trim(input.author)", "status": "toRead", "addedOn": "=env.today" } }, { "return": "=id" } ] } ``` | Field | What it is | | --- | --- | | `description` | Required. What the action does, for people and agents alike. | | `input` | The fields the caller passes, read as `input.title`. | | `output` | The type of what `return` gives back. | | `allow` | An expression: who may run it. When it is not `true`, the call fails with `action.forbidden` and the caller is not told why. | | `require` | A list of entries with `that` (an expression) and `message`: what must hold now. The first that is not `true` fails the call with `action.refused` and its `message`. | | `confirm` | `true`, or an object with a `message`: a person must agree before it runs. | | `done` | An object with a `message`: what to say once it has been done (below). | | `internal` | `true` keeps it off the agent surface; only this app's own steps and screens can run it. | | `steps` | Required. What it does, in order. | ## Input `input` is a field map: each field has a `type` and a `description`. - A field is required unless it has a `default` or says `"required": false`. - A field with a `default` takes it when the caller leaves it out. Prefer this to `"required": false`: a left-out field without a default is missing, and reading `input.author` then fails. Read such a field with `default(input.author, '')` or `has(input.author)`. - The caller's input is checked before anything else: a missing required field, an unknown field or a value of the wrong type fails with `action.invalidInput`. - An enum is written as a schema object in `type`: `{ "type": "string", "enum": ["toRead", "reading", "read"] }`. ## Who may, and whether now `allow` answers "may this caller ever do this?". `require` answers "can it be done now?", and its `message` tells the person or agent what to change. Prefer `require` with a clear message for anything the caller can put right; keep `allow` for who may act at all, since its refusal says nothing. ```json example=timeoff#/actions/decline { "description": "Decline someone's time off request.", "input": { "id": { "type": "string", "description": "Which request." } }, "confirm": { "message": "The person is told their request is declined." }, "require": [ { "that": "'approver' in user.roles", "message": "Only an approver can decide time off." }, { "that": "state.requests.exists(r, r.id == input.id && r.status == 'pending' && r.personId != user.person.id)", "message": "This request is not waiting for your decision." } ], "steps": [ { "send": "decline", "to": "approval", "key": "=input.id" } ] } ``` `confirm` asks a person before the steps run. When an agent calls the action, the person the agent works for is asked; an agent never confirms for itself. A declined question fails the call with `action.declined`. Ask the person first: a step that waits on a person (a call that picks a file, takes a photo or saves where they choose, or a button's `run` of an action with `confirm`) must come before every step of the same work that changes something, and never goes in a rule or a flow (`action.waitsOnPerson`). Others keep using the app meanwhile, so what must still hold when the person answers goes in `require`, which is checked again then. ## Saying it was done When the result of an action is not where the person is looking (the form closes, the screen goes back, a record goes to someone else), say that it was done with `done`. Whoever started the action hears its `message`: the person who pressed sees it for a moment outside the screen, also after the screen went back; an agent finds it after the output of its tool call; a voice intent without a `reply` speaks it. The time off app's form runs `askForTimeOff` and goes back to the list, so the action says: ```json example=timeoff#/actions/askForTimeOff/done { "message": "Request sent." } ``` The message may be an expression over `input`, the `state` the steps left and `output`, what the action gave back. It is said only when the action succeeded, and never for an action that another action, a rule or a flow runs. Leave it out when the change is in front of the person already, such as a box they ticked or a row added to the list they look at. Keep it to a short line: a host cuts it at 200 characters (`action.doneTooLong`). No step shows a message, and a text kept in the state is never cleared (see `mistakes`). ## Steps A step is an object with one kind key, written first. | Step | Shape | Does | | --- | --- | --- | | `set` | `{ "set": "state.goal", "to": value }` | Writes a stored entry, or a field inside one. | | `append` | `{ "append": "state.books", "value": value }` | Adds an element at the end of a list. | | `remove` | `{ "remove": "state.books", "where": expression }` | Removes the elements for which `where` is true; `item` is the element. | | `patch` | `{ "patch": "state.books", "where": expression, "with": value }` | Merges `with` into each element for which `where` is true. Without `where`, merges into an object. | | `let` | `{ "let": "id", "to": value }` | Names a value for the steps after it. | | `if` | `{ "if": expression, "then": [steps], "else": [steps] }` | Chooses; `else` is optional. | | `each` | `{ "each": expression, "as": "b", "do": [steps] }` | Runs steps for each element of a list. | | `call` | `{ "call": "notify.send", "with": value, "as": "sent" }` | Uses an operation of a capability (see `capabilities`). | | `run` | `{ "run": "addBook", "with": value, "as": "id" }` | Runs another action of this app. | | `code` | `{ "code": "fewestStamps", "with": value, "as": "picked" }` | Runs a code module of this app (see `code`). | | `refresh` | `{ "refresh": "state.forecast" }` | Reads a sourced entry again now. | | `send` | `{ "send": "approve", "to": "approval", "key": value }` | Sends an event to a flow (see `flows`). | | `emit` | `{ "emit": "allRead", "with": value }` | Raises an app event that rules and agents can follow. | | `return` | `{ "return": value }` | Ends the action with its output. | | `fail` | `{ "fail": "book.notFound", "message": value }` | Ends the action with an error of your own code and message. | The values (`to`, `value`, `with`, `return`, `message`) take `=` for an expression; `where`, `if` and `each` are always expressions. A write's path starts with `state` and names a stored entry, such as `state.books`. A derived or sourced entry cannot be written (`state.readonly`), and any other target is `write.invalidTarget`. ## Changing one element of a list `patch` and `remove` act on every element for which `where` is true, with `item` the element. In the `with` of a `patch` that has `where`, `item` is the element too, so a field can be computed from its old value, as `tick` does in `start`. A list inside the element grows the same way: `+` joins the old list and a list of the new element. This patch adds a note to one book; `default` covers a book stored before notes: ```json patch=reading consent=no [ { "op": "add", "path": "/types/Book/properties/notes", "value": { "type": "array", "items": { "type": "string" } } }, { "op": "add", "path": "/actions/addNote", "value": { "description": "Add a note to a book.", "input": { "id": { "type": "string", "description": "Which book." }, "note": { "type": "string", "description": "The note." } }, "steps": [ { "patch": "state.books", "where": "item.id == input.id", "with": { "notes": "=default(item.notes, []) + [input.note]" } } ] } } ] ``` A path can also pick one element with a selector in square brackets, as in `state.books[id=input.id].status`. It picks the first element whose field (here `id`) equals the expression's value: ```json example=reading#/actions/setStatus/steps [ { "set": "state.books[id=input.id].status", "to": "=input.status" } ] ``` A write through a selector that finds no element fails with `state.noElement`. Selectors are allowed only in the targets of `set`, `append`, `remove` and `patch`, and in bindings. ## When a step fails A failed step fails the whole action, unless the step handles it. A `call`, `run` or `code` step may carry: - `onError`: steps that run when it fails, with `error.code` and `error.message` to read. `"onError": []` handles the failure and does nothing. - `orElse`: the value its `as` name takes when it fails. The plant care app asks for a schedule only when needed, and the person may say no. The step handles that, so adding a plant still works: ```json example=plants#/actions/addPlant/steps/2 { "call": "clock.wakeAt", "with": { "key": "=id", "at": "=atTime(addDays(env.today, input.everyDays), '09:00')" }, "onError": [] } ``` ## All or nothing An action's writes are applied together when it ends. If it fails, none of them is kept, and the person or agent sees the error. What a capability already did outside (a message sent, a record filed) cannot be taken back. To make such a call safe to run again, give it `once`: a key naming the effect, such as `` "=`report:${input.id}`" ``. A second call with the same key and the same input does not repeat the effect. `once` is only for operations that change something (`call.onceEffect`). ## Running other actions `run` runs another action of this app, with its own `allow`, `require` and input checks. Use an `internal` action for steps that several actions share. A `run` of an action that has `confirm` would skip the person's question, so it is refused in rules, in flows and in actions that do not confirm themselves (`action.confirmBypassed`). A screen's handler may run it: the person is asked there. Actions must not run each other in a circle (`action.cycle`). ## Events Each action that succeeds raises `action:`, which rules can follow, with its input and output. `emit` raises an event of your own, such as `allRead` in the reading list example; a rule can follow it, and an agent surface can list it. ## Next - `views` to run actions from a screen. - `capabilities` for `call` and the permissions it needs. - `rules` and `flows` for steps that run on their own. - `mistakes` for the diagnostics actions produce. --- # Views The visual surface is the app's screens. A view shows state through controls and starts actions from their events; it holds no logic of its own. ## A view with a form ```json example=reading#/surfaces/visual/views/addBook { "title": "Add a book", "state": { "title": { "type": "string?", "description": "The title being typed." }, "author": { "type": "string?", "description": "The author being typed." } }, "body": { "control": "core:form", "props": { "submitLabel": "Add", "cancelLabel": "Cancel" }, "on": { "submit": [ { "run": "addBook", "with": { "title": "=default(view.title, '')", "author": "=default(view.author, '')" } }, { "navigate": "back" } ], "cancel": { "navigate": "back" } }, "children": [ { "control": "core:textInput", "props": { "label": "Title", "required": true }, "bind": { "value": "view.title" } }, { "control": "core:textInput", "props": { "label": "Author" }, "bind": { "value": "view.author" } } ] } } ``` - `state` is view state: values that belong to this visit of the view, read and written as `view.title`. Each visit starts fresh, and the values are gone when the view closes. A view state entry has `type`, `description` and an optional `initial`, worked out as the view opens. Unlike a stored entry's `initial`, which reads only `env`, it may read `state`, `user`, `env` and the view's input, as `view.id`. - `bind` ties a control's value to a place: what the person types is written there, and the control shows what is there. - `on.submit` runs the action, then goes back. The form raises `submit` only when every input in it is acceptable (a `required` input is filled, a number is within `min` and `max`). - When the action fails, the handler stops: it does not go back, and the form shows the action's message, such as a `require` entry's. No error plumbing is needed. ## The surface `surfaces.visual` has `start` (the first view), `views` (by name) and, optionally, `navigation`: the app's main sections, in order. ```json example=timeoff#/surfaces/visual/navigation [ { "view": "mine", "label": "My time off", "icon": "calendar" }, { "view": "decide", "label": "To decide", "icon": "check", "when": "'approver' in user.roles" } ] ``` A section's `when` decides whether it is offered, never what is allowed: guards on the actions decide that. `with` opens the section's view with input, as a `navigate` step's `with` does, and must give every required input. `count` shows a number beside the label and is hidden at 0. Without `navigation` the app has no main sections. Sections can come from the app's own data. A section with `each` is offered once for every element of its list, named by `as` and told apart by `key`; its `label`, `count` and `with` read the element. A `group` stands its `sections` under a heading. The notes app offers one section for each notebook, under the heading Notebooks: ```json example=notes#/surfaces/visual/navigation/1 { "group": "Notebooks", "sections": [ { "each": { "in": "state.notebooks", "as": "book", "key": "book.id" }, "view": "notebook", "with": { "id": "=book.id" }, "label": "=book.name", "icon": "file", "count": "=size(state.notes.filter(n, n.notebook == book.id))" }, { "view": "newNotebook", "label": "New notebook", "icon": "add" } ] } ``` Repeat sections for places a person goes to and stays in, such as notebooks, channels or projects, when there are few enough to scan, and always give `each` a `key`, so that the chosen section stays chosen when the list changes. Records a person searches, sorts or acts on, such as notes, orders or tickets, belong in a list inside a view. Give every section an `icon`: a host may show the navigation as icons alone, and a section without one is then the first letter of its label. A view has `title` (text or `=` expression), `input` (a field map of what it is opened with, read as `view.id`), `state` and `body`. View state and input names must differ (`name.collision`). The host draws the `title` as the heading of the page or of the card, so the `body` does not begin with a `core:heading` that says it again (`view.headingRepeatsTitle`). An app with one view and no `navigation` is drawn as one card, not as a page: give the view a `title`, which heads the card, and make the one thing the app shows its `body`. When the body is a canvas, chart, table, list or diagram with a `label`, or a group with a `title`, that control's own card is the app's card and its head shows the view's title. Without a view title the card is headed by the app's name. ## Nodes The `body` is a tree of nodes. A node names a `control` from the catalog (see `controls`) and may have: | Field | What it is | | --- | --- | | `props` | The control's props: a literal, or `=` and an expression. | | `bind` | Props tied two-way to a path, or outputs written to one. | | `on` | Event name to a step or a list of steps. `event` holds the event's payload. | | `children` | Nodes inside, for controls that take children (`stack`, `grid`, `group`, `tabs`, `dialog`, `form`). | | `slots` | A node used as a template, such as a list's `item`. | | `when` | An expression: the node exists only while it is `true`. | | `each` | An object with `in` (a list), `as` (a name) and `key`: the node repeats once per element. | | `id` | A name for the node, unique in the view. | | `fallback` | A node to draw instead when a host lacks the control. | Use `when` to leave a node out; `hidden` keeps its place and what was typed in it; `disabled` shows it but takes no input. A prop the control requires must be set or bound (`prop.missing`); a prop it does not have is `prop.unknown`. ## Lists of things To show a list, give a `core:list` or `core:table` its `items`. A slot is the template for one element, with `item` the element, as in the groceries app in `start`. A table shows `columns` of fields; a column with `"format": "custom"` is drawn by the table's `cell` slot, which reads `value` (the field's value), `item` and `column`. ## One record opened from a list Most apps with records have a list of them and a view for one. Picking a row of the reading list's table raises `select` with `event.item`, the record, and opens the `book` view with its id: ```json example=reading#/surfaces/visual/views/home/body/children/2/on { "select": { "navigate": "book", "with": { "id": "=event.item.id" } } } ``` In a `core:list`, a button in the row does the same with `item.id`. The `book` view declares `id` under `input` and reads it as `view.id`. It shows the one record with a node's `each` over a list of one, which names it `book` for the nodes inside; when the book is removed, the list is empty and another node says so: ```json example=reading#/surfaces/visual/views/book/body/children/1/each { "in": "state.books.filter(b, b.id == view.id)", "as": "book", "key": "book.id" } ``` Its "Change" button opens the `editBook` view with the same id. There the form starts filled with the saved book, because each view state `initial` reads the record by the view's input: ```json example=reading#/surfaces/visual/views/editBook/state { "title": { "type": "string?", "initial": "=state.books.find(b, b.id == view.id).title", "description": "The title being typed." }, "author": { "type": "string?", "initial": "=state.books.find(b, b.id == view.id).author", "description": "The author being typed." } } ``` Its form runs `editBook`, which patches the book, then goes back. A host may show the opened record beside the list on a wide screen; you write nothing for that. When the rows of a table can be picked (`selection`), pressing a row picks it, so it cannot also open the record. Then open it from a `core:link` (or a button with `"emphasis": "low"`) in the cell of the record's name: give that column `"format": "custom"`, draw the link in the table's `cell` slot with its `view` and `input`, and leave the row's press to picking. ## A form in steps Sign-up, checkout or a request with several parts reads best one step at a time. The booking app keeps the step in view state (`view.step`, from 1) and gives each step a `core:form` that is there only on its step (`when`). A form raises `submit` only when its own inputs are acceptable, so "Next" goes on only once the step is filled in, and its `cancel` is "Back": ```json example=booking#/surfaces/visual/views/book/body/children/2 { "control": "core:form", "when": "view.step == 2", "props": { "submitLabel": "Next", "cancelLabel": "Back" }, "on": { "submit": { "set": "view.step", "to": 3 }, "cancel": { "set": "view.step", "to": 1 } }, "children": [ { "control": "core:choice", "props": { "label": "Room", "required": true, "options": [ { "value": "Harbor", "label": "Harbor, 4 seats" }, { "value": "Garden", "label": "Garden, 8 seats" }, { "value": "Hall", "label": "Hall, 12 seats" } ] }, "bind": { "value": "view.room" } } ] } ``` The first step's `cancel` goes back to the list, and the last step's form runs the action and then goes back. A line of text above the forms says "Step 2 of 3"; a `core:progress` would do as well. What was typed in an earlier step stays in view state while its form is not shown. ## Handlers A handler is what an event does: one step, or a list. It may hold only steps that stay with the person and the view: `set`, `append`, `remove`, `patch`, `let`, `if`, `each`, `navigate`, `refresh` and `run`. Everything else (a `call`, `send`, `emit`, `code` or `return`) belongs in an action, which the handler runs (`view.handlerStep`). A handler writes view state and the person's own state directly, never a `shared` entry (`write.sharedDirect`). Pass the action what it needs in `with`: an action cannot read `view`. ## Bindings `bind` maps a prop the control marks bindable (usually `value`) to a path: `view.` for view state, or `state.` for a stored entry that is not shared. A path may pick a list element with a selector: `state.books[id=view.id].status`. Bind outputs the same way: a form's `valid` output tells whether every input is acceptable. Bind to view state for a form whose result goes through an action. Bind to the person's own state for a setting that should take effect as soon as it changes, such as a toggle for a preference. ## Navigation `{ "navigate": "book", "with": { "id": "=event.item.id" } }` opens a view with its input; `{ "navigate": "back" }` closes the current one. A `navigate` or `core:link` to a main section, with the section's input, goes to that section as choosing it in the navigation does; any other view opens on top of the current one, with a way back. ## Showing what can be done Show a button only to someone who can use it, with `can` or `canSend` (see `expressions`), so that the screen follows the guards instead of copying them: ```json example=timeoff#/surfaces/visual/views/request/body/children/4/children/0 { "control": "core:button", "when": "canSend('approval', 'approve', request.id)", "props": { "label": "Approve", "emphasis": "high" }, "on": { "press": { "run": "approve", "with": { "id": "=request.id" } } } } ``` Use `grants..held` and `grants..declined` to show what depends on a permission, and `sources..status` to show loading and errors (see `state`). ## Layout Lay out with `core:stack` (one after another, `direction` vertical or horizontal), `core:grid` (equal `columns`) and `core:group` (a titled section). Spacing, sizes and colors are the design system's: a definition names no pixels, fonts or colors. Give the one main action of a view `"emphasis": "high"`. In a horizontal stack the first child, when it is a `core:text`, a `core:heading` or a `core:stack`, takes the room the others leave, so what follows sits at the end of the row, such as a title with a button after it. Children that one `each` repeats are drawn alike. `core:tabs` shows one child at a time and names each tab by that child's label. Make each child a `core:group`: its `title` is the tab's name, and it is not drawn again in the panel. A child with nothing to name it, such as a plain `core:stack`, is only "Tab 1" (`view.tabUnnamed`). ```json example=booking#/surfaces/visual/views/home/body/children/1 { "control": "core:tabs", "children": [ { "control": "core:group", "props": { "title": "Coming up" }, "children": [ { "control": "core:table", "props": { "label": "Coming up", "items": "=state.bookings.filter(b, b.day >= env.today)", "columns": [ { "field": "day", "label": "Day", "format": "date", "sortable": true }, { "field": "room", "label": "Room" } ], "empty": "Nothing booked." } } ] }, { "control": "core:group", "props": { "title": "Past" }, "children": [ { "control": "core:table", "props": { "label": "Past", "items": "=state.bookings.filter(b, b.day < env.today)", "columns": [ { "field": "day", "label": "Day", "format": "date", "sortable": true }, { "field": "room", "label": "Room" } ], "empty": "No past bookings." } } ] } ] } ``` ## Actions of one control What a person does with one chart, table, list, group, canvas or diagram (edit it, export it, add to it, choose its period) goes in that control's `actions` slot, which the host draws at the end of the control's header. The slot is for buttons and a choice whose options say what they are: the host shows no label there, so an input that needs its label goes in the content, and a canvas's own settings in its `tools` slot. What a person does with the whole view stays a button of the view. The weather app refreshes its forecast from the header of the list of days: ```json example=weather#/surfaces/visual/views/home/body/children/4/slots/actions { "control": "core:button", "props": { "label": "Refresh the forecast", "icon": "refresh", "iconOnly": true, "emphasis": "low" }, "on": { "press": { "refresh": "state.forecast" } } } ``` The slot holds one node: a button, or a horizontal `core:stack` of a few, such as a `core:choice` and a button. It reads what a child at its place would: state, view state and the names of an `each` around the control. A table, list or canvas with actions shows its `label` as the header's title. An alert takes the same slot for what to do about what it says, such as "Retry", drawn after its message. `"iconOnly": true` draws a button as its `icon` alone; its `label` stays its name and is shown when the pointer rests on it. ## Next - `controls` for every control with its props and events. - `actions` for what handlers run. - `expressions` for props and `when`. - `agents` for what the same app gives an agent. --- # Controls Controls are the parts a view is built from. They come from the core catalog, which the definition names under `uses.catalogs` (alias `core`), and a node names one as `core:button`. This topic says which control to reach for, then lists every control with its props, events and slots. ## Which control | You want to | Use | | --- | --- | | Lay parts out one after another, or side by side | `core:stack` with `direction` | | Lay out equal columns, such as figures or cards | `core:grid` with `columns` | | Gather related parts under a title | `core:group` | | Show one of several panels | `core:tabs`, each child a `core:group` whose `title` names its tab | | Ask something on top of the view | `core:dialog`, with `open` bound to view state | | Show words | `core:text`, `core:heading` | | Show one key figure | `core:stat` | | Show progress toward a target | `core:progress` | | Mark a status or a count | `core:badge` with a `tone` | | Say that something failed, needs attention, or worked | `core:alert` with a `tone` | | Show a simple list | `core:list` with an `item` slot | | Show records to compare, sort and pick | `core:table` with `columns` | | Show how numbers compare or change | `core:chart` | | Explain how parts connect: an architecture, a flow, a process | `core:diagram`: give `boxes` and `connections`, never positions; the host lays them out | | Let a person type text, a number or a date | `core:textInput`, `core:numberInput`, `core:dateInput` | | Let a person pick | `core:toggle` (on or off), `core:choice` (one option), `core:multiChoice` (several), `core:slider` (a number in a range) | | Let a person pick a color or a tool | `core:choice` with a `swatch` or an `icon` on every option | | Let a person attach a file or take a photo | `core:fileInput` (needs no permission) | | Gather inputs that are sent together | `core:form`, with `submit` and `cancel` | | Start something | `core:button` | | Go to another view, or to a web address | `core:link` | | Draw a game or a custom picture that is not boxes and connections | `core:canvas` | Things to know: - **Inputs.** Every input control has a bindable `value` and raises `change` with `event.value`. Bind `value` to view state inside a form, or handle `change` with a `run`. - **Labels.** Inputs, tables, charts and buttons need a `label`: it is what the person reads and what assistive technology announces. - **Numbers.** `stat`, `progress`, `numberInput`, `slider` and table columns take a `format` (`plain`, `currency`, `percent`). Percent values are fractions: `0.25` shows as 25%. - **Money.** Give `"format": "currency"` and leave `currency` out: the host uses the person's currency, `env.currency`, and shows a plain number when it knows none (the reference host never guesses one). Name a code only when the person named their currency, and never write `"=env.currency"` in a table column (see `mistakes`). - **Choices.** `options` is a list of maps with `value` and `label`. The bound value is the picked option's `value`, with its own type. Make the options from a list with `map`: ```json quiet=groceries#/surfaces/visual/views/home/body/children/3 { "control": "core:choice", "props": { "label": "Item", "options": "=state.items.map(i, {value: i.id, label: i.name})" } } ``` - **Colors and tools.** A choice of colors or of tools is a `core:choice` whose options all carry `swatch` (a color name, as a canvas shape's `fill` takes) or `icon`: the host draws up to 12 as small color dots or tool buttons, one picked. A look says "color palette" or "symbol palette" with each option's color or symbol in parentheses, or "not a palette" and why. Never draw a picker on a canvas (see `mistakes`). A canvas's own tools go in its `tools` slot, in a vertical stack: such choices and icon-only buttons are drawn in a strip beside the surface, and a slider or another input placed there (a pen size) in a bar under it. ```json quiet=groceries#/surfaces/visual/views/home/body/children/3 { "control": "core:choice", "props": { "label": "Pen", "options": [ { "value": "black", "label": "Black", "swatch": "text" }, { "value": "teal", "label": "Teal", "swatch": "accent" } ] } } ``` - **Drawing along a drag.** A canvas's `pointer` event has a `phase`: `down` at the press, `move` for each move while pressed, then `up`, or `cancel` when the gesture is lost. A pen stroke is one `path` shape. At `down` start a stroke in view state with an `id` (`uuid()`) and one point, `{x: event.x, y: event.y}`; at each `move` append the point to it; at `up` or `cancel` add the stroke to the list and clear it. Let the scene draw each stroke, and the one in progress, as one path, so the line shows while it is drawn and a press alone leaves a dot. An eraser takes away the stroke whose `id` is `event.target`, the named shape under the pointer. Never build a stroke from one `line` per move: a canvas draws at most 5000 shapes and 50000 path points and an expression has a budget, and such a stroke meets them within a minute of drawing. ```expr (state.ink + (view.stroke == null ? [] : [view.stroke])).map(s, {kind: 'path', id: s.id, points: s.points, stroke: s.color, strokeWidth: 0.006}) ``` - **Keys for a game.** A canvas hears the keys in its `keys` once the person presses it or tabs to it, and when it gives way to another canvas with `keys` (by `when`, as a part's view or in the next view) the keys follow, so a game needs no "click to continue" between its screens. - **Round and curved shapes.** Draw a shape as what it is: a tile with rounded corners is a `rect` with `radius`, a stretched circle an `ellipse`, a gauge or a ring of progress an `arc` (`from` and `to` in degrees clockwise from pointing right, so a ring of progress runs from `-90` to `-90 + 360` times the share done), and a piece of a pie an `arc` with a `fill`. A smooth line or outline is a `path` whose points carry control points: `cx` and `cy` for a gentle bend, `c1x`, `c1y`, `c2x` and `c2y` for an S or a precise curve. Every line takes `dash` (`dashed`, `dotted`), `cap` and `join`; a text takes `"weight": "emphasis"` to stand out. - **Colors on a canvas.** A color is named by its role, such as `text` for ink: the host draws it in the page's light or dark mode. A color is a name of the design's (surface, surfaceRaised, surfaceSunken, text, textMuted, border, outline, accent, onAccent, focus, neutral, info, success, warning, danger, category1 to category8); a hex value or a CSS name such as "red" or "none" is not one: the host paints another color in its place, and the look names it. No fill or no stroke is a `fill` or `stroke` left out. Give the canvas a `mode` only when its colors must never change, as in a drawing that is printed. - **Symbols and motion.** A figure a scene shows many times (a block of a game with its light and shade, a playing piece, a marker) is a symbol: write it once in the canvas's `symbols`, around its origin, in units of the width, with `"fill": "given"` on the part that takes a color, and place it with a `use` of its own `x`, `y`, `scale`, `rotation` and `color`. A `group` moves, turns and scales shapes as one: a board of cells is a group scaled to one cell, its blocks placed at their column and row. For motion, give the canvas `"motion": "standard"` and each shape that moves an `id`: when the state changes, the host glides it to its new place. A piece a rule moves step by step keeps an even pace with `{ "over": "PT0.3S", "ease": "linear" }` at the rule's interval. A scene paints in order, so draw a label after the piece it stands on: the look names texts later shapes may cut. ```expr {kind: 'group', x: 0.3, y: 0.05, scale: 0.04, shapes: state.cells.map(c, {kind: 'use', symbol: 'block', x: c.col, y: c.row, color: c.color})} ``` - **Gradients and shadows.** A `fill` may run between colors, `{gradient: 'linear', stops: ['category1', 'accent']}` (top to bottom; `angle` 0 runs left to right) or `radial` from the middle out, and a stop `{color: 'surface', opacity: 0}` fades to nothing, so a shine is a second shape over a plain one. A `shadow` of `'low'`, `'medium'` or `'high'` lifts a shape, a group or a placement. They serve the few things a person picks up or that catch the light, one level for things of one kind; on every shape, or between unrelated colors, they spoil a drawing. A host that draws neither shows the first stop and no shadow, so put the main color first. - **Charts.** Say what the numbers are: `unit` for what they count (`"hours"`, `"kg"`; money and percentages take `format` instead) and `valueLabel` for what they are, with `categoryLabel` for the categories. For a ranking or long category names, lay bars on their side with `"orientation": "horizontal"`. Show a target on a bar, line or area chart with `"goal": { "value": 40, "label": "Weekly target" }`. A pressed bar, point or slice is kept in `selected` as `{ "item": "Mar", "series": "hours" }`, the record named by its `category` or by `itemKey`: bind it to view state, and set that to `null` when the app forgets the pick, so the outline goes with the words. In a `select` handler `event.selected` is `null` when the press or Escape cleared the selection, so words about the pick check it first. - **Tables.** With `complete` true (the default) the host sorts and pages `items` itself. `selected` holds the `itemKey` values of picked rows. A column shows its field as it is. For a stored code in words, give each element the words in a field of their own (see `flows`), or draw them in the `cell` slot of a `"format": "custom"` column, as the reading list does. - **Items that move between lists.** When a person moves items from list to list, such as the cards of a board between its columns, give the lists one `moveGroup` and each a `label`, and handle `move` on each by changing the field the lists filter on to that list's own (made with `each`, the column's). When a person keeps items in an order of their own, such as priorities or the cards of a column, make the list `reorderable` and keep the order `move` gives: `{ "set": "state.books", "to": "=state.books.sortBy(b, indexOf(event.order, b.id))" }`. Shared state is set in an action passed `event.order`. Such a list shows its items in the order the app keeps them, so sort them by nothing else. The host gives every item its own Move control, so draw no buttons that move an item between those lists or up and down. - **Images.** `core:image` `source` and a canvas `image` shape are remote props. A picture that is part of the app (a header photo, a logo, the sprites of a game) is added first with the tool add_asset, then named as `"asset:"` (an asset nothing names yet is only a warning): the app carries it, so it shows in the chat too and asks nothing. A picture that differs for each record stays a web address, which needs a grant (see `capabilities`) and does not show in a chat. At most 64 pictures, each a PNG, JPEG, WebP or GIF of at most 768 KB and 4096 pixels a side, 1.875 MB in all; a picture from the web is not shrunk, so where a library's page offers smaller sizes (Wikimedia Commons, Unsplash, Pexels, Pixabay), take one, and give `credit` when the license asks. A person's own photo given by path that is too large, or a HEIC, is made smaller on a Mac; elsewhere, ask the person to save it at 2048 pixels on its longer side first. add_asset removes the place where a photo was taken. - **Formatted text.** Text that arrives formatted, such as a model's reply, notes people write or a description from a service, often uses Markdown. Give its `core:text` `"format": "markdown"`: the host draws its headings, lists, tables, code and links, the same on every host, and shows anything else, HTML included, as its characters. Keep the app's own labels and sentences plain, and never join strings to put marks such as two asterisks or a hash around your own words: `style`, `core:heading`, `core:badge` and `core:group` do that. A link in it is followed as a `core:link` with a `url` is. ```json quiet=weather#/surfaces/visual/views/home/body/children/4/slots/item { "control": "core:text", "props": { "value": "=item.summary", "format": "markdown" } } ``` - **Variants.** `variant` names a preset of props from the design system. You can always set the props themselves instead, which works with every design system. Icon names every host knows (for `icon` props, `meta.icon` and a main section's `icon`): `add`, `remove`, `edit`, `delete`, `close`, `check`, `search`, `filter`, `sort`, `menu`, `more`, `back`, `forward`, `up`, `down`, `home`, `settings`, `user`, `users`, `calendar`, `clock`, `location`, `camera`, `image`, `file`, `attach`, `download`, `upload`, `share`, `copy`, `link`, `mail`, `phone`, `chat`, `notification`, `star`, `heart`, `info`, `help`, `warning`, `error`, `success`, `lock`, `play`, `pause`, `stop`, `refresh`, `chart`, `dashboard`, `list`, `table`, `folder`, `tag`, `inbox`, `money`, `undo`, `redo`, `eraser`, `line`, `rectangle`, `ellipse`, `text`, `pointer`, `hand`, `fill`. A name the host does not know shows no symbol, and the check warns about it (`value.notKnown`). ## Every control Every control also takes `variant`, `hidden` and `disabled`. "Required" props must be set in `props` or bound in `bind`. A bindable prop can be bound; a remote prop can make the host fetch from the network, unless it is `"asset:"`. Types the props use: - `Spacing`: "small" \| "medium" \| "large" - `Emphasis`: "high" \| "medium" \| "low" - `Tone`: "neutral" \| "info" \| "success" \| "warning" \| "danger" - `NumberFormat`: "plain" \| "currency" \| "percent" - `ChoiceValue`: string \| number \| boolean - `ChoiceOption`: `value` ChoiceValue, `label` string, `description`? string, `icon`? IconName, `swatch`? string - `Trend`: `direction` "up" \| "down" \| "flat", `label`? string, `sentiment`? "positive" \| "negative" \| "neutral" - `TableColumn`: `field` string, `label` string, `format`? "text" \| "number" \| "currency" \| "percent" \| "date" \| "datetime" \| "boolean" \| "custom", `currency`? string, `sortable`? boolean - `SortKey`: `field` string, `direction` "asc" \| "desc" - `ChartSeries`: `field` string, `label` string, `color`? string, `format`? NumberFormat, `unit`? string - `ChartGoal`: `value` number, `label`? string - `ChartValue`: `item` string \| number \| boolean, `series` string - `Shape`: one of these, told apart by `kind`: "rect" (`id`? string, `x` number, `y` number, `width` number from 0, `height` number from 0, `radius`? number from 0, `fill`? Fill, `stroke`? string, `strokeWidth`? number from 0, `dash`? "solid" \| "dashed" \| "dotted", `cap`? "round" \| "flat" \| "square", `join`? "round" \| "sharp" \| "bevel", `rotation`? number, `opacity`? number 0 to 1, `motion`? Motion, `shadow`? Shadow); "circle" (`id`? string, `x` number, `y` number, `r` number from 0, `fill`? Fill, `stroke`? string, `strokeWidth`? number from 0, `dash`? "solid" \| "dashed" \| "dotted", `cap`? "round" \| "flat" \| "square", `opacity`? number 0 to 1, `motion`? Motion, `shadow`? Shadow); "ellipse" (`id`? string, `x` number, `y` number, `radiusX` number from 0, `radiusY` number from 0, `fill`? Fill, `stroke`? string, `strokeWidth`? number from 0, `dash`? "solid" \| "dashed" \| "dotted", `cap`? "round" \| "flat" \| "square", `rotation`? number, `opacity`? number 0 to 1, `motion`? Motion, `shadow`? Shadow); "arc" (`id`? string, `x` number, `y` number, `radius` number from 0, `from` number, `to` number, `stroke`? string, `strokeWidth`? number from 0, `fill`? Fill, `dash`? "solid" \| "dashed" \| "dotted", `cap`? "round" \| "flat" \| "square", `join`? "round" \| "sharp" \| "bevel", `opacity`? number 0 to 1, `motion`? Motion, `shadow`? Shadow); "line" (`id`? string, `x` number, `y` number, `x2` number, `y2` number, `stroke`? string, `strokeWidth`? number from 0, `dash`? "solid" \| "dashed" \| "dotted", `cap`? "round" \| "flat" \| "square", `opacity`? number 0 to 1, `motion`? Motion, `shadow`? Shadow); "path" (`id`? string, `points` list, `stroke`? string, `strokeWidth`? number from 0, `fill`? Fill, `closed`? boolean, `dash`? "solid" \| "dashed" \| "dotted", `cap`? "round" \| "flat" \| "square", `join`? "round" \| "sharp" \| "bevel", `opacity`? number 0 to 1, `motion`? Motion, `shadow`? Shadow); "text" (`id`? string, `x` number, `y` number, `text` string, `size`? number from 0, `align`? "start" \| "center" \| "end", `weight`? "body" \| "emphasis", `fill`? Fill, `rotation`? number, `opacity`? number 0 to 1, `motion`? Motion, `shadow`? Shadow); "image" (`id`? string, `x` number, `y` number, `width` number from 0, `height` number from 0, `source` string, `rotation`? number, `opacity`? number 0 to 1, `motion`? Motion, `shadow`? Shadow); "group" (`id`? string, `x`? number, `y`? number, `scale`? number from 0, `rotation`? number, `opacity`? number 0 to 1, `motion`? Motion, `shadow`? Shadow, `shapes` Shape[]); "use" (`symbol` string, `id`? string, `color`? string, `x`? number, `y`? number, `scale`? number from 0, `rotation`? number, `opacity`? number 0 to 1, `motion`? Motion, `shadow`? Shadow) - `PathPoint`: `x` number, `y` number, `cx`? number, `cy`? number, `c1x`? number, `c1y`? number, `c2x`? number, `c2y`? number - `Fill`: string (A color token name, such as accent or category2), or { `gradient` "linear" \| "radial", `angle`? number, `stops` GradientStop[] } - `GradientStop`: string (A color token name, fully opaque), or { `color` string, `opacity`? number 0 to 1, `at`? number 0 to 1 } - `Shadow`: "low" \| "medium" \| "high" - `Motion`: string (none, or the name of a motion token of the design system: quick, standard or slow in the default one), or { `over` string, `ease`? "smooth" \| "linear" } - `FileKind`: "image" \| "video" \| "audio" \| "document" \| "spreadsheet" \| "text" \| "any" - `FileRef`: `id` string, `name` string, `mediaType` string, `size`? integer from 0, `uri`? string ### core:stack Arrange parts one after another, down the view or across it. - Props: `direction` "vertical" \| "horizontal" (default "vertical"); `gap` Spacing (default "medium"); `align` "start" \| "center" \| "end" \| "stretch" (default "stretch"). - Children: many. ### core:grid Arrange parts in equal columns, filling row by row. - Props: `columns` integer 1 to 6 (default 2); `gap` Spacing (default "medium"). - Children: many. ### core:group A titled section that gathers related parts, such as the fields of an address or the figures for one month. - Props: `title` string (required); `description` string; `emphasis` Emphasis (default "medium"). - Slots: `actions`, one node drawn once, which reads the names around the control. - Children: many. ### core:tabs Show one of several panels at a time, with a tab for each that its panel names, so each child is usually a group whose title names its tab. - Props: `selected` integer (bindable, default 0); `label` string. - Events: `change` with `event` holding `value` integer. - Children: many. ### core:dialog Ask for a person's attention or a short decision on top of the current view, without leaving it. - Props: `open` boolean (bindable, default false); `title` string (required); `dismissible` boolean (default true). - Events: `dismiss` with no payload. - Children: many. ### core:divider Separate groups of content with a visible break. - Props: `label` string. ### core:text Show a piece of text, such as a sentence, a value or a note. - Props: `value` string (required); `style` "body" \| "caption" \| "emphasis" (default "body"); `format` "plain" \| "markdown" (default "plain"). ### core:heading Title a view or a section of one, so people can scan and navigate by headings. - Props: `value` string (required); `level` integer 1 to 3 (default 2). ### core:image Show a picture, such as a photo, an illustration or a picked image file. - Props: `source` string (remote, required); `alt` string (required); `fit` "contain" \| "cover" (default "contain"); `size` "small" \| "medium" \| "large" \| "fill" (default "fill"). ### core:icon Show a small symbol named by meaning, such as add, delete, warning or search. - Props: `name` IconName (required); `label` string. ### core:badge Mark something with a short status or count, such as New, Overdue or 3. - Props: `label` string (required); `tone` Tone (default "neutral"). ### core:stat Show one key figure with its name and, optionally, which way it is moving. - Props: `label` string (required); `value` number \| string (required); `format` NumberFormat (default "plain"); `currency` string; `trend` Trend. ### core:progress Show progress toward a numeric target, or that work is under way when the amount is unknown. - Props: `value` number?; `max` number (default 100); `label` string (required); `format` NumberFormat (default "plain"); `currency` string. ### core:alert Tell a person something important in place: that an action failed, that something needs attention, or that something worked. - Props: `title` string (required); `message` string; `tone` Tone (default "info"); `dismissible` boolean (default false). - Events: `dismiss` with no payload. - Slots: `actions`, one node drawn once, which reads the names around the control. ### core:textInput Let a person enter text: a name, an email address, a note or a longer description. - Props: `value` string? (bindable); `label` string (required); `hint` string; `multiline` boolean (default false); `kind` "text" \| "email" \| "phone" \| "url" \| "secret" (default "text"); `required` boolean (default false); `maxLength` integer from 1; `error` string?. - Events: `change` with `event` holding `value` string?. ### core:numberInput Let a person enter a number, such as an amount of money, a quantity or a percentage. - Props: `value` number? (bindable); `label` string (required); `hint` string; `min` number; `max` number; `step` number from 0; `format` NumberFormat (default "plain"); `currency` string; `required` boolean (default false); `error` string?. - Events: `change` with `event` holding `value` number?. ### core:dateInput Let a person choose a calendar date, a date and time, or a time of day, such as a due date, an appointment or an alarm. - Props: `value` string? (bindable); `mode` "date" \| "datetime" \| "time" (default "date"); `label` string (required); `hint` string; `min` string; `max` string; `required` boolean (default false); `error` string?. - Events: `change` with `event` holding `value` string?. ### core:toggle Let a person turn one setting on or off. - Props: `value` boolean (bindable, default false); `label` string (required); `hint` string. - Events: `change` with `event` holding `value` boolean. ### core:choice Let a person pick exactly one option from a list. - Props: `value` ChoiceValue? (bindable); `options` ChoiceOption[] (required); `label` string (required); `hint` string; `required` boolean (default false); `error` string?. - Events: `change` with `event` holding `value` ChoiceValue?. ### core:multiChoice Let a person pick any number of options from a list, such as tags or days of the week. - Props: `value` ChoiceValue[] (bindable, default []); `options` ChoiceOption[] (required); `label` string (required); `hint` string; `required` boolean (default false); `error` string?. - Events: `change` with `event` holding `value` ChoiceValue[]. ### core:slider Let a person set a number within a fixed range by feel, such as volume, a rating or a budget split. - Props: `value` number (bindable, default 0); `label` string (required); `min` number (default 0); `max` number (default 100); `step` number from 0 (default 1); `format` NumberFormat (default "plain"); `currency` string. - Events: `change` with `event` holding `value` number. ### core:fileInput Let a person attach files, or take a photo or recording with the device, for example to add a receipt to an expense. - Props: `value` FileRef[] (bindable, default []); `label` string (required); `accept` FileKind[] (default ["any"]); `multiple` boolean (default false); `capture` "none" \| "camera" \| "microphone" (default "none"); `required` boolean (default false); `error` string?. - Events: `change` with `event` holding `value` FileRef[]. ### core:form Gather related inputs into one unit that is submitted together, and report whether every input is acceptable. - Props: `label` string; `submitLabel` string; `cancelLabel` string. - Events: `submit` with no payload; `cancel` with no payload. - Outputs (bind them to read them): `valid` boolean. - Children: many. ### core:button Let a person start something: save, send, add, delete, start a game. - Props: `label` string (required); `emphasis` Emphasis (default "medium"); `icon` IconName; `destructive` boolean (default false); `iconOnly` boolean (default false). - Events: `press` with no payload. ### core:link Take a person somewhere: another view of this app, or a web address outside it. - Props: `label` string (required); `view` string; `input` any; `url` string. - Events: `activate` with no payload. ### core:list Show a collection of items one after another, each drawn by the item template, and let a person pick one, move one to another list, or put one at a place of their choosing. - Props: `items` any[] (required); `itemKey` string (default "id"); `label` string; `empty` string; `moveGroup` string; `reorderable` boolean (default false). - Events: `select` with `event` holding `item` any, `index` integer; `move` with `event` holding `item` any, `index` integer?, `order` any[]?. - Slots: `item` (required), whose node reads `item`, `index`; `actions`, one node drawn once, which reads the names around the control. ### core:table Show records as rows with named columns so people can compare, sort, select and page through them. - Props: `items` any[] (required); `columns` TableColumn[] (required); `label` string (required); `itemKey` string (default "id"); `complete` boolean (default true); `sort` SortKey? (bindable); `pageSize` integer from 1; `page` integer from 1 (bindable, default 1); `total` integer from 0; `selection` "single" \| "multiple" (default "single"); `selected` any[] (bindable, default []); `empty` string. - Events: `select` with `event` holding `item` any, `index` integer, `selected` any[]; `sort` with `event` holding `field` string, `direction` "asc" \| "desc"; `page` with `event` holding `page` integer. - Slots: `cell`, whose node reads `item`, `index`, `column`, `value`; `actions`, one node drawn once, which reads the names around the control. ### core:chart Show how numbers compare or change, drawn from a list of records. - Props: `kind` "bar" \| "line" \| "area" \| "pie" \| "scatter" (required); `items` any[] (required); `category` string (required); `series` ChartSeries[] (required); `label` string (required); `stacked` boolean (default false); `format` NumberFormat (default "plain"); `currency` string; `unit` string; `categoryLabel` string; `valueLabel` string; `orientation` "vertical" \| "horizontal" (default "vertical"); `goal` ChartGoal; `selected` ChartValue? (bindable, default null); `itemKey` string. - Events: `select` with `event` holding `item` any, `series` string, `selected` ChartValue?. - Slots: `actions`, one node drawn once, which reads the names around the control. ### core:canvas A drawing surface for casual games and custom visuals. - Props: `scene` Shape[] (remote, required); `label` string (required); `summary` string; `aspect` number 0.1 to 10 (default 1); `background` string; `mode` "light" \| "dark"; `keys` string[] (default []); `symbols` object (remote); `motion` Motion (default "none"). - Events: `pointer` with `event` holding `phase` "down" \| "move" \| "up" \| "cancel", `x` number, `y` number, `target` string?; `key` with `event` holding `key` string, `phase` "down" \| "up", `repeat` boolean. - Slots: `actions`, one node drawn once, which reads the names around the control; `tools`, one node drawn once, which reads the names around the control. ### core:diagram Explain how parts connect: an architecture, a flow or a process. - Props: `boxes` DiagramBox[] (required); `connections` DiagramConnection[] (default []); `groups` DiagramGroup[]; `selected` string? (bindable, default null); `highlight` string[] (default []); `label` string (required); `summary` string. - Events: `select` with `event` holding `box` DiagramBox?, `selected` string?. - Slots: `actions`, one node drawn once, which reads the names around the control. ## Next - `views` for nodes, bindings and handlers. - `capabilities` for what the app uses outside the screen. --- # Capabilities and grants A capability is the app's access to something outside it: notifications, a web service, a schedule, the camera. The definition names a contract, such as `core:http`, never a provider: the host connects one. Nothing happens outside the app unless a grant request covers it and someone entitled to answer said yes. A first web read needs the next two sections and the sourced entries of `state`; look up the rest in the reference at the end. ## A capability and its grant request ```json example=weather#/capabilities { "weather": { "contract": "core:http", "description": "The weather service the forecast comes from.", "config": { "origin": "https://weather.example.com" } } } ``` ```json example=weather#/grants { "readForecast": { "capability": "weather", "scopes": ["http.read"], "reason": "Read the forecast for the city you choose. Only the city's name is sent.", "where": "input.path == '/v1/forecast'", "rate": { "count": 48, "per": "P1D" } } } ``` The key of a capability (`weather`) is its alias: steps call `weather.get`, and grant requests name `weather`. | Capability field | What it is | | --- | --- | | `contract` | Required. `core:` and the contract's name. | | `description` | Required. Why the app uses it, in the person's words. | | `config` | The contract's settings, such as the `origin` of a web service. May read only `env`. | | `required` | Default `true`. With `false` the app opens without it, and `capabilities..available` says whether it is there. | | Grant request field | What it is | | --- | --- | | `capability` | The alias it covers. | | `scopes` | The contract's scopes it asks for; each operation needs one. Ask for the fewest. | | `operations` | Optional: only these operations within the scopes. | | `reason` | Required. Shown to the person before they answer: say what is read or done, and what is not. | | `where` | An expression over `input` (the operation's input) and `env`: a call is allowed only when it holds. | | `rate` | At most `count` calls `per` duration. | | `duration` | The longest the permission lasts, such as `P90D`. | | `required` | Default `true`. With `false` the app opens without it (see below). | Every operation the app uses must be covered by a request for its scope (`grant.uncovered` without one), and a scope the contract lacks is `grant.unknownScope`. ## Web services and web images A `core:http` capability reaches exactly one `origin`, an https address such as `https://weather.example.com`, and paths under it. Narrow the request with `where` on `input.path`. A response is a `core:HttpResponse`: a read that the service answers with an error status still succeeds, so test `status`. A web address in a remote prop, such as an image's `source`, makes the host fetch it. That needs an `http.read` grant on a capability whose `origin` is that address's origin: the check reports `egress.ungranted` for a literal address with no such grant, and `egress.originMismatch` for one on another origin. A file a person gave the app needs none, and so does a picture the app carries, `"asset:"` (see `controls`). ## When the person is asked | The request | Is asked | | --- | --- | | Every scope "given by use" (choosing a file, taking a photo, sharing) | Never: the person's own act each time is the consent. | | A code module (`"code"`) | Never: it runs in the host's sandbox and reaches nothing. A host may ask all the same. | | A capability the host serves from sample data, or keeps inside the app | Never, on that host: a demonstration service, or a service the host keeps inside the app, is not asked for. Never count on it: another host asks. | | `"required": true` (the default) | When the app is first opened, before it opens. | | `"required": false` | When something the person does first needs it. When several people share the app, the reference host asks the owner as the app opens instead, for every request the owner answers. | With one person, an optional request that nothing a person does needs is never asked. A call made by a rule that time or an event started asks nobody: it fails with `grant.denied`, so what depends on the permission never happens, and nobody sees an error. A host may ask sooner; never count on it. So: - **Leave a request required unless the app is useful without it.** - **When it is optional, give the person a control whose action uses it**, shown only while the request is unanswered. The plant care app asks for its schedule when the first plant is added (`addPlant` calls `wakeAt`), and for notifications when the person presses "Turn on reminders", whose action sends a first notification. No step asks for a permission on its own: the question comes with a call that needs it. A host that shows notifications only inside the app gives them without asking, and the button never shows there. ```json example=plants#/surfaces/visual/views/home/body/children/1 { "control": "core:button", "when": "!grants.reminders.held && !grants.reminders.declined", "props": { "label": "Turn on reminders", "icon": "notification" }, "on": { "press": { "run": "turnOnReminders" } } } ``` When the point of the app is its reminders, say on the screen that they are off until the person turns them on: ```json example=plants#/surfaces/visual/views/home/body/children/2 { "control": "core:text", "when": "!grants.reminders.held", "props": { "value": "=grants.reminders.declined ? 'Reminders are off. You can turn them on in the permissions of the app.' : 'Reminders are off until you turn them on.'", "style": "caption" } } ``` - **A call can be refused.** When the person says no, the call fails with `grant.denied`. Give such a `call` an `onError` so the action still does the rest. - `grants..held` is `true` while the permission is in force; `grants..declined` while a no stands. ## Who answers Most capabilities act for the app as a whole: the owner answers once, for everyone who uses it. Capabilities marked "personal" below (files, media, location, clipboard, share) act for one person, and each person answers for themselves. ## Working while nobody has the app open `every` rules, flow timers (`after`) and timed refreshes run only while a person has the app open, unless the app holds a grant on a capability with the `background` trait: in the core catalog, `core:scheduler`. An `every` rule without one is warned about (`trigger.noBackground`) unless it says `"foreground": true`, meaning it is meant to run only while the app is open. The scheduler also lets the app wake itself at a time it chooses (`wakeAt`), and a rule follows the `wake` event: see the plant care example. The grant must be held before the app is closed. Make its request required, or have an act of the person's call the scheduler first, as adding a plant does. ## Notifications `notify.send` notifies the person on whose behalf the work runs: the one who pressed the button, or the person a rule acts for. `notify.sendTo` notifies someone else, by id, and needs the scope `notify.others`. Give `view` to open a view when the notification is opened. ## Using an operation An operation is used by a `call` step (see `actions`) or, when it only reads, by a sourced state entry (see `state`), with the input the reference below lists. ## Every core capability | Capability | Operations | Events | | --- | --- | --- | | `core:notify` | `send`, `sendTo` | none | | `core:scheduler` | `wakeAt`, `cancel` | `wake` | | `core:http` | `get`, `send` | none | | `core:files` | `pick`, `read`, `save` | none | | `core:media` | `capturePhoto`, `captureAudio` | none | | `core:location` | `current` | none | | `core:directory` | `me`, `get`, `manager`, `members`, `find` | none | | `core:records` | `list`, `get`, `count`, `aggregate`, `create`, `update`, `delete` | `changed` | | `core:share` | `send` | none | | `core:clipboard` | `write`, `read` | none | Scopes marked "given by use" are never asked: the person's own act at that moment is the consent. Every other scope is asked. "Personal" means each person answers for themselves. ### core:notify Send a notification to the person using the app, or to another named person, such as a reminder, an alert or a request for approval. - Scope `notify.self` (low): Send you notifications. - Scope `notify.others` (medium): Send notifications to other people on your behalf. - Operation `send` (`notify.self`, external): input `title` string (required); `body` string; `view` string; `viewInput` object; `urgency` "low" \| "normal" \| "high" (default "normal"); output string. Notify the current user: the person the acting principal is or acts for, never an agent or the app. - Operation `sendTo` (`notify.others`, external): input `to` string (required); `title` string (required); `body` string; `view` string; `viewInput` object; `urgency` "low" \| "normal" \| "high" (default "normal"); output string. Notify another principal, by id, on behalf of the current user: the person the acting principal is or acts for, never an agent or the app. ### core:scheduler Let the app run while nobody has it open. - Traits: `background`. - Scope `scheduler.background` (medium): Let this app run while nobody has it open: its repeating rules, deadlines and scheduled data refreshes run unattended, it responds to events from its other capabilities and to changes such as coming back online, and it can wake itself at times it sets. - Operation `wakeAt` (`scheduler.background`, write): input `at` datetime (required); `key` string (required); output datetime. Wake the app once at the given time, raising the wake event on behalf of the person for whom it is scheduled. - Operation `cancel` (`scheduler.background`, write): input `key` string (required); output boolean. Cancel a pending wake by its key. - Event `wake` (`scheduler.background`): payload `key` string, `at` datetime. A scheduled wake arrived. ### core:http Read from or send to one web service. - Traits: `egress`. - Config: `origin` string (required); `auth` "none" \| "host" (default "none"). - Scope `http.read` (high): Read data from the named web service, and show images and other content from it in this app. - Scope `http.send` (high): Send data from this app to the named web service. - Operation `get` (`http.read`, read): input `path` string (default "/"); `query` object; `headers` object; output HttpResponse. Fetch a resource from the service without changing anything. - Operation `send` (`http.send`, external): input `method` "POST" \| "PUT" \| "PATCH" \| "DELETE" (default "POST"); `path` string (default "/"); `query` object; `headers` object; `body` any; `encoding` "json" \| "form" \| "text" (default "json"); output HttpResponse. Send data to the service, such as submitting a form or creating an item there. ### core:files Work with the user's own files: ask them to choose files, read what they chose, and save new files where they decide. - Traits: `offline`, `personal`. - Scope `files.pick` (low, given by use): Ask you to choose files for this app. - Scope `files.read` (medium, given by use): Read the contents of files given to this app: files you choose, photos and recordings you take, files it saved, and files that other people using it shared with you. - Scope `files.save` (medium, given by use): Save files to a place you choose. - Operation `pick` (`files.pick`, read, interactive): input `accept` FileKind[] (default ["any"]); `multiple` boolean (default false); output FileRef[]. Ask the person the app is acting for to choose one or more files, on a surface of theirs that is open; with none, the call fails with capability.unavailable. - Operation `read` (`files.read`, read): input `file` FileRef (required); `as` "text" \| "json" \| "records" \| "base64" (default "text"); output any. Read the contents of a file whose reference the host issued to this app instance: by pick, by save, by a capture, or for a file an agent handed to the host. - Operation `save` (`files.save`, write, interactive): input `name` string (required); `content` any (required); `as` "text" \| "json" \| "records" \| "base64" (default "text"); `mediaType` string; output FileRef?. Ask the person the app is acting for to choose a place, on a surface of theirs that is open, and save a new file there; with no such surface, the call fails with capability.unavailable. ### core:media Capture a photo or a short audio clip with the device, with the user taking the photo or making the recording themselves. - Traits: `offline`, `personal`. - Scope `media.camera` (high, given by use): Use your camera when you choose to take a photo. - Scope `media.microphone` (high, given by use): Use your microphone when you choose to record. - Operation `capturePhoto` (`media.camera`, read, interactive): input `facing` "any" \| "front" \| "back" (default "any"); output FileRef?. Open the camera for the person the app is acting for to take one photo, on a surface of theirs that is open; with none, the call fails with capability.unavailable. - Operation `captureAudio` (`media.microphone`, read, interactive): input `maxDuration` duration; output FileRef?. Let the person the app is acting for record one audio clip, on a surface of theirs that is open; with none, the call fails with capability.unavailable. ### core:location Find where the device is right now, once per request. - Traits: `personal`. - Scope `location.current` (high): See where your device is when the app asks. - Operation `current` (`location.current`, read): input `precision` "approximate" \| "precise" (default "approximate"); `maxAge` duration; output GeoPoint. Get the device's current position. ### core:directory Look up people and their roles: who the current user is, who their manager is, who holds a role, and who matches a name. - Traits: `multiUser`. - Scope `directory.self` (low): See your own name and roles. - Scope `directory.read` (medium): See the names, roles and reporting lines of people in your organization. - Operation `me` (`directory.self`, read): input none; output Principal. Get the current user as the directory knows them: the person the acting principal is or acts for, never an agent or the app. - Operation `get` (`directory.read`, read): input `id` string (required); output Principal?. Get a principal by id. - Operation `manager` (`directory.read`, read): input `of` string; output Principal?. Get the manager of a principal, or, when of is absent, of the current user: the person the acting principal is or acts for, never an agent or the app. - Operation `members` (`directory.read`, read): input `role` string (required); output Principal[]. List the principals that hold a role. - Operation `find` (`directory.read`, read): input `text` string (required); `limit` integer 1 to 100 (default 20); output Principal[]. Find people whose name matches some text, for choosing an assignee or approver. ### core:records Read and change a collection of records kept somewhere else, such as tickets in a tracker, rows in a spreadsheet or rows in a database table. - Config: `collection` string (required). - Scope `records.read` (medium): Read records in the collection. - Scope `records.write` (medium): Add and change records in the collection. - Scope `records.delete` (high): Remove records from the collection. - Operation `list` (`records.read`, read, paged): input `filter` RecordCondition[] (default []); `sort` SortKey[] (default []); `limit` integer 1 to 500 (default 50); `cursor` string?; output RecordPage. List records that pass every condition, in the requested order, one page at a time. - Operation `get` (`records.read`, read): input `id` string (required); output Record?. Get one record by id. - Operation `count` (`records.read`, read): input `filter` RecordCondition[] (default []); output RecordCount. Count the records that pass every condition. - Operation `aggregate` (`records.read`, read): input `filter` RecordCondition[] (default []); `groupBy` string[] (default []); `measures` object (required); `limit` integer 1 to 1000 (default 100); output RecordAggregate. Group the records that pass every condition and compute measures for each group. - Operation `create` (`records.write`, write): input `fields` object (required); output Record. Add a new record. - Operation `update` (`records.write`, write): input `id` string (required); `fields` object (required); output Record. Change some fields of a record. - Operation `delete` (`records.delete`, write): input `id` string (required); output boolean. Remove a record. - Event `changed` (`records.read`): payload `id` string, `change` "created" \| "updated" \| "deleted", `record` Record?. A record in the collection was added, changed or removed, by this app or anyone else. ### core:share Hand text, a link or files to the device's share mechanism, so the user picks where they go. - Traits: `personal`. - Scope `share.send` (low, given by use): Offer content from this app for you to share wherever you choose. - Operation `send` (`share.send`, external, interactive): input `title` string; `text` string; `url` string; `files` FileRef[]; output boolean. Open the share mechanism with the given content for the person the app is acting for, on a surface of theirs that is open; with none, the call fails with capability.unavailable. ### core:clipboard Copy text to the clipboard, and, with a separate and more sensitive permission, read what is on it. - Traits: `personal`. - Scope `clipboard.write` (low): Copy text to your clipboard. - Scope `clipboard.read` (high): Read whatever text is on your clipboard, which may have come from other apps. - Operation `write` (`clipboard.write`, write): input `text` string (required); output boolean. Put text on the clipboard, replacing what was there. - Operation `read` (`clipboard.read`, read): input none; output string?. Get the text currently on the clipboard, or null if it holds no text. ## Next - `sample-data` to run an app that uses a service without one. - `actions` for `call`, `onError` and `once`. - `rules` for following capability events. --- # Sample data A sample document answers for a service, so that an app that reads from one can run without it. The host's scripted providers return the sample's answers as if the service had given them. The definition does not change: the same file runs against the real service when the host connects one. ## The shape ```json sample=weather { "weather": { "get": { "status": 200, "headers": { "content-type": "application/json" }, "body": { "city": "Lisbon", "now": 18, "days": [ { "date": "2026-11-13", "high": 19, "low": 12, "summary": "Sunny" }, { "date": "2026-11-14", "high": 17, "low": 11, "summary": "Showers" }, { "date": "2026-11-15", "high": 16, "low": 10, "summary": "Cloudy" } ] } } } } ``` - Each top-level key is a capability alias of the definition, here `weather`. - Under it, each key is an operation of that capability's contract, here `get`. - The value is the operation's output, exactly as the contract types it: a `core:http` `get` returns a `core:HttpResponse` with `status`, `headers` and `body`. Every call returns a copy of the same value, whatever its input. - An operation with no answer in the sample fails when it is called, with a message that names the alias and the operation. Give an answer for every operation the app calls on that capability. Run the app with it: ```sh oad run weather.oad.json --sample weather.sample.json ``` A look at the app, and `oad run` without `--sample`, read a `sample-data.json` beside the definition when there is one. When an answer does not fit the operation's output type, the host warns as the app starts, naming the path in the sample. ## Which capabilities need one Write sample answers for capabilities that reach a service: `core:http` and contracts from other catalogs. A core capability the sample does not name is served by the host's own implementation: notifications, the schedule, records, files and the device capabilities work on the reference host without a sample. A `core:http` capability the sample does not name reaches the real address in its `origin`. ## Records a service already holds A `core:records` capability that reads records kept elsewhere, such as tickets in a help desk, starts with an empty collection on the host. Give the records instead of answers, under `$records`: ```json records=helpdesk { "helpdesk": { "$records": [ { "id": "T-1", "subject": "Printer jams", "priority": "high", "status": "open" }, { "id": "T-2", "subject": "Refund not received", "priority": "low", "status": "pending" } ] } } ``` The host's records provider then answers every operation from them: filters, sorting, paging, counts and aggregates follow what the app asks, what it writes is kept, and its first screen is not empty. A fixed answer for `list` gives the same page whatever the filter, the order or the cursor. The records are for everyone, never under `$person`, and the alias holds nothing beside them. ## People in a directory A `core:directory` capability gives its people under `$people`, each with their manager's id: `{ "people": { "$people": [{ "id": "u-1", "name": "Ana Silva", "manager": "u-2" }, { "id": "u-2", "name": "Mara Lind" }] } }`. The host's directory answers from them. ## Writing good answers - **Make the answer look like the real service.** The app's expressions read the answer's fields (`state.forecast.body.days` above), so name the fields as the service does. - **Keep dates current.** Give `"$asOf": "2026-11-13"` at the top level: the day your dates were written for. The host moves each value its type declares a `date` or `datetime` by whole weeks to today, so weekdays and gaps stay. A date in text or in an untyped value, such as the weather `body` above, is not moved: pick dates the app copes with. - **Answers per person.** Under the top-level key `$person`, each key is a person's id and holds answers for that person only, in the same shape as the whole document. Everyone else gets the answers at the top level. - **Errors.** A sample cannot make a call fail; an app's error handling is tried by leaving the operation out of the sample, which makes its calls fail. ## What a sample does not do Outside `$records`, it does not deliver capability events, and it does not remember what the app wrote: a write operation returns its sample answer and changes nothing that a later read returns. Records under `$records` keep each write and announce it as a record changing. ## Next - `capabilities` for the operations and their output types. - `state` for sourced entries that read them. - `start` for how to work: write, check, look, change. --- # Mistakes and their fixes The check reports each problem as a severity, a code, a JSON Pointer to the place and a message. Errors make the definition invalid; warnings mark something legal that probably does not do what you meant. Fix both. Each entry below shows a wrong fragment, what it causes, and the fix. The fragments are changes to this guide's examples. ## Mistakes nothing reports These are not reported: the app checks clean and looks right when you try it alone. Each block below checks with no diagnostic. **A list for several people without `"scope": "shared"`.** Each person gets a list of their own, and nobody sees what the others add. Fix: give the entry `"scope": "shared"`, with `"conflict": "merge"` and `"key": "id"` for a list of records. ```json quiet=groceries#/state/items { "type": "Item[]", "initial": [], "description": "Everything on the household's list, bought or not." } ``` **A notification that only the clock sends, on an optional permission.** Nothing a person does needs the permission, so it may never be asked: the call fails with `grant.denied`, no error is shown, and nothing is sent. Fix: give the person a control whose action uses the permission, as "Turn on reminders" does in the plant care app, or leave the request required (see `capabilities`). Without that button, the plant care app, used by one person, never reminds anyone: ```json quiet=plants#/surfaces/visual/views/home/body/children/1 { "control": "core:text", "props": { "value": "Reminders come by themselves." } } ``` **Reading into a sourced entry before its first answer.** The entry is `null` until the service answers: a required prop that fails draws a placeholder for its control, an optional one its default. Fix: show the node only once the answer is there (`"when": "state.found"` in the weather app), or read with `default`. ```json quiet=weather#/surfaces/visual/views/home/body/children/3 { "control": "core:stat", "props": { "label": "Now", "value": "=`${state.forecast.body.now}°`" } } ``` **An optional input field with no `default`.** A caller that leaves it out leaves it absent, not empty, and the first step that reads it fails the action with `expression.error`. Fix: give the field a plain `default`, or read it with `default(input.author, '')`. ```json quiet=reading#/actions/addBook/input/author { "type": "string", "description": "Who wrote it.", "required": false } ``` **A table column whose `currency` is `"=env.currency"`.** A host that does not know the person's currency gives `null`, which a column cannot hold: the table is replaced by a placeholder. Fix: leave `currency` out, `{ "field": "amount", "label": "Amount", "format": "currency" }`; the host then uses the person's currency when it knows it, and a plain number when not. ```json quiet=reading#/surfaces/visual/views/home/body/children/3 { "control": "core:table", "props": { "label": "Spent", "items": "=[{what: 'Lunch', amount: 12.5}]", "columns": [ { "field": "what", "label": "What" }, { "field": "amount", "label": "Amount", "format": "currency", "currency": "=env.currency" } ] } } ``` **A text in the state that stands for a message.** A step writes "Request sent." into an entry and a text on the screen shows it. Nothing clears it: it still says so after a later request fails, and an agent that did the work never hears it. Fix: give the action `done` (see `actions`); the person sees its message for a moment, and whoever started the action hears it. ```json patch=timeoff consent=no [ { "op": "add", "path": "/state/notice", "value": { "type": "string", "initial": "", "description": "What the app last said." } }, { "op": "add", "path": "/actions/askForTimeOff/steps/2", "value": { "set": "state.notice", "to": "Request sent." } }, { "op": "add", "path": "/surfaces/visual/views/mine/body/children/0", "value": { "control": "core:text", "props": { "value": "=state.notice" } } } ] ``` **A row above a control that holds a heading and a button, to stand in for its header.** It is a row of its own: the button is not announced as the control's, and on a narrow screen it can wrap away from the title. Fix: put the button in the control's `actions` slot, as the weather app's list of days does (see `views`). This row above that list checks clean: ```json quiet=weather#/surfaces/visual/views/home/body/children/3 { "control": "core:stack", "props": { "direction": "horizontal" }, "children": [ { "control": "core:heading", "props": { "value": "Next days", "level": 3 } }, { "control": "core:button", "props": { "label": "Refresh", "icon": "refresh" }, "on": { "press": { "refresh": "state.forecast" } } } ] } ``` **A picker drawn as shapes on a canvas.** Circles on a `core:canvas` as colors, or squares as tools: a canvas grows with its column, so a dot can be a hand wide, and one picture is no radio group: a screen reader cannot tell the options apart, nor the keyboard move between them. Fix: a `core:choice` whose options carry `swatch` or `icon` (see `controls`); a canvas's tools go in its `tools` slot. ```json quiet=groceries#/surfaces/visual/views/home/body/children/3 { "control": "core:canvas", "props": { "label": "Pen color", "aspect": 5, "scene": [ { "kind": "circle", "x": 0.1, "y": 0.5, "r": 0.08, "fill": "text" }, { "kind": "circle", "x": 0.3, "y": 0.5, "r": 0.08, "fill": "accent" } ] } } ``` **A pen stroke drawn as one `line` per move.** A scene that makes a `line` of each pair of a stroke's points costs about 40 units of the expression budget for each point, and a canvas draws at most 5000 shapes: within a minute of drawing, the canvas is replaced by a note, its tools and actions with it, or new strokes are not drawn. Fix: one `path` for each stroke, whose cost does not grow with its points, and an eraser by `event.target` (see `controls`). ```expr flatten(state.ink.map(s, range(size(s.points) - 1).map(i, {kind: 'line', x: s.points[i].x, y: s.points[i].y, x2: s.points[i + 1].x, y2: s.points[i + 1].y}))) ``` **A curve or a round shape made of many points.** A circle as a `path` of points, corners rounded with points, or a gauge of dozens of short lines: each point counts against the canvas's 50000 and costs budget, and edges blur on a large canvas. Fix: an `ellipse`, a `rect` with `radius`, an `arc`, or a `path` whose points carry control points (see `controls`). **A rule that fires many times a second to make motion look smooth.** A game that moves a piece a cell every 300 ms but ticks every 50 ms to slide it works twenty times a second, sends its whole scene each time, and still steps. Fix: a rule at the pace of the game, and `motion` on the canvas or on the piece, with an `id` on the piece; `{ "over": "PT0.3S", "ease": "linear" }` glides it at an even speed (see `controls`). A figure drawn again and again, such as a block, is a symbol placed by `use`. **Up and down buttons on each row of a list a person puts in order.** Two buttons on each row to move it a place up or down fill every row, cannot be dragged, and take a press for each place. Fix: make the list `reorderable` and keep the order `move` gives (see `controls`); the host offers each row a Move control that moves it up or down, and dragging where it can. **Arrow buttons that move an item from list to list.** Back and forward buttons on each card fill every card, cannot be dragged, and take a press for each column. Fix: give the columns one `moveGroup` and a `move` handler that changes the field they filter on (see `controls`); the host offers each card a Move control naming the other columns, and dragging where it can. **One section written by hand for each item of the app's data.** The navigation keeps the notebooks there were when it was written: one made later never gets a section, and one taken away keeps a section that opens an empty page. Fix: one section with `each` over the list, as the notes app does (see `views`). ```json quiet=notes#/surfaces/visual/navigation/1/sections [ { "view": "notebook", "with": { "id": "work" }, "label": "Work", "icon": "file" }, { "view": "notebook", "with": { "id": "home" }, "label": "Home", "icon": "file" }, { "view": "newNotebook", "label": "New notebook", "icon": "add" } ] ``` **Records in the navigation.** Every note as a main section: the navigation grows with the data until a host shows only the first ones and how many more there are, and a person cannot search, sort or act on them there. Fix: keep records in a list inside a view, as the notebook's view lists its notes, and repeat sections only for places a person goes to and stays in. ```json quiet=notes#/surfaces/visual/navigation/1/sections/0 { "each": { "in": "state.notes", "as": "n", "key": "n.id" }, "view": "notebook", "with": { "id": "=n.notebook" }, "label": "=n.text", "icon": "file" } ``` **A part that exports an action which writes an input its parent drives.** The jar exporting `setGoal`: alone it works, but inside the gift fund, whose `with` drives the goal, every run fails with `state.readonly`. Fix: export only actions that leave driven inputs alone; the parent changes the input through what it gives in `with` (see `parts`). ```json quiet=jar#/exports/actions ["putIn", "setGoal"] ``` **The same long formula written in several places.** A change made to one copy and not the others goes unseen. Fix: a derived state entry when it takes no input, a code module when it does (see `code`). **"1 pieces".** A count beside a noun needs `plural`: `plural(size(state.books), {one: 'book', other: 'books'})`, in an app in one language too. ## The document **`schema.invalid`**: a key the format does not have, a required key left out, or a value of the wrong shape. The commonest: an action without `description`. ```json wrong=water#/actions/drink expect=schema.invalid { "steps": [ { "set": "state.glasses", "to": "=state.today + 1" } ] } ``` Fix: add the missing key, or remove or rename the unknown one. The message names it. A step the format does not have is the same mistake, such as one that would show a message after the form is sent: ```json wrong=timeoff#/surfaces/visual/views/ask/body/on/submit/1 expect=schema.invalid { "toast": "Request sent." } ``` Fix: no step shows a message. Give the action `done` with the words, and the host shows them to the person who pressed. **`contract.unknown`**: a `core:` name with no `core` entry in `uses.catalogs`, or a control or capability the catalog does not have. ```json wrong=water#/uses expect=contract.unknown { "catalogs": {} } ``` Fix: add the `uses` block of the smallest app (see `start`), and take names from `controls` and `capabilities`. ## Expressions **`expression.syntax`**: an expression that does not parse. Often an `=` in a field that is always an expression: ```json wrong=water#/state/today/derive expect=expression.syntax "=state.glasses" ``` Fix: no `=` in `derive`, `when`, `if`, `allow`, `where`, `becomes`, `that`. **`reference.unknownState`**: a state entry that does not exist, usually a typo. ```json wrong=water#/state/today/derive expect=reference.unknownState "state.glass" ``` **`expression.unknownRoot`**: a name that is not available at that place, such as `input` in a `derive`, or a local name used outside its step list. ```json wrong=water#/state/today/derive expect=expression.unknownRoot "input.count" ``` **`expression.unknownMember`**: a field a closed type does not have, such as a misspelt record field. ```json wrong=reading#/state/toRead/derive expect=expression.unknownMember "state.books.count(b, b.staus == 'toRead')" ``` **`expression.typeMismatch`**: a value of the wrong kind: text joined to a number with `+`, a list where a condition is expected, a list where a number is declared. ```json wrong=water#/surfaces/visual/views/home/body/children/1/props/value expect=expression.typeMismatch "=state.today + ' of ' + state.goal" ``` Fix: a template, ``"=`${state.today} of ${state.goal}`"``; a comparison, `size(state.books) > 0`; a `derive` whose value fits the `type`. **`expression.effectNotAllowed`**: `uuid()` or `random()` outside a step, or `can` and `canSend` in a guard or a `derive`. ```json wrong=timeoff#/actions/cancel/require expect=expression.effectNotAllowed [ { "that": "canSend('approval', 'cancel', input.id)", "message": "Only a waiting request of yours can be taken back." } ] ``` Fix: write the condition itself in the guard; use `can` and `canSend` in views. ## Writing state **`write.sharedDirect`**: a screen writes `shared` state directly. Fix: run an action that writes it. ```json wrong=groceries#/surfaces/visual/views/home/body/children/1/slots/item/children/1/on/press expect=write.sharedDirect { "set": "state.items", "to": [] } ``` **`view.handlerStep`**: a handler holds a `call`, `send`, `emit`, `code` or `return`. Fix: move the step into an action and `run` it. ```json wrong=plants#/surfaces/visual/views/home/body/children/1/on/press expect=view.handlerStep { "call": "notify.send", "with": { "title": "Reminders are on" } } ``` ## Names and inputs **`field.missing`**: a `with` that leaves out a field the target requires: an action's input, an operation's input or a view's input. ```json wrong=reading#/surfaces/visual/views/home/body/children/2/on/select expect=field.missing { "navigate": "book" } ``` ## Controls **`prop.unknown`** and **`prop.missing`**: a prop the control does not have, or a required prop left out. Take prop names from `controls`. ```json wrong=water#/surfaces/visual/views/home/body/children/2/props expect=prop.missing { "text": "I drank a glass" } ``` This fragment causes both codes: `text` is unknown, and the required `label` is missing. The message of `prop.unknown` names the props the control has. A text field's example text is its `hint`, not `"placeholder"`: ```json wrong=reading#/surfaces/visual/views/addBook/body/children/0/props expect=prop.unknown { "label": "Title", "required": true, "placeholder": "Such as Middlemarch" } ``` Fix: `"hint": "Such as Middlemarch"`. A chart's names are its own: what the values are is `valueLabel`, not `"yLabel"`, with `unit` for what they count; the categories are `categoryLabel`, not `"xLabel"`; a target line is `goal`, not `"target"`; and a series has no `"kind"`, as one chart draws one kind. The message lists the chart's props: ```json wrong=water#/surfaces/visual/views/home/body/children/1 expect=prop.unknown { "control": "core:chart", "props": { "kind": "bar", "label": "Glasses by day", "category": "day", "items": [{ "day": "Mon", "glasses": 6 }], "series": [{ "field": "glasses", "label": "Glasses" }], "yLabel": "Glasses", "target": 8 } } ``` Fix: `"valueLabel": "Glasses", "unit": "glasses", "goal": { "value": 8, "label": "Daily goal" }`. **`value.notKnown`** (warning) on an icon: a name the hosts do not know, such as `"graph"`. It is still a valid value, so nothing fails, but the web host draws no symbol: the button shows its label alone, even with `"iconOnly": true`. The message gives the nearest known names. Fix: a known name, such as `"chart"`; `controls` lists them, and so does `oad catalog` under `IconName`. ```json wrong=water#/surfaces/visual/views/home/body/children/2/props expect=value.notKnown { "label": "I drank a glass", "icon": "graph" } ``` **`view.headingRepeatsTitle`** (warning): the view begins with a heading that says its `title` again. The host already draws the title as the page's or card's heading, so the words show twice. Fix: remove the heading. ```json wrong=water#/surfaces/visual/views/home/body/children/0 expect=view.headingRepeatsTitle { "control": "core:heading", "props": { "value": "Water today" } } ``` **`prop.markdownInPlainText`** (warning): a plain `core:text` holds words written in Markdown (two asterisks around words, lines that start with a hash or a dash, a link written as words in brackets followed by an address), so the person sees the marks. Fix: write the words plainly, with `style` or a `core:heading` for what should stand out; when the text really is formatted, give it `"format": "markdown"`. ```json wrong=water#/surfaces/visual/views/home/body/children/0 expect=prop.markdownInPlainText { "control": "core:text", "props": { "value": "Drink **eight** glasses a day." } } ``` ## Capabilities and grants **`grant.uncovered`**: an operation is called, or read as a source, with no grant request for its scope. ```json wrong=weather#/grants expect=grant.uncovered {} ``` **`state.sensitivityUnstated`** (warning): a source on a scope of `high` sensitivity without `sensitive`. Fix: say `"sensitive": true` or `"sensitive": false`. **`trigger.noBackground`** (warning): an `every` rule, or a flow's `after` timer, with no grant on a `background` capability. It runs only while the app is open. ```json wrong=water#/rules expect=trigger.noBackground { "tick": { "description": "Checks the count every minute.", "when": { "every": "PT1M" }, "do": [] } } ``` Fix: add `"foreground": true` beside `every` when that is what you mean, or ask for `core:scheduler` (see `capabilities`). ## Parts **`part.notExported`**: the parent reads, runs, hears or places something the part does not list in its `exports`. Fix: add it to the part's `exports`, or use what the part exports. ```json wrong=gift#/state/weeksLeft/derive expect=part.notExported "ceil(parts.jar.state.goal / 20)" ``` **`action.unknown`** for a part's action run without the part's name. Fix: `jar.putIn`, the part's name, a dot and the action. ```json wrong=gift#/actions/saveWeek/steps expect=action.unknown [ { "run": "putIn", "with": { "amount": 20 } } ] ``` **`part.unknownDefinition`**: a part's `definition` names the app or its id, not the alias under `uses.definitions`. Fix: `"definition": "jarApp"`. ```json wrong=gift#/parts/jar/definition expect=part.unknownDefinition "jar" ``` ## Other codes the check reports | Code | Cause | Fix | | --- | --- | --- | | `reference.unknownInput` | An `input` field the action does not declare. | Declare it, or fix the name. | | `value.typeMismatch` | A literal that does not fit its type, such as `"eight"` for an `integer`, or an expression as an input field's `default`. | Write a value of the type; a `default` is never an expression (see `expressions`). | | `type.unresolved` | A type name not declared under `types`, or a misspelt primitive. | Declare the type, or fix the name. | | `state.readonly` | A step or binding writes a derived or sourced entry. | Write the stored entries it reads. | | `action.unknown` | A `run` or `can` of an action that does not exist. | Fix the name. | | `field.unknown` | A `with` names a field the action, operation or view does not take. | Use the names its input declares. | | `event.unknown` | A handler for an event the control does not raise, such as click on a button. | Take event names from `controls` (`press`). | | `slot.unknown` | A slot the control does not have, such as `actions` on a `core:stat`. | Put the actions in a group around it, or a button beside it. | | `prop.iconOnlyWithoutIcon` | A button with `"iconOnly": true` and no `icon`: its label is shown. | Give it an `icon`; its `label` stays its name. | | `grant.unknownScope`, `operation.unknown` | A scope or an operation the contract does not have. | Take names from `capabilities`. | | `action.confirmBypassed` | A rule, a flow or an action without `confirm` runs an action that has one. | Let a person run it from a screen. | | `flow.fieldWrite` | A step writes the field that holds a flow's stage. | Move the stage with `send`. | | `flow.unknownEvent` | A `send` of an event no stage of the flow handles. | Fix the name. | | `export.notStored` | An exported input whose path is not a stored entry, such as `"goal"` for `"state.goal"`. | Give the path of a stored entry, such as `state.goal`. | | `view.tabUnnamed` (warning) | A child of `core:tabs` with nothing to name its tab, such as a plain `core:stack`. | Wrap it in a `core:group` with a `title` (see `views`). | ## Texts in several languages | Mistake | What you see | Fix | | --- | --- | --- | | A key added to a translation only | `localization.keyUnknown` | Add it to the default table first. | | A fixed place naming a text with a blank | `localization.fixedNeedsPlainText` | Name a plain text. | | A sentence joined from translated pieces | Words out of order; nothing reported | One entry with blanks (see `languages`). | ## When the app runs These come from a running app, not from the check. The person or agent sees the code and a message. | Code | Cause | Fix | | --- | --- | --- | | `action.invalidInput` | Missing, unknown or wrongly typed input. | Pass what the action's `input` declares. | | `action.forbidden` | `allow` was not true, or the caller has no access. | Expected for callers who may not act; give the reason with `require` instead where the caller can put it right. | | `action.refused` | A `require` entry was not true; carries its `message`. | Expected; make the message say what to change. | | `action.declined` | The person said no to a `confirm`. | Expected. | | `grant.denied` | No permission covers the call: declined, or never asked. | Handle it with `onError` when the request is optional. | | `expression.error` | An expression failed, such as reading a missing optional input. | Read it with `default` or test it with `has`, or give the field a `default`. | | `state.invalidValue` | A write that does not fit the entry's type. | Make the value fit, or widen the type. | | `state.noElement` | A selector found no element. | Check that the element exists, in a `require`. | | `flow.forbidden` | A transition's `allow` was not true. | Expected; check with `canSend` before offering it. | | `flow.noTransition` | The element is not in a state that takes the event. | Offer the event only where `canSend` is true. | ## Next - `start` for how to work and the rules of thumb. - `expressions`, `state`, `actions`, `views` and `capabilities` for each area in full. - `parts` for an app that includes another. --- # Rules A rule is "when this happens, do that": a trigger in `when`, an optional condition in `if`, and steps in `do`. Use one for what the app does on its own, in answer to a change, an event or time. What a person or an agent asks for is an action, not a rule. ```json example=reading#/rules { "allRead": { "description": "When every book on the list has been read, let your agents know.", "when": { "becomes": "size(state.books) > 0 && state.finished == size(state.books)" }, "do": [ { "emit": "allRead" } ] } } ``` `description` is required. `do` holds steps, as an action's `steps` do, and its writes are applied together. ## Triggers `when` holds exactly one trigger: | Trigger | Fires | `event` holds | | --- | --- | --- | | `{ "becomes": expression }` | When the expression turns from not true to `true`. | Nothing useful. | | `{ "changes": path }` | When the value at a state path changes. | `previous` and `current`. | | `{ "event": name }` | On an event: one the app emits (`allRead`), a capability event (`clock.wake`), an action that succeeded (`action:addBook`), a flow transition (`flow:approval`). | The event's payload. | | `{ "every": duration }` | Repeatedly, such as every `PT1M`, while the app is open. | Nothing. | | `{ "lifecycle": "install" }` | When the app is installed; also `open` and `close`, as a person opens or closes it. | Nothing. | An event name must exist: an emitted name needs an `emit` step somewhere, and a capability event must be one of its contract (`event.unknown`): ```json wrong=plants#/rules/remind/when expect=event.unknown { "event": "clock.alarm" } ``` ## `becomes` and `if` `becomes` fires on the edge, once, when its condition turns true; it does not fire again while the condition stays true, and it does not fire when the app opens and the condition is already true (add `"initial": true` beside it for that). Put every part of the condition that the edge depends on inside `becomes`, not in `if`, which is tested only when the edge happens. A condition already true at the start never becomes true: the reading list's rule tests `size(state.books) > 0` inside `becomes`, since with no books every book is read. ## Following a capability event The plant care app schedules a wake for each plant (`clock.wakeAt`), and a rule follows the `wake` event. `event.key` and `event.at` are its payload: ```json example=plants#/rules/remind { "description": "On the morning a plant is due, tell you to water it.", "when": { "event": "clock.wake" }, "do": [ { "let": "plant", "to": "=state.plants.find(p, p.id == event.key)" }, { "if": "plant != null", "then": [ { "call": "notify.send", "once": "=`water:${event.key}:${event.at}`", "with": { "title": "=`Water ${plant.name}`", "body": "=`${plant.name} needs water today.`", "view": "home" }, "onError": [] } ] } ] } ``` A grant must cover the event's scope, as for an operation. `once` makes sure the reminder is sent once even if the rule runs again for the same wake. ## Timers An `every` rule runs only while someone has the app open, once per interval in each open session. Say so with `"foreground": true` beside `every`; otherwise the check warns (`trigger.noBackground`). To run while the app is closed, ask for `core:scheduler` (see `capabilities`); to act at one time rather than repeatedly, schedule a wake with `wakeAt`, as the plant care app does. **A clock for a game.** Count time, not firings. A firing that falls due while other work runs is folded into the next one, a host may hold `every` to a longer interval, and each open window of a person fires the rule once more. So keep the moment of the last step in the state (not in `session` scope), step when `durationBetween` from it to `env.now` reaches the step's length, and keep `env.now` as the new moment. Let the rule fire a few times a step, such as `PT0.05S` for steps of a fifth of a second. What should look smooth between two steps is the canvas's `motion` (see `controls`), not a faster rule. In a chat's frame a change is drawn soon after it happens, at most about ten times a second, or about once a second in a chat that cannot keep a call open. **A scene within its budget.** A canvas's scene is evaluated again on every frame, and like every expression it may use 100,000 cost units: a frame whose scene needs more is not drawn, so an animation stutters, and a canvas whose scene cannot be drawn at all shows a placeholder. A shape costs about 20 to 40 units for a cell placed and colored from its index, so one expression builds a few thousand such shapes at most. What is the same on every frame belongs in a derived state entry, which is evaluated only when what it reads changes and has a budget of its own; the scene adds the shapes that move to it with `+`. A scene may also hold several expressions, each with its own budget, such as groups whose `shapes` are an expression each. A board of 3,000 cells is over the budget as one expression, and drawn on every frame as two derived entries or two groups of 1,500. create_app, change_app and look_at_app name each expression that used more than 80 percent of its budget, and say how many frames of an animation could not be drawn. **Every day at a time of day.** A wake comes once. To act every day at one local time, the rule that follows it schedules the next, as this last step of `remind` would. A time the person chooses is kept as text `HH:MM` (see `start`); pass it to `atTime` in place of `'09:00'`: ```json quiet=plants#/rules/remind/do/2 { "call": "clock.wakeAt", "with": { "key": "=event.key", "at": "=atTime(addDays(env.today, 1), '09:00')" }, "onError": [] } ``` The first wake, when the record is added, is today at that time while it is still to come, else tomorrow. A datetime from `atTime` compares in time order with `env.now`, to the second; this is `true`: ```expr true atTime('2026-11-24', '09:00', 'UTC') > '2026-11-24T08:59:59.500Z' ``` So the first wake is: ```expr example=plants#/actions/addPlant/steps let(at, atTime(env.today, '09:00'), at > env.now ? at : atTime(addDays(env.today, 1), '09:00')) ``` ## Who a rule acts as A rule acts as the app, on behalf of the person whose work caused it: in a rule, `user.kind` is `app` and `user.roles` is empty, and `user.person` is that person. So record who did something in the action they ran (`user.person.name` in `askForTimeOff`), not in a rule it causes. A rule's writes are made for that person: a rule that one person's change fires does not write another person's `user` state. A rule may not run an action that has `confirm` (`action.confirmBypassed`): nobody is there to agree. ## Next - `flows` for processes with named stages. - `actions` for the steps in `do`. - `capabilities` for events, schedules and notifications. --- # Flows A flow is a state machine: a process with named stages, where only some moves between them are allowed. Use one when a record goes through stages (draft, waiting, approved) and who may move it depends on the stage. For a value that just changes, a stored entry and an action are enough. ## A flow over a list of records ```json example=timeoff#/flows/approval { "description": "A request waits for an approver, who approves or declines it; the person who asked can take it back while it waits.", "over": { "collection": "state.requests", "key": "id", "field": "status" }, "initial": "pending", "states": { "pending": { "on": { "approve": { "to": "approved", "allow": "'approver' in user.roles && user.person.id != item.personId", "do": [ { "patch": "item", "with": { "decidedBy": "=user.person.name" } } ] }, "decline": { "to": "declined", "allow": "'approver' in user.roles && user.person.id != item.personId", "do": [ { "patch": "item", "with": { "decidedBy": "=user.person.name" } } ] }, "cancel": { "to": "cancelled", "allow": "user.person.id == item.personId" } } }, "approved": { "final": true }, "declined": { "final": true }, "cancelled": { "final": true } } } ``` - `over` makes one flow instance per element of a stored list: `collection` is the list's path, `key` the field that identifies an element, `field` the field that holds the element's stage. All three are required. - `initial` is the stage of a new element. Append an element without the `field`: the host writes `initial` into it, so the field may still be `required` in the record type, as `status` is in the time off example: ```json example=timeoff#/types/Request/required ["id", "personId", "personName", "from", "to", "note", "status", "decidedBy"] ``` - `states` maps each stage to what it accepts. `on` maps an event name to a transition, or to a list of transitions of which the first whose `if` holds is taken. - A transition has `to` (required), `if` (which transition), `allow` (who may take it) and `do` (steps). In them, `item` is the element and `event` the `with` of the `send`. Write to the element with `{ "patch": "item", "with": ... }`. - `"final": true` marks a stage with no moves out. A move may go back to an earlier stage. With this `declined` stage, the person who asked can hand a request in again, corrected by the `with` of the `send`: ```json quiet=timeoff#/flows/approval/states/declined { "on": { "handIn": { "to": "pending", "allow": "user.person.id == item.personId", "do": [ { "patch": "item", "with": { "note": "=event.note", "decidedBy": "" } } ] } } } ``` ## Moving a flow An action sends an event with a `send` step; for a flow over a list, `key` says which element: ```json example=timeoff#/actions/approve/steps [ { "send": "approve", "to": "approval", "key": "=input.id" } ] ``` A `send` carries data in `with`, which the transition reads as `event`. This patch lets an approver give a reason when declining: ```json patch=timeoff consent=no [ { "op": "add", "path": "/actions/decline/input/reason", "value": { "type": "string", "description": "Why, in words the person reads.", "default": "" } }, { "op": "replace", "path": "/actions/decline/steps", "value": [ { "send": "decline", "to": "approval", "key": "=input.id", "with": { "reason": "=input.reason" } } ] }, { "op": "replace", "path": "/flows/approval/states/pending/on/decline/do", "value": [ { "patch": "item", "with": { "decidedBy": "=`${user.person.name}: ${event.reason}`" } } ] } ] ``` A handler cannot `send` (`view.handlerStep`): the screen runs the action, so an agent moves the flow on the same terms. A flow over a list needs `key`, a flow without `over` must not have one (`flow.keyMismatch`): ```json wrong=timeoff#/actions/approve/steps expect=flow.keyMismatch [ { "send": "approve", "to": "approval" } ] ``` When the transition's `allow` is not true, the event fails with `flow.forbidden` and nothing moves; the reason is not told. When the element's stage has no transition for the event, it fails with `flow.noTransition`. Give the person words by checking the same conditions in the action's `require` (see the time off example's `decline`), and show a button only where `canSend` is true (see `views`). ## The stage field belongs to the flow Only the flow writes the element's stage. A step or binding that writes it is `flow.fieldWrite`, whether through the list or through `item`. Read it freely: `state.requests.filter(r, r.status == 'pending')`. To show it in words, read a map by it; the time off example's table gives each row its words in a field of its own: ```json example=timeoff#/surfaces/visual/views/mine/body/children/1/props/items "=state.requests.filter(r, r.personId == user.person.id).map(r, merge(r, {stage: {pending: 'Waiting', approved: 'Approved', declined: 'Declined', cancelled: 'Taken back'}[r.status]}))" ``` ## Stages with steps and timers A stage may have `enter` and `exit` steps, run when an element arrives in it and leaves it. A stage may have `after`: a duration mapped to a transition taken when the element stays that long, such as the duration `P3D` mapped to a transition to a later stage. Timers run only while someone has the app open, unless the app holds a `core:scheduler` grant (`trigger.noBackground` warns otherwise). ## A flow without `over` A flow without `over` has one instance for the whole app, such as the phases of a game. Its stage is read as `flows..state`, and `send` takes no `key`. ## Events Every transition raises `flow:` with `from`, `to`, `event` and `key`. A rule can follow it, and an agent surface can list it. To notify people of a move, do it in the transition's `do`, or in a rule that follows `flow:`. ## Next - `people` for roles and who may move a record. - `actions` for the actions that send events. - `rules` for following transitions. --- # Code modules A code module is a small JavaScript function that the app carries in its definition and runs in a sandbox. It is the last resort: most apps need none. ## What a module is A pure function from its input to its output, with no network, storage, clock, randomness, timers, host objects or capabilities: a date made without arguments fails ("this sandbox has no clock"), and so do Date.now and Math.random. Pass in what it needs: the time as `env.now` or `env.today`, a random number from `random()` in a `let` step before the call. Dates in a module are UTC. Its result is plain JSON of its `output` type. ## When to write one, and when not Try expressions first: a host explains them to the person in plain words, the checks follow every name in them, and each is bounded by the cost budget. The checks cannot see into a module. Write a module when: - the same logic would be written in several places with different inputs: expressions have no functions of your own; - the logic is a search or a parse whose steps depend on what it finds, such as the moves of a computer player, a scorer that looks ahead, or the fewest stamps that make a sum; - an expression comes near its cost budget and cannot be split. Do not write one for arithmetic, text or a list that an expression says in a line, or for anything that needs the outside world: that is a capability (see `capabilities`). ## Saying a thing once without code A derived state entry is the way to write logic once when it takes no input of its own: every place reads `state.said`. No parameters, a derived entry; parameters, a module. ## Writing one The postage example finds the fewest stamps that pay a postage exactly: ```json example=postage#/code/fewestStamps { "description": "Finds the fewest stamps whose values add up to the postage exactly, largest first, trying every mix of the values given. It fails when no mix makes the postage.", "runtime": "js", "input": { "postage": { "type": "integer", "description": "The postage to pay, in cents." }, "values": { "type": "integer[]", "description": "The values of the stamps to choose from, in cents." } }, "output": "integer[]", "source": "export default function ({ postage, values }) { const best = [[]]; for (let a = 1; a <= postage; a++) { for (const v of values) { const rest = best[a - v]; if (v > 0 && v <= a && rest !== undefined && (best[a] === undefined || rest.length + 1 < best[a].length)) best[a] = [...rest, v]; } } if (best[postage] === undefined) throw new Error(`no mix of these stamps makes ${postage}`); return best[postage].sort((x, y) => y - x); }", "limits": { "timeMs": 50, "memoryMb": 16 } } ``` - `runtime` is `"js"`: `source` is a module whose default export is the function, called with the input as one object. - `input` is a field map, as an action's, and `output` a type. Both are checked as values cross into and out of the sandbox. - Write the text in `source`. The hosts of these tools do not run a module given by address in `module`: its step fails with `code.unsupported`. Every module needs a grant request that names it (`code.noGrant` without one). It may set only `reason`, `rate`, `duration` and `required`: ```json example=postage#/grants { "stampMath": { "code": "fewestStamps", "reason": "Works out which of your stamps to use. It runs inside the app and reaches nothing else." } } ``` ## Calling one A `code` step runs it, with `with` for the input and `as` for the output: ```json example=postage#/actions/stampLetter/steps/0 { "code": "fewestStamps", "with": { "postage": "=state.letterPostage", "values": "=state.stamps" }, "as": "picked", "orElse": "=error.code == 'code.failed' ? [] : null" } ``` The steps of an action, of a rule's `do` and of a flow transition's `do` can call a module. A view's handler cannot (`view.handlerStep`): run an action from it. Nor can an expression: a `derive` or a prop that names a module is reported (`expression.unknownFunction`) and fails when it runs. So an action runs the module and stores its result, and the view shows what is stored. In the example, `stampLetter` and `stampParcel` both call `fewestStamps`, each with its own postage, and both store the result in `state.last`, which the screen shows through `state.said`. ## What a person is told Nobody is asked: a module reaches nothing, so its request is given without asking, and the person may turn it off in the app's permissions. A person reads the module's `description` (`oad explain` shows it with the input, the limits and the actions that run it) and the request's `reason`, never the source. Say truthfully what the module does, and when it fails. ## Limits and failures A module may run 100 ms and use 32 MB unless `limits` asks for other values. A host may cap what it asks: the hosts of these tools give at most 10 seconds and 256 MB. A failure is the step's, with `error.code`: | Code | When | | --- | --- | | `code.limit` | It ran longer than its time, or needed more than its memory. | | `code.failed` | It threw (`error.message` holds its message), returned nothing or something that is not plain data, or returned a value that is not of its `output` type. | | `code.unsupported` | The host cannot run it. Where a chat cannot reach the tools, it shows a preview of the app, which refuses every module, says so in a line and offers "Open in browser", where the module runs. | Handle it on the step: `orElse` is the value of the `as` name when the step fails, and `onError` holds steps that run first, with `error` to read. Without either, the action fails and nothing it wrote is kept. The example tells the two apart: `[]` when no mix of stamps makes the postage, `null` when the module could not run, and `state.said` words each. ## Next - `actions` for steps and failures. - `state` for derived entries. - `expressions` for what to try before a module. - `capabilities` for grant requests and when they are asked. --- # People and roles One installation of an app can be used by several people: a household's shopping list, a team's time off. The person who installed it is its owner; the others are members. ## Who sees what What each person sees follows from where each value lives (see `state`). A list that several people work on is written as the groceries list in `start` is, with `"scope": "shared"`, `"conflict": "merge"` and `"key": "id"`; without `"scope": "shared"` each person sees only their own list, and nothing reports it. ## Who is acting: `user` `user` is whoever is acting: `user.id`, `user.name`, `user.kind` (`person`, `agent` or `app`), `user.roles`, and `user.person`, the person behind the act. For a person, `user.person` is that person; for an agent working for someone, it is that someone. - **Record who did something with `user.person`**, in the action they ran: `askForTimeOff` stores `user.person.id` and `user.person.name` on the request, so a request an agent files for Sam is Sam's. - **Compare with `user.person.id`** to let a person, or an agent acting for them, act on their own records: `user.person.id == item.personId`. - **Require `user.kind == 'person'`** for an act a person must do themselves, not through an agent, and say so in the `require` message. ## Ids and names A person's id never changes; their name is what the host calls them now. Store the id on a record: you compare it with `user.person.id`, and it finds the person again. A name stored beside it is a copy, as it was then. When you run an app with nobody named, its one person has the id `"local-user"` and the name `"You"`, so a name stored then reads "You" to everyone. Run it with people named (see the end of this topic) to see real names: each person then has the id and the name you give, and a name left out is the id. To show the name of someone a record names, find their id in a list of the app's people, such as the one below. ## Roles A role names what someone may do anywhere in the app, such as approving time off. Declare each role the guards test, with a description: ```json example=timeoff#/roles { "approver": { "description": "Approves or declines other people's time off." } } ``` The definition never says who holds a role: the host assigns roles. The owner holds every declared role unless the host's policy says otherwise; a member holds the roles the owner or the host's policy gives them, and none by default. Test a role with `'approver' in user.roles`. **Only the person who set it up may.** Declare a role, require it in the action, and show the control only when it holds. The owner holds the role, and nobody else does until given it. This patch lets only the owner of the groceries app take things off the list: ```json patch=groceries consent=no [ { "op": "add", "path": "/roles", "value": { "organizer": { "description": "Set the list up, and may take things off it." } } }, { "op": "add", "path": "/actions/removeItem/require", "value": [ { "that": "'organizer' in user.roles", "message": "Only the person who set up the list can take things off it." } ] }, { "op": "add", "path": "/surfaces/visual/views/home/body/children/1/slots/item/children/2/when", "value": "'organizer' in user.roles" } ] ``` A link between a person and one record ("the manager of this request") is not a role: store the person's id on the record and compare it with `user.person.id`. That is how the time off flow keeps an approver from deciding their own request: `user.person.id != item.personId`. ## Who uses the app An app cannot ask for the list of everyone who uses it: no expression and no operation gives the people of an installation. The directory, `core:directory`, is an organization's list of people, not the app's. It knows only whom the host's directory lists; on the reference host it lists nobody unless a sample document answers for it. Use it only in an app for an organization whose host connects its directory (its operations are in `capabilities`). For a household or a team, use a shared list that people add themselves to, with one press: it works on every host. Each person's id and name come from `user.person`. This patch gives the groceries app one, and shows a name found by id. Its `join` keeps one record for each person, under their id: an `if` adds the record, or changes it when the person has one, the shape of any "one answer each" app: ```json patch=groceries consent=no [ { "op": "add", "path": "/types/Person", "value": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" } }, "required": ["id", "name"], "additionalProperties": false } }, { "op": "add", "path": "/state/people", "value": { "type": "Person[]", "initial": [], "scope": "shared", "conflict": "merge", "key": "id", "description": "The people of the household who joined the list." } }, { "op": "add", "path": "/actions/join", "value": { "description": "Join the household's list, or bring your name on it up to date.", "steps": [ { "if": "state.people.exists(p, p.id == user.person.id)", "then": [ { "patch": "state.people", "where": "item.id == user.person.id", "with": { "name": "=user.person.name" } } ], "else": [ { "append": "state.people", "value": { "id": "=user.person.id", "name": "=user.person.name" } } ] } ] } }, { "op": "add", "path": "/surfaces/visual/views/home/body/children/-", "value": { "control": "core:button", "props": { "label": "=state.people.exists(p, p.id == user.person.id) ? 'Update my name' : 'Join this list'" }, "on": { "press": { "run": "join" } } } }, { "op": "add", "path": "/surfaces/visual/views/home/body/children/-", "value": { "control": "core:text", "props": { "value": "=`Joined as ${default(state.people.find(p, p.id == user.person.id).name, 'nobody yet')}`" } } } ] ``` To give a record to someone, offer the joined people in a `core:choice` (each `value` an id, each `label` a name) and store the id. Someone who has not joined cannot be chosen, so say on the screen that each person joins once. ## Who may act - Every member may run every action that is not `internal`, unless the host's policy narrows it. Guard each action that not everyone may run, with `allow` or `require`. - Guard actions, not screens. A section's `when` and a button's `when` decide what is shown; the guards decide what is allowed, for every surface. ## Permissions with several people The owner answers most grant requests once, for everyone; with several people, the reference host asks the owner as the app opens. Each person answers for personal capabilities (see `capabilities`). ## Trying it with several people Look at the app as each kind of person: the tool you were given to look at an app takes the people who use it, the owner first, and `oad run` takes them at a terminal: ```sh oad run timeoff.oad.json --person 'olga:Olga' --person 'sam:Sam' --person 'ana:Ana:approver' ``` Give a member only roles the app declares. ## Next - `state` for scopes and conflicts. - `flows` for records that move through stages. - `agents` for what an agent acting for a person may do. - `capabilities` for the directory and when permissions are asked. --- # Agents An app can be used by agents as well as people. The agent surface turns the app's actions into tools an agent calls and its state into resources it reads. There is no separate logic for agents: a tool is an action, with the same `allow`, `require` and `confirm`. ## The agent surface ```json example=reading#/surfaces/agent { "instructions": "Use addBook once per book, with the author when the person gives one. Read books to say what is on the list. removeBook asks the person to confirm.", "tools": { "include": ["addBook", "setStatus", "removeBook"], "describe": { "setStatus": "Say whether the person has not started a book, is reading it, or has read it. Take its id from the books resource." } }, "resources": { "include": ["books", "toRead"] }, "events": { "include": ["allRead"] } } ``` The surface exists only when `surfaces.agent` is there: `"agent": {}` is a complete one, and without the key an app gives agents nothing. | Field | What it does | | --- | --- | | `instructions` | What an agent should know to use the app well: which tool to use for what, units, what needs the person. | | `tools` | Every action that is not `internal` is a tool. `include` or `exclude` (one of them) narrows the list; `describe` replaces an action's description for agents. | | `resources` | Every state entry that is neither sensitive nor `internal` is a resource. `include` or `exclude` narrows the list; `include` is the only way to give an agent a sensitive entry. | | `events` | App events (from `emit`) and `flow:` that an agent is told of when work done for its person raises them. | A name in these lists must exist (`surface.unknownName`), and an `internal` entry or action cannot be included (`state.internal`, `action.internal`): ```json wrong=reading#/surfaces/agent/resources expect=state.internal { "include": ["heading"] } ``` ## What makes a good tool - **The description is the documentation.** An agent learns what a tool does from the action's `description` (or its `describe` text) and the descriptions of its input fields. Say what the action does, what each field means, and its units. - **Inputs with defaults.** An agent leaves out what it does not know; a field with a `default` lets it. - **Refusals with words.** A `require` entry's `message` reaches the agent, which can tell the person or try again. An `allow` refusal says nothing, and an unknown tool, an `internal` action and an action the agent may not use are refused alike (`action.forbidden`). - **Return something useful.** `output` and `return` give the agent what it needs next, such as the id of what it created. ## What an agent may do An agent acts for a person, with the access that person gave it, and never with more. In expressions, `user` is the agent (`user.kind` is `agent`) and `user.person` is the person it acts for (see `people` for records and acts that belong to the person). So: - An action with `confirm` asks the person, never the agent. The agent's call waits for the answer, and fails with `action.declined` when the person says no. - An agent never runs a screen's handlers or writes a binding: only tools. ## Keeping things from agents - Mark an entry `"sensitive": true` to keep it off the surface unless `resources.include` names it, or `"internal": true` so it is never a resource (see `state`). - Mark an action `"internal": true` for steps that only the app's own screens and steps should run. ## Trying it `oad run reading.oad.json --agent` starts the app and serves the agent surface, printing where an agent connects and a client configuration for it. ## Next - `actions` for descriptions, input, `require` and `confirm`. - `people` for who the agent acts for. - `state` for `sensitive` and `internal`. --- # Parts A part is a whole app shown and used inside another app. The app that includes it, the parent, places the part's views on its own screens, reads some of its state, runs some of its actions and hears some of its events. The part keeps its own state, actions, rules and permissions, and offers the parent only what it lists under `exports`. The examples of this topic are a pair: `jar`, a savings jar that is useful by itself, and `gift`, a gift fund that includes the jar as a part named `jar`. Both are whole examples, printed in full at the end of this topic. ## When to reach for a part, and when not Reach for a part when a piece of an app is an app in its own right: - **A piece several apps share.** One savings jar inside a gift fund, a trip planner and a wedding planner, written once. - **A piece useful alone and inside something larger.** The person uses the jar by itself today, and the gift fund shows the same jar tomorrow. Most apps are one definition, and should stay one. Two mistakes: - **Splitting one app into parts to tidy it.** Every value the parent reads and every action it runs must then be exported and named across the boundary. Keep one app, with several views and a `types` entry for each record shape. - **A part for what a view or a type already does.** A piece of screen used in two places is a view; a record shape used in two places is a type (see `views` and `state`). What a part cannot do: it is fixed when the app loads. The parent cannot choose a part, open one or add one while it runs. Each name under `parts` is one instance with its own state; two jars are two names, each with its own entry. ## The included app's side: exports The part lists what a parent may use. This is the jar's: ```json example=jar#/exports { "inputs": { "goal": "state.goal" }, "state": ["saved", "remaining"], "actions": ["putIn"], "events": ["goalReached"], "views": ["summary"] } ``` | Kind | What it lists | What the parent may do with it | | --- | --- | --- | | `inputs` | An input name and the path of a stored entry it fills. | Give it a value with `with`. While the parent drives it, the entry is read-only inside the part. | | `state` | Entries, stored or derived. | Read `parts.jar.state.remaining` in any expression. | | `actions` | Actions. | Run `{ "run": "jar.putIn" }` in its steps. | | `events` | Events the part raises with an `emit` step. | Hear `{ "event": "jar.goalReached" }` in a rule. | | `views` | Views. | Place `{ "part": "jar", "view": "summary" }` among its nodes. | Everything else stays private. The parent cannot read the jar's `goal` (it gives it instead), run `setGoal` or `empty`, or show the `home` view. The jar runs its own rules and asks for its own permissions wherever it is shown. A view you export should not offer to change a driven input: inside the gift fund, the jar's summary shows the goal but has no form for it. ## The parent's side The parent names the definition it includes under `uses.definitions`, by its `id` and a range of versions, under an alias of its choosing: ```json example=gift#/uses { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } }, "definitions": { "jarApp": { "id": "com.example.jar", "version": "^1.0.0" } } } ``` Then it gives the part a name under `parts`, with the alias as its `definition`: ```json example=gift#/parts { "jar": { "definition": "jarApp", "with": { "goal": "=state.price" }, "capabilities": { "notify": "notify" }, "grants": { "goalNotice": { "rate": { "count": 1, "per": "P1D" } } } } } ``` - **`with`** gives each exported input an expression of the parent's. It follows the parent: when the price changes, the jar's goal changes with it. Its type must fit the input's (`expression.typeMismatch` otherwise). - **Reading state.** The gift fund derives the weeks to go from the jar: ```json example=gift#/state/weeksLeft { "type": "integer", "derive": "ceil(parts.jar.state.remaining / 20)", "description": "Weeks to go at 20 dollars a week." } ``` - **Running an action.** A step runs the part's action by the part's name and the action's, with its input: ```json example=gift#/actions/saveWeek { "description": "Put this week's 20 dollars in the jar.", "steps": [ { "run": "jar.putIn", "with": { "amount": 20 } } ] } ``` - **Hearing an event.** A rule of the parent triggers on the part's event; `event` holds what the part's `emit` gave (here `event.saved`): ```json example=gift#/rules/noteTheDay { "description": "When the jar reaches the price, note the day.", "when": { "event": "jar.goalReached" }, "do": [ { "set": "state.savedOn", "to": "=env.today" } ] } ``` - **Placing a view.** A part node takes `part`, `view` and, if you like, `id` and `when`, and nothing else: ```json example=gift#/surfaces/visual/views/home/body/children/1 { "part": "jar", "view": "summary" } ``` ### Capabilities and permissions A part's capability that the parent does not map is bound for the part as if it ran alone. `capabilities` maps one of the part's aliases to one of the parent's, which must have the same contract; the parent declares it under its own `capabilities` even when only the part uses it. The jar's `notify` goes through the gift fund's. The part's grant requests are put to the person as the app's, named with the part: the person is asked for `jar.goalNotice`, with the jar's reason. Under `grants`, the parent may narrow a request (a lower `rate`, a shorter `duration`, fewer `scopes`, an added `where`) or decline it with `false`, and then nobody is asked for it. It can never widen one. The gift fund lets the jar notify once a day instead of three times. A part's service is answered by the parent's sample document, as when the app runs: under the parent's alias for a capability it maps, and under the part's name and alias joined by a dot for one it does not (see `sample-data`). ## How to work 1. Write the part first, as an app of its own, with its `exports`. Save it, then check it and look at it by itself. 2. Write the parent and save it under another name. The tools find the part among the person's apps by its `id` and the range under `uses.definitions`, whatever its name or file; where several versions fit, the highest wins. 3. Leave `digest` out while both are drafts: it pins one exact text of the part, and the part changes with every change you make. `source` is not needed either. 4. A change to the part is seen the next time the parent is shown or looked at. A change that removes an export raises the part's major version, and the parent's range must follow it: `^2.0.0` for 2.0.0. 5. Taking back a change of the parent brings back the parent only; the part stays as it is now. 6. Download writes one file with copies of the apps it includes, so it opens alone. A file may carry such copies; they are used as they came. To change one, take the draft apart with unpack_app. What the tools say when a part cannot be used, and what to do: | They say | Do | | --- | --- | | No app has the id | Save the part first, or fix the `id`. | | None fits the range, and the versions there are | Write a range that one of them fits. | | A digest that differs | Leave `digest` out. | | The part does not pass its checks, with its first problem | Fix the part first, then try the parent again. | | A cycle, or more than 8 levels of parts | Take an include out; a part never includes its parent. | | More than 16 parts in all, or more of them than one definition holds (2.5 MiB) | Use fewer parts. | ## The whole pair The jar, the part: ```json example=jar { "oad": "0.2", "id": "com.example.jar", "version": "1.0.0", "meta": { "name": "Savings jar", "description": "Money put aside toward a goal: what is saved, what is left, and a word when the goal is reached." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "capabilities": { "notify": { "contract": "core:notify", "description": "Tells you when the jar reaches its goal.", "required": false } }, "grants": { "goalNotice": { "capability": "notify", "scopes": ["notify.self"], "reason": "Tell you when the jar reaches its goal.", "rate": { "count": 3, "per": "P1D" }, "required": false } }, "state": { "goal": { "type": "number", "initial": 100, "description": "How much to save, in US dollars." }, "saved": { "type": "number", "initial": 0, "description": "How much is in the jar, in US dollars." }, "remaining": { "type": "number", "derive": "max(state.goal - state.saved, 0)", "description": "How much is still to save." } }, "actions": { "putIn": { "description": "Put money in the jar.", "input": { "amount": { "type": "number", "description": "How much, in US dollars." } }, "steps": [ { "set": "state.saved", "to": "=state.saved + input.amount" }, { "if": "state.saved >= state.goal && state.saved - input.amount < state.goal", "then": [ { "emit": "goalReached", "with": { "saved": "=state.saved" } }, { "call": "notify.send", "with": { "title": "Goal reached", "body": "=`The jar holds ${state.saved} dollars.`" }, "onError": [] } ] } ] }, "setGoal": { "description": "Change how much to save.", "input": { "goal": { "type": "number", "description": "The new goal, in US dollars." } }, "steps": [ { "set": "state.goal", "to": "=input.goal" } ] }, "empty": { "description": "Take everything out of the jar.", "confirm": { "message": "=`The ${state.saved} dollars in the jar are taken out.`" }, "steps": [ { "set": "state.saved", "to": 0 } ] } }, "exports": { "inputs": { "goal": "state.goal" }, "state": ["saved", "remaining"], "actions": ["putIn"], "events": ["goalReached"], "views": ["summary"] }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "Savings jar", "state": { "goal": { "type": "number?", "description": "The goal being typed." } }, "body": { "control": "core:stack", "children": [ { "control": "core:progress", "props": { "label": "Saved", "value": "=state.saved", "max": "=state.goal", "format": "currency", "currency": "USD" } }, { "control": "core:button", "props": { "label": "Put in 10 dollars", "emphasis": "high" }, "on": { "press": { "run": "putIn", "with": { "amount": 10 } } } }, { "control": "core:form", "props": { "submitLabel": "Set the goal" }, "on": { "submit": [ { "run": "setGoal", "with": { "goal": "=default(view.goal, state.goal)" } }, { "set": "view.goal", "to": null } ] }, "children": [ { "control": "core:numberInput", "props": { "label": "Goal in dollars", "min": 1, "required": true }, "bind": { "value": "view.goal" } } ] }, { "control": "core:button", "props": { "label": "Empty the jar", "emphasis": "low", "destructive": true }, "on": { "press": { "run": "empty" } } } ] } }, "summary": { "title": "Savings jar", "body": { "control": "core:stack", "children": [ { "control": "core:progress", "props": { "label": "Saved", "value": "=state.saved", "max": "=state.goal", "format": "currency", "currency": "USD" } }, { "control": "core:text", "props": { "value": "=state.remaining == 0 ? 'The goal is reached.' : `${state.remaining} dollars to go.`" } } ] } } } } } } ``` The gift fund, the parent: ```json example=gift { "oad": "0.2", "id": "com.example.gift", "version": "1.0.0", "meta": { "name": "Gift fund", "description": "Saving for one gift with a savings jar: the gift's price is the jar's goal, and the app notes the day enough is saved." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } }, "definitions": { "jarApp": { "id": "com.example.jar", "version": "^1.0.0" } } }, "parts": { "jar": { "definition": "jarApp", "with": { "goal": "=state.price" }, "capabilities": { "notify": "notify" }, "grants": { "goalNotice": { "rate": { "count": 1, "per": "P1D" } } } } }, "capabilities": { "notify": { "contract": "core:notify", "description": "Passed to the savings jar, so it can tell you when the gift is paid for.", "required": false } }, "state": { "gift": { "type": "string", "initial": "A new bike", "description": "The gift to save for." }, "price": { "type": "number", "initial": 240, "description": "What the gift costs, in US dollars." }, "savedOn": { "type": "date?", "initial": null, "description": "The day the jar reached the price." }, "weeksLeft": { "type": "integer", "derive": "ceil(parts.jar.state.remaining / 20)", "description": "Weeks to go at 20 dollars a week." } }, "actions": { "saveWeek": { "description": "Put this week's 20 dollars in the jar.", "steps": [ { "run": "jar.putIn", "with": { "amount": 20 } } ] }, "setPrice": { "description": "Change what the gift costs.", "input": { "price": { "type": "number", "description": "The new price, in US dollars." } }, "steps": [ { "set": "state.price", "to": "=input.price" }, { "set": "state.savedOn", "to": null } ] } }, "rules": { "noteTheDay": { "description": "When the jar reaches the price, note the day.", "when": { "event": "jar.goalReached" }, "do": [ { "set": "state.savedOn", "to": "=env.today" } ] } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "=state.gift", "state": { "price": { "type": "number?", "description": "The price being typed." } }, "body": { "control": "core:stack", "children": [ { "control": "core:text", "props": { "value": "=state.savedOn != null ? `Enough was saved on ${formatDate(state.savedOn, 'long')}.` : (state.weeksLeft == 0 ? 'Enough is saved.' : `${state.weeksLeft} weeks to go at 20 dollars a week.`)" } }, { "part": "jar", "view": "summary" }, { "control": "core:button", "props": { "label": "Save this week's 20 dollars", "emphasis": "high" }, "on": { "press": { "run": "saveWeek" } } }, { "control": "core:form", "props": { "submitLabel": "Set the price" }, "on": { "submit": [ { "run": "setPrice", "with": { "price": "=default(view.price, state.price)" } }, { "set": "view.price", "to": null } ] }, "children": [ { "control": "core:numberInput", "props": { "label": "Price in dollars", "min": 1, "required": true }, "bind": { "value": "view.price" } } ] } ] } } } } } } ``` ## Next - `views` for the views a part exports and the nodes around them. - `capabilities` for requests and how a part's are asked. - `mistakes` for the mistakes made most with parts. --- # Changing an app An app is changed by editing its definition, in small steps that a person can review. People may already use it: their data stays, and what they agreed to is asked again only when it changed. ## Small edits as patches Everything named in a definition lives in an object keyed by its name, so each thing has a stable JSON Pointer: `/actions/drink`, `/state/goal`, `/surfaces/visual/views/home`. An edit is a JSON Patch (RFC 6902): a list of operations, each with `op` (`add`, `replace`, `remove`, and also `move`, `copy`, `test`), a `path` and, for `add` and `replace`, a `value`. Adding to the end of a list uses `-` as the last segment of the path. This patch gives the water app a button that starts the day's count again: ```json patch=water consent=no [ { "op": "replace", "path": "/version", "value": "1.1.0" }, { "op": "add", "path": "/actions/reset", "value": { "description": "Start today's count again from zero.", "confirm": true, "steps": [ { "set": "state.glasses", "to": 0 }, { "set": "state.countedOn", "to": "=env.today" } ] } }, { "op": "add", "path": "/surfaces/visual/views/home/body/children/-", "value": { "control": "core:button", "props": { "label": "Start again", "emphasis": "low" }, "on": { "press": { "run": "reset" } } } } ] ``` Apply it with `oad patch`. The result is checked first; if it has errors, nothing is written. It prints, in plain words, what changed: ```sh oad patch water.oad.json --patch edit.json --in-place ``` `--dry-run` checks and describes without writing; without `--in-place` or `--out` the patched definition is printed. `oad diff` describes the difference between two files, and with `--patch` prints it as a patch. With the chat tools, a new app that fails its checks is kept unfinished under its name. Mend it with change_app, a small patch of the places the diagnostics name, never the whole definition again: each patch that applies is kept, and the app is made once the checks pass. ## Changes that widen what the app may do Some changes need a person's yes before they are made: a new or wider permission, a new capability call or web address, a removed or loosened guard (`allow`, `require`, `confirm`), more given to agents, a value that is no longer sensitive. This patch makes the water app send a notification, so it needs one: ```json patch=water consent=yes [ { "op": "replace", "path": "/version", "value": "1.2.0" }, { "op": "add", "path": "/capabilities", "value": { "notify": { "contract": "core:notify", "description": "Tells you when you reach the day's goal." } } }, { "op": "add", "path": "/grants", "value": { "goalNotice": { "capability": "notify", "scopes": ["notify.self"], "reason": "Tell you once a day when you reach your goal.", "required": false } } }, { "op": "add", "path": "/rules", "value": { "goalReached": { "description": "When today's count reaches the goal, say so.", "when": { "becomes": "state.goal > 0 && state.today >= state.goal" }, "do": [ { "call": "notify.send", "once": "=`goal:${user.person.id}:${env.today}`", "with": { "title": "Goal reached" }, "onError": [] } ] } } } ] ``` `oad patch` writes such a change only with `--allow-wider`, and otherwise exits with status 3 and lists what needs consent. Show the person that list and ask before you add the flag. Never add it on your own. ## Keeping a history With `--history`, `oad patch` records each change in a file beside the definition (`water.oad.history.json`): the version, the time, who made it, the request in the requester's words, and the patch. `--by` says who made the change and `--intent` gives the request; a widening change also needs `--approved-by` with the person who agreed: ```sh oad patch water.oad.json --patch edit.json --in-place --history --by agent:editor --intent "Add a button to start the day again" ``` `oad undo water.oad.json --in-place` takes back the last recorded change. Before you change an app the person has used, call the tool read_use_report: it says which actions failed for them, with the host's code, and which permissions they declined. ## Versions - Raise `version` with every change. `oad patch --history` refuses a change that leaves it as it was. - Removing or renaming an action, an action's input field, a state entry an agent can read, or anything in `exports` breaks the people and agents that use it: raise the first number (`2.0.0`). Adding is a smaller change (`1.1.0`); fixing a description or a label, the last (`1.0.1`). - Never change `id`: a new id is a different app, which starts with no data. ## What happens to people's data When the owner runs the new version, the host keeps the stored values. A state entry the new version adds starts at its `initial`. A stored value that no longer fits its entry's new `type` is replaced by the `initial`, so change a type with care, or add a new entry and leave the old one. A record of a collection flow in a stage the new version no longer has goes back to the flow's `initial`. A grant request that changed is asked again; one that did not keeps its answer. ## Next - `mistakes` for what `oad validate` reports after an edit. - `capabilities` for what counts as a permission. - `start` for how to work. --- # Texts in several languages An app can carry its own texts in several languages, in one table: `localization`. Each person sees the app in the language they read, when the app has it, and in its default language otherwise. Nothing translates for you: you write every text in every language, and the checks and tools count what is missing. The host's own words (its buttons, its permission sheet) stay as they are. ## When to add a table Add `localization` when the person asks for an app in a language other than English, or for readers of more than one language. The smallest table is the default language alone. It says which language the app's plain texts are in, and so which way they read: an app written in Arabic, Hebrew, Persian or Urdu reads right to left only when it says so. ```json patch=water consent=no [ { "op": "add", "path": "/localization", "value": { "default": "en" } } ] ``` `default` is a language tag: two or three lower-case letters, then optionally a script of four letters and a region of two capitals or three digits, such as `"en"`, `"ar"`, `"pt-BR"`, `"zh-Hant"`, `"sr-Latn"`. Write `"zh"` and `"sr"` with their script. ## A table of texts `strings` holds a table for each language, and one for `default`. The default table is complete: every key the app names is there. Each key maps to the text in that language. This is the whole table of the example `guests`: ```json example=guests#/localization { "default": "en", "strings": { "en": { "appName": "Guest book", "appDescription": "Guests sign with their name, and everyone sees who signed and how many.", "signedDescription": "The names of everyone who signed.", "lastDescription": "The name of the guest who signed last.", "signDescription": "Sign the guest book with a name.", "nameDescription": "The name to sign with.", "nameMissing": "Write your name first.", "yourName": "Your name", "sign": "Sign", "welcome": "Welcome, {name}!", "signatures": "Signatures", "empty": "Nobody has signed yet.", "count": { "by": "count", "forms": { "=0": "No guests yet.", "one": "{count} guest has signed.", "other": "{count} guests have signed." } } }, "ar": { "appName": "دفتر الزوار", "appDescription": "يوقّع الضيوف بأسمائهم، ويرى الجميع من وقّع وكم عددهم.", "signedDescription": "أسماء كل من وقّع.", "lastDescription": "اسم آخر ضيف وقّع.", "signDescription": "التوقيع في دفتر الزوار باسم.", "nameDescription": "الاسم الذي يُوقَّع به.", "nameMissing": "اكتب اسمك أولًا.", "yourName": "اسمك", "sign": "وقّع", "welcome": "أهلًا بك يا {name}!", "signatures": "التوقيعات", "empty": "لم يوقّع أحد بعد.", "count": { "by": "count", "forms": { "=0": "لا ضيوف بعد.", "one": "وقّع ضيف واحد.", "two": "وقّع ضيفان.", "few": "وقّع {count} ضيوف.", "many": "وقّع {count} ضيفًا.", "other": "وقّع {count} ضيف." } } }, "ja": { "appName": "ゲストブック", "appDescription": "ゲストが名前を書いて記帳し、誰が何人記帳したかを全員が見られます。", "signedDescription": "記帳した全員の名前。", "lastDescription": "最後に記帳したゲストの名前。", "signDescription": "名前を書いてゲストブックに記帳します。", "nameDescription": "記帳する名前。", "nameMissing": "先に名前を書いてください。", "yourName": "お名前", "sign": "記帳する", "welcome": "ようこそ、{name}さん!", "signatures": "記帳した人", "empty": "まだ誰も記帳していません。", "count": { "by": "count", "forms": { "=0": "まだゲストはいません。", "other": "{count}人のゲストが記帳しました。" } } } }, "notes": { "welcome": "Shown after a guest signs. {name} is the name they wrote.", "count": "Below the list. {count} is how many guests signed." } } ``` - **Keys** start with a letter and hold letters, digits, `"_"` and `"."`, at most 80 characters, such as `"appName"` or `"cart.empty"`. A dot only groups names for a reader. Name a key for what the text is for, not for its words. - **Blanks.** `"{name}"` in a text is filled with the value passed for `name`. Write `"{{"` for a brace the person sees, and `"}}"` for its pair; any other brace is an error. A translation may leave a blank out, but never adds one the default text lacks. - **Forms** choose a text by a value: `by` names the blank, `forms` maps each case to a text, and `other` is required. For a number: `"=0"` and any exact number first, then the plural category of the language (`one`, `two`, `few`, `many`, `zero`), then `other`. For a text or a true or false value: the form of that name, else `other`. Each language writes its own forms: Arabic above has six where English has three, and a language may write one plain text where another needs forms. - **Notes** are for whoever translates later: what the text is for, what each blank holds. Nobody using the app sees them. ## Using a text from an expression Wherever an expression stands, `t` gives the text of a key in the language shown, with its blanks filled. The first argument is the key, written as it is; the second is a map of the blank values: ```expr example=guests t('welcome', { name: 'Ana' }) t('count', { count: size(state.signed) }) t('signatures') ``` Pass exactly the blanks the default text has, and for forms the `by` blank too. A number is written for the person's region, as `formatNumber` writes it. Write one entry with blanks for a whole sentence: never join pieces of translated text with `+` or a template, since languages put words in other orders. ## Fixed places A few places never hold an expression: `meta.name` and `meta.description`, a grant request's `reason`, the `description` of a capability, role, state entry, action, input field, type, rule, flow, flow state and code module, a type's `title`, an asset's `credit`, and the agent surface's `instructions` and tool descriptions. There, a value that is exactly `"=t('key')"` (single quotes, no spaces, no second argument) shows the text of that key: ```json example=guests#/actions/sign { "description": "=t('signDescription')", "input": { "name": { "type": "string", "description": "=t('nameDescription')" } }, "require": [ { "that": "size(trim(input.name)) > 0", "message": "=t('nameMissing')" } ], "steps": [ { "append": "state.signed", "value": "=trim(input.name)" }, { "set": "state.last", "to": "=trim(input.name)" } ] } ``` The text a fixed place names is a plain text in every language: no blanks, no forms, not empty. A key with a blank there is refused: ```json wrong=guests#/meta/name expect=localization.fixedNeedsPlainText "=t('welcome')" ``` ## Adding a language Add a whole language in ONE operation, with a text for every key of the default table: ```json patch=guests consent=no [ { "op": "add", "path": "/localization/strings/fr", "value": { "appName": "Livre d'or", "appDescription": "Les invités signent de leur nom, et chacun voit qui a signé et combien.", "signedDescription": "Les noms de tous ceux qui ont signé.", "lastDescription": "Le nom du dernier invité qui a signé.", "signDescription": "Signer le livre d'or avec un nom.", "nameDescription": "Le nom avec lequel signer.", "nameMissing": "Écrivez d'abord votre nom.", "yourName": "Votre nom", "sign": "Signer", "welcome": "Bienvenue, {name} !", "signatures": "Les signatures", "empty": "Personne n'a encore signé.", "count": { "by": "count", "forms": { "=0": "Aucun invité pour l'instant.", "one": "{count} invité a signé.", "other": "{count} invités ont signé." } } } } ] ``` An `add` at a language's path REPLACES that whole table. To add or change one text, write at the key's own path, such as `"/localization/strings/ar/sign"`. To give an app with no table its first languages, add `localization` with the default table, then point each place at a key. ## Adding a key Add the key to the default table first, then to every other table, and use it, in one patch. It also chooses a text by a true or false value: ```json patch=guests consent=no [ { "op": "add", "path": "/localization/strings/en/thanks", "value": { "by": "first", "forms": { "true": "You are the first guest!", "other": "Thank you for signing." } } }, { "op": "add", "path": "/localization/strings/ar/thanks", "value": { "by": "first", "forms": { "true": "أنت أول ضيف!", "other": "شكرًا لتوقيعك." } } }, { "op": "add", "path": "/localization/strings/ja/thanks", "value": { "by": "first", "forms": { "true": "最初のゲストです!", "other": "記帳ありがとうございます。" } } }, { "op": "add", "path": "/surfaces/visual/views/home/body/children/-", "value": { "control": "core:text", "when": "state.last != null", "props": { "value": "=t('thanks', { first: size(state.signed) == 1 })" } } } ] ``` A key only in a translation is never shown: every key the app names is in the default table. ## A language may stay partial A language may lack texts: a person shown it reads those in another of the app's languages, along a chain that ends at the default. The checks and tools count what each language lacks (`localization.untranslated`). A regional table holds only what differs: a table `"es-MX"` beside `"es"` gives a reader in Mexico its own words and takes the rest from `"es"`. ## Direction, numbers and dates The language shown decides everything else: Arabic, Hebrew, Persian and Urdu read right to left, and numbers, dates and plural forms follow the language with the person's region. A chart's plot, a diagram's layout and a canvas never turn. `"=env.language"` names the language shown and `"=env.direction"` its direction, for the rare rule that needs them. ## Looking as a reader of a language The look shows the app as a person of en-US by default. Give it the languages of the person to look as, the way a browser lists them, and read its line `"language:"` (the language shown, which way it reads, the locale of numbers and dates, and the languages the app carries): ```text look_at_app { "name": "guests", "languages": ["ar-EG"] } language: ar for a reader of ar-EG, right to left, numbers and dates written for ar-EG; the app carries en (default), ar, ja ``` Look as a reader of each language the app carries. A whole read of the app shows the default table and names the others after the JSON; read one with its pointer, such as `"/localization/strings/ar"`. ## What the checks say | Code | What it means | What to do | | --- | --- | --- | | `localization.tagInvalid` | A tag is not written as a language tag. | Use the spelling the message gives, such as `"en-US"` for `"en_us"`. | | `localization.defaultMissing` | `strings` has no table for `default`. | Add that table, or change `default`. | | `localization.entryInvalid` | A text has a lone brace, or forms lack `other` or have a bad case. | Write `"{{"` for a brace; give `other`; write numbers as `"=1"`. | | `localization.keyUnknown` | A `t` or a fixed place names a key the default table lacks. | Add the key to the default table, or use one the message suggests. | | `localization.valuesMismatch` | A `t` passes other blanks than the default text has. | Pass every blank of the default text and its `by`, and nothing else. | | `localization.blankUnknown` | A translation uses a blank the default text lacks. | Use the default's blanks only. | | `localization.fixedNeedsPlainText` | A fixed place names a text with blanks or forms, or an empty one. | Point it at a plain text. | | `localization.untranslated` | A language lacks texts for some keys. | Translate them, or leave them on purpose. | | `localization.keyNotInDefault` | A translation or a note has a key the default lacks. | Add it to the default, or remove it. | | `localization.keyUnused` | A key of the default table is named nowhere. | Use it, or remove it from every table. | | `localization.sameAsDefault` | A translation is word for word the default text. | Translate it, or remove it. | | `localization.scriptUnclear` | `"zh"` or `"sr"` without a script. | Write `"zh-Hans"`, `"zh-Hant"`, `"sr-Cyrl"` or `"sr-Latn"`. | | `localization.fixedTextForm` | A fixed place is written like a reference but is not exactly one, such as `"=t('key', {})"`. | Write it as `"=t('key')"`. | | `localization.directionUndeclared` | Most texts read right to left, and the app declares no language. | Add `localization` with its `default`. | | `localization.languagesBeyondFloor`, `localization.keysBeyondFloor`, `localization.textBeyondFloor` | More than 64 languages, 2,000 keys in one, 2,000 characters in a text or 24 forms. | Keep within: some hosts take no more. | ## Next - `views` and `controls` for the places a text is shown; `changing` for patches; `mistakes` for the errors met most. - The example Front desk (`front-desk.oad.json`, a playground sample): a whole app in English, Arabic and Japanese. --- # Example app `water`: Water today Counts the glasses of water you drink today against a daily goal. ```json { "oad": "0.2", "id": "com.example.water", "version": "1.0.0", "meta": { "name": "Water today", "description": "Counts the glasses of water you drink today against a daily goal." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "state": { "goal": { "type": "integer", "initial": 8, "description": "Glasses to drink each day." }, "glasses": { "type": "integer", "initial": 0, "description": "Glasses drunk on the day in countedOn." }, "countedOn": { "type": "date", "initial": "=env.today", "description": "The day the count belongs to." }, "today": { "type": "integer", "derive": "state.countedOn == env.today ? state.glasses : 0", "description": "Glasses drunk today." } }, "actions": { "drink": { "description": "Count one more glass of water today.", "steps": [ { "set": "state.glasses", "to": "=state.today + 1" }, { "set": "state.countedOn", "to": "=env.today" } ] } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "Water today", "body": { "control": "core:stack", "children": [ { "control": "core:progress", "props": { "label": "Glasses today", "value": "=state.today", "max": "=state.goal" } }, { "control": "core:text", "props": { "value": "=`${state.today} of ${state.goal} glasses`" } }, { "control": "core:button", "props": { "label": "I drank a glass", "emphasis": "high" }, "on": { "press": { "run": "drink" } } } ] } } } } } } ``` --- # Example app `reading`: Reading list Keeps the books you want to read, are reading and have read, and lets an agent add to the list. ```json { "oad": "0.2", "id": "com.example.reading", "version": "1.0.0", "meta": { "name": "Reading list", "description": "Keeps the books you want to read, are reading and have read, and lets an agent add to the list." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "types": { "Book": { "type": "object", "properties": { "id": { "type": "string" }, "title": { "type": "string", "minLength": 1 }, "author": { "type": "string" }, "status": { "type": "string", "enum": ["toRead", "reading", "read"] }, "addedOn": { "type": "string", "format": "date" } }, "required": ["id", "title", "author", "status", "addedOn"], "additionalProperties": false } }, "state": { "books": { "type": "Book[]", "initial": [], "description": "Every book on your list." }, "toRead": { "type": "integer", "derive": "state.books.count(b, b.status == 'toRead')", "description": "Books not started yet." }, "finished": { "type": "integer", "derive": "state.books.count(b, b.status == 'read')", "description": "Books you have read." }, "heading": { "type": "string", "internal": true, "derive": "state.toRead == 0 ? 'Nothing to read' : `${state.toRead} to read`", "description": "The title of the home screen, for the screen only." } }, "actions": { "addBook": { "description": "Put a book on your list, to read later.", "input": { "title": { "type": "string", "description": "The book's title." }, "author": { "type": "string", "description": "Who wrote it.", "default": "" } }, "output": "string", "require": [ { "that": "size(trim(input.title)) > 0", "message": "Give the book a title." } ], "steps": [ { "let": "id", "to": "=uuid()" }, { "append": "state.books", "value": { "id": "=id", "title": "=trim(input.title)", "author": "=trim(input.author)", "status": "toRead", "addedOn": "=env.today" } }, { "return": "=id" } ] }, "setStatus": { "description": "Say whether you have not started a book, are reading it, or have read it.", "input": { "id": { "type": "string", "description": "Which book." }, "status": { "type": { "type": "string", "enum": ["toRead", "reading", "read"] }, "description": "toRead, reading or read." } }, "require": [ { "that": "state.books.exists(b, b.id == input.id)", "message": "That book is not on your list." } ], "steps": [ { "set": "state.books[id=input.id].status", "to": "=input.status" } ] }, "editBook": { "description": "Change the title or the author of a book on your list.", "input": { "id": { "type": "string", "description": "Which book." }, "title": { "type": "string", "description": "The title." }, "author": { "type": "string", "description": "Who wrote it.", "default": "" } }, "require": [ { "that": "state.books.exists(b, b.id == input.id)", "message": "That book is not on your list." }, { "that": "size(trim(input.title)) > 0", "message": "Give the book a title." } ], "steps": [ { "patch": "state.books", "where": "item.id == input.id", "with": { "title": "=trim(input.title)", "author": "=trim(input.author)" } } ] }, "removeBook": { "description": "Take a book off your list.", "input": { "id": { "type": "string", "description": "Which book." } }, "confirm": { "message": "=`${state.books.find(b, b.id == input.id).title} is taken off your list.`" }, "steps": [ { "remove": "state.books", "where": "item.id == input.id" } ] } }, "rules": { "allRead": { "description": "When every book on the list has been read, let your agents know.", "when": { "becomes": "size(state.books) > 0 && state.finished == size(state.books)" }, "do": [ { "emit": "allRead" } ] } }, "surfaces": { "agent": { "instructions": "Use addBook once per book, with the author when the person gives one. Read books to say what is on the list. removeBook asks the person to confirm.", "tools": { "include": ["addBook", "setStatus", "removeBook"], "describe": { "setStatus": "Say whether the person has not started a book, is reading it, or has read it. Take its id from the books resource." } }, "resources": { "include": ["books", "toRead"] }, "events": { "include": ["allRead"] } }, "visual": { "start": "home", "views": { "home": { "title": "=state.heading", "body": { "control": "core:stack", "children": [ { "control": "core:grid", "props": { "columns": 2 }, "children": [ { "control": "core:stat", "props": { "label": "To read", "value": "=state.toRead" } }, { "control": "core:stat", "props": { "label": "Read", "value": "=state.finished" } } ] }, { "control": "core:button", "props": { "label": "Add a book", "icon": "add", "emphasis": "high" }, "on": { "press": { "navigate": "addBook" } } }, { "control": "core:table", "props": { "label": "Books", "items": "=state.books", "columns": [ { "field": "title", "label": "Title", "sortable": true }, { "field": "author", "label": "Author", "sortable": true }, { "field": "status", "label": "Status", "format": "custom" } ], "empty": "No books yet. Add the first one." }, "slots": { "cell": { "control": "core:badge", "props": { "label": "=value == 'read' ? 'Read' : (value == 'reading' ? 'Reading' : 'To read')", "tone": "=value == 'read' ? 'success' : 'neutral'" } } }, "on": { "select": { "navigate": "book", "with": { "id": "=event.item.id" } } } } ] } }, "addBook": { "title": "Add a book", "state": { "title": { "type": "string?", "description": "The title being typed." }, "author": { "type": "string?", "description": "The author being typed." } }, "body": { "control": "core:form", "props": { "submitLabel": "Add", "cancelLabel": "Cancel" }, "on": { "submit": [ { "run": "addBook", "with": { "title": "=default(view.title, '')", "author": "=default(view.author, '')" } }, { "navigate": "back" } ], "cancel": { "navigate": "back" } }, "children": [ { "control": "core:textInput", "props": { "label": "Title", "required": true }, "bind": { "value": "view.title" } }, { "control": "core:textInput", "props": { "label": "Author" }, "bind": { "value": "view.author" } } ] } }, "book": { "title": "=default(state.books.find(b, b.id == view.id).title, 'Book')", "input": { "id": { "type": "string", "description": "Which book to show." } }, "body": { "control": "core:stack", "children": [ { "control": "core:text", "when": "!state.books.exists(b, b.id == view.id)", "props": { "value": "This book is no longer on your list." } }, { "control": "core:stack", "each": { "in": "state.books.filter(b, b.id == view.id)", "as": "book", "key": "book.id" }, "children": [ { "control": "core:text", "props": { "value": "=book.author == '' ? 'Author not given' : `By ${book.author}`" } }, { "control": "core:text", "props": { "value": "=`Added ${formatDate(book.addedOn, 'long')}`", "style": "caption" } }, { "control": "core:choice", "props": { "label": "Status", "value": "=book.status", "options": [ { "value": "toRead", "label": "To read" }, { "value": "reading", "label": "Reading" }, { "value": "read", "label": "Read" } ] }, "on": { "change": { "run": "setStatus", "with": { "id": "=book.id", "status": "=event.value" } } } }, { "control": "core:button", "props": { "label": "Change", "icon": "edit" }, "on": { "press": { "navigate": "editBook", "with": { "id": "=book.id" } } } }, { "control": "core:button", "props": { "label": "Remove", "icon": "delete", "destructive": true }, "on": { "press": [ { "run": "removeBook", "with": { "id": "=book.id" } }, { "navigate": "back" } ] } } ] } ] } }, "editBook": { "title": "Change the book", "input": { "id": { "type": "string", "description": "Which book to change." } }, "state": { "title": { "type": "string?", "initial": "=state.books.find(b, b.id == view.id).title", "description": "The title being typed." }, "author": { "type": "string?", "initial": "=state.books.find(b, b.id == view.id).author", "description": "The author being typed." } }, "body": { "control": "core:form", "props": { "submitLabel": "Save", "cancelLabel": "Cancel" }, "on": { "submit": [ { "run": "editBook", "with": { "id": "=view.id", "title": "=default(view.title, '')", "author": "=default(view.author, '')" } }, { "navigate": "back" } ], "cancel": { "navigate": "back" } }, "children": [ { "control": "core:textInput", "props": { "label": "Title", "required": true }, "bind": { "value": "view.title" } }, { "control": "core:textInput", "props": { "label": "Author" }, "bind": { "value": "view.author" } } ] } } } } } } ``` --- # Example app `timeoff`: Time off A team asks for days off, and an approver approves or declines each request. ```json { "oad": "0.2", "id": "com.example.timeoff", "version": "1.0.0", "meta": { "name": "Time off", "description": "A team asks for days off, and an approver approves or declines each request." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "types": { "Request": { "type": "object", "properties": { "id": { "type": "string" }, "personId": { "type": "string" }, "personName": { "type": "string" }, "from": { "type": "string", "format": "date" }, "to": { "type": "string", "format": "date" }, "note": { "type": "string" }, "status": { "type": "string", "enum": ["pending", "approved", "declined", "cancelled"] }, "decidedBy": { "type": "string" } }, "required": ["id", "personId", "personName", "from", "to", "note", "status", "decidedBy"], "additionalProperties": false } }, "roles": { "approver": { "description": "Approves or declines other people's time off." } }, "state": { "requests": { "type": "Request[]", "initial": [], "scope": "shared", "conflict": "merge", "key": "id", "description": "Every time off request of the team." } }, "actions": { "askForTimeOff": { "description": "Ask for days off, from the first day to the last day.", "input": { "from": { "type": "date", "description": "The first day off." }, "to": { "type": "date", "description": "The last day off." }, "note": { "type": "string", "description": "Anything the approver should know.", "default": "" } }, "output": "string", "require": [ { "that": "input.from >= env.today", "message": "Time off cannot start in the past." }, { "that": "input.to >= input.from", "message": "The last day cannot be before the first day." } ], "done": { "message": "Request sent." }, "steps": [ { "let": "id", "to": "=uuid()" }, { "append": "state.requests", "value": { "id": "=id", "personId": "=user.person.id", "personName": "=user.person.name", "from": "=input.from", "to": "=input.to", "note": "=input.note", "decidedBy": "" } }, { "return": "=id" } ] }, "approve": { "description": "Approve someone's time off request.", "input": { "id": { "type": "string", "description": "Which request." } }, "require": [ { "that": "'approver' in user.roles", "message": "Only an approver can decide time off." }, { "that": "state.requests.exists(r, r.id == input.id && r.status == 'pending' && r.personId != user.person.id)", "message": "This request is not waiting for your decision." } ], "steps": [ { "send": "approve", "to": "approval", "key": "=input.id" } ] }, "decline": { "description": "Decline someone's time off request.", "input": { "id": { "type": "string", "description": "Which request." } }, "confirm": { "message": "The person is told their request is declined." }, "require": [ { "that": "'approver' in user.roles", "message": "Only an approver can decide time off." }, { "that": "state.requests.exists(r, r.id == input.id && r.status == 'pending' && r.personId != user.person.id)", "message": "This request is not waiting for your decision." } ], "steps": [ { "send": "decline", "to": "approval", "key": "=input.id" } ] }, "cancel": { "description": "Take back a request of yours that is still waiting.", "input": { "id": { "type": "string", "description": "Which request." } }, "require": [ { "that": "state.requests.exists(r, r.id == input.id && r.status == 'pending' && r.personId == user.person.id)", "message": "Only a waiting request of yours can be taken back." } ], "steps": [ { "send": "cancel", "to": "approval", "key": "=input.id" } ] } }, "flows": { "approval": { "description": "A request waits for an approver, who approves or declines it; the person who asked can take it back while it waits.", "over": { "collection": "state.requests", "key": "id", "field": "status" }, "initial": "pending", "states": { "pending": { "on": { "approve": { "to": "approved", "allow": "'approver' in user.roles && user.person.id != item.personId", "do": [ { "patch": "item", "with": { "decidedBy": "=user.person.name" } } ] }, "decline": { "to": "declined", "allow": "'approver' in user.roles && user.person.id != item.personId", "do": [ { "patch": "item", "with": { "decidedBy": "=user.person.name" } } ] }, "cancel": { "to": "cancelled", "allow": "user.person.id == item.personId" } } }, "approved": { "final": true }, "declined": { "final": true }, "cancelled": { "final": true } } } }, "surfaces": { "visual": { "start": "mine", "navigation": [ { "view": "mine", "label": "My time off", "icon": "calendar" }, { "view": "decide", "label": "To decide", "icon": "check", "when": "'approver' in user.roles" } ], "views": { "mine": { "title": "My time off", "body": { "control": "core:stack", "children": [ { "control": "core:button", "props": { "label": "Ask for time off", "emphasis": "high" }, "on": { "press": { "navigate": "ask" } } }, { "control": "core:table", "props": { "label": "My requests", "items": "=state.requests.filter(r, r.personId == user.person.id).map(r, merge(r, {stage: {pending: 'Waiting', approved: 'Approved', declined: 'Declined', cancelled: 'Taken back'}[r.status]}))", "columns": [ { "field": "from", "label": "From", "format": "date", "sortable": true }, { "field": "to", "label": "To", "format": "date" }, { "field": "stage", "label": "Status" } ], "empty": "You have not asked for time off yet." }, "on": { "select": { "navigate": "request", "with": { "id": "=event.item.id" } } } } ] } }, "decide": { "title": "To decide", "body": { "control": "core:table", "props": { "label": "Waiting for a decision", "items": "=state.requests.filter(r, r.status == 'pending' && r.personId != user.person.id)", "columns": [ { "field": "personName", "label": "Who" }, { "field": "from", "label": "From", "format": "date", "sortable": true }, { "field": "to", "label": "To", "format": "date" } ], "empty": "Nothing is waiting for you." }, "on": { "select": { "navigate": "request", "with": { "id": "=event.item.id" } } } } }, "ask": { "title": "Ask for time off", "state": { "from": { "type": "date?", "description": "The first day being chosen." }, "to": { "type": "date?", "description": "The last day being chosen." }, "note": { "type": "string?", "description": "The note being typed." } }, "body": { "control": "core:form", "props": { "submitLabel": "Ask", "cancelLabel": "Cancel" }, "on": { "submit": [ { "run": "askForTimeOff", "with": { "from": "=view.from", "to": "=view.to", "note": "=default(view.note, '')" } }, { "navigate": "back" } ], "cancel": { "navigate": "back" } }, "children": [ { "control": "core:dateInput", "props": { "label": "First day off", "required": true, "min": "=env.today" }, "bind": { "value": "view.from" } }, { "control": "core:dateInput", "props": { "label": "Last day off", "required": true, "min": "=default(view.from, env.today)" }, "bind": { "value": "view.to" } }, { "control": "core:textInput", "props": { "label": "Note for the approver", "multiline": true }, "bind": { "value": "view.note" } } ] } }, "request": { "title": "Time off request", "input": { "id": { "type": "string", "description": "Which request to show." } }, "body": { "control": "core:stack", "each": { "in": "state.requests.filter(r, r.id == view.id)", "as": "request", "key": "request.id" }, "children": [ { "control": "core:heading", "props": { "value": "=`${request.personName}: ${formatDate(request.from, 'long')} to ${formatDate(request.to, 'long')}`" } }, { "control": "core:badge", "props": { "label": "={pending: 'Waiting', approved: 'Approved', declined: 'Declined', cancelled: 'Taken back'}[request.status]", "tone": "=default({approved: 'success', declined: 'danger'}[request.status], 'neutral')" } }, { "control": "core:text", "when": "request.note != ''", "props": { "value": "=request.note" } }, { "control": "core:text", "when": "request.decidedBy != ''", "props": { "value": "=`Decided by ${request.decidedBy}`", "style": "caption" } }, { "control": "core:stack", "props": { "direction": "horizontal" }, "children": [ { "control": "core:button", "when": "canSend('approval', 'approve', request.id)", "props": { "label": "Approve", "emphasis": "high" }, "on": { "press": { "run": "approve", "with": { "id": "=request.id" } } } }, { "control": "core:button", "when": "canSend('approval', 'decline', request.id)", "props": { "label": "Decline", "destructive": true }, "on": { "press": { "run": "decline", "with": { "id": "=request.id" } } } }, { "control": "core:button", "when": "canSend('approval', 'cancel', request.id)", "props": { "label": "Take back" }, "on": { "press": { "run": "cancel", "with": { "id": "=request.id" } } } } ] } ] } } } } } } ``` --- # Example app `weather`: Weather Shows the weather now and for the next days in a city you choose, from a weather service. ```json { "oad": "0.2", "id": "com.example.weather", "version": "1.0.0", "meta": { "name": "Weather", "description": "Shows the weather now and for the next days in a city you choose, from a weather service." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "types": { "Day": { "type": "object", "properties": { "date": { "type": "string", "format": "date" }, "high": { "type": "number" }, "low": { "type": "number" }, "summary": { "type": "string" } }, "required": ["date", "high", "low", "summary"] } }, "capabilities": { "weather": { "contract": "core:http", "description": "The weather service the forecast comes from.", "config": { "origin": "https://weather.example.com" } } }, "grants": { "readForecast": { "capability": "weather", "scopes": ["http.read"], "reason": "Read the forecast for the city you choose. Only the city's name is sent.", "where": "input.path == '/v1/forecast'", "rate": { "count": 48, "per": "P1D" } } }, "state": { "city": { "type": "string", "initial": "Lisbon", "description": "The city whose weather is shown." }, "forecast": { "type": "core:HttpResponse", "sensitive": false, "description": "The weather service's answer for the city.", "source": { "call": "weather.get", "with": { "path": "/v1/forecast", "query": { "city": "=state.city" } }, "refresh": { "every": "PT1H" } } }, "found": { "type": "boolean", "derive": "state.forecast != null && state.forecast.status == 200", "description": "Whether the service knew the city." }, "days": { "type": "Day[]", "derive": "state.found ? default(state.forecast.body.days, []) : []", "description": "The forecast for the next days." } }, "actions": { "chooseCity": { "description": "Show the weather for another city.", "input": { "city": { "type": "string", "description": "The city's name, such as Lisbon." } }, "require": [ { "that": "size(trim(input.city)) > 0", "message": "Type the name of a city." } ], "steps": [ { "set": "state.city", "to": "=trim(input.city)" } ] } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "=`Weather in ${state.city}`", "state": { "city": { "type": "string?", "initial": "=state.city", "description": "The city being typed." } }, "body": { "control": "core:stack", "children": [ { "control": "core:progress", "when": "sources.forecast.status == 'loading'", "props": { "label": "Asking the weather service" } }, { "control": "core:alert", "when": "sources.forecast.status == 'error'", "props": { "title": "The weather service did not answer", "message": "=default(sources.forecast.error.message, '')", "tone": "warning" } }, { "control": "core:alert", "when": "state.forecast != null && !state.found", "props": { "title": "=`No forecast for ${state.city}`", "message": "Check the name of the city.", "tone": "info" } }, { "control": "core:stat", "when": "state.found", "props": { "label": "Now", "value": "=`${default(state.forecast.body.now, '')}°`" } }, { "control": "core:list", "props": { "label": "Next days", "items": "=state.days", "itemKey": "date", "empty": "No forecast yet." }, "slots": { "item": { "control": "core:text", "props": { "value": "=`${formatDate(item.date, 'medium')}: ${item.summary}, ${item.low}° to ${item.high}°`" } }, "actions": { "control": "core:button", "props": { "label": "Refresh the forecast", "icon": "refresh", "iconOnly": true, "emphasis": "low" }, "on": { "press": { "refresh": "state.forecast" } } } } }, { "control": "core:form", "props": { "submitLabel": "Show" }, "on": { "submit": { "run": "chooseCity", "with": { "city": "=default(view.city, '')" } } }, "children": [ { "control": "core:textInput", "props": { "label": "City", "required": true }, "bind": { "value": "view.city" } } ] } ] } } } } } } ``` Its sample document: ```json { "weather": { "get": { "status": 200, "headers": { "content-type": "application/json" }, "body": { "city": "Lisbon", "now": 18, "days": [ { "date": "2026-11-13", "high": 19, "low": 12, "summary": "Sunny" }, { "date": "2026-11-14", "high": 17, "low": 11, "summary": "Showers" }, { "date": "2026-11-15", "high": 16, "low": 10, "summary": "Cloudy" } ] } } } } ``` --- # Example app `plants`: Plant care Reminds you to water each of your plants when it is due. ```json { "oad": "0.2", "id": "com.example.plants", "version": "1.0.0", "meta": { "name": "Plant care", "description": "Reminds you to water each of your plants when it is due." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "types": { "Plant": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "everyDays": { "type": "integer", "minimum": 1 }, "wateredOn": { "type": "string", "format": "date" } }, "required": ["id", "name", "everyDays", "wateredOn"], "additionalProperties": false } }, "capabilities": { "clock": { "contract": "core:scheduler", "description": "Wakes the app on the morning a plant needs water, even when it is closed." }, "notify": { "contract": "core:notify", "description": "Tells you which plant needs water." } }, "grants": { "wakeUp": { "capability": "clock", "scopes": ["scheduler.background"], "reason": "Wake the app on the morning a plant is due, so the reminder comes even when the app is closed.", "required": false }, "reminders": { "capability": "notify", "scopes": ["notify.self"], "reason": "Tell you when a plant needs water, at most a few times a day.", "rate": { "count": 10, "per": "P1D" }, "required": false } }, "state": { "plants": { "type": "Plant[]", "initial": [], "description": "Your plants and when each was last watered." }, "due": { "type": "Plant[]", "derive": "state.plants.filter(p, daysBetween(p.wateredOn, env.today) >= p.everyDays)", "description": "Plants that need water today." } }, "actions": { "addPlant": { "description": "Add a plant, watered today, that needs water every few days.", "input": { "name": { "type": "string", "description": "What you call the plant." }, "everyDays": { "type": "integer", "description": "How many days between waterings.", "default": 7 } }, "require": [ { "that": "size(trim(input.name)) > 0", "message": "Give the plant a name." }, { "that": "input.everyDays >= 1", "message": "Water it at least every day: use 1 or more." } ], "steps": [ { "let": "id", "to": "=uuid()" }, { "append": "state.plants", "value": { "id": "=id", "name": "=trim(input.name)", "everyDays": "=input.everyDays", "wateredOn": "=env.today" } }, { "call": "clock.wakeAt", "with": { "key": "=id", "at": "=atTime(addDays(env.today, input.everyDays), '09:00')" }, "onError": [] } ] }, "water": { "description": "Say that you watered a plant today.", "input": { "id": { "type": "string", "description": "Which plant." } }, "require": [ { "that": "state.plants.exists(p, p.id == input.id)", "message": "That plant is not in your list." } ], "steps": [ { "patch": "state.plants", "where": "item.id == input.id", "with": { "wateredOn": "=env.today" } }, { "let": "plant", "to": "=state.plants.find(p, p.id == input.id)" }, { "call": "clock.wakeAt", "with": { "key": "=input.id", "at": "=atTime(addDays(env.today, plant.everyDays), '09:00')" }, "onError": [] } ] }, "removePlant": { "description": "Take a plant off your list.", "input": { "id": { "type": "string", "description": "Which plant." } }, "steps": [ { "remove": "state.plants", "where": "item.id == input.id" }, { "call": "clock.cancel", "with": { "key": "=input.id" }, "onError": [] } ] }, "turnOnReminders": { "description": "Send a first notification, so that reminders can reach you.", "steps": [ { "call": "notify.send", "with": { "title": "Reminders are on", "body": "You will hear from Plant care when a plant needs water." } } ] } }, "rules": { "remind": { "description": "On the morning a plant is due, tell you to water it.", "when": { "event": "clock.wake" }, "do": [ { "let": "plant", "to": "=state.plants.find(p, p.id == event.key)" }, { "if": "plant != null", "then": [ { "call": "notify.send", "once": "=`water:${event.key}:${event.at}`", "with": { "title": "=`Water ${plant.name}`", "body": "=`${plant.name} needs water today.`", "view": "home" }, "onError": [] } ] } ] } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "Plant care", "state": { "name": { "type": "string?", "description": "The name being typed." }, "everyDays": { "type": "integer?", "initial": 7, "description": "The days between waterings being chosen." } }, "body": { "control": "core:stack", "children": [ { "control": "core:alert", "when": "size(state.due) > 0", "props": { "title": "=`${size(state.due)} ${plural(size(state.due), {one: 'plant needs', other: 'plants need'})} water`", "tone": "warning" } }, { "control": "core:button", "when": "!grants.reminders.held && !grants.reminders.declined", "props": { "label": "Turn on reminders", "icon": "notification" }, "on": { "press": { "run": "turnOnReminders" } } }, { "control": "core:text", "when": "!grants.reminders.held", "props": { "value": "=grants.reminders.declined ? 'Reminders are off. You can turn them on in the permissions of the app.' : 'Reminders are off until you turn them on.'", "style": "caption" } }, { "control": "core:list", "props": { "label": "Your plants", "items": "=state.plants", "empty": "No plants yet." }, "slots": { "item": { "control": "core:stack", "props": { "direction": "horizontal" }, "children": [ { "control": "core:text", "props": { "value": "=`${item.name}: watered ${relativeTime(item.wateredOn)}, every ${item.everyDays} days`" } }, { "control": "core:button", "props": { "label": "Watered" }, "on": { "press": { "run": "water", "with": { "id": "=item.id" } } } }, { "control": "core:button", "props": { "label": "Remove", "destructive": true, "emphasis": "low" }, "on": { "press": { "run": "removePlant", "with": { "id": "=item.id" } } } } ] } } }, { "control": "core:form", "props": { "label": "Add a plant", "submitLabel": "Add" }, "on": { "submit": [ { "run": "addPlant", "with": { "name": "=default(view.name, '')", "everyDays": "=default(view.everyDays, 7)" } }, { "set": "view.name", "to": null } ] }, "children": [ { "control": "core:textInput", "props": { "label": "Name", "required": true }, "bind": { "value": "view.name" } }, { "control": "core:numberInput", "props": { "label": "Water every how many days?", "min": 1, "step": 1, "required": true }, "bind": { "value": "view.everyDays" } } ] } ] } } } } } } ``` --- # Example app `groceries`: Groceries A shopping list the whole household shares: add what to buy, tick it off, take it off. ```json { "oad": "0.2", "id": "com.example.groceries", "version": "1.0.0", "meta": { "name": "Groceries", "description": "A shopping list the whole household shares: add what to buy, tick it off, take it off." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "types": { "Item": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "bought": { "type": "boolean" } }, "required": ["id", "name", "bought"], "additionalProperties": false } }, "state": { "items": { "type": "Item[]", "initial": [], "scope": "shared", "conflict": "merge", "key": "id", "description": "Everything on the household's list, bought or not." }, "bought": { "type": "integer", "derive": "state.items.count(i, i.bought)", "description": "How many things are ticked off." } }, "actions": { "addItem": { "description": "Put something on the shopping list.", "input": { "name": { "type": "string", "description": "What to buy, such as milk." } }, "require": [ { "that": "size(trim(input.name)) > 0", "message": "Say what to buy." } ], "steps": [ { "append": "state.items", "value": { "id": "=uuid()", "name": "=trim(input.name)", "bought": false } } ] }, "tick": { "description": "Tick something off as bought, or untick it.", "input": { "id": { "type": "string", "description": "Which item, by its id." } }, "steps": [ { "patch": "state.items", "where": "item.id == input.id", "with": { "bought": "=!item.bought" } } ] }, "removeItem": { "description": "Take something off the list.", "input": { "id": { "type": "string", "description": "Which item, by its id." } }, "confirm": { "message": "=`${state.items.find(i, i.id == input.id).name} is taken off the list for everyone.`" }, "steps": [ { "remove": "state.items", "where": "item.id == input.id" } ] }, "clearBought": { "description": "Take everything ticked off the list, after a shop.", "confirm": { "message": "=`Everything ticked off (${state.bought}) is taken off the list for everyone.`" }, "steps": [ { "remove": "state.items", "where": "item.bought" } ] } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "Groceries", "state": { "name": { "type": "string?", "description": "What is being typed." } }, "body": { "control": "core:stack", "children": [ { "control": "core:form", "props": { "submitLabel": "Add" }, "on": { "submit": [ { "run": "addItem", "with": { "name": "=default(view.name, '')" } }, { "set": "view.name", "to": null } ] }, "children": [ { "control": "core:textInput", "props": { "label": "Add to the list", "required": true }, "bind": { "value": "view.name" } } ] }, { "control": "core:list", "props": { "label": "Shopping list", "items": "=state.items", "empty": "The list is empty." }, "slots": { "item": { "control": "core:stack", "props": { "direction": "horizontal" }, "children": [ { "control": "core:text", "props": { "value": "=item.bought ? `${item.name} (bought)` : item.name" } }, { "control": "core:button", "props": { "label": "=item.bought ? 'Undo' : 'Bought'", "icon": "check" }, "on": { "press": { "run": "tick", "with": { "id": "=item.id" } } } }, { "control": "core:button", "props": { "label": "Remove", "destructive": true, "emphasis": "low" }, "on": { "press": { "run": "removeItem", "with": { "id": "=item.id" } } } } ] } } }, { "control": "core:button", "when": "state.bought > 0", "props": { "label": "Clear ticked off", "emphasis": "low" }, "on": { "press": { "run": "clearBought" } } } ] } } } } } } ``` --- # Example app `booking`: Room booking Book a meeting room in three steps: the day and how many come, the room, then a last look before booking. ```json { "oad": "0.2", "id": "com.example.booking", "version": "1.0.0", "meta": { "name": "Room booking", "description": "Book a meeting room in three steps: the day and how many come, the room, then a last look before booking." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "types": { "Booking": { "type": "object", "properties": { "id": { "type": "string" }, "day": { "type": "string", "format": "date" }, "room": { "type": "string" }, "people": { "type": "integer" }, "note": { "type": "string" } }, "required": ["id", "day", "room", "people", "note"], "additionalProperties": false } }, "state": { "bookings": { "type": "Booking[]", "initial": [], "description": "The rooms you booked." } }, "actions": { "book": { "description": "Book a meeting room for a day.", "input": { "day": { "type": "date", "description": "The day of the meeting." }, "room": { "type": "string", "description": "Which room." }, "people": { "type": "integer", "description": "How many people come." }, "note": { "type": "string", "description": "What the meeting is about.", "default": "" } }, "require": [ { "that": "input.day >= env.today", "message": "A room cannot be booked for a day that has passed." }, { "that": "input.people >= 1", "message": "At least one person comes." } ], "steps": [ { "append": "state.bookings", "value": { "id": "=uuid()", "day": "=input.day", "room": "=input.room", "people": "=input.people", "note": "=input.note" } } ] } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "Bookings", "body": { "control": "core:stack", "children": [ { "control": "core:button", "props": { "label": "Book a room", "emphasis": "high" }, "on": { "press": { "navigate": "book" } } }, { "control": "core:tabs", "children": [ { "control": "core:group", "props": { "title": "Coming up" }, "children": [ { "control": "core:table", "props": { "label": "Coming up", "items": "=state.bookings.filter(b, b.day >= env.today)", "columns": [ { "field": "day", "label": "Day", "format": "date", "sortable": true }, { "field": "room", "label": "Room" } ], "empty": "Nothing booked." } } ] }, { "control": "core:group", "props": { "title": "Past" }, "children": [ { "control": "core:table", "props": { "label": "Past", "items": "=state.bookings.filter(b, b.day < env.today)", "columns": [ { "field": "day", "label": "Day", "format": "date", "sortable": true }, { "field": "room", "label": "Room" } ], "empty": "No past bookings." } } ] } ] } ] } }, "book": { "title": "Book a room", "state": { "step": { "type": "integer", "initial": 1, "description": "The step being shown, from 1 to 3." }, "day": { "type": "date?", "description": "The day being chosen." }, "people": { "type": "integer?", "initial": 2, "description": "How many people come." }, "room": { "type": "string?", "description": "The room being chosen." }, "note": { "type": "string?", "description": "The note being typed." } }, "body": { "control": "core:stack", "children": [ { "control": "core:text", "props": { "value": "=`Step ${view.step} of 3`", "style": "caption" } }, { "control": "core:form", "when": "view.step == 1", "props": { "submitLabel": "Next", "cancelLabel": "Cancel" }, "on": { "submit": { "set": "view.step", "to": 2 }, "cancel": { "navigate": "back" } }, "children": [ { "control": "core:dateInput", "props": { "label": "Day", "required": true, "min": "=env.today" }, "bind": { "value": "view.day" } }, { "control": "core:numberInput", "props": { "label": "People", "required": true, "min": 1, "max": 12, "step": 1 }, "bind": { "value": "view.people" } } ] }, { "control": "core:form", "when": "view.step == 2", "props": { "submitLabel": "Next", "cancelLabel": "Back" }, "on": { "submit": { "set": "view.step", "to": 3 }, "cancel": { "set": "view.step", "to": 1 } }, "children": [ { "control": "core:choice", "props": { "label": "Room", "required": true, "options": [ { "value": "Harbor", "label": "Harbor, 4 seats" }, { "value": "Garden", "label": "Garden, 8 seats" }, { "value": "Hall", "label": "Hall, 12 seats" } ] }, "bind": { "value": "view.room" } } ] }, { "control": "core:form", "when": "view.step == 3", "props": { "submitLabel": "Book", "cancelLabel": "Back" }, "on": { "submit": [ { "run": "book", "with": { "day": "=view.day", "room": "=view.room", "people": "=view.people", "note": "=default(view.note, '')" } }, { "navigate": "back" } ], "cancel": { "set": "view.step", "to": 2 } }, "children": [ { "control": "core:text", "props": { "value": "=`${view.room} on ${formatDate(view.day, 'long')}, for ${view.people} ${plural(view.people, {one: 'person', other: 'people'})}`", "style": "emphasis" } }, { "control": "core:textInput", "props": { "label": "What the meeting is about", "multiline": true }, "bind": { "value": "view.note" } } ] } ] } } } } } } ``` --- # Example app `notes`: Notes Notes kept in notebooks: each notebook is a main section, with the number of its notes beside it. ```json { "oad": "0.2", "id": "com.example.notes", "version": "1.0.0", "meta": { "name": "Notes", "description": "Notes kept in notebooks: each notebook is a main section, with the number of its notes beside it.", "icon": "edit" }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "types": { "Notebook": { "type": "object", "required": ["id", "name"], "properties": { "id": { "type": "string" }, "name": { "type": "string" } } }, "Note": { "type": "object", "required": ["id", "notebook", "text"], "properties": { "id": { "type": "string" }, "notebook": { "type": "string" }, "text": { "type": "string" } } } }, "state": { "notebooks": { "type": "Notebook[]", "description": "The notebooks, in the order they were made.", "initial": [ { "id": "work", "name": "Work" }, { "id": "home", "name": "Home" } ] }, "notes": { "type": "Note[]", "description": "Every note, each in one notebook.", "initial": [ { "id": "n1", "notebook": "work", "text": "Send the slides to Sam" }, { "id": "n2", "notebook": "home", "text": "Call the plumber" } ] } }, "actions": { "addNotebook": { "description": "Make a new, empty notebook.", "input": { "name": { "type": "string", "description": "The notebook's name." } }, "output": "string", "require": [{ "that": "size(trim(input.name)) > 0", "message": "Give the notebook a name." }], "steps": [ { "let": "id", "to": "=uuid()" }, { "append": "state.notebooks", "value": { "id": "=id", "name": "=trim(input.name)" } }, { "return": "=id" } ] }, "addNote": { "description": "Write a note in a notebook.", "input": { "notebook": { "type": "string", "description": "Which notebook it goes in." }, "text": { "type": "string", "description": "What the note says." } }, "require": [ { "that": "state.notebooks.exists(b, b.id == input.notebook)", "message": "That notebook is gone." }, { "that": "size(trim(input.text)) > 0", "message": "Write something first." } ], "steps": [{ "append": "state.notes", "value": { "id": "=uuid()", "notebook": "=input.notebook", "text": "=trim(input.text)" } }] }, "removeNote": { "description": "Throw a note away.", "input": { "id": { "type": "string", "description": "Which note." } }, "steps": [{ "remove": "state.notes", "where": "item.id == input.id" }] } }, "surfaces": { "visual": { "start": "all", "navigation": [ { "view": "all", "label": "All notes", "icon": "home" }, { "group": "Notebooks", "sections": [ { "each": { "in": "state.notebooks", "as": "book", "key": "book.id" }, "view": "notebook", "with": { "id": "=book.id" }, "label": "=book.name", "icon": "file", "count": "=size(state.notes.filter(n, n.notebook == book.id))" }, { "view": "newNotebook", "label": "New notebook", "icon": "add" } ] } ], "views": { "all": { "title": "All notes", "body": { "control": "core:list", "props": { "label": "Every note", "items": "=state.notes", "empty": "No notes yet. Open a notebook to write one." }, "slots": { "item": { "control": "core:text", "props": { "value": "=item.text" } } } } }, "notebook": { "title": "=default(state.notebooks.find(b, b.id == view.id).name, 'Notebook')", "input": { "id": { "type": "string", "description": "Which notebook to show." } }, "state": { "text": { "type": "string?", "description": "The note being written." } }, "body": { "control": "core:stack", "children": [ { "control": "core:form", "props": { "submitLabel": "Add note" }, "on": { "submit": [{ "run": "addNote", "with": { "notebook": "=view.id", "text": "=default(view.text, '')" } }, { "set": "view.text", "to": null }] }, "children": [{ "control": "core:textInput", "props": { "label": "New note", "required": true }, "bind": { "value": "view.text" } }] }, { "control": "core:list", "props": { "label": "Notes", "items": "=state.notes.filter(n, n.notebook == view.id)", "empty": "This notebook is empty." }, "slots": { "item": { "control": "core:stack", "props": { "direction": "horizontal" }, "children": [ { "control": "core:text", "props": { "value": "=item.text" } }, { "control": "core:button", "props": { "label": "Remove", "destructive": true, "emphasis": "low" }, "on": { "press": { "run": "removeNote", "with": { "id": "=item.id" } } } } ] } } } ] } }, "newNotebook": { "title": "New notebook", "state": { "name": { "type": "string?", "description": "The name being typed." } }, "body": { "control": "core:form", "props": { "submitLabel": "Make it" }, "on": { "submit": [{ "run": "addNotebook", "with": { "name": "=default(view.name, '')" }, "as": "id" }, { "navigate": "notebook", "with": { "id": "=id" } }] }, "children": [{ "control": "core:textInput", "props": { "label": "Name", "required": true }, "bind": { "value": "view.name" } }] } } } } } } ``` --- # Example app `jar`: Savings jar Money put aside toward a goal: what is saved, what is left, and a word when the goal is reached. ```json { "oad": "0.2", "id": "com.example.jar", "version": "1.0.0", "meta": { "name": "Savings jar", "description": "Money put aside toward a goal: what is saved, what is left, and a word when the goal is reached." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "capabilities": { "notify": { "contract": "core:notify", "description": "Tells you when the jar reaches its goal.", "required": false } }, "grants": { "goalNotice": { "capability": "notify", "scopes": ["notify.self"], "reason": "Tell you when the jar reaches its goal.", "rate": { "count": 3, "per": "P1D" }, "required": false } }, "state": { "goal": { "type": "number", "initial": 100, "description": "How much to save, in US dollars." }, "saved": { "type": "number", "initial": 0, "description": "How much is in the jar, in US dollars." }, "remaining": { "type": "number", "derive": "max(state.goal - state.saved, 0)", "description": "How much is still to save." } }, "actions": { "putIn": { "description": "Put money in the jar.", "input": { "amount": { "type": "number", "description": "How much, in US dollars." } }, "steps": [ { "set": "state.saved", "to": "=state.saved + input.amount" }, { "if": "state.saved >= state.goal && state.saved - input.amount < state.goal", "then": [ { "emit": "goalReached", "with": { "saved": "=state.saved" } }, { "call": "notify.send", "with": { "title": "Goal reached", "body": "=`The jar holds ${state.saved} dollars.`" }, "onError": [] } ] } ] }, "setGoal": { "description": "Change how much to save.", "input": { "goal": { "type": "number", "description": "The new goal, in US dollars." } }, "steps": [ { "set": "state.goal", "to": "=input.goal" } ] }, "empty": { "description": "Take everything out of the jar.", "confirm": { "message": "=`The ${state.saved} dollars in the jar are taken out.`" }, "steps": [ { "set": "state.saved", "to": 0 } ] } }, "exports": { "inputs": { "goal": "state.goal" }, "state": ["saved", "remaining"], "actions": ["putIn"], "events": ["goalReached"], "views": ["summary"] }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "Savings jar", "state": { "goal": { "type": "number?", "description": "The goal being typed." } }, "body": { "control": "core:stack", "children": [ { "control": "core:progress", "props": { "label": "Saved", "value": "=state.saved", "max": "=state.goal", "format": "currency", "currency": "USD" } }, { "control": "core:button", "props": { "label": "Put in 10 dollars", "emphasis": "high" }, "on": { "press": { "run": "putIn", "with": { "amount": 10 } } } }, { "control": "core:form", "props": { "submitLabel": "Set the goal" }, "on": { "submit": [ { "run": "setGoal", "with": { "goal": "=default(view.goal, state.goal)" } }, { "set": "view.goal", "to": null } ] }, "children": [ { "control": "core:numberInput", "props": { "label": "Goal in dollars", "min": 1, "required": true }, "bind": { "value": "view.goal" } } ] }, { "control": "core:button", "props": { "label": "Empty the jar", "emphasis": "low", "destructive": true }, "on": { "press": { "run": "empty" } } } ] } }, "summary": { "title": "Savings jar", "body": { "control": "core:stack", "children": [ { "control": "core:progress", "props": { "label": "Saved", "value": "=state.saved", "max": "=state.goal", "format": "currency", "currency": "USD" } }, { "control": "core:text", "props": { "value": "=state.remaining == 0 ? 'The goal is reached.' : `${state.remaining} dollars to go.`" } } ] } } } } } } ``` --- # Example app `gift`: Gift fund Saving for one gift with a savings jar: the gift's price is the jar's goal, and the app notes the day enough is saved. ```json { "oad": "0.2", "id": "com.example.gift", "version": "1.0.0", "meta": { "name": "Gift fund", "description": "Saving for one gift with a savings jar: the gift's price is the jar's goal, and the app notes the day enough is saved." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } }, "definitions": { "jarApp": { "id": "com.example.jar", "version": "^1.0.0" } } }, "parts": { "jar": { "definition": "jarApp", "with": { "goal": "=state.price" }, "capabilities": { "notify": "notify" }, "grants": { "goalNotice": { "rate": { "count": 1, "per": "P1D" } } } } }, "capabilities": { "notify": { "contract": "core:notify", "description": "Passed to the savings jar, so it can tell you when the gift is paid for.", "required": false } }, "state": { "gift": { "type": "string", "initial": "A new bike", "description": "The gift to save for." }, "price": { "type": "number", "initial": 240, "description": "What the gift costs, in US dollars." }, "savedOn": { "type": "date?", "initial": null, "description": "The day the jar reached the price." }, "weeksLeft": { "type": "integer", "derive": "ceil(parts.jar.state.remaining / 20)", "description": "Weeks to go at 20 dollars a week." } }, "actions": { "saveWeek": { "description": "Put this week's 20 dollars in the jar.", "steps": [ { "run": "jar.putIn", "with": { "amount": 20 } } ] }, "setPrice": { "description": "Change what the gift costs.", "input": { "price": { "type": "number", "description": "The new price, in US dollars." } }, "steps": [ { "set": "state.price", "to": "=input.price" }, { "set": "state.savedOn", "to": null } ] } }, "rules": { "noteTheDay": { "description": "When the jar reaches the price, note the day.", "when": { "event": "jar.goalReached" }, "do": [ { "set": "state.savedOn", "to": "=env.today" } ] } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "=state.gift", "state": { "price": { "type": "number?", "description": "The price being typed." } }, "body": { "control": "core:stack", "children": [ { "control": "core:text", "props": { "value": "=state.savedOn != null ? `Enough was saved on ${formatDate(state.savedOn, 'long')}.` : (state.weeksLeft == 0 ? 'Enough is saved.' : `${state.weeksLeft} weeks to go at 20 dollars a week.`)" } }, { "part": "jar", "view": "summary" }, { "control": "core:button", "props": { "label": "Save this week's 20 dollars", "emphasis": "high" }, "on": { "press": { "run": "saveWeek" } } }, { "control": "core:form", "props": { "submitLabel": "Set the price" }, "on": { "submit": [ { "run": "setPrice", "with": { "price": "=default(view.price, state.price)" } }, { "set": "view.price", "to": null } ] }, "children": [ { "control": "core:numberInput", "props": { "label": "Price in dollars", "min": 1, "required": true }, "bind": { "value": "view.price" } } ] } ] } } } } } } ``` --- # Example app `guests`: Guest book Guests sign with their name, and everyone sees who signed and how many. ```json { "oad": "0.2", "id": "com.example.guests", "version": "1.0.0", "meta": { "name": "=t('appName')", "description": "=t('appDescription')" }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "localization": { "default": "en", "strings": { "en": { "appName": "Guest book", "appDescription": "Guests sign with their name, and everyone sees who signed and how many.", "signedDescription": "The names of everyone who signed.", "lastDescription": "The name of the guest who signed last.", "signDescription": "Sign the guest book with a name.", "nameDescription": "The name to sign with.", "nameMissing": "Write your name first.", "yourName": "Your name", "sign": "Sign", "welcome": "Welcome, {name}!", "signatures": "Signatures", "empty": "Nobody has signed yet.", "count": { "by": "count", "forms": { "=0": "No guests yet.", "one": "{count} guest has signed.", "other": "{count} guests have signed." } } }, "ar": { "appName": "دفتر الزوار", "appDescription": "يوقّع الضيوف بأسمائهم، ويرى الجميع من وقّع وكم عددهم.", "signedDescription": "أسماء كل من وقّع.", "lastDescription": "اسم آخر ضيف وقّع.", "signDescription": "التوقيع في دفتر الزوار باسم.", "nameDescription": "الاسم الذي يُوقَّع به.", "nameMissing": "اكتب اسمك أولًا.", "yourName": "اسمك", "sign": "وقّع", "welcome": "أهلًا بك يا {name}!", "signatures": "التوقيعات", "empty": "لم يوقّع أحد بعد.", "count": { "by": "count", "forms": { "=0": "لا ضيوف بعد.", "one": "وقّع ضيف واحد.", "two": "وقّع ضيفان.", "few": "وقّع {count} ضيوف.", "many": "وقّع {count} ضيفًا.", "other": "وقّع {count} ضيف." } } }, "ja": { "appName": "ゲストブック", "appDescription": "ゲストが名前を書いて記帳し、誰が何人記帳したかを全員が見られます。", "signedDescription": "記帳した全員の名前。", "lastDescription": "最後に記帳したゲストの名前。", "signDescription": "名前を書いてゲストブックに記帳します。", "nameDescription": "記帳する名前。", "nameMissing": "先に名前を書いてください。", "yourName": "お名前", "sign": "記帳する", "welcome": "ようこそ、{name}さん!", "signatures": "記帳した人", "empty": "まだ誰も記帳していません。", "count": { "by": "count", "forms": { "=0": "まだゲストはいません。", "other": "{count}人のゲストが記帳しました。" } } } }, "notes": { "welcome": "Shown after a guest signs. {name} is the name they wrote.", "count": "Below the list. {count} is how many guests signed." } }, "state": { "signed": { "type": "string[]", "initial": [], "description": "=t('signedDescription')" }, "last": { "type": "string?", "initial": null, "description": "=t('lastDescription')" } }, "actions": { "sign": { "description": "=t('signDescription')", "input": { "name": { "type": "string", "description": "=t('nameDescription')" } }, "require": [ { "that": "size(trim(input.name)) > 0", "message": "=t('nameMissing')" } ], "steps": [ { "append": "state.signed", "value": "=trim(input.name)" }, { "set": "state.last", "to": "=trim(input.name)" } ] } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "=t('appName')", "state": { "name": { "type": "string?", "description": "=t('nameDescription')" } }, "body": { "control": "core:stack", "children": [ { "control": "core:text", "when": "state.last != null", "props": { "value": "=t('welcome', { name: state.last })" } }, { "control": "core:form", "props": { "submitLabel": "=t('sign')" }, "on": { "submit": [ { "run": "sign", "with": { "name": "=default(view.name, '')" } }, { "set": "view.name", "to": null } ] }, "children": [ { "control": "core:textInput", "props": { "label": "=t('yourName')", "required": true }, "bind": { "value": "view.name" } } ] }, { "control": "core:list", "props": { "label": "=t('signatures')", "items": "=state.signed", "empty": "=t('empty')" }, "slots": { "item": { "control": "core:text", "props": { "value": "=item" } } } }, { "control": "core:text", "props": { "value": "=t('count', { count: size(state.signed) })" } } ] } } } } } } ``` --- # Example app `postage`: Postage Works out the fewest of your stamps that pay the postage of a letter or a parcel. ```json { "oad": "0.2", "id": "com.example.postage", "version": "1.0.0", "meta": { "name": "Postage", "description": "Works out the fewest of your stamps that pay the postage of a letter or a parcel." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "types": { "Plan": { "type": "object", "properties": { "item": { "type": "string" }, "postage": { "type": "integer" }, "stamps": { "type": ["array", "null"], "items": { "type": "integer" } } }, "required": ["item", "postage", "stamps"], "additionalProperties": false } }, "state": { "stamps": { "type": "integer[]", "initial": [20, 30, 50], "description": "The values of the stamps you keep, in cents." }, "letterPostage": { "type": "integer", "initial": 60, "description": "The postage of a letter, in cents." }, "last": { "type": "Plan?", "initial": null, "description": "The stamps worked out last, and what for." }, "said": { "type": "string", "derive": "state.last == null ? 'Press a button to see which stamps to use.' : state.last.stamps == null ? `${state.last.item}: the stamps could not be worked out here.` : size(state.last.stamps) == 0 ? `${state.last.item}: no mix of your stamps makes ${state.last.postage} cents.` : `${state.last.item}: ${state.last.postage} cents in ${size(state.last.stamps)} ${plural(size(state.last.stamps), {one: 'stamp', other: 'stamps'})}, ${join(state.last.stamps.map(s, string(s)), ' + ')}.`", "description": "What the screen says of the stamps worked out last." } }, "code": { "fewestStamps": { "description": "Finds the fewest stamps whose values add up to the postage exactly, largest first, trying every mix of the values given. It fails when no mix makes the postage.", "runtime": "js", "input": { "postage": { "type": "integer", "description": "The postage to pay, in cents." }, "values": { "type": "integer[]", "description": "The values of the stamps to choose from, in cents." } }, "output": "integer[]", "source": "export default function ({ postage, values }) { const best = [[]]; for (let a = 1; a <= postage; a++) { for (const v of values) { const rest = best[a - v]; if (v > 0 && v <= a && rest !== undefined && (best[a] === undefined || rest.length + 1 < best[a].length)) best[a] = [...rest, v]; } } if (best[postage] === undefined) throw new Error(`no mix of these stamps makes ${postage}`); return best[postage].sort((x, y) => y - x); }", "limits": { "timeMs": 50, "memoryMb": 16 } } }, "grants": { "stampMath": { "code": "fewestStamps", "reason": "Works out which of your stamps to use. It runs inside the app and reaches nothing else." } }, "actions": { "stampLetter": { "description": "Work out the stamps for a letter.", "steps": [ { "code": "fewestStamps", "with": { "postage": "=state.letterPostage", "values": "=state.stamps" }, "as": "picked", "orElse": "=error.code == 'code.failed' ? [] : null" }, { "set": "state.last", "to": { "item": "A letter", "postage": "=state.letterPostage", "stamps": "=picked" } } ] }, "stampParcel": { "description": "Work out the stamps for a parcel of the given weight.", "input": { "grams": { "type": "integer", "description": "The parcel's weight in grams." } }, "require": [ { "that": "input.grams >= 1 && input.grams <= 20000", "message": "A parcel weighs from 1 to 20000 grams." } ], "steps": [ { "let": "postage", "to": "=150 + 40 * ceil(input.grams / 500)" }, { "code": "fewestStamps", "with": { "postage": "=postage", "values": "=state.stamps" }, "as": "picked", "orElse": "=error.code == 'code.failed' ? [] : null" }, { "set": "state.last", "to": { "item": "=`A parcel of ${input.grams} g`", "postage": "=postage", "stamps": "=picked" } } ] } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "Postage", "state": { "grams": { "type": "integer", "initial": 1200, "description": "The weight of the parcel being stamped." } }, "body": { "control": "core:stack", "children": [ { "control": "core:text", "props": { "value": "=`Your stamps: ${join(state.stamps.map(s, string(s)), ', ')} cents`" } }, { "control": "core:button", "props": { "label": "Stamp a letter", "emphasis": "high" }, "on": { "press": { "run": "stampLetter" } } }, { "control": "core:numberInput", "props": { "label": "Parcel weight in grams", "min": 1, "max": 20000 }, "bind": { "value": "view.grams" } }, { "control": "core:button", "props": { "label": "Stamp a parcel" }, "on": { "press": { "run": "stampParcel", "with": { "grams": "=view.grams" } } } }, { "control": "core:text", "props": { "value": "=state.said" } } ] } } } } } } ``` --- # Open App Definition (OAD) 0.2: Core Specification Status: working draft. The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are to be read as in RFC 2119. ## 1. What OAD is An **app definition** is a single JSON document that describes what an app does: the values it holds, the things it can do, when it does them, what it needs from the outside world, what it is permitted to touch, and how people and agents use it. A **host** loads a definition, binds real capabilities, enforces grants and serves surfaces. An AI writes and edits definitions; people and agents use the resulting apps. Four principles are fixed: 1. **Intent over implementation.** A definition says what the app does, never how a platform draws or runs it. 2. **Explicit, enforceable permissions.** Nothing has an effect outside the app unless a grant covers it. 3. **Everything is versioned.** The spec, catalogs, contracts and definitions all carry versions. 4. **Inspectable by any user.** A person or agent can always see what an app does, what it touches and why. ## 2. The model in one page OAD is built around a **kernel** and **projections** of it. The kernel is the app itself, with no user interface in it: - **State**: named, typed values. Stored, derived from other values, or sourced from a capability. - **Actions**: named, typed operations. Every outside effect, and every change to state that others share, is an action or runs inside one. The handlers and bindings of a visual surface write view state and the person's own state directly, and start everything else by running an action (section 12.2). - **Rules**: "when X, do Y". A trigger plus steps. - **Flows**: explicit state machines for multi-step processes. - **Code**: sandboxed pure functions for logic nothing else can express. Around the kernel: - **Capabilities**: typed access to the outside world (data, devices, services), referenced by contract and bound by the host. - **Grants**: the permissions the app asks for. Every capability operation and every code module is gated by one. - **Surfaces**: projections of the kernel for a kind of user. A visual surface projects state into controls and events into actions. An agent surface projects actions into callable tools and state into readable resources. A voice surface projects actions into intents. Every surface is optional, and none of them holds logic. - **Parts**: other definitions included in this one. A host runs a definition as an **instance**: one installation with its own state, issued grants and audit log, owned by one person or organization and used by its members (section 6.4). Two consequences follow, and both are deliberate: - An app with no surfaces is still a complete app. A headless agent app and a visual app share one model. - Any action a person can trigger from a screen, an agent can call as a tool, subject to the same grants and the same guards. There is no second, weaker path for agents. ## 3. Document format - A definition is a JSON document (RFC 8259), UTF-8, conventionally named `*.oad.json`. - JSON is the only canonical form. Tools MAY offer other authoring views, but interchange is JSON. - Named things live in **objects keyed by name**, not arrays, wherever order carries no meaning. This gives every element a stable JSON Pointer (`/rules/warnOverBudget`), which is what makes small, reviewable AI edits (RFC 6902 patches) reliable. - **Names** MUST match `^[a-z][a-zA-Z0-9]*$` and MUST NOT be one of the reserved words `true`, `false`, `null` and `in`. This applies to every key that names something: entries of `state`, `actions`, `rules`, `flows`, `code`, `capabilities`, `grants`, `parts`, `roles` and `assets`, views and their `state` entries, flow states, events, intents, field-map keys, local names bound by `as`, `let` and `indexAs`, and catalog or definition aliases. Type names in `types` MUST match `^[A-Z][a-zA-Z0-9]*$`. - Capability aliases and part names share one namespace and MUST be distinct, because both appear before a dot in references such as `bank.listTransactions` and `budget.logDeposit`. - Unknown keys are an error at every level of the document. The one extension point is the top-level `extensions` object, keyed by a reverse-DNS namespace (`"com.vendor.feature": {...}`) whose values are objects. Hosts MUST ignore extension namespaces they do not understand. A top-level `$schema` key holding a schema URI or relative reference is permitted so editors can validate files. - `description` fields are part of the contract with users. They are the source of the plain-language explanation of the app (section 15). They are REQUIRED on actions, rules, flows, code modules and capabilities, and `reason` is REQUIRED on grants. ### 3.1 Top-level shape ```json { "oad": "0.2", "id": "com.example.trip-savings", "version": "1.0.0", "meta": { "name": "Trip Savings", "description": "Tracks progress toward a savings goal." }, "uses": { "catalogs": {}, "definitions": {}, "design": null }, "types": {}, "roles": {}, "capabilities": {}, "grants": {}, "state": {}, "actions": {}, "rules": {}, "flows": {}, "code": {}, "parts": {}, "exports": {}, "surfaces": {}, "assets": {}, "localization": { "default": "en" }, "extensions": {}, "included": [] } ``` Only `oad`, `id`, `version` and `meta` are required. Every other key defaults to empty, except `localization`: a definition without it declares no language (section 12.6). `included` holds the carried copies of what the definition refers to (section 4); it is not part of the app's own content and never part of its digest (section 16). | Key | Meaning | | --- | --- | | `oad` | Spec version the document targets, `MAJOR.MINOR`. `0.2` for this specification (section 16). | | `id` | Globally unique identifier in reverse-DNS form, lowercase, segments of `[a-z0-9-]`, at least two segments. An `id` that begins with `org.openappdefinition.` names a document of the format itself (section 4). | | `version` | Semantic version (semver 2.0.0) of this definition. | | `meta` | `name` (required), `description` (required), and optional `authors` (array of strings), `license` (SPDX expression), `tags` (array of strings), `icon` (a name of the core catalog's icon vocabulary, its type `IconName`, as an icon control's `name` takes; `contracts.md` section 1), `homepage` (absolute URI), `derivedFrom` (`{ "id", "version", "digest" }` with `digest` optional, set when a definition is forked or remixed). | | `included` | Carried copies: whole definitions and design systems the file brings along so that it opens alone (section 4). | ### 3.2 Values and expressions Many fields accept a **dynamic value**: a JSON value that may contain expressions. - A string that starts with `=` is an expression. `"=state.goal - state.saved"` evaluates to a number. - A string that starts with `==` is a literal string starting with a single `=` (the first `=` is removed). - Any other JSON value is a literal. Objects and arrays are walked recursively, so `{ "amount": "=input.amount", "note": "Deposit" }` is a dynamic value. Some fields are **always expressions** and are written without the leading `=`: `derive`, `when`, `if`, `allow`, `where`, `becomes`, `each.in` and the other fields this document marks as *expression*. Some fields are **paths**: a reference to a writable location, such as `state.form.amount`. Paths are written without `=` and are marked *path*. A path names fields with dots. Where this document allows it, a path MAY also select one element of a list with a **selector**, `[field=expression]`: `state.answers[id=item.id].note` is the `note` of the first element of `state.answers` whose `id` equals the value of `item.id`, compared as `==` compares. The expression in a selector sees the roots of the position the path is in. Selectors are allowed in the targets of `set`, `append`, `remove` and `patch` (section 8.1) and in `bind` (section 12.2); a path with a selector anywhere else is an error (`expression.syntax`). The grammar of paths is in `expressions.md`, section "Paths". Fields of values an app writes through paths are named as identifiers; data from outside with other key shapes is read with index syntax (`row["posted-at"]`) and reshaped by an expression before it is stored. The expression language is defined in `expressions.md`. In short: it uses a subset of the syntax of the Common Expression Language (CEL) plus template strings (`` `Saved ${state.saved}` ``), is side-effect free, has no loops or recursion beyond bounded macros over finite lists, and always terminates. `expressions.md` also gives every function a signature and says how types flow through expressions, and validation uses this to report operations and values that cannot be right wherever the types involved are known (`validation.md`). ### 3.3 Types A **type reference** is either a string shorthand or a JSON Schema object. - Shorthand primitives: `string`, `number`, `integer`, `boolean`, `date` (ISO 8601 calendar date), `datetime` (ISO 8601 timestamp with `Z` or a numeric offset; hosts produce UTC with `Z`), `duration` (ISO 8601 duration), `any`. Values of `date`, `datetime` and `duration` are strings in those forms (`expressions.md`, section "Date, datetime and duration formats"), so they conform wherever `string` is expected. - A name defined in this document's `types`: `Transaction`. - A type defined by a catalog, written `alias:TypeName` with an alias from `uses.catalogs`: `finance:Transaction`. - Suffix `[]` for a list and `?` for nullable, list first: `Transaction[]`, `string?`, `finance:Transaction[]?`. At most one of each is allowed; deeper nesting needs a named type. - A JSON Schema object (2020-12) restricted to: `type` (a JSON type name, or an array of them such as `["string", "null"]`), `properties`, `required`, `additionalProperties`, `items`, `minItems`, `maxItems`, `uniqueItems`, `enum`, `const`, `oneOf`, `format` (`date`, `date-time`, `duration` or `uri`), `minimum`, `maximum`, `minLength`, `maxLength`, `pattern`, `default`, `description`, `title` and `$ref`. A `$ref` is `#/types/Name` for a type in the same document or, in a definition or in a catalog that declares `uses.catalogs`, `alias:TypeName` for a catalog type, and MAY appear wherever a schema object may, including inside `items` and `properties`. Members of `oneOf` SHOULD be objects told apart by a `const` property, so hosts and people can name the variants. The one other accepted pattern is a nullable reference: a `$ref` beside `{ "type": "null" }`. Any other JSON Schema keyword is an error. A string type in a catalog's `types` MAY also carry `known` (`contracts.md` section 1). - A `pattern` is written in the restricted pattern dialect of `expressions.md`, section "Patterns", which can be matched in time linear in the input. A pattern outside the dialect is an error (`type.invalid`). `types` is an object of type name to JSON Schema object. A **field map** describes named inputs. It is used for action input, capability operation input, code module input, view input, control props and capability config: ```json { "amount": { "type": "number", "description": "Amount saved" }, "memo": { "type": "string", "description": "Optional note", "required": false }, "kind": { "type": "string", "description": "Deposit or withdrawal", "default": "deposit" } } ``` `type` is required. `required` defaults to `true`. A field with a `default` is optional and MUST NOT also set `required: true`. The default is a literal JSON value, used when the field is absent. An optional field with no default that the caller leaves out is absent from the value: `has(input.memo)` is `false` and reading `input.memo` fails with `missing`, so such a field is read with `has(input.memo)` or `default(input.memo, '')`. ### 3.4 Expression scope Expressions read from a fixed set of root names. Which roots are present depends on where the expression sits. | Root | Holds | Present | | --- | --- | --- | | `env` | The environment (section 3.5). | Everywhere. | | `state` | Every state entry, by name. | Everywhere except state `initial`, capability `config` and a grant's `where`. | | `sources` | For each sourced entry: `{ "status", "error", "updatedAt", "partial" }` (section 7.1). | Wherever `state` is, except a view state `initial`. | | `capabilities` | For each alias: `{ "available": boolean }`. | As `sources`. | | `grants` | For each grant request: `{ "held": boolean, "declined": boolean }` (section 6). | As `sources`. | | `flows` | For each singleton flow: `{ "state": name }`. | As `sources`. | | `parts` | For each part: `{ "state": { exported entries } }`. | As `sources`. | | `user` | The acting principal (sections 6.1 and 6.4.4). In `derive`, the principal the value is read for (section 7). | Wherever `state` is. | | `input` | The action's input, or the operation input in a grant's `where`. | Action `allow`, `require`, `confirm`, `done` and steps; grant `where`; voice `reply`. | | `output` | The output of the action an intent ran, or of the action whose `done` message it is. | Voice `reply`; action `done`. | | `event` | The payload of the trigger or control event. In a flow, the `with` of the `send` that caused the transition, or `null` for an `after` transition. | Rule `if` and `do`; flow transitions (`if`, `allow`, `do`) and `enter` and `exit` steps; visual handlers; voice `announce`. | | `view` | The current view's input values and view state, by name (`view.requestId`). | Visual surface. | | `item`, `index` | The current element and its position. | `where` of `remove` and `patch`, and `with` of a `patch` that has `where` (section 8.1); the transitions and `enter` and `exit` steps of a collection flow; `each` of a step, a node or a navigation section (`item` only when `as` is not given, `index` only when `indexAs` is not given). | | `error` | `{ "code", "message" }` of the failed step. | `onError` steps and `orElse`. | The **base roots** are `env`, `state`, `sources`, `capabilities`, `flows`, `parts`, `grants` and `user`. A grant's `where` is the exception to the table: it sees only `input` and `env`, so a permission never depends on app state the app itself can change. `validation.md`, section "Expression scope", gives the roots at every position in a definition. Local names bound by `as` (on `call`, `run`, `code` and `each` steps, on a node's `each` and on a navigation section's `each`), by a `let` step, and by `indexAs` (on an `each` step, a node's `each` and a navigation section's `each`) join the scope: for a step, the steps after it in the same list, including steps nested in them (for `each`, the steps of its body); for a node's `each`, the node, the nodes inside it and their event handlers; for a navigation section's `each`, the section's `label`, `when`, `with`, `count` and `each.key`. A local name MUST NOT be any root name in this table. Variables bound by list macros inside an expression are separate and MAY reuse any name (see `expressions.md`). ### 3.5 Environment `env` is read-only and supplied by the host. | Field | Meaning | | --- | --- | | `env.now` | Current UTC datetime. Fixed for the duration of an action. For derived values and view bindings the host refreshes it at least once a minute in each active session (section 6.4), and while an agent is connected. A refresh while no session is active tests no trigger and causes no source read (section 6.4.4). | | `env.today` | Current calendar date in `env.timezone`. | | `env.timezone` | IANA time zone name. | | `env.locale` | BCP 47 language tag of the locale that formats numbers, dates, relative times and plural categories. For a definition with `localization`, the formatting locale of `env.language` for the person (section 12.7), so that formats agree with the words beside them. For a definition without it, the locale the host gives for the person. | | `env.language` | The shown language (section 12.7): one of the app's own language tags. `null` when the definition has no `localization`. | | `env.direction` | `'ltr'` or `'rtl'`: the direction of `env.language` (section 12.7); `'ltr'` when that is `null`. | | `env.currency` | ISO 4217 code of the user's default currency, or `null`. | | `env.online` | Whether the host currently has network connectivity. | | `env.surface` | The surface the current invocation came from, or that is evaluating the expression for display (a view title, a prop, a node's `when`): `visual`, `voice` or `agent`. `null` for rules, timers and derived values. | | `env.invocation` | The id of the audit record (section 15) of the outermost invocation: the action invoked from a surface, the visual handler, the rule firing or the timer. It lets app records point at the audit log. `null` in derived values and wherever no invocation is running. | | `env.host` | `{ "name", "version" }` of the host. | When an `env` field changes (`online`, `today`, or `now` when the host refreshes it), the host re-evaluates the derived values, bindings, `becomes` triggers and source `with` values that read it, as it does when state changes. A source whose `with` reads `env.now` is therefore read again each time `now` is refreshed, when its `refresh.on` includes `change`. A definition without `localization` behaves as if these languages did not exist: `env.language` is `null`, `env.direction` is `'ltr'`, and `env.locale` is the person's locale as the host gives it. When the person's languages or the kept choice of language (section 12.7) change while the app runs, `env.language`, `env.direction` and `env.locale` change like any other `env` field. The host then treats `env.language` and `env.locale` as changed even where a value stays the same, because a text taken from another table of the text chain follows the person's languages directly. ## 4. Uses: catalogs, definitions, design ```json "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } }, "definitions": { "budgetApp": { "id": "com.example.budget", "version": "^1.2.0", "digest": "sha256-RBNvo1WzZ4oRRq0W9-hknpT7T8If536DEMBg9hyq_4o" } }, "design": { "id": "com.example.brand", "version": "^2.0.0" } } ``` - `catalogs` maps a local alias to a catalog `id` and a semver range. Controls and capability contracts are referenced as `alias:contractName` (`core:list`). The core catalog's controls, with their props, events and slots, and its capabilities, with their operations, are described in `catalogs/core/README.md`. - `definitions` maps a local alias to another definition, by `id` and semver range. `digest` is optional and pins exact content (section 16). `source` is an optional URI hint for where to fetch it. - `design` optionally references a design system (section 12.4). - Version ranges use a subset of node-semver syntax: exact versions, comparators and space-separated comparator sets (`>=1.2.0 <2.0.0`), caret and tilde ranges, `x` and `*` wildcards, hyphen ranges, and `||` alternatives. Hosts resolve these references. A reference of `definitions` or `design` is looked up first among the carried copies (below). Otherwise, how a host locates a catalog or definition by `id` (registry, local folder, bundle) is outside this document. A catalog the host cannot find does not by itself fail the load (section 14). **Carried copies.** A definition MAY have a top-level member `included`: an array of whole documents, each a definition or a design system, called its **carried copies**. They let one file hold what it refers to, so that it opens alone wherever it is handed. A catalog is never a carried copy: a catalog names what a host itself provides, and no file can bring that along. - `included` changes where a reference of `uses.definitions` and `uses.design` is looked up, and nothing else. A reference written in a document is looked up first among the carried copies of the **file the document came in**, then where the host looks otherwise. - The file a document came in is: for the definition a host or tool was given, that document; for a carried copy, the document that carries it; for a definition the host found elsewhere (a registry, a folder, another draft), that definition itself, with its own `included` if it has one. The copies a file carries therefore serve that file and the copies in it, and no other document: a definition found elsewhere does not see the carried copies of the app that includes it. - Among the carried copies of the right kind with the referenced `id`, the one with the highest version that satisfies the range is chosen. When one is chosen, no other place is consulted for that reference, even when another place holds a higher version that fits, so the same file opens as the same app everywhere. When none fits, the lookup goes on as it would without `included`. - A pinned `digest` is checked against the chosen copy exactly as against a definition found elsewhere. A mismatch is an error (`uses.digestMismatch` in `validation.md`); the lookup does not go on to another place. - `included` is flat: a carried definition MUST NOT have an `included` of its own, and a document of one kind, `id` and `version` is in the list at most once. A tool that writes the carried form puts the copies of copies in the one list. - A carried copy serves only the document that carries it. A host or tool MUST NOT put a carried copy into any store from which the references of other apps are resolved, and MUST NOT take it for the definition of an instance because its `id` matches (section 13). - A carried design system MAY name a catalog of custom controls as any design system may; the host resolves that catalog as always. - An `id` that begins with `org.openappdefinition.` belongs to the format: it names a document of the format itself, such as the core catalog `org.openappdefinition.core` and the default design system `org.openappdefinition.design.default`, which every host provides. Such a document is never carried. A carried copy MUST NOT have such an `id` (`included.reserved` in `validation.md`), a reference to such an `id` is never looked up among the carried copies but where the host looks otherwise, and a tool that writes the carried form leaves such a document out. A file therefore cannot bring a default design system of its own, and a written file does not hold the look to the default design system of the day it was written. A tool that writes the carried form of a definition sets `included` to exactly what the definition's references reach: every definition a part of the app, or a part of a part, resolves to, once each, and every design system the app or one of those definitions names that resolves, the format's own documents left out. A copy nothing reaches is dropped. Two different documents that claim one kind, `id` and `version` (their digests differ) cannot both be carried: the tool writes nothing and names both, with the references through which each was reached. It writes the definitions first and then the design systems, each ordered by `id` and then by version in ascending order of precedence, so that the same app is written as the same bytes, and it changes no other member of the document, so the digest stays the same (section 16). ## 5. Capabilities A capability is typed access to something outside the app. A definition never names a provider or protocol. It names a **contract** from a catalog, and the host binds any provider that implements that contract. This is what lets a definition move between hosts. ```json "capabilities": { "bank": { "contract": "finance:accounts", "description": "Your bank accounts, used to read deposits into savings.", "config": { "accountKind": "savings" }, "required": true, "prefer": ["com.examplebank.connector"] } } ``` | Field | Meaning | | --- | --- | | `contract` | `alias:name` of a capability contract. Required. | | `description` | Why the app uses it, in plain language. Required. | | `config` | Dynamic value matching the contract's `config` field map, with only `env` in scope. Evaluated once, when the capability is bound for the instance, with the owner's `env`, and kept until an update. A required field MAY be left out for the host to supply (below). | | `required` | Default `true`. When `false`, the app loads without it and `capabilities..available` is `false` in expressions. | | `prefer` | Optional ordered list of provider ids. A preference, never a requirement: the host and user have the final say over which equivalent provider is bound. | Capabilities have **operations** (called by steps), and MAY have **events** (which trigger rules). Both are declared by the contract (see `contracts.md`). **Configuration left to the host.** A definition MAY leave out a required `config` field, such as the collection an organization keeps its tickets in, so that the definition can be shared without it. The host supplies the value when it binds the capability, from the owner or from host policy; for a `personal` capability, each person supplies it when they answer its requests, or host policy does. Leaving one out is not a validation error. The resolution report shows the value supplied, and it is part of what the approver answered (section 6, rule 5). A host that has no value reports the capability as `missing` (section 14). **Personal capabilities.** A capability whose contract has the `personal` trait (`contracts.md` section 4) acts for one person: their device, their accounts, their files. Grants on it are answered by each person for themselves (section 6.4.2). **File references.** A file reference (the core catalog's `FileRef`) is a handle the host issued; it identifies a file without containing it. Its `id` MUST be unguessable: at least 128 random bits. - A file reference in an operation input, at any depth of the input type, that the contract types as the core catalog's `FileRef` is resolved by the host, so the provider receives a file it can read. A contract in another catalog names that type through its catalog's `uses` (`contracts.md` section 1). - A file reference in an agent's tool input MUST be one the host issued to that agent for this instance: one the agent received from this instance (in a tool's output or a resource), or one the host gave it for a file the agent handed over. The check applies to every field typed as a file reference, at any depth of the input type, and a host SHOULD apply it to any value that carries the host's own reference form, whatever its declared type. Anything else is refused as invalid input (`action.invalidInput`). - A file reference stays readable for as long as the instance's stored state holds it, across restarts. A host that cannot keep the file MUST NOT leave the reference in state looking valid: reading it fails, and controls that show it show their fallback. - A file reference kept in `shared` state shares that file with every member whose grant covers reading it. - A host SHOULD give agents a way to hand a file to the host and get a reference back. How is up to the adapter. ## 6. Grants The `grants` section lists what the app **asks for**. It never contains issued permissions: those are created by the host when a person approves, and they live with the host, not in the file. Who answers a request, and whom the issued grant covers, is set out in section 6.4.2. ```json "grants": { "readSavings": { "capability": "bank", "scopes": ["transactions.read"], "reason": "Read deposits into your savings account to track progress.", "rate": { "count": 24, "per": "P1D" }, "duration": "P90D", "required": true }, "readTickets": { "capability": "helpdesk", "scopes": ["http.read"], "reason": "Fetch open support tickets.", "where": "input.path.startsWith('/v1/tickets')" }, "lookUpManagers": { "capability": "people", "scopes": ["directory.read"], "operations": ["manager"], "reason": "Find the manager who approves each request." }, "scoring": { "code": "scoreWord", "reason": "Runs a small scoring function for the game." } } ``` | Field | Meaning | | --- | --- | | `capability` or `code` | Exactly one. The capability alias or code module name the request covers. | | `scopes` | For capabilities: scope names defined by the contract. Required and non-empty. | | `operations` | For capabilities: a non-empty list of names of operations and events of the capability. Optional. The issued grant then covers only those operations and events, within its scopes, and the list is shown to the approver. Each name MUST be an operation or event of the capability whose scope is one of `scopes` (`grant.operationUnknown`). | | `reason` | Plain-language justification shown to the approver. Required. | | `where` | *Expression* over `input` (the operation input) and `env`. A call is permitted only if it evaluates to `true`. `input` is the operation input after the contract's defaults are applied, so a field the call left out reads as its default. Optional. This is also how a permission is narrowed by an input value, for example `input.precision == 'approximate'`. | | `rate` | `{ "count", "per" }` with an ISO 8601 duration. Optional. Counted per issued grant: per instance for an instance grant, per person for a personal grant (section 6.4.2). Every request has its own rate, a part's included (section 13). | | `duration` | Longest lifetime requested for the issued grant. Optional; hosts MAY shorten it. | | `required` | Default `true`. When `false`, the app loads if the request is declined, and operations it would have covered fail with `grant.denied`. | A request that names `code` MAY set only `reason`, `rate`, `duration` and `required`. **Knowing what was granted.** `grants..held` is `true` while an issued grant for request `` is in force for the principal acting: the instance's grant for an instance request, or the grant of the acting principal's person for a personal request (section 6.4.2). `grants..declined` is `true` while a decline of the request stands for that same instance or person: someone entitled to answer said no, or a grant for it was revoked (rule 4), and nobody entitled has allowed it since; or the including definition declined a part's request (section 13). A request that has not been answered yet, or that is asked again because it changed, is neither held nor declined, and so is one that went unanswered only because nobody entitled was present (rule 6). An app offers what an optional request would allow while the request is not declined, so that a person's use of it can bring the question ("When a request is asked", below), stops offering it once they have said no, and shows what depends on the grant only while it is held. The `grants` root is present wherever `state` is, and never in a grant's `where`. A part sees its own requests, under their own names. Enforcement rules: 1. A host MUST refuse a capability operation unless an issued, unexpired, unrevoked grant covers it: the grant was issued for a request of the definition whose steps made the call (section 13), it is held for the principal acting (section 6.4.2), it includes the operation's scope and, when its request lists `operations`, names the operation, it satisfies `where`, and the call is within `rate`. Likewise a host MUST NOT deliver a capability event to the app unless such a grant covers the event's scope and, when its request lists `operations`, names the event. A grant's `where` narrows events as it narrows operations: it is evaluated with `input` set to the event payload, and an event for which it is not true, or cannot be evaluated because the payload lacks a field it reads, is not delivered. Delivery does not count against `rate`. 2. A host MUST refuse to run a code module without an issued grant naming it. When it runs a module, it MUST refuse to run it unless the module's text is the text the grant was issued for. 3. The definition's requests are an upper bound. A host MUST NOT issue the app more than it requested. 4. Issued grants are scoped, time-limited and revocable. An instance grant is revoked by the owner; a personal grant by its person or by the owner. Revocation takes effect before the next operation, and leaves the request declined: it is not asked again, and nothing is issued for it, until a person entitled to answer allows it. 5. A grant answers one request as it was put to the approver. A host that keeps grants between runs MUST treat a kept grant as covering a request only while what the approver would be asked now is what they were asked then: the request itself, the capability it names (its contract, its `config`, including values the host supplied when binding it, the origin it reaches, and whether its provider keeps the request inside the app) and, for a code request, the module's text. When any of these has changed the host MUST withdraw the kept grant and ask again, and SHOULD tell the approver that the request replaces one they answered before. For a request that needs no answer ("When a request is asked", below), the host withdraws the kept grant and issues a new one without asking. A kept grant for a request the definition no longer makes MUST be withdrawn. Narrowing chosen by the approver is not a change: a grant issued narrower than its request stays in force while the request is unchanged. A `reason` written as a reference to a text (section 12.6) counts as the text the approver was shown: the host keeps, with a kept grant, the language whose text it showed, and the grant holds while the reason's text in that language is unchanged. Adding a language, or editing another language's text, does not ask again; editing the text the approver read does. A reason written as plain text is compared as it is. Section 6.4.1 applies this rule to updates. 6. A request that needs an answer ("When a request is asked", below) is answered by a person entitled to answer it (section 6.4.2) who can see it. A host MAY hold the review until such a person is present. When nobody entitled is present to answer (an agent served on its own, a run without a screen), a request that was not answered earlier is declined; a host MUST NOT approve it on that person's behalf. A request declined because nobody entitled was present is declined for that use only, and is asked again when such a person is present. **When a request is asked.** Every question costs a person attention, and a person asked too often stops reading. A host asks where an answer protects something, once, and in plain words. - **Given by use.** A contract MAY mark a scope as given by use (`contracts.md` section 4): nothing happens under it unless a person does it themselves at that moment in the host's own interface, such as choosing a file or taking a photo, or has already handed the app the thing acted on. A request whose scopes are all given by use needs no answer. The mark is a catalog's promise, so it counts only from a catalog the host trusts to make it: the core catalog, and any other that the host's operator or the person has chosen to trust. A scope marked by any other catalog is asked like any other scope. - **Contained.** A request is contained when everything done under it stays inside the app, so that an answer would protect nothing. A request that names `code` is contained: its module is a pure function run in the host's sandbox, with no network, storage, clock or host object (section 11). A capability request is contained when the provider the host binds for it promises, for every scope the request names, that everything done under that scope stays inside the app: the provider gives the app nothing that belongs to a person or to anyone else outside the app (data made for a demonstration belongs to nobody), changes nothing outside the instance's own state and what the host shows for this app, reaches no network, no other program and no other person, cannot cost anyone money, and does nothing once the host no longer runs the app. A provider that reaches the web, a real account, a real device sensor, another person or the device's own notifications does not keep that promise. What a person turns on themselves in the host's own interface, such as having the app's notices also shown by their device, is that person's choice made with the host, and not something the provider reaches. Only the host makes the promise, through the provider it binds, about what that provider really does; nothing a definition or a catalog says makes a request contained, and neither a scope's sensitivity nor a contract's traits change whether it is. A contained request needs no answer. - **Without an answer.** Wherever this document says a request is asked, the host instead issues the grant for a request given by use or contained without asking, and records that nobody was asked: when the instance is installed for an instance request, when work on a person's behalf first needs it for a personal request (whether that person or an agent of theirs started the work), and again when the request has changed (rule 5) or its grant has expired. It does so also when nobody entitled to answer is present, since there is nothing to answer (rule 6). The grant is otherwise a grant like any other: issued for the module's text for a code request (rule 2), limited by the request's `operations`, `where`, `rate` and `duration`, shown with the app's other grants, and revocable. Once it is declined or revoked, nothing is issued for the request until a person entitled to answer allows it in the host's own interface. A host MAY ask for a request given by use or contained all the same. - **Required requests.** Any other request with `required: true` is asked before the load completes for the person who answers it. - **Optional requests.** Any other request with `required: false` MAY be left unanswered when the app loads. The host then asks it later, at a moment of its choosing, while a person entitled to answer is present. When work makes a call that an unanswered request would cover, the host MAY hold the call and ask, and it MUST do so when a person entitled to answer started that work from a surface of theirs that is still active. Holding the call does not hold the instance (section 8.2, "Waiting on a person"). The call continues if a grant is issued that covers it. Otherwise, and whenever the host does not ask, the call fails with `grant.denied`. A host that shares an instance among several people SHOULD put its optional instance requests to the owner at install, since no member can answer them. - **Once.** An answer stands until the request changes (rule 5), its grant expires, or the person who gave it changes it. A host MUST NOT ask again for a request whose decline stands; the person changes their answer in the host's own interface. When a person opens an app that cannot load because a required request of theirs stands declined, the host says which request that is and lets them change the answer there. - **Plainly.** A host MAY put all the requests it asks at one moment to the approver together and take one act as the answer to all of them. What the approver sees names each request in the words of its scopes, keeps its `reason` and limits within reach, and sets apart the requests that deserve a closer look: a scope of `high` sensitivity, a provider that may charge, a capability with the `background` or `egress` trait, a code module where the host asks for one, and a request that replaces one the approver answered before. ### 6.1 Principals and delegation A **principal** is a person, an agent or an app. Expressions see the acting principal as `user`: `{ "id", "kind": "person" | "agent" | "app", "name", "roles": [...], "onBehalfOf": principal or null, "person": { "id", "name" } or null }`. A principal's **person** is the principal itself when it is a person, and otherwise the person at the end of its `onBehalfOf` chain, or none when the chain reaches no person; `user.person` gives it. A definition that records who owns something, or compares a stored person id with the caller, uses `user.person.id`, so that work an agent does for a person belongs to that person and an agent acting for the person passes the comparison. It compares with `user.id` only where the person themselves must act. A principal holds **full access** when its access says every action, as the owner's does, as a member's does unless host policy narrowed it, and as a delegation of all of such an access does. An access that lists actions is never full access, even when the list names every action the definition has today. Which principal acts at each point is set out in section 6.4.4. Delegation is **attenuation only**. A principal MAY delegate a grant it holds to another principal, and the derived grant MUST have: scopes that are a subset of the parent's, an expiry no later than the parent's, and constraints (`where`, `rate`) no looser than the parent's. Revoking a grant revokes everything derived from it. A host MUST record the delegation chain and MUST be able to show it. To **use an app**, a principal needs access to its actions. The owner of an instance holds access to all of them; a member holds the access the host's policy gives them (section 6.4). Access names what can be invoked from outside a definition: its actions that are not `internal`, and an action that one of its parts exports, as `part.action`. An action that cannot be named this way, an `internal` action or an action of a part that the part does not export, is reached only through the steps and visual handlers of the definition that holds it and needs no access of its own: a person who uses a view runs what its handlers run, subject to each action's `allow`, `require` and `confirm`. A person MAY delegate access they hold to an agent for a subset of actions and of the resources an agent may read (section 12.1), optionally time-limited. Limits on resources bind agents: a person who holds access to an instance sees what its surfaces show them. When an agent builds an app for another agent, the grants the new app requests MUST be approved by a principal that itself holds them and is allowed to delegate them, so approval always traces back to a person or organization policy. **Approval.** Who answers a grant request is set out in section 6.4.2. A person entitled to answer MAY delegate the answer to an agent for that contract; an agent never approves a request to run code. A request put to an approver that receives no decision is declined for that use only, as one that could be put to nobody is (section 6, rule 6). `onBehalfOf` records for whom a principal acts and lends it nothing: an agent has exactly the access, and the roles, delegated to it (section 6.4.3). A capability or code grant belongs to the instance, or the person within it, it was issued to (section 6.4.2), and cannot be delegated to another holder. **Agents and surfaces.** An agent uses an app only through its agent surface (section 12.1). A host MUST NOT let an agent run a visual handler or write a binding, whatever access the agent holds. ### 6.2 Roles ```json "roles": { "finance": { "description": "Gives final approval and releases payment." }, "director": { "description": "Decides requests that waited too long for a manager." } } ``` `roles` declares the role names the app's guards refer to, each with a required `description`. A definition never says who holds a role: the host assigns roles (section 6.4.3) and exposes them as `user.roles`. A definition SHOULD declare every role its guards test. A role says what a principal may do anywhere in the app. A relationship between a principal and one record, such as "this request's manager", is not a role: store it on the record and compare it with `user.person.id` (section 6.1), or with `user.id` where the person themselves must act, as the manager's approval in section 10 does with `managerId`. ### 6.3 Egress A network request made in order to present or run the app is an outside effect even when no step asked for it: loading an image, map tiles, a font or media named by a control prop, or prefetching a link. Such a request could carry app state to a third party inside its address. - A host MUST NOT make such a request unless the app holds a grant, on a capability whose contract declares the `egress` trait, whose configured origin matches the request. In the core catalog that capability is `http`, with scope `http.read`. - The grant's `where` and `rate` apply to such a request as they would to a read operation, with `input` being `{ "path", "query" }` of the requested address. - A grant request that carries `operations` (section 6) permits egress only if its list names an operation whose `effect` is `read`. Without `operations`, the rule above applies unchanged. - Control contracts mark props that can cause requests with `remote: true` (see `contracts.md`). Hosts and validators use the mark to find every place egress can occur. - A value in such a prop is a **remote address** when it is an absolute `http` or `https` URL. Loading it is egress, under the rules above. - A value is an **asset reference** when it is the string `asset:` followed by an asset name, such as `asset:logo`. It refers to the asset of that name in the definition the control belongs to: for a view of a part, the part's own definition (section 12.5). Loading an asset is not egress and needs no grant. An asset reference that names no entry of that definition's `assets` MUST NOT be loaded. - Every other value MUST be a **reference the host itself issued**, such as the `uri` of a file reference returned by a capability or the name of a resource bundled with the host. Loading content the host already holds is not egress and needs no grant. A reference is good only for the app instance the host issued it to. - A value of none of these three kinds MUST NOT be loaded. - The rule is enforced when content is loaded, whatever a validator reported, so an app that holds no egress grant can never cause a request. An app that shows only its own assets and content the host holds requests no egress grant. - Following a link is a user action, not egress, provided a person activates it and the host shows the destination before leaving the app. - Fetching a resource the definition or a catalog pins by digest, such as a control's implementation module or a code module's `module.uri`, is the host's own act when it installs the app, checked against the digest (section 16). It is not egress and needs no grant. - A refused request fails with `egress.denied`, and the control shows its fallback or its accessible label. ### 6.4 Instances An **app instance** is one installation of a definition on a host: its state, its issued grants and its audit log. A definition can have many instances, on one host or several, and they share nothing. An instance has one **owner**: the person who installed it, or the person or organization the host's policy names. Where this document says the owner answers or acts, an organization does so through a person or a policy acting for it. Other people who use the instance are its **members**. How people come to use an instance, such as by invitation or through a directory group, is host policy. The owner holds access to every action (section 6.1). Unless host policy says otherwise, a member holds access to every action that is not `internal`, the actions its parts export included. A person who holds no access to an instance cannot load it: the load fails with `instance.forbidden`, and nothing of the instance's state or audit log is shown. Access that is taken away or runs out ends at once: the host ends the sessions of a principal that no longer holds access, shows it nothing further, asks it nothing, and runs nothing on its behalf. A **session** is one principal's use of an instance through a surface on one device, from when it opens the app until it closes the app or the host ends the session. Locking the device or moving the app to the background does not end a session. A person using an instance on two devices has two sessions. The session's person is the person of its principal (section 6.1). A surface is **active** while a person has it open. A session is active while its surface is, and the app is active while any session is. An agent's connection alone does not make the app active: `every` rules, flow `after` timers and timed source refreshes need a person's active session (section 6.4.4 says whose) or a `background` grant (section 9). An agent's own calls run whenever it makes them. #### 6.4.1 Updates The host records the version and digest of the definition an instance runs, including the versions and digests of the parts it resolved. Running the instance with a definition of the same `id` and a different digest is an **update**, and so is a change in any part the instance resolves. - Only the owner may update an instance. Anyone else who presents a different definition for it is refused with `instance.forbidden`, and the instance keeps the definition it runs. - The host MUST record an update in the audit log: who updated, the previous and new version and digest, and for each part whose definition changed, its path and its previous and new `id`, version and digest (only the side that exists for a part that is new or gone). It SHOULD show the owner what changed before applying it. An update that adds no request and changes nothing an approver answered (section 6, rule 5) asks nothing. - Kept grants follow section 6, rule 5: a grant stays in force only while its request is unchanged. A changed request is asked again as a new request would be (section 6, "When a request is asked"): an instance request of the owner, a personal request of each person. - A stored entry the new definition adds gets its `initial`, evaluated at the update (section 7). A stored value that no longer conforms to its entry's `type` under the new definition is replaced by the entry's `initial`, evaluated at the update. Flow state is treated the same way: a collection element whose flow field names a state the new definition no longer declares, or a singleton flow in such a state, is put in the flow's `initial` state without running `enter` steps. The resolution report says which entries were replaced and which flow instances were reset. The host SHOULD keep the replaced values, and the values of entries the new definition no longer declares, where the person they belong to can retrieve them: `shared` values for the owner and a `user` value for its person. `device` and `session` values are not kept. A member SHOULD be told, at their next use, that the definition changed, also when only a part changed. - A host MAY refuse an update that does not descend from the running definition, judged by its history (section 16) or its signer (`contracts.md` section 7). #### 6.4.2 Personal and instance grants Every grant request is either personal or for the instance. - A request on a capability whose contract has the `personal` trait is a **personal request**. Each person answers it for themselves: the first time they use the instance when it is `required`, and otherwise when section 6 says it is asked. The grant issued covers only operations done on that person's behalf: by the person, by an agent acting for them, or by the app acting on their behalf (section 6.4.4). Its `rate` is counted per person. - Every other request, including every code request, is an **instance request**. The owner answers it once, when it needs an answer. The grant issued covers the instance, whoever is using it, and its `rate` is counted per instance. Members are not asked; a member can see the instance grants at their first use and whenever they look. - A request given by use or contained is answered by nobody (section 6): its grant is issued for the instance, or for each person, without a question. - A request that needs an answer when nobody entitled to answer it is present is declined for that use only (section 6, rule 6). A request that is waiting to be asked is neither held nor declined. - A member for whom a required personal request is declined cannot load the app; others are unaffected. A required instance request the owner declined fails the load for everyone. - A principal that acts for no person holds no personal grant. An instance with a required personal request does not load for it, and a call it makes on a personal capability fails with `grant.denied`. - With one person, nothing changes: the owner is that person and answers everything. An operation is done on a person's behalf when the person of the principal acting (section 6.1) is that person. A capability event on a personal capability is delivered under the grant of the person it concerns, and the rules it fires act on that person's behalf. `contracts.md` section 9 lists which core capabilities are personal. #### 6.4.3 Roles in an instance The owner assigns roles. The owner holds every declared role unless host policy assigns otherwise. A member holds the roles the host assigns, whether they come from the owner, from organization policy or from a capability with the `multiUser` trait (such as a directory), and none by default. A host that takes roles from a capability decides how the capability's roles map onto the app's; a definition cannot assume that a directory role is the app role of the same name. When a person delegates access to an agent (section 6.1), the delegation MAY include roles the person holds; the agent then holds exactly those, and none by default. A delegation can never carry a role its giver does not hold. The app principal holds no roles. #### 6.4.4 Who acts Every expression that reads `user`, and every grant check, uses the principal acting at that point: | Work | Acting principal | | --- | --- | | An action invoked from a surface (a voice intent, an agent's tool call, a `run` in a visual handler), and a visual handler's own steps. | The invoking principal. | | A flow transition taken because of a `send`, with its `exit`, `do` and `enter` steps. | The principal whose steps sent the event. `user` in the transition's `allow` is that principal. | | A rule fired by a write made by work that has an acting principal (an action invoked from a surface, a rule's steps, a transition's steps), or by an app event such work raised. | The app principal, on behalf of that principal's person. The trigger is tested, and the rule fires, once, with the values of that person and of the work's session when it has one. | | A rule fired by the result of a source read. | The app principal, on behalf of the person the value belongs to. The trigger is tested, and the rule fires, once, with that person's values and those of the session that occasioned the read when there is one. | | A rule fired by a change of the environment of an active session (`env.online`, `env.today`, `env.now` when the host refreshes it, or another `env` field). | The app principal, on behalf of the session's person, in that session, with its values. Each session has its own environment, so the same rule can fire in several sessions. With no active session and a `background` grant held, the environment is the host's own and the rule fires once for the instance, on behalf of the owner. | | An `every` rule. | The app principal. It fires once per interval in each active session, on behalf of that session's person; with no active session and a `background` grant held, once per interval for the instance, on behalf of the owner, unless the rule says `"foreground": true` (section 9), in which case it does not fire. | | A `lifecycle` rule. | The app principal, on behalf of the session's person. | | A source read. | The app principal, on behalf of the person whose value it reads; section 7.1 says whose values each occasion reads. | | A flow `after` transition, with its steps. | The app principal. It is taken once per flow instance; its `event` is `null`, and its `flow:` payload has `"event": null`. A singleton flow, or a flow over a `shared` collection, acts on behalf of the owner, and its timers run while the app is active or a `background` grant is held. A flow over a collection that is not `shared` acts on behalf of the person whose collection holds the element, and its timers run while that person has an active session or a `background` grant is held. | | A rule fired by an event of a `personal` capability. | The app principal, once, on behalf of the person under whose grant the event was delivered. | | A rule fired by a capability event that its contract says belongs to a person. | The app principal, once, on behalf of that person. In the core catalog a scheduler `wake` belongs to the person on whose behalf it was scheduled (`contracts.md` section 9). | | A rule fired by any other capability event. | The app principal, once in each active session, on behalf of that session's person; with no active session and a `background` grant held, once for the instance, on behalf of the owner. | | `becomes`, `source.with`, `source.when` and a part's `with`. | The app principal, on behalf of the person of the place where it is evaluated: the work that made the change, the person whose value is read, or the session whose environment changed. | | A derived value, a view title, prop or binding, a navigation section's `label`, `when`, `with` or `count`, a navigation group's heading or `when`. | The principal for whom the value is read (section 7). | Actions that a `run` step runs, and transitions that a `send` step causes, act as the principal of the steps that ran or sent them. **Where triggers are tested.** A `becomes` or `changes` trigger is tested where a change happens, by comparing its value before and after that change, with the values of that place. There are exactly three kinds of change: a write made by work that has an acting principal, the result of a source read, and a change of the environment of a session (the rows above). A scheduler wake or a capability event changes state only through a rule's steps or a source read, and so through one of these. - A change made in one place fires no rule in another. When one person's write makes a trigger true for another person as well, no rule fires on the other person's behalf: nobody's action makes the app act under another person's grants. - With no session, `session` and `device` entries hold their `initial` values and `env` is the host's own. - An event for a person who has no active session is delivered only when a `background` grant is held. - An effect that must happen once for a person, or once for the instance, carries `once` (section 8.3). **A principal with no person.** Where this section speaks of a principal's person and the principal has none (section 6.1), the principal itself stands in that place: `user`, `device` and `session` values and sourced values are kept for that principal, and the app principal acting for its work has `user.onBehalfOf` set to that principal and `user.person` `null`. A principal with no person holds no personal grant, so a call on a personal capability fails with `grant.denied`. For the app principal, `user.kind` is `app`, `user.id` is the `id` of the definition whose rule or flow is running (a part's own `id` inside a part), `user.name` is that definition's `meta.name`, `user.roles` is empty, and `user.onBehalfOf` and `user.person` are the person it acts for. Since a rule never acts as a person, anything that identifies the person who acted, such as who filed a record, is captured in the action they invoked or read from `user.person`. ## 7. State ```json "state": { "goal": { "type": "number", "initial": 5000, "description": "Savings target" }, "startDate": { "type": "date", "initial": "=env.today", "description": "Day saving started" }, "deposits": { "type": "finance:Transaction[]", "sensitive": true, "source": { "call": "bank.listTransactions", "with": { "since": "=state.startDate" }, "refresh": { "every": "PT1H" } } }, "saved": { "type": "number", "sensitive": false, "derive": "sum(default(state.deposits, []).map(d, d.amount))", "description": "Total saved, which may be shown without the transactions behind it" }, "remaining": { "type": "number", "derive": "state.goal - state.saved" } } ``` Each entry is exactly one of three kinds: - **Stored**: has `initial` or no kind key at all (starts as `null`). `initial` is a dynamic value with `env` in scope. It is evaluated once, when the instance is created, and the result is stored: every later load, and every value of the entry that starts later (a new person's `user` value, a new session's `session` value), starts from that same result, so a start date stays the day the app was installed. An entry that an update adds is evaluated at that update (section 6.4.1). Written by steps and by bindings; a `shared` entry only by actions (section 8.1). A write whose value does not conform to the entry's `type` fails with `state.invalidValue`. - **Derived**: has `derive` (*expression*). Recomputed when any value it reads changes. Read-only. Derived values MUST NOT form a cycle; this is a load-time error. A derived entry read during an action reflects that action's pending writes. Inside `derive`, `user` is the principal for whom the value is read: during an action, a rule, a flow transition or a `can` or `canSend` evaluation, the acting principal (section 6.4.4); on a visual or voice surface, the person using it; for an agent reading a resource, the agent. A derived entry that reads `user` therefore has one value per principal. To follow the person an agent or the app acts for, read `user.person`. `env.surface` and `env.invocation` are `null` in `derive`. A `derive` that fails, or whose value does not conform to `type`, yields `null` and a diagnostic (section 17). - **Sourced**: has `source`. The value is the output of a capability operation (section 7.1). Read-only. Common fields: | Field | Meaning | | --- | --- | | `type` | Type reference. Required. | | `description` | Recommended. | | `scope` | Stored entries only. Where the value lives: `session` (one value per session, gone when the session ends, section 6.4), `device` (one value per person on each device; another person using the same device does not see it), `user` (default; one value per person, following them across devices), `shared` (one value for the whole instance). | | `sensitive` | Whether the host keeps the value out of view (section 7.3). Default `false`, except for a derived entry that reads a sensitive entry. | | `internal` | Default `false`. When `true`, the entry is never an agent resource and never an export. Naming it in `resources.include` or `exports.state` is an error (`state.internal`). | | `conflict` | Stored entries with `user` or `shared` scope only. How concurrent or offline writes resolve: `lastWrite` (default), `merge` or `reject` (section 7.2). | | `key` | Stored entries with `conflict: "merge"` only. The field that identifies elements when a list value is merged. | **Ownership.** State belongs to the instance and the people who use it, never to the definition's author: a `user` value to its person, a `shared` value to the instance and so to its owner. The host stores it. A definition file carries no user data; `initial` is seed data and SHOULD be small. **Texts keep their language.** A text in the app's languages (section 12.6) that is written into state, sent, as in a notification, or recorded in the audit log is a plain string in the language of the moment it was made, and stays in that language when the shown language changes later. ### 7.1 Sources ```json "openTickets": { "type": "core:RecordPage", "source": { "call": "tickets.list", "with": { "filter": [ { "field": "team", "op": "eq", "value": "=state.teamId" } ], "limit": 500 }, "when": "state.teamId != null", "pages": 10, "refresh": { "every": "PT1H", "on": ["open", "change", "tickets.changed"] } } } ``` | Field | Meaning | | --- | --- | | `call` | `alias.operation` of an operation whose `effect` is `read` and that is not `interactive`. Required. | | `with` | Dynamic value: the operation input. | | `when` | *Expression*. Optional. The entry is read only while it is `true`; otherwise its status is `idle` and its value is kept. A `when` that becomes `true` causes a read. | | `pages` | Integer from 1 to 50, default 1. How many pages to read and join (below). A value above 1 needs an operation that declares `paging` (`contracts.md` section 4); otherwise it is an error (`state.sourceNotPaged`). | | `refresh` | `{ "every", "on" }`. Optional. `every` is an ISO 8601 duration. `on` lists occasions: `open`, `change` (when the value of `with` or `when` changes) and capability events written `alias.event`. `on` defaults to `["open", "change"]` whenever it is absent, also when `every` is given. | - A sourced entry has one value per person, read on that person's behalf (section 6.4.4). Each occasion reads these persons' values: - `open`: the value of the person whose session opens. - `change`: `with` and `when` are evaluated for each person, and a change for a person reads that person's value. - `refresh.every`: the value of each person who has an active session, once per interval for each; with no active session and a `background` grant held, the owner's value. - A capability event named in `on`: the values of the persons the event reaches (section 6.4.4). - A `refresh` step: the value of the acting principal's person. - The value is `null` until the first successful read, whatever `type` says. After that it is the output of the latest successful read. While loading, or after a failed read, the previous value is kept. - `type` MAY be narrower than the operation's output. An output that does not conform to `type` is a failed read with `state.invalidValue`. - At most one read per entry and person is in flight. A trigger that arrives during a read causes exactly one more read after it. - A read caused by what another read returned, because a `with` or `when` reads a sourced entry directly or through derived values or the writes of rules, is a level of a cascade as a rule is (section 9). A read that would be made more than 16 levels below the work that started the cascade is not made, and `rule.cascade` is recorded in the audit log against that work. So a sourced entry whose `with` reads its own value settles and does not read without end. - A read that would exceed the grant's `rate` is put off until the rate allows; it does not fail. - `refresh.every` runs while no surface is active only when the app holds a grant on a capability with the `background` trait, as an `every` rule does (section 9). - The host keeps the last value read, for the person it was read for, so after a restart the entry holds that value while it loads. A `becomes` trigger sees no edge for values restored at load (section 9). - With `pages` above 1, the host calls the operation, then, while the output's `next` field is present and not `null` and fewer than `pages` calls were made, calls it again with the same input and the `cursor` input set to that `next` value (the fields named by the operation's `paging`). The value is the output of the last call with its `items` field replaced by the items of every call, in order. Every call counts against `rate`. - `sources.` exposes, for every sourced entry, `{ "status", "error", "updatedAt", "partial" }`. `status` is `idle`, `loading`, `ready` or `error`. `error` is `{ "code", "message" }` of the latest read when it failed, and `null` otherwise. `updatedAt` is the datetime of the latest successful read, or `null`. `partial` is `true` when the latest read stopped with pages remaining. - A `refresh` step asks for a read at once (section 8.1). ### 7.2 Scopes, offline and conflicts - `session` and `device` values are always available, with or without a network. A `device` value belongs to one person on one device. - For `user` and `shared` values, a host that synchronizes them between devices or people keeps a local copy: reads see the last known value, and writes made offline are applied on reconnection under the entry's `conflict` policy. - `lastWrite`: the later write wins. `device` entries always resolve this way. - `merge` applies to the top level of the value. For a list with `key`, elements are matched by that field: an element added on either side is kept, one removed on either side is removed, and an element changed on both sides is taken whole from the later write. For an object, each top-level field is taken from the side that changed it, and a field changed on both sides from the later write. A list without `key`, and any other value, resolve as `lastWrite`. - `reject`: a write based on a value that has since changed fails with `state.conflict`. A write whose base still equals what storage holds is not a conflict. A write made offline that conflicts when it is applied is discarded, and the host records that in the audit log. ### 7.3 Sensitivity A value that is **sensitive** is kept out of view: - The host MUST redact it in audit records, together with any recorded input, output or error message computed from it (section 15). Redaction follows the value: a recorded value that was not computed from a sensitive value is recorded in full, even when the same invocation also read sensitive values. - The host MUST NOT expose it on an agent surface unless `resources.include` names the entry (section 12.1). - An explanation MUST NOT print a value written in the definition for the entry (section 15). **What is sensitive.** A stored or sourced entry is sensitive when it sets `sensitive: true`. A derived entry that reads a sensitive entry, directly, through other derived entries or through a part's exported state, is itself sensitive unless it sets `sensitive: false`, which is the author's statement that the computed value may be shown. A derived entry MAY also set `sensitive: true` on its own account. A value is **computed from a sensitive value** when the expression that produced it has among its references (`expressions.md`, section "Static analysis") a sensitive entry, a part's exported state that is sensitive in the part, or a local name, `input` field or `event` field whose value was itself so computed. The output of a `call` or `code` step is so computed when its input was. A derived entry with `sensitive: false`, and a stored entry without `sensitive: true`, are not sensitive values, whatever was written to them. A condition does not make a value sensitive: the result of `state.secret > 100 ? 'a' : 'b'` is not computed from `state.secret`. **Messages and outputs.** A message returned to an agent (a `require` message, a `done` message, a `fail` message, an error's message) that was computed from a sensitive value the agent cannot read as a resource is replaced by the host's own words. A tool's output is returned as computed: an action that returns a sensitive value makes it readable by every principal that may call the action. A sourced entry whose operation's scope has sensitivity `high` SHOULD state `sensitive` either way; validation warns when it does not (`state.sensitivityUnstated`). ## 8. Actions An action is a named, typed, described operation. Actions are the only entry points into the app's behavior: surfaces invoke them, rules and flows run them, parent definitions call them. ```json "actions": { "setGoal": { "description": "Change the savings target.", "input": { "amount": { "type": "number", "description": "New target amount" } }, "require": [ { "that": "input.amount > 0", "message": "The goal must be more than zero." } ], "steps": [ { "set": "state.goal", "to": "=input.amount" } ] }, "startOver": { "description": "Start saving again from today.", "confirm": { "message": "=`This sets aside the ${state.saved} saved so far.`" }, "steps": [ { "set": "state.startDate", "to": "=env.today" } ] } } ``` | Field | Meaning | | --- | --- | | `description` | Required. Written for both people and agents. | | `input` | Field map. Default empty. | | `output` | Type reference of the value produced by `return`. Optional. An action that ends without `return` produces `null`, and a value is checked against `output` only when a `return` ran. | | `allow` | *Expression* guard: who may run the action. It sees `input`, `state`, `user` and the other base roots. If present and not `true`, the invocation fails with `action.forbidden`. | | `require` | Array of `{ "that": expression, "message": dynamic value }`: what must hold for the action to be done now. Optional. Each `that` and `message` sees what `allow` sees. The first entry whose `that` is not `true` fails the invocation with `action.refused` and that entry's `message`. | | `confirm` | `true`, `false` (the default) or `{ "message": dynamic value }`. Whether a person must confirm before the action runs (below). | | `done` | `{ "message": dynamic value }`: what to say when the action has been done, to whoever invoked it from outside (below). Optional. | | `internal` | Default `false`. When `true`, the action is callable only from steps inside this definition, including the steps of its own visual handlers. It is never a tool, an intent or an export. | | `steps` | Array of steps. Required. | **Invoking an action.** An invocation passes these checks in order, and stops at the first that fails: 1. The action exists, is not `internal` (unless it is run from this definition's own steps), is exposed by the surface the call came through, and the caller holds access to it where access names it (section 6.1). Otherwise the invocation fails with `action.forbidden`, with the same message whatever the reason, so that a refusal does not tell whether the name exists. 2. The input is validated against `input` and defaults are applied. Missing required fields, unknown fields and values that do not conform fail with `action.invalidInput`. 3. `allow` is evaluated. If it is not `true`, the invocation fails with `action.forbidden`. The refusal MUST NOT carry the guard's text. 4. The `require` entries are evaluated in order. The first whose `that` is not `true` fails the invocation with `action.refused`, carrying that entry's `message`. A message that cannot be evaluated is replaced by the host's own words. `allow` answers who may act; `require` answers whether it can be done now, and its message is written to be shown to whoever asked. 5. When `confirm` is set, confirmation is obtained. A declined or unanswered confirmation fails the invocation with `action.declined`. 6. The steps run (section 8.2). A failing `allow` or `that` expression counts as not `true` (section 17). **Confirmation.** When `confirm` is `true` or an object, the host MUST obtain confirmation from a person before running the action when the caller is an agent, and SHOULD when the caller is a person. Confirmation is asked of the person of the calling principal (section 6.1); when it has none, the invocation fails with `action.declined`. The host shows the person the action, its input and who is asking. With `{ "message" }` it also shows the message, evaluated before asking with the roots `allow` sees, beside them and marked as the app's own words; a message that cannot be evaluated is replaced by the host's own words. An agent never confirms for itself, and a request that receives no answer is declined. For a person's own act the confirmation need not interrupt: asking at the control they activated is enough, provided they see the action and the message there and can open its input, where it has any, from the same place. The person chose the act, so the host need not repeat its values to them unasked; for work an agent does, the input is always shown with the question. When the answer arrives, checks 1 to 4 are evaluated again, so a confirmed invocation still fails if, meanwhile, its caller lost access or a `require` stopped holding. A pending answer never holds up other work on the app (section 8.2): the host asks before the work starts, or while the work is suspended. Confirmation cannot be bypassed. A `run` step that targets an action with `confirm` is an error (`action.confirmBypassed`) when it is in a rule's steps, in a flow's steps (a transition's `do`, a state's `enter` or `exit`), or in an action that does not itself have `confirm`. A `run` in a visual handler, and a voice intent's action, are the person's own invocation and are allowed. When a confirmed action runs another action with `confirm`, the person is not asked twice. **Saying it was done.** `done.message` is what the app says when the action has been done, so that whoever asked knows, also when the result is not where they look: a form that closed, a view that went back, a record sent elsewhere. Whoever invoked the action from outside hears it, and nobody else: a person through a visual handler's `run` (section 12.2) or a voice intent (section 12.3), and an agent through the agent surface (section 12.1). An action that another action's `run` step runs, or that a rule or a flow runs, says nothing, and its message is not evaluated; the steps of a parent definition, its visual handlers included, that run an action of a part get its output only (section 13). - The message is evaluated once, when the steps have ended without failure, and is said only once the work the invocation belongs to has completed and its writes are kept (section 8.2). It is never evaluated for an invocation that failed, was refused or was declined. - It sees what `allow` sees, with `state` as the steps left it, and `output`, the value the action produced (`null` when no `return` ran). Its evaluation changes nothing and calls nothing. - A message that cannot be evaluated, that is not text, or that is empty once cleaned is no message: the action has still succeeded, and the failure is reported as a failing expression is elsewhere (section 17). - The host cleans the message as it cleans a notification's title, to plain text on one line that is never markup or a link, and cuts it at 200 characters with an ellipsis. Validation warns about a literal message that is longer (`action.doneTooLong`). As with a `require` message, the message is the app's words for whoever asked: its author writes it for that reader, and puts nothing in it that the reader may not see. It is for a result that is not in front of the person already; a change the person sees where they look needs no message. ### 8.1 Steps A step is an object with exactly one **kind key** from the table below, plus that kind's other fields. By convention the kind key is written first. Steps run in order. | Step | Shape | Effect | | --- | --- | --- | | `set` | `{ "set": path, "to": value }` | Write a stored or view state value, or a field inside one. | | `append` | `{ "append": path, "value": value }` | Add an element to the end of a list. | | `remove` | `{ "remove": path, "where": expression }` | Remove the list elements for which `where` is true. | | `patch` | `{ "patch": path, "where": expression, "with": value }` | Shallow-merge `with` into each list element for which `where` is true. Without `where`, `path` is an object and `with` is merged into it. | | `let` | `{ "let": name, "to": value }` | Bind a local name to a value for the steps that follow. | | `call` | `{ "call": "alias.operation", "with": value, "as": name, "once": value, "orElse": value }` | Invoke a capability operation. The output is bound to `name` for later steps. `once` makes the effect happen at most once (section 8.3). | | `run` | `{ "run": "actionName", "with": value, "as": name, "orElse": value }` | Run another action in this definition, or `partName.actionName` for an exported action of a part. Its output is bound to `name`. | | `code` | `{ "code": "moduleName", "with": value, "as": name, "orElse": value }` | Run a sandboxed code module. Its output is bound to `name`. | | `refresh` | `{ "refresh": "state." }` | Ask for a sourced entry to be read again (section 7.1), without waiting for the result. Naming an entry that is not sourced is an error (`state.notSourced`). | | `send` | `{ "send": "eventName", "to": "flowName", "key": value, "with": value }` | Send an event to a flow instance. `key` is required for collection flows. | | `emit` | `{ "emit": "eventName", "with": value }` | Raise an app event that rules can trigger on and parent definitions and agents can observe. | | `if` | `{ "if": expression, "then": [steps], "else": [steps] }` | Branch. `else` is optional. A failing condition counts as `false`. | | `each` | `{ "each": expression, "as": name, "indexAs": name, "do": [steps] }` | Run steps once per element of a finite list. Without `as` the element is `item`, which hides any outer `item` for the body. The position is bound to `indexAs` when given, and otherwise to `index`, which hides any outer `index`. A value that is not a list fails the step with `expression.error`. | | `return` | `{ "return": value }` | End the action with an output. | | `fail` | `{ "fail": "code", "message": value }` | End the action with an error. `code` has the form `area.problem`; an app MAY use its own codes as well as those of section 17. | `return` and `fail` end the action whose steps contain them from any depth of `if`, `each` and `onError`. An action that a `run` step ran ends on its own `return` or `fail`; a `fail` there fails the `run` step. **Write targets.** The path of `set`, `append`, `remove` and `patch` MUST start with `state.` followed by the name of a stored entry. In a view's handlers it MAY instead start with `view.` followed by the name of one of that view's state entries (section 12.2). In the steps of a collection flow (a transition's `do` and a state's `enter` and `exit`) it MAY be `item`, which writes through to the element (section 10). Any other target is an error (`write.invalidTarget`). A binding, and a step written directly in a visual handler, MUST NOT target a `shared` stored entry (`write.sharedDirect`): shared state changes only through actions, run from the handler with `run`, so every change passes an `allow` and an agent can make it on the same terms. Entries of other scopes may be written directly, as the person using the surface. Which other steps a visual handler may hold is set out in section 12.2 (`view.handlerStep`). Writing to a derived or sourced entry is a load-time error (`state.readonly`). A part's step that writes an input its parent drives fails with `state.readonly` (section 13), and a step that writes the state field of a collection flow fails with `flow.fieldWrite` (section 10). A path MAY select list elements with selectors (section 3.2); a write through a selector that matches no element fails with `state.noElement`. `set` on a nested path creates missing intermediate objects, and fails with `state.invalidValue` if an intermediate value exists and is not an object. **Elements in `remove` and `patch`.** In `where`, `item` and `index` are the element under test. In the `with` of a `patch` that has `where`, they are the element being patched, so `{ "patch": "state.players", "where": "item.id == input.id", "with": { "score": "=item.score + 1" } }` adds one to a score. Both hide any outer `item` and `index`; name an outer element with `as` and its position with `indexAs` to keep them visible. A `where` that fails counts as `false`. **Failures.** `call`, `run` and `code` steps MAY carry `onError`, an array of steps that runs when the step fails, with `error` (`{ "code", "message" }`) in scope, and `orElse`, a dynamic value for the step's `as` name when it fails. A step with either handles its own failure: the `onError` steps run first, and when they finish normally the failure counts as handled; the `as` name is then bound to `orElse`, evaluated after the `onError` steps with `error` in scope, or to `null` without it; and the action continues with the next step. An empty `onError` handles a failure and does nothing else. A failure inside the `onError` steps fails the action. Without `onError` or `orElse`, a failed step fails the action. When a `run` step fails, the writes made by the action it ran are discarded; writes made before it by the calling steps are kept, and the calling action continues if the failure is handled. ### 8.2 Execution semantics - **Scope.** Expressions in an action's steps see `state`, `sources`, `input`, `env`, `user`, `flows`, `parts`, `capabilities`, `grants` and local names (section 3.4). The steps of a rule, a flow or a visual handler see `event` in place of `input`. An action run from such steps receives only what the `run` step's `with` passes. - **Principal.** The principal an action, rule or transition acts as is set out in section 6.4.4. - **Order.** Work on an instance is serial: an invocation, a visual handler, a binding's write, a timer firing or a capability event, with the rules it triggers, runs to its end before the next piece of work starts, in the order they arrived. The one exception is a wait on a person (next item). - **Waiting on a person.** Work MUST NOT hold the instance while it waits on a person. A wait on a person is a call of an `interactive` operation (`contracts.md` section 4), a confirmation (section 8), or a request asked at the moment of a call (section 6, "When a request is asked"). Work waits on a person only while it has changed nothing: it has written no state, sent no flow event, raised no app event and called no operation whose `effect` is not `read`; validation places the steps that wait by their nature accordingly (`action.waitsOnPerson`). At such a wait the work is suspended: its turn ends with nothing to commit, and other work on the instance goes on. When the person has answered, the work continues where it stopped, in a turn of its own; it is not run again. On continuing, the `allow` and `require` of every action the work is inside are evaluated again against the state as it is then, and a failure ends the work as that check does at the start: nothing is written and the person's answer is dropped. Names bound before the wait keep their values, `env.now` is the time of continuing, and state read from then on is the state then. The rules the continued work triggers run as for any work. If the instance stops, or the person's session ends, while the work is suspended, the work ends and nothing is written. Work that reaches a wait on a person after it changed something, and the steps of a rule or a flow, which have nobody to ask, do not wait: a call of an `interactive` operation fails with `capability.unavailable`, and a confirmation with `action.declined`. A request asked at a call made after the work changed something MAY hold the instance, but no longer than the host's limit for a call that waits on no person; unanswered by then, the call fails with `grant.denied`, the question stays open, and its answer serves the next try. - **Transaction.** State writes made by an action are applied atomically when the outermost action completes. Steps see their own pending writes, and a derived entry read during the action reflects them; a `send` to a collection flow finds an element appended earlier in the same action. If the action fails, its writes are discarded. Outside effects (capability calls) that already happened are not undone; they are recorded in the audit log, and `once` (section 8.3) keeps a retry from repeating them. - **Only the definition runs.** A host MUST execute only steps, bindings and expressions that are part of the loaded definition. A surface names a handler or a binding by its location in the definition and supplies data for its scope; it never supplies steps. - **Events.** An app event raised by `emit`, an `action:` event and a `flow:` event are delivered only if the transaction that raised them commits. An event is observed where it is raised: by rules at that place (section 6.4.4), and by the surfaces of the person on whose behalf the work ran, that person's agents included. Work that ran on behalf of no person is observed by the surfaces of the principal that did it. Other people learn what changed through the state they can read. `action:` is raised each time the action succeeds, including when another action ran it, with payload `{ "input", "output" }`. - **Termination.** There are no unbounded loops. `each` iterates a finite list. `run` MUST NOT recurse: the static call graph of actions MUST be acyclic, which is a load-time check. - **Effectful functions.** `random()` and `uuid()` are available only in step expressions, never in `derive`, guards or view bindings. Time comes from `env.now`, which is fixed for the duration of an action, and of each turn of work that continued after a wait on a person. ### 8.3 Effects that happen once A `call` step MAY carry `once`: a dynamic value giving a string of 1 to 200 code points that names the effect, such as `` "=`report:${item.id}`" ``. Within an instance, a call takes effect at most once per **effect record**. A record is identified by the definition whose steps made the call (the root definition or a part instance), the capability alias, the operation, the `once` key and, for a personal capability, the person on whose behalf the call is made. The record also holds a digest of the operation input after defaults. - When a call succeeded under the same identity with an equal input, the host does not call the provider again, and the step produces the recorded output. The repeated call still needs a grant that covers it, does not count against `rate`, and is recorded in the audit log as repeated. - When a call succeeded under the same identity with a different input, the step fails with `capability.onceMismatch`, and the provider is not called. - A call made while another with the same identity is in progress waits for that call's outcome, and then follows these rules. - A call that failed is not recorded and may be tried again. - The host keeps the record outside the action's transaction, as it keeps the audit log, so a call that succeeded stays recorded when the action that made it fails. It keeps each record for at least 30 days. - The host also passes the key to the provider, so the provider can refuse a duplicate the host could not know about (`contracts.md` section 4). - `once` is allowed only on operations whose `effect` is `write` or `external` (`call.onceEffect`). A `once` value that is not a string of 1 to 200 code points fails the step with `capability.failed`, and the operation is not called. `once` is what makes a failed action safe to run again: an action that files a report and then fails on a later step can be retried, and the report is filed once. The key names the thing the effect is about; a key made with `uuid()` differs on every attempt and protects nothing. A key names the effect for the whole instance, so an effect that should happen once for each person includes `user.person.id` in its key. ### 8.4 Asking in advance Two functions let a view or a rule ask whether something would be allowed, so that guards are not repeated: - `can(actionName, input?)` is `true` when `input` (default `{}`) is valid input for the action, its `allow` holds and every `require` entry holds, for the principal acting where the expression is evaluated. - `canSend(flowName, event, key?)` is `true` when the flow instance exists (for a collection flow, the element with that `key`), its current state has a transition for `event` that would be taken, and that transition's `allow` holds. While the transitions' `if` and `allow` are evaluated for this purpose, the root `event` is `null`. Both are usable wherever `user` is in scope, except in `derive` and in the guards they evaluate: an action's `allow` and a `require` entry's `that`, and a flow transition's `if` and `allow`, where they would recurse. `actionName` names an action as a `run` step does (`action.unknown`); `flowName` names a declared flow (`flow.unknown`) and `event` an event it handles (`flow.unknownEvent`); all three MUST be string literals. `key` is given exactly when the flow is a collection flow (`flow.keyMismatch`). Neither function runs steps, asks for confirmation or is recorded in the audit log, and `can` does not consider grants or the caller's access to the action. `expressions.md`, section "Questions about the app", defines them exactly. ## 9. Rules ```json "rules": { "celebrateGoal": { "description": "When savings reach the goal, send a congratulation.", "when": { "becomes": "state.goal > 0 && state.saved >= state.goal" }, "do": [ { "call": "notify.send", "once": "=`goal:${user.person.id}:${state.goal}`", "with": { "title": "Goal reached", "body": "=`You saved ${formatNumber(state.saved, { style: 'currency' })}`" } } ] } } ``` `when` holds exactly one trigger: | Trigger | Fires | | --- | --- | | `{ "becomes": expression }` | When the expression changes from not-true to `true` (edge-triggered). It does not fire when a session opens while the expression is already true, unless `"initial": true` is set beside it: it then fires when a session opens while the expression is true, in that session. Values restored at load make no edge (section 7.1). Where the trigger is tested is set out in section 6.4.4. | | `{ "changes": path }` | When the value at a state path changes. `event` is `{ "previous", "current" }`. | | `{ "event": name }` | On an app event raised by `emit`, a capability event `alias.event`, an action completion `action:name`, a flow transition `flow:name`, or a part's exported event `part.name`. `event` is the payload. | | `{ "every": duration, "foreground": boolean }` | Repeatedly at an ISO 8601 interval while the app is active, first one interval after the trigger starts running. `foreground` is optional (below). | | `{ "lifecycle": "install" \| "open" \| "close" }` | `install` at the first load of an instance; `open` when a session's first surface opens; `close` when its last surface closes. | `if` is an optional *expression* guard. A failing `if` counts as `false`. `do` is an array of steps, run as an anonymous internal action with the same semantics as section 8.2. A condition that must hold for an edge to mean anything belongs inside `becomes`, because `if` is tested only when the edge happens. If a goal starts at 0, `state.saved >= state.goal` is true from the start, and raising the goal to an amount below what is saved never makes it become true, so a rule with that trigger and `"if": "state.goal > 0"` never fires. With `state.goal > 0 && state.saved >= state.goal` in `becomes`, as in the example, the edge happens when the goal is set. An app that waits for a condition of the environment, such as `env.online`, and may already find it true when a session opens, sets `"initial": true`. Rules always act as the app principal, on behalf of a person, or of the principal that caused the work when it has no person (section 6.4.4): inside a rule `user.kind` is `app`, `user.roles` is empty, and `user.onBehalfOf` is that person or principal. A rule runs after the transaction that triggered it commits, in its own transaction. Where a trigger is tested, and so where and how often a rule fires, is set out in section 6.4.4: a change made in one place fires no rule in another, and other sessions receive the resulting state. - A rule with an `every` trigger runs only while a surface is active (a person has it open, section 6.4), unless the app holds a grant on a capability whose contract declares the `background` trait. Unattended execution is an outside effect and is permissioned like one. Validation warns about an `every` trigger with no such grant request (`trigger.noBackground`) unless it says `"foreground": true`, the author's statement that it is meant to run only while a surface is active. The statement binds: a rule that says so runs only while a surface is active, whatever grant the app holds, so an app that holds a `background` grant for one purpose does not run its other rules unattended. - A schedule (`every`, `refresh.every`) that fell due more than once while the app was not running, across a jump of the clock, or while other work on the instance ran (section 8.2), fires once when it can, not once per missed interval. The audit record of that firing says how many times it fell due. - Hosts MUST bound rule cascades (a rule's writes triggering further rules). The limit is 16 levels, counting only rules whose `if` held: a rule that would run more than 16 levels below the work that started the cascade does not run, and `rule.cascade` is recorded in the audit log against that work. - A capability event that follows from a call made in a cascade, as a store's event that a record changed follows the write that changed it, is a level of that cascade as a rule is: the rules it fires and the reads it causes count from the level of the call, also in another instance that receives the event. So a rule that writes to a capability whose events fire it settles and does not run without end. A scheduler `wake` whose time lay after the call that scheduled it starts new work, because time caused it; a wake that was already due when it was scheduled is a level of the cascade that scheduled it. - Hosts MAY enforce a minimum interval for `every`, and MAY hold a flow's `after` (section 10) to the same minimum: a transition whose duration is shorter is taken when the minimum has passed. A host that renders a visual surface SHOULD support intervals down to 16 ms. ## 10. Flows A flow is a finite state machine. Use one when a process has named stages and only certain moves between them are legal. ```json "flows": { "approval": { "description": "Purchase requests move from draft through manager and finance review.", "over": { "collection": "state.requests", "key": "id", "field": "status" }, "initial": "draft", "states": { "draft": { "on": { "submit": [ { "to": "managerReview", "if": "item.amount > 500", "allow": "user.person.id == item.requesterId" }, { "to": "approved", "allow": "user.person.id == item.requesterId" } ] } }, "managerReview": { "description": "Waiting for the requester's manager.", "on": { "approve": { "to": "financeReview", "allow": "user.id == item.managerId" }, "reject": { "to": "rejected", "allow": "user.id == item.managerId", "do": [ { "patch": "item", "with": { "rejectedBy": "=user.id" } } ] } }, "after": { "P3D": { "to": "escalated" } } }, "financeReview": { "on": { "approve": { "to": "approved", "allow": "'finance' in user.roles" }, "reject": { "to": "rejected", "allow": "'finance' in user.roles" } } }, "escalated": { "on": { "approve": { "to": "financeReview", "allow": "'director' in user.roles" } } }, "approved": { "final": true }, "rejected": { "final": true } } } } ``` `state.requests` is a `shared` list, so the whole team works on the same requests. Each request stores `requesterId` and `managerId` when it is filed. Only the requester, or an agent acting for them, may submit it. The filing action reads `managerId` from the directory (`directory.manager`), never from its own input, so a requester cannot name themselves; only that manager can approve the request at the first stage, and an agent acting for the manager is not the manager. No action changes `amount`, `managerId` or `requesterId` after filing, since the guards rely on them. `finance` and `director` are roles (section 6.2). - Without `over`, the flow is a **singleton**: one instance per app instance, current state readable as `flows..state`. Its bookkeeping (the current state and when the instance entered it) lives with the app instance. - With `over`, there is one instance **per element** of a stored list. `collection` is a *path* to that list, `key` names the element's identity field and `field` names the element field that holds the current flow state; all three are required. The flow's bookkeeping lives with the collection, in that entry's scope. In transitions and in `enter` and `exit` steps, `item` is the element and `index` its position, and steps may write to it (`{ "patch": "item", "with": {...} }`). - **The state field belongs to the flow.** Only the flow writes `field`. Any step that writes it, through the collection's path or through `item`, fails with `flow.fieldWrite`: a load-time error where validation can see it, and otherwise a failure of the step at run time. At run time, when a step or binding writes the collection or any path inside it, the host compares each element, by key, before and after the write. The write fails with `flow.fieldWrite` if an existing element's field changed, if an added element's field is neither absent nor `initial`, or if an existing element's key changed. An element added again after it was removed starts at `initial`. An appended element MAY omit the field or give the flow's `initial`. The host writes `initial` into an element appended without it, as it is appended, so reads always see a state. No `enter` steps run for the initial state of a new element. - `states..on.` is a transition or an ordered array of transitions; the first whose `if` is true (or absent) is taken. A transition has `to` (required), `if` (*expression*), `allow` (*expression* guard) and `do` (steps). A false or failing `if` moves on to the next candidate. When the transition taken has an `allow` that is not true, the event fails with `flow.forbidden`, nothing moves, and the refusal MUST NOT carry the guard's text. - A transition taken because of a `send` acts as the principal whose steps sent the event, and `user` in its `allow` is that principal (section 6.4.4). `event` is the `with` of the `send`. - `enter` and `exit` are optional step arrays on a state. Order on a transition: source `exit`, transition `do`, state change, target `enter`. All run in one transaction. `to` MAY name the state the transition leaves; that state's `exit` and `enter` steps then run, and its `after` timers start again. - `after` maps an ISO 8601 duration to a transition taken if the instance stays in the state that long. The transition is taken once per flow instance, however many sessions have the app open; its `event` is `null`. On whose behalf it acts, and when its timers run, depends on whether the collection is `shared` (section 6.4.4); a timer that must fire while no surface is active needs a `background` grant. - An event sent to an element that does not exist, or to an instance whose current state has no transition for it (or none whose `if` holds), fails with `flow.noTransition`. - `final: true` marks a state with no outgoing transitions. - Every transition raises the app event `flow:` with `{ "from", "to", "event", "key" }`: `event` is the event's name, or `null` for an `after` transition, and `key` is the element's key, or `null` for a singleton flow. - `canSend` (section 8.4) tells a view whether an event would be accepted. ## 11. Code Code is the last resort, for logic that expressions, steps, rules and flows cannot express. ```json "code": { "scoreWord": { "description": "Scores a word by letter rarity and length.", "runtime": "js", "input": { "word": { "type": "string" } }, "output": "integer", "source": "export default function ({ word }) { return word.length * 2; }", "limits": { "timeMs": 50, "memoryMb": 16 } } } ``` - A module is a **pure function** from input to output. It has no ambient authority: no network, storage, clock, randomness, timers or host objects. Anything it needs is passed in `input`. It cannot call capabilities. - `runtime` is `js` (an ECMAScript module whose default export is the function) or `wasm` (reserved in 0.2). - `source` holds the module text inline. `module` MAY be used instead: `{ "uri", "digest" }`, where `digest` is the digest of the module's bytes (section 16). - Hosts MUST run code in an isolated sandbox, MUST enforce `limits` (defaults: 100 ms, 32 MB), and MUST require a grant naming the module and issued for its text (section 6, rule 2). Since the module can reach nothing, its request is contained: the host issues that grant without asking anyone, unless it chooses to ask (section 6, "When a request is asked"). Hosts MAY decline to support code at all; a definition that uses code on such a host fails resolution for the steps that need it (section 14). - Input and output are validated against their declared types and copied by value across the sandbox boundary as plain JSON data. A result that holds anything else (a function, `undefined`, a class instance, a non-finite number, a cycle) fails with `code.failed`. - `limits` cover everything the module does: evaluating it, the call, any promise it returns and copying the result. A returned promise is awaited; one that cannot settle fails with `code.failed`. A host MAY cap the limits a module asks for. - A module has no time zone: dates behave as UTC. ## 12. Surfaces A surface is a projection of the kernel. Surfaces hold no logic of their own: event handlers on a visual node hold only the steps section 12.2 allows, which run as in an action body, and SHOULD be a single `run` step in anything but trivial cases. A surface exists only if its key is present. `"agent": {}` is a complete agent surface. ### 12.1 Agent surface ```json "surfaces": { "agent": { "instructions": "Use setGoal before logging deposits. Amounts are in the user's currency.", "tools": { "include": ["setGoal", "logDeposit"], "describe": { "setGoal": "Set the savings target in whole currency units." } }, "resources": { "include": ["goal", "saved", "remaining"] }, "events": { "include": ["goalReached"] } } } ``` - **Tools.** Every non-`internal` action is a tool: its name, `description`, `input` and `output` are the tool's schema. `tools.include` or `tools.exclude` narrows the set; a surface gives one or the other, not both. `include` MAY name a part's exported action as `part.action`. `describe` overrides a description for agent readers. - **Resources.** Every state entry that is neither sensitive (section 7.3) nor `internal` is a readable resource with its type and description. `resources.include` or `resources.exclude` narrows the set in the same way. `include` is the only way to expose a sensitive entry, MAY name a part's exported state entry as `part.name`, and MUST NOT name an internal entry. View state is never a resource. A derived entry that reads `user` is read for the agent (section 7). - **Events.** An app event that is listed is observable by an agent (as a notification or a subscription, depending on the adapter) when it was raised by work that ran on behalf of the agent's person, the agent's own work included (section 8.2), while the agent holds access to the app. `events.include` MAY name a part's exported event as `part.name`. An agent learns an event's name and time. Access grants in 0.2 do not name events, so a host SHOULD withhold event payloads from agents; an agent reads what changed through the resources it has access to. - **Files.** A file reference in a tool's input follows section 5: it MUST be one the host issued to that agent for this instance. - **Discovery.** A host MUST be able to produce, for any loaded app, a machine-readable **manifest**: the app's `id`, `version`, `meta`, instructions, tools with input and output schemas, resources with types, events, and the grants the app holds. This is how agents discover what an app can do. Adapters map the manifest onto concrete protocols (for example MCP tools and resources). An app that declares no `agent` surface exposes no tools, resources or events to agents; its manifest still carries its identity, `meta` and grants. - An agent invoking a tool is subject to the action's `allow`, `require` and `confirm`, and to the agent's own access to that action (section 6.1). A refusal for `require` carries the entry's message, which is how an agent learns why it cannot act. - **Results.** A tool call that succeeds returns the action's output and, when the action has a `done` message (section 8), the message beside the output, where the agent reads it. An adapter carries the message without changing the output, so an output that conforms to the tool's output schema still does. - **Least privilege.** A host SHOULD show an agent only the tools and resources its access covers. A refusal MUST NOT tell an agent whether a name exists: an unknown name, an `internal` action, a name the surface does not expose and a name the agent's access does not cover are refused alike, with `action.forbidden` (section 8). Change notices reach an agent only for resources it may read. ### 12.2 Visual surface ```json "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "Trip Savings", "state": { "draftGoal": { "type": "number?", "initial": "=state.goal", "description": "The goal being typed" } }, "body": { "control": "core:stack", "children": [ { "control": "core:progress", "props": { "value": "=state.saved", "max": "=state.goal", "label": "Saved so far" } }, { "control": "core:numberInput", "props": { "label": "New goal" }, "bind": { "value": "view.draftGoal" } }, { "control": "core:button", "props": { "label": "Update goal", "disabled": "=!can('setGoal', { amount: default(view.draftGoal, 0) })" }, "on": { "press": { "run": "setGoal", "with": { "amount": "=view.draftGoal" } } } }, { "control": "core:list", "props": { "items": "=default(state.deposits, [])", "itemKey": "id" }, "slots": { "item": { "control": "core:text", "props": { "value": "=default(item.memo, '')" } } } }, { "control": "core:badge", "each": { "in": "state.milestones", "as": "m", "key": "m.id" }, "props": { "label": "=m.name" } } ] } } } } } ``` A **view** has these fields. `start` names the first view; when the app lists main sections (below), `start` is normally the first of them. | Field | Meaning | | --- | --- | | `title` | Dynamic value. Optional. | | `input` | Field map of values passed on navigation, read as `view.`. Optional. | | `state` | View state: entries of `{ "type", "initial", "description" }` (below). Optional. | | `body` | The node drawn. Required. | **Main navigation.** `navigation`, beside `start` and `views`, lists the app's main sections in order, so that a host can draw them as the app's own navigation and does not have to guess which views are sections. Sections can come from the app's data, as the channels of a chat app, the folders of a mail app or the projects of a planner do: ```json "navigation": [ { "view": "activity", "label": "Activity", "icon": "notification" }, { "group": "Channels", "sections": [ { "each": { "in": "state.channels", "as": "c", "key": "c.id" }, "view": "channel", "with": { "id": "=c.id" }, "label": "=c.name", "count": "=state.messages.count(m, m.channelId == c.id && !m.read)" }, { "view": "newChannel", "label": "New channel", "icon": "add" } ] } ] ``` The list holds 1 to 12 entries. Each entry is a **section**, a **repeated section** (a section with `each`) or a **group**. A section has these fields: | Field | Meaning | | --- | --- | | `view` | A declared view. Required. | | `label` | Dynamic value giving the section's name. Required. | | `icon` | A name of the core catalog's icon vocabulary, as `meta.icon` takes. A host that does not know the name shows no symbol. Optional. | | `when` | *Expression*. The section is offered only while it is `true`. Optional. | | `with` | Dynamic value: the input the section opens its view with, as the `with` of a `navigate` step. It MUST give every required input of the view and MUST fit the view's input as a `navigate` step's `with` does. Without it the view is opened with no input, so its view MUST then take no required input. Optional. | | `count` | Dynamic value giving a whole number not below zero, or `null`: how many things wait in the section, such as unread messages or open tasks. Optional. | | `each` | `{ "in": expression, "as": name, "indexAs": name, "key": expression }`, with the shape and meaning of a node's `each`: the section is offered once for each element of the list, in order, with its other fields evaluated with the element in scope. `as` defaults to `item`; the position is `index`, or the name given by `indexAs`; `key` gives elements a stable identity. Optional. | A **group** is `{ "group": value, "when": expression, "sections": [...] }`: `group` is a dynamic value giving the heading drawn above the group's sections; `when`, optional, offers the group only while it is `true`; `sections` holds 1 to 12 sections or repeated sections. A group holds no group. A section's `label`, `when`, `count` and `with` are evaluated with the base roots and, in a repeated section, the names its `each` binds, for the principal the views are read for, and follow state as a view's title does; a group's `group` and `when` see the base roots only. None of them reads `view`. A `label` that cannot be evaluated is replaced by the view's name; a `when` that cannot be evaluated counts as not `true`; a `count` that cannot be evaluated, or is not a whole number not below zero, counts as `null`; a section whose `with` cannot be evaluated, or does not fit the view's input, is not offered, since it could not be opened; and an `each` whose list cannot be evaluated, or is not a list, offers nothing. A group's heading that cannot be evaluated is replaced by no text. Two sections that have neither `each` nor `with` MUST NOT name the same view; otherwise a view MAY be named by several sections, such as one for each channel. A host shows the sections that are offered as the app's navigation, in the app's design and in whatever form suits the window (a sidebar, a bar, a menu), with a group's heading above the group's sections and a count above zero beside its section's label, as part of the section's accessible name. A group whose `when` holds is offered with its heading even when none of its sections is offered, as an empty "Channels" group is while the app has no channel; a host MAY leave out the heading of a group that offers no section. The host marks the offered section whose view is at the bottom of the navigation stack with an input equal to the section's `with`, inputs compared as a `navigate` step compares them and a section without `with` standing for an input of nothing; when several are equal, the first is marked. Choosing a section replaces the navigation stack with its view, opened with its `with`; when that view with that input is already at the bottom of the stack, choosing it returns to it and closes the views above, as a `navigate` to an open view does. A host tells the sections it offers apart by keys of its own, and a section's key stays the same while its element keeps its `each` key, so that a list that changes while the person chooses never opens another section than the one they meant: choosing a section that is no longer offered changes nothing. A `navigate` step or a link to the view of an offered section, with the input that section opens with, chooses that section, as the paragraph on the `navigate` step below describes. `when` decides what is offered, never what is allowed: a section that is not offered can still be opened by a `navigate` step, which then shows it on top of the current view, and what a person may do is decided by each action's `allow`. The navigation offers at most 200 sections, counted in order; what a repeated section would offer beyond that is left out, and the host knows how many elements each repeated section left out, so that it can say that there are more. A host resolves the whole navigation within one bounded cost, as it resolves views; once that cost is spent, the sections already resolved are offered and the elements not yet looked at are left out and counted as such. Without `navigation` the app has no main navigation and a host shows none. **An app of one view.** An app whose visual surface declares exactly one view and no `navigation` is one tool for one purpose, such as a whiteboard, a small dashboard or a calculator. The definition alone decides this form, so every host draws the same apps this way: a host that draws views as pages SHOULD draw such an app as one card and nothing above it, headed by the view's `title`, or by `meta.name` when the view has none, as the page's only heading. When the view's `body` is one control that draws a box with a head of its own (a canvas, chart, table, list or diagram with a label, or a group with a title), that box is the card, its head shows the title, and the control's own label or title stays its accessible name. What the host shows of its own, such as the app's name and a way to its information about the app, it places outside the card. Every other app is drawn as pages in the host's frame. A view the app opens on top of its one view still has its way back. **View state.** A view's `state` entries hold values that belong to one visit of the view, such as a form being filled in. `type` is required; `initial` is a dynamic value evaluated when the view opens, with `view` inputs, `state`, `user` and `env` in scope, and without it the entry starts as `null`. Entries are read as `view.` beside the view's inputs, whose names they MUST NOT share (`name.collision`). They are written by `bind` and by `set`, `append`, `remove` and `patch` steps in that view's handlers (path `view.`); a write that does not conform to `type` fails with `state.invalidValue`. A view pushed on the navigation stack opens with fresh view state; returning to a view still on the stack finds its view state as it was left; view state is gone when its view leaves the stack. Actions never see `view`: a handler passes what an action needs in `with`. View state is never a resource. A **node** is one of: - A control node: `{ "control": "alias:name", ... }`. - A part node: `{ "part": "partName", "view": "viewName" }`, which embeds an exported view of a part. It MAY also carry `id` and `when`, and nothing else. In the resolved view, the node that stands for the embedded view carries the part node's `id` when it has one, so edits and tests can address it, and the ids of the nodes inside the embedded view are qualified by the part's name and a dot (`savings.total`, and `outer.inner.total` for a part within a part), so they never clash with the ids of the including view. A `navigate` step in an embedded part view's handlers does nothing, and the host reports it as a diagnostic. Control node fields: | Field | Meaning | | --- | --- | | `control` | `alias:name` of a control contract. Required. | | `id` | Optional name, unique within the view. Gives the node a stable address for edits and tests. | | `props` | Object of prop name to dynamic value, matching the contract's props. | | `bind` | Object of bindable prop name or output name to a *path* into a stored state entry that is not `shared` (section 8.1), or into a view state entry. The path MAY select a list element (section 3.2), which is how a row of a repeated list binds to its own element. For a bindable prop the binding is two-way: the control shows the value and writes user input back. For an output the control only writes. A bound prop counts as supplied when the contract marks it required. A binding whose selector matches no element shows an empty, disabled control. | | `on` | Object of event name to a step or an array of steps. `event` holds the control event's payload. | | `children` | Array of nodes, for controls whose contract accepts children. | | `slots` | Object of slot name to a node, for controls with named template regions. The variables a slot's template can read are declared by the contract, not by the node. | | `when` | *Expression*. The node exists only while it is `true`. | | `each` | `{ "in": expression, "as": name, "indexAs": name, "key": expression }`. Repeats the node itself once per element. `as` defaults to `item`; the position is `index`, or the name given by `indexAs`. The names are visible to the node, the nodes inside it and their handlers. `key` is optional and gives elements a stable identity across updates. To feed a list-like control, pass the list as a prop instead. | | `fallback` | A node used instead if the host cannot provide the control (section 14). A fallback is a complete node of its own: it takes nothing from the node it replaces except its place, so it carries its own `props`, `bind` and `on`. The outer node's `when` and `each` apply to whichever is drawn. | **Handlers.** A visual event handler holds only steps that stay with the person and the view: `set`, `append`, `remove` and `patch` (never on `shared` state, section 8.1), `let`, `if`, `each`, `navigate`, `refresh` and `run`. A `call`, `code`, `send`, `emit` or `return` step in a handler, at any depth (also inside its `if`, `each` and `onError` steps), is an error (`view.handlerStep`). Every outside effect, flow event and app event therefore starts in an action, passes an `allow`, and can be done by an agent on the same terms. Within that limit a handler's steps run like an action's body (section 8.2), as the person using the surface. When a step fails and the failure is not handled, the handler ends: later steps, including a `navigate`, do not run, and its writes are discarded. When a handler fails and has no `onError` for the failure, the host SHOULD show the error's message to the person at the control that raised the event; for a form's `submit`, in the form. **Saying what was done.** A `run` step of a visual handler is the person's own invocation. When the handler has ended without failure, the host SHOULD show the person the `done` message (section 8) of an action such a step ran, for a moment, in its own interface outside the view, so that the message is still seen when the handler went on to `navigate`. It is set as the app's words and never as the host's. When several actions a handler ran have a message, the last one is shown. The message is announced to assistive technology without taking the focus, and the person can dismiss it. Navigation is a built-in step available only in visual handlers, including steps nested inside them: `{ "navigate": "viewName", "with": value }` and `{ "navigate": "back" }`. `with` supplies the view's input. Inputs are compared after the view's input is checked and its defaults are filled in, and a section without `with` stands for an input of nothing. A `navigate` to a view that the main navigation offers as a section at that moment, with an input equal to the one that section opens with, chooses that section: the navigation stack is replaced with that view, and when that view with that input is already at the bottom of the stack, navigation returns to it and closes the views above, keeping its view state, exactly as when the person chooses the section. Any other `navigate` to a named view pushes it on the navigation stack, except that when the stack already holds that view with equal input, navigation returns to it and closes the views above it. The same holds for a link that opens a view and for a host that opens a view for the person, as for a notification they opened; an app without `navigation` has no sections, so its views are always pushed or returned to. `navigate: "back"` closes the current view; followed by a named `navigate` in the same handler, it replaces the current view, or chooses the section when the named view and its input are one. No view may be named `back`. A host MAY show more than one view of the stack at a time, such as a list with the record opened from it beside it. A `navigate` step, `back` included, of a handler that runs in a view below the top first closes the views above that view, so that opening another record from the list replaces the one that was open. A handler that does not navigate closes nothing, whichever view it runs in. Props that a contract marks `remote` are subject to the egress rule in section 6.3. Behaviour that controls share, such as how `when`, `hidden` and `disabled` differ, is in `contracts.md` section 8; the core controls and their props are described in `catalogs/core/README.md`. The definition never specifies pixels, coordinates, fonts or colors. Layout intent is expressed through layout controls (stack, grid, group) and their props (`direction`, `gap` as a named size, `emphasis`), which the host and design system realize. ### 12.3 Voice surface The voice surface is less proven than the agent and visual surfaces, and its shape may change in a later version. ```json "voice": { "greeting": "=`You have saved ${state.saved} of ${state.goal}.`", "intents": { "logDeposit": { "action": "logDeposit", "examples": ["I saved {amount} dollars", "add {amount} to savings"], "reply": "=`Added ${input.amount}. ${state.remaining} to go.`" }, "howFar": { "examples": ["how much is left", "how am I doing"], "reply": "=`${state.remaining} to go.`" } }, "announce": { "goalReached": "Goal reached. Well done." } } ``` | Field | Meaning | | --- | --- | | `greeting` | Dynamic value spoken when a voice session starts. Optional. | | `intents` | Object of intent name to intent (below). | | `announce` | Object from an app event name (an `emit` name or `flow:`) to a dynamic value spoken when that event is raised while a voice session is active, with `event` (the payload) in scope. Nothing is spoken when no voice session is active. Optional. | Intent fields: | Field | Meaning | | --- | --- | | `examples` | Required, at least one. Phrases a person might say, with `{slot}` placeholders that each name an input field of the action (`voice.unknownSlot`). An intent without `action` has no slots. | | `action` | Optional. The action the intent invokes. Without it the intent only replies. | | `reply` | Dynamic value spoken after the action succeeds, with `state` as it is after the action, `input`, `output`, `env` and `user` in scope. Without `action`, `input` is `{}` and `output` is `null`. Without `reply`, the host speaks the action's `done` message (section 8), when it has one. Optional. | - Recognizing speech, and matching it to intents, is the host's job. Examples are guidance, not patterns. As a minimum a host MUST recognize each example as written with its slots filled, MUST convert slot values to the field's type and ask again when it cannot, MUST NOT run an action whose required input it could not fill, and MUST say so when nothing fits. - The person speaking is the invoking principal, and `env.surface` is `voice`. An intent's action is the person's own invocation (section 8). - When the action fails, the host speaks the error's message and not the reply. A refusal for `require` speaks the entry's message. - For an action with `confirm`, the host asks aloud and proceeds only on a clear yes. - A control's `surfaces.voice` support level (`contracts.md` section 2) describes how a voice host that presents views reads a view out. It is independent of intents. ### 12.4 Design systems A design system is a separately versioned document referenced from `uses.design`. It supplies **tokens** (named colors, type styles, spacing, motion), **variants** (named prop presets for controls), and MAY reference a catalog of custom controls. For agent surfaces it MAY supply naming and error-message conventions. Definitions refer to tokens and variants by name only (`"variant": "primary"`, `"gap": "medium"`), so swapping the design system restyles every app that references it. A design system MAY restyle any control but MUST NOT change a control's contract (props, events, accessibility role). The design system document format is specified in `contracts.md`. ### 12.5 Assets A definition MAY carry the pictures it shows, such as a header photo, a logo or the sprites of a game, in its top-level `assets` member: an object from asset name to entry. An asset name is a name (section 3) of at most 64 characters. A prop that a contract marks `remote` refers to an asset as `asset:` followed by its name (section 6.3). ```json "assets": { "logo": { "type": "image/png", "digest": "sha256-rtVn_O8tnRRoQYWK0VMl6WNaojSAA9tc5TN8320NCy8", "data": "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAw…", "width": 64, "height": 64, "credit": "Logo by Ada Example, CC BY 4.0." } }, "surfaces": { "visual": { "start": "home", "views": { "home": { "title": "Home", "body": { "control": "core:image", "props": { "source": "asset:logo", "alt": "The Trip Savings logo" } } } } } } ``` The `data` above is shortened with an ellipsis to fit the page: a real entry carries the whole base64 text of the picture, here 16,560 characters. | Member | Meaning | | --- | --- | | `type` | Required. The picture's media type: `image/png`, `image/jpeg`, `image/webp` or `image/gif`. No other type is an asset in 0.2; in particular an SVG drawing is not. | | `digest` | Required. The digest of the picture's bytes (section 16). It says which picture the asset is. | | `data` | Optional. The picture's bytes as base64 (RFC 4648, section 4): the standard alphabet, with padding, with no line break and no other character, and with zero in the bits that padding leaves unused, so that the same bytes always give the same text. | | `width`, `height` | Optional. The size in pixels the picture shows at, each from 1 to 4096. When given, they MUST be that size: the size its header gives, with the two swapped when its orientation turns it a quarter (see "Orientation" below). | | `source` | Optional. The absolute `http` or `https` address the bytes came from, for people. A host MUST NOT load it. | | `credit` | Optional. One line of at most 300 characters that credits the author and the license. A host SHOULD show it where it tells about the app, as its explanation does (section 15). | An entry has no other member. **What an asset is.** An asset is the picture whose bytes have its `digest`. `data` is one way those bytes travel with the definition, and an entry without `data` is valid. A host that holds bytes with that digest, from the entry's `data` or from anywhere else, shows the asset. A host that holds none has no asset to show, and the control shows what it shows for a picture that cannot be loaded. A host or a tool MAY therefore keep the bytes apart from the document it works on and put them back as `data` when it hands the definition on: the digest of a definition leaves `data` out (section 16), so the definition stays the same. **Showing an asset.** An asset reference (section 6.3) is the whole string `asset:` and a name, either the value of a `remote` prop or a string inside it, such as the `source` of an image shape on a canvas. A host shows the asset of that name in the definition the control belongs to, which for a view of a part is the part's own definition, never its parent's. Loading an asset is not egress and needs no grant. A host MUST NOT show bytes whose digest is not the entry's `digest`. **Bytes that are carried.** Where `data` is present, all of these hold, and a definition that breaks any of them is not valid (`validation.md`, section 9.1): - `data` is base64 in the one form the table above gives; - the digest of its bytes is `digest`; - its bytes are a picture of the type `type` says, recognized from the bytes as the table below sets out; - the picture is at most 4096 pixels wide and at most 4096 pixels high, as its header gives them; - `width` and `height`, where given, are the size the picture shows at. A picture is recognized from its header alone, read without decoding the picture. Offsets count from the first byte, at 0. A header that gives a width or a height of 0 is not a picture. | Type | The bytes are | Width and height | | --- | --- | --- | | `image/png` | the eight bytes `89 50 4E 47 0D 0A 1A 0A`, then a chunk whose 32-bit big-endian length is 13 and whose type is `IHDR`, complete with its CRC (33 bytes in all). | The 32-bit big-endian integers at offsets 16 and 20. | | `image/jpeg` | `FF D8`, then segments. A segment starts with `FF`, after any number of further `FF` bytes, and a marker byte. Markers `01` and `D0` to `D7` stand alone; every other marker is followed by a 16-bit big-endian length, at least 2, that counts itself, and its segment lies within the bytes. A start-of-frame segment (markers `C0` to `CF` except `C4`, `C8` and `CC`), of length at least 8, comes before any marker `00`, `D8`, `D9` or `DA`. | In the first start-of-frame segment, after its length and one byte of sample precision: the 16-bit big-endian height, then the width. | | `image/webp` | `RIFF`, four bytes, `WEBP`, then a first chunk whose 32-bit little-endian size (offset 16) is at least 10 for `VP8 ` and `VP8X` and at least 5 for `VP8L`, and whose header lies within the bytes: for `VP8 `, a key frame (bit 0 of the byte at offset 20 is 0) with the start code `9D 01 2A` at offset 23; for `VP8L`, the byte `2F` at offset 20 and 0 in the top three bits of the 32-bit little-endian integer at offset 21; for `VP8X`, 30 bytes in all. | `VP8 `: the low 14 bits of the 16-bit little-endian integers at offsets 26 and 28. `VP8L`: bits 0 to 13 and bits 14 to 27 of the integer at offset 21, each plus one. `VP8X`: the 24-bit little-endian integers at offsets 24 and 27, each plus one. | | `image/gif` | `GIF87a` or `GIF89a`, at least 13 bytes. | The 16-bit little-endian integers at offsets 6 and 8. | **Orientation.** A photo taken with the camera held upright is often stored on its side, with an EXIF orientation that says how to turn it. A JPEG or a PNG has an orientation when it carries EXIF data (in a JPEG, an `APP1` segment that starts with `Exif` and two zero bytes; in a PNG, an `eXIf` chunk) whose first directory has the tag `0112` as one SHORT from 1 to 8; the first such data gives it. A host MUST show a JPEG or a PNG turned and mirrored as its orientation says, as browsers do. The orientations 5 to 8 turn the picture a quarter, so it shows with its width and height swapped: a photo stored 2048 by 1536 pixels with orientation 6 shows 1536 by 2048, and that is its `width` and `height`. A WebP and a GIF show as they are stored, whatever EXIF data they carry. The limit of 4096 pixels a side holds either way. **Where a picture was taken.** A photo's metadata often says where it was taken, as coordinates or as a place named in words. Its location is: the GPS directory of its EXIF data; in its XMP data, every property whose local name starts with `GPS` (other than `GPSVersionID`), and the properties that name a place, `photoshop:City`, `photoshop:State`, `photoshop:Country`, `Iptc4xmpCore:Location`, `Iptc4xmpCore:CountryCode`, and the structures `Iptc4xmpExt:LocationCreated` and `Iptc4xmpExt:LocationShown` whole; and in its IPTC data (IPTC-NAA, as a JPEG carries it in the Photoshop resources of an `APP13` segment), the datasets 2:26 (content location code), 2:27 (content location name), 2:90 (city), 2:92 (sublocation), 2:95 (province or state), 2:100 (country code) and 2:101 (country name). Nothing else is part of it: a title, a caption, keywords, a credit, an author or a copyright notice stays, even where its words name a place. Carried in an asset, that location travels to everyone who receives the definition, though nothing shows it. A tool that adds a picture to a definition for its author SHOULD remove that location from the picture first, and leave the rest of the picture as it is, so that the `digest` is of the bytes without it. A validator SHOULD warn about a carried picture that holds a location, naming the asset; a definition that has one is still valid. A host shows a picture as it is: it MUST NOT change the bytes of an asset, since they must keep their digest. The sizes of a definition and of its assets that every host accepts are given in section 18.1. ### 12.6 Localization A definition MAY carry its own texts in several languages, in its top-level `localization` member: the language its plain texts are written in, and for each language a table from key to text. A host shows the app in one of these languages, chosen for the person (section 12.7). ```json "localization": { "default": "en", "strings": { "en": { "appName": "Trip planner", "welcome": "Welcome back, {name}", "nights": { "by": "count", "forms": { "one": "{count} night", "other": "{count} nights" } } }, "ar": { "appName": "مخطط الرحلات", "welcome": "مرحبًا بعودتك يا {name}" } }, "notes": { "welcome": "Top of the home page. {name} is the traveler's first name." } } ``` | Member | Meaning | | --- | --- | | `default` | Required. A language tag: the language of every plain text of the document, and the last table a text is looked for in. `"localization": { "default": "ar" }` alone is valid: it declares the language of an app that carries no table. | | `strings` | Optional. An object from language tag to that language's table, an object from key to entry. When present it MUST have a member for `default`. The default language is complete: every key the definition uses is in its table. The other languages MAY be partial. | | `notes` | Optional. An object from key to a note of 1 to 300 characters for whoever translates the app later: what the text is for, what each blank holds. A host never shows a note to a person using the app. | `localization` has no other member. The app's own tags are the keys of `strings`, or `default` alone when there is no `strings`. **Language tags.** `default` and every key of `strings` is a language tag written `language[-Script][-REGION]` exactly, in ASCII. It matches `^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$` that is: 2 or 3 lower-case letters; then optionally a hyphen and 4 letters, the first upper-case and the other three lower-case (the script, an ISO 15924 code); then optionally a hyphen and 2 upper-case letters or 3 digits (the region, an ISO 3166 code or a UN M49 area). Nothing else: no variant, no extension, no private use. The language MUST NOT be `und`, and MUST NOT be one of the old codes of table `aliases` (Appendix A): an app writes `he`, never `iw`. A tag has this one spelling, so `en-us`, `en_US` and `EN` are not tags (`validation.md` reports them with their valid spelling). A bare `zh` or `sr` is read by its region (section 12.7); an app SHOULD write the script of these two (`zh-Hans`, `zh-Hant`, `sr-Cyrl`, `sr-Latn`). **Keys.** A key matches `^[A-Za-z][A-Za-z0-9_.]{0,79}$`: an ASCII letter, then ASCII letters, digits, `_` or `.`, at most 80 characters in all. Case matters. Dots only group names for a reader: a table is flat, and `home.title` is one key. **Entries.** An entry is a text or forms. - A **text** holds blanks, written `{name}`, where the name is an ASCII letter or `_` followed by ASCII letters, digits or `_`. `{{` writes one `{` and `}}` writes one `}`; any other brace makes the text malformed. The empty text is a text. - **Forms** are `{ "by": "", "forms": { "
": "" } }`, with no other member: the text used is chosen by the value given for the blank `by`. The form `other` is required; the other form keys are the plural category names `zero`, `one`, `two`, `few` and `many`, `=` followed by a number (`=0`, `=12`), and any other text that does not begin with `=`, matched exactly. - Each language writes its own entry: a text in one language MAY be forms in another, and the reverse. `expressions.md` section 8.7, "Texts of the app", gives the syntax of a text exactly, how a form is chosen, how blanks are filled, and the function `t` that shows an entry from an expression: `t('welcome', { name: user.name })`. **Fixed-text references.** Some places of a definition hold text that is never an expression: a leading `=` is a character there. In these places one value is read differently. A value that is exactly `=t('key')` (the characters `=t('`, a key, then `')`, with single quotes, no space and no second argument) is a reference to that key, and the place shows the key's text. Any other value is the literal text, as it is elsewhere. - The entry of a referenced key MUST be, in every language that has it, a text without blanks that is not empty. - The text shown is the entry with `{{` read as `{` and `}}` read as `}`, the same text `t('key')` gives. Every check on the place, such as its length, being one line, or holding no Markdown, reads that text. - The places are: `meta.name` and `meta.description`; a grant request's `reason`; the `description` of a capability, a role, a state entry (a view's own state entries too), an action, an input field, a type, a rule, a flow, a flow state and a code module; a type's `title`; an asset's `credit`; and the agent surface's `instructions` and the descriptions of its tools. - The reference does not apply to `meta.tags`, `meta.authors`, `meta.license`, icon names, the `source` of code, or voice `examples` (phrases a person says, which stay as written). - **Which language.** Where a person in a session reads the text, as in a list of apps, the title of a page, the heading of an app of one view, a permission sheet or a confirmation, the text is read in that person's shown language, along its text chain (section 12.7). Where no person in a session reads it, as in an agent's manifest and tool schemas, the explanation of section 15 and everything else that must be the same on every machine, and the `user.name` of the app's own principal, it is read in the default language. **Sizes.** Section 18.1 gives the number of languages, keys, characters and forms every host accepts. ### 12.7 Language, formats and direction A host shows a definition that has `localization` in one of the app's own languages, the **shown language**, chosen from the languages the person reads. From the shown language it derives the app's direction, left-to-right or right-to-left, and the locale that formats numbers and dates beside its words. A definition without `localization` has no shown language: it is shown left-to-right, and its `env.locale` is the locale the host gives for the person (section 3.5). This version says nothing of the words of the host itself, such as its hints, sheets and messages. The rules of this section use the five tables of Appendix A and nothing else: `aliases` (old codes), `sameLanguage` (languages compared as one), `scripts` (the script of a language), `parents` (regional parents) and `rtlScripts` (scripts written right to left). A host MUST apply them as written and MUST NOT consult other locale data, such as the likely subtags of Unicode CLDR, to choose the shown language or to work out its direction, its text chain or its formatting locale, so that every host gives the same answers for the same person. How a locale then writes a number or a date is not part of these rules. The rows of `conformance/0.2/languages/` hold a host to these rules. #### What a host is given - **The person's languages**, in order of preference: a list of BCP 47 tags as the platform gives them, such as a browser's `navigator.languages`, the locale a chat gives a frame and then the page's languages, or a command's flag and else the locale of the process. The list may be empty. - **A kept choice** for this app and this person, or none: one of the app's own tags, which the person chose through the host's language switch and the host remembers. #### Reading a person's tag A tag from the person's list is read as follows. A tag that cannot be read so is skipped. 1. It is at most 64 characters, and splitting it at each hyphen gives subtags of 1 to 8 ASCII letters or digits. Case is ignored. 2. The first subtag is the language: 2 or 3 letters, read in lower case, not `und`. 3. A subtag of 4 letters right after the language is the script, read with its first letter in upper case and the others in lower case. 4. A subtag of 2 letters or 3 digits right after the language, or right after the script when there is one, is the region, read in upper case. 5. A language that table `aliases` lists is replaced by the tag the table gives: its language becomes the language, and its script, when it has one, becomes the script when the person's tag wrote none. `iw-IL` is read as `he-IL` and `sh` as `sr-Latn`. 6. The **Unicode keywords** are the first subtag `u` after the language, script and region, with the subtags that follow it up to the next subtag of one character or the end, joined with hyphens in lower case. There are none when there is no such `u`, or when the subtag after it is missing or has one character. They are kept for the formatting locale. 7. Every other subtag is not used. An app's own tags are read by their one spelling (section 12.6), without these allowances. #### Comparing tags - **The language as compared.** Table `sameLanguage` gives, for a language it lists, the language it is compared as: `no` is compared as `nb`. Every other language is compared as itself. - **The row of a language** in table `scripts` is the row of the language as compared, or, when that has none, the row of the language itself. A language with a row is a language the table lists. - **The script of a tag**, for a language the table lists, is the script the tag writes; else, when the tag has a region that the row names for another script, that script; else the row's usual script. A tag of a language the table does not list has no script for comparing. - **The same language and script.** Two tags have the same language and script when their languages are compared as the same language and, in addition: when the table lists the language of either, the scripts of the two tags are equal; when it lists neither, they do not both write a script that differs. So `zh-TW` and `zh-Hant` have the same language and script, `zh` and `zh-TW` do not, and for a language the table lacks, `xyz-Latn` and `xyz-Arab` differ while `xyz` goes with either. - **The regions of a tag**, in order: its own region; then the parent of that region; then the parent of that one; and so on, at most 8 regions in all; then, last, no region. A tag without a region has only that last step. The parent is looked up in table `parents` under `language-Script-REGION`, with the tag's language as written and its script for comparing, for a language the table of scripts lists, and under `language-REGION` for any other language, whatever script the tag writes. The region of the parent is its last subtag. `es-MX` has the regions `MX`, `419`, then none; `en-AT` has `AT`, `150`, `001`, then none; `zh-MO` and `zh-Hant-MO` have `MO`, `HK`, then none. - **Shortest first.** Of several tags, the one with fewer characters comes first, and of tags of equal length the one that comes first in ascending order of code points. Table `scripts` lists the languages written in more than one script and the languages whose usual script runs right to left. Two of its rows differ from the likely subtags of Unicode CLDR on purpose, so that the table stays small and stable: a bare `zh` is Traditional only in `TW`, `HK` and `MO`, and a bare `sr` is Latin only in `ME`. In every other region the two keep their usual scripts, Simplified and Cyrillic. #### Choosing the shown language 1. A kept choice that is one of the app's tags is the shown language. A kept choice that is not one of them is ignored. 2. Otherwise the person's tags are taken in order. For each tag that can be read, the **candidates** are the app's tags that have the same language and script as it. A tag with no candidate passes to the next. 3. With candidates, the regions of the person's tag are walked in order. At each step the candidates whose region is exactly that region are hits, and at the last step the candidates without a region. Of several hits, the shortest first. The first hit is the shown language. 4. When no step has a hit, the shortest candidate is the shown language. 5. When no tag of the person has a candidate, `default` is the shown language. A script is never crossed: a reader of Traditional Chinese is not given `zh`, and a reader of Latin Serbian is not given `sr`. The first of the person's tags that has a candidate decides, even when a later tag would match more closely: for `["de-AT", "fr"]` an app with `de` and `fr` shows `de`. #### Direction The direction of an app's tag is right-to-left when its script is in table `rtlScripts` and left-to-right otherwise. Its script is the one the tag writes, else its script for comparing. A tag of a language the table of scripts does not list, with no script written, is left-to-right. An app in such a language that is written right to left states its direction by writing the script in its tag: `xyz-Arab`. `env.direction` is the direction of the shown language. Direction comes from the shown language only: never from the person's region, and never from a setting. A definition cannot set its direction apart from its language. #### The text chain A text of a key is looked for in these tables, in order: 1. the table of the shown language; 2. the tables of the app's other tags that have the same language and script as the shown language, met along the regions of the shown language: at each step, the tags whose region is exactly that region, and at the last step those without a region; several tags at one step in the order shortest first. For `es-MX` these are `es-419`, then `es`; for `nb-NO` among `en`, `no`, `nb` and `nb-NO` they are `nb`, then `no`; 3. the table of `default`. A tag is in the chain once, where it is first met. The first table that has the key gives its entry, whole: the forms of one table are never mixed with those of another. The language of that table is the language of the text. #### The formatting locale Numbers, dates, relative times and plural categories follow the words they stand beside, written for the person's region. The formatting locale of an app's tag T for the person is made as follows. - P is the first of the person's tags that can be read and has the same language and script as T; else the first of the person's tags that can be read; else there is none. - The region is P's region; else T's region; else there is none. - The script is the script T writes. When T writes none and there is a region, it is T's script for comparing when the table lists T's language and the script for comparing of a tag of T's language with that region and no script is another; otherwise there is none. - The locale is T's language, then the script, then the region, joined with hyphens, leaving out what there is none of, then, when P has Unicode keywords, a hyphen and those keywords. | Shown language | The person's languages | Formatting locale | | --- | --- | --- | | `en` | `ja-JP` | `en-JP` | | `ar` | `ar-EG-u-nu-latn` | `ar-EG-u-nu-latn` | | `ar` | `en-US` | `ar-US` | | `zh` | `zh-Hans-HK` | `zh-Hans-HK` | | `pa` | `ur-PK` | `pa-Guru-PK` | | `no` | `en-GB`, `nb-NO` | `no-NO` | | `xyz-Arab` | `en-US`, `xyz-Latn-MA` | `xyz-Arab-US` | `env.locale` is the formatting locale of the shown language. A text taken from another table of the chain is formatted with the formatting locale of that table's tag. `formatNumber`, `formatDate`, `relativeTime` and `plural` read `env.locale`, and so agree with the words of the app. ## 13. Parts: building apps from apps ```json "uses": { "definitions": { "budgetApp": { "id": "com.example.budget", "version": "^1.2.0" } } }, "parts": { "budget": { "definition": "budgetApp", "with": { "goal": "=state.tripCost" }, "capabilities": { "bank": "bank" }, "grants": { "readSavings": { "rate": { "count": 4, "per": "P1D" } } } } } ``` The included definition declares what it offers in its own `exports`: ```json "exports": { "inputs": { "goal": "state.goal" }, "state": ["saved", "remaining"], "actions": ["logDeposit"], "events": ["goalReached"], "views": ["summary"] } ``` - **Encapsulation.** A parent sees only what a part exports: `parts.budget.state.remaining` in expressions, `{ "run": "budget.logDeposit" }` in steps, `{ "event": "budget.goalReached" }` in rule triggers, `{ "part": "budget", "view": "summary" }` in views, and `budget.logDeposit`, `budget.remaining` and `budget.goalReached` in an agent surface's `include` lists (section 12.1). Everything else is private. A `run` of a part's action from the parent's steps gives the parent its output, never its `done` message (section 8). - **Inputs.** `exports.inputs` maps an input name to a stored state *path* in the part. The parent's `with` drives it reactively: the part's value follows the parent's expression. A driven input is read-only inside the part: a part step that writes it fails with `state.readonly`. Its type must accept every value the parent can drive. Validation reports a known type that cannot be accepted, but not `null`. At run time a driven value that does not conform is not written: the input keeps its previous value, and the host reports `state.invalidValue`. A driven value changes like any write, so the part's `becomes` triggers over it follow section 9: one that is already true when the parent first drives the input does not fire. - **State.** Each part instance has its own isolated state. Nothing is shared implicitly. A definition MAY be included more than once under different part names. A host MAY let a person start a part from the state of an instance of that definition the person owns. Only `shared` entries and the person's own `user` entries are copied; other people's values, `device` and `session` values, flow bookkeeping, grants, `once` records and the audit log are not. The copy is recorded in the source instance's audit log, and the two instances are independent afterwards. For a part whose definition is a carried copy (section 4), a host offers this only when the copy's digest is the digest the source instance runs: a carried copy is not the definition of an instance because its `id` matches. - **Capabilities.** `parts..capabilities` maps each of the part's capability aliases to one of the parent's. Contracts MUST be compatible: the same catalog id and contract name, at the same major version. Unmapped part capabilities are bound by the host as if the part were standalone. - **Grants.** A part's grant requests become part of the parent's and are shown to the approver as such, attributed to the part. `parts..grants` MAY attenuate a request (an additional `where`, which is combined with the part's own by logical and, a lower `rate`, a shorter `duration`, fewer `scopes`, a shorter `operations` list) or decline it with `false`. A parent can never widen what a part requested, and a part can never exercise more than the parent holds. A call made by a part's steps is covered only by that part's requests, as the parent attenuated them; a call made by the parent's steps is covered only by the parent's requests. Each request has its own rate, also when the part's capability is mapped to the parent's. A part's request that the parent declines with `false` is not put to the approver. - **Language.** A part is its own definition with its own `localization`. The host applies the same person's languages, and the kept choice of the app that includes the part, to the part's own tags by the rules of section 12.7, so a part can show another language than its parent. A part's `env.language`, `env.direction` and `env.locale` are its own. - **Versions.** A part is resolved by its semver range, and by `digest` when given, first among the carried copies of the file (section 4). Two parts MAY resolve to different versions of the same definition; instances are independent. - **Carried copies.** A part whose definition is a carried copy is a part like any other: encapsulation, a part's requests shown as the parent's, attenuation, the part's own language, the limits below, and that a change in any part an instance resolves is an update of the instance (section 6.4.1) all hold unchanged. - **Limits.** The include graph MUST be acyclic and MUST NOT be more than 8 levels deep, a depth every host supports. ## 14. Resolution and graceful degradation Before running a definition, a host **resolves** it and produces a **resolution report**: for every catalog, control, capability, part, surface, grant and code module, one of `satisfied`, `degraded` (with a note on what differs) or `missing`. For a part whose definition is a carried copy, and for a design system that is one, the report says it is carried in the file (section 4). - A missing `required` capability, a declined `required` grant, or an unresolvable part fails the load. A declined required personal request fails it only for that person (section 6.4.2). - A request for a capability that is unavailable, or for code the host cannot run, is not asked and does not fail the load. The steps that need it fail when they run (`capability.unavailable`, `code.unsupported`). - A request with no grant in force is `missing`, and the report says which it is: declined, or not asked yet (section 6). An optional request left to be asked later does not fail the load. A request given by use or contained is `satisfied` unless it was declined, and the report says that nobody was asked and why. - A catalog the host cannot find does not fail the load by itself. Its controls are `missing` and resolve to their fallbacks, and its capabilities are `missing`, which fails the load only if one of them is required. Validation tools still need the catalog to check a definition (`uses.catalogNotFound`). - A capability whose required `config` the host cannot supply is `missing` (section 5). - A missing optional capability leaves `capabilities..available` as `false`. Calls to it fail with `capability.unavailable`. - A missing control is replaced by the node's `fallback` if present, otherwise by the control contract's declared degradation (`degradeTo`, which MAY name a contract in a catalog the control's catalog uses), otherwise by a host placeholder that shows the node's accessible label. The app still loads. - A host that lacks a whole surface simply does not serve it. The kernel is unaffected. A declared surface is `satisfied` only when the host serves it, and `missing` otherwise. - A type from a catalog the host cannot find is treated as `any` at run time, and the report marks it `degraded`. - A part's request that the parent declined with `false` is listed as declined by the including definition, not as `missing`. A request the parent attenuated, and that the approver granted as shown, is `satisfied`; `degraded` is for a grant narrower than what the approver was shown. - When `meta.derivedFrom` carries a `digest` and the host holds the definition it names, the host MUST verify the digest and fail the load on a mismatch. When the host does not hold that definition, the report says the origin is unverified. - The report shows configuration values the host supplied (section 5) and, after an update, which stored values were replaced and which flow instances were reset (section 6.4.1). - The report MUST be available to the owner, to members and to agents that hold access to the app. For an agent that does not hold full access, a host MAY reduce it to the name and status of each item. ## 15. Inspection, explanation and audit - **Explain.** A host MUST be able to render any definition as plain language without running it: what the app holds, its main sections where it lists them, each action with who may run it, what it requires, whether it asks for confirmation and what it says once done, each rule as "When ..., then ...", each flow's stages and moves, each capability and each grant request with its reason and limits, who answers it, and whether it is asked, given by use, or given without asking (section 6), and the `credit` of each picture it carries that has one, with its `source` where given (section 12.5). Where it says what the app is made of, it says of a part whose definition is a carried copy that it is carried in the file (section 4). The rendering is derived from structure plus `description`, `reason`, and `require` and `done` message text. It is deterministic, so two people looking at the same definition see the same explanation. An explanation is meant to be shown and passed on, so it MUST NOT print a value written in the definition for an entry that is sensitive (section 7.3). It describes the whole definition, so a host SHOULD give it only to principals that hold full access to the app or hold the definition itself. - **Audit.** A host MUST record, per app instance: every action invocation (principal, surface, input, outcome), every capability operation (grant used, outcome; a call repeated under `once` is marked as repeated), every capability event delivered, every code run, every rule firing, timer and flow transition (with a reference to the record that caused it), every update of the instance (section 6.4.1), every grant issue, delegation, denial and revocation, and every load that failed because a required request was declined. A denial is either a declined request (which request, who declined, when) or a refused operation. Each record has a `kind`: `action`, `operation`, `event` (a capability event delivered), `egress`, `code`, `rule`, `flow`, `handler` (a visual handler's invocation), `timer` (an `every` trigger, a flow `after` timer or a timed source refresh firing), `state` (a write from a binding), `lifecycle`, `update`, `access` (access given to a principal), `grant.issue`, `grant.delegate`, `grant.deny` or `grant.revoke`. A record's id is what `env.invocation` gives (section 3.5). Routine refreshes of the environment, such as the minute tick of `env.now`, are not recorded. `every` firings at intervals under one minute are recorded as one `timer` record per minute, with a count. Writes to view state are not recorded, and successive writes from one binding while the person types form one record. - **Redaction.** A recorded input, output or error message is redacted when it was computed from a sensitive value (section 7.3). A value that was not is recorded in full, even when the same invocation also read sensitive values, so the log can still show, for example, the fixed text of a notification. - **Causes.** The record of a state change names as its cause the record of the action whose step made the write, also when that action was run by another action or belongs to a part. The record of a flow `after` transition names as its cause the record of the transition that put the flow instance in that state. A timed source read names its timer. - **Keeping records.** A host MAY bound the size of the log, but MUST keep the records of grants (issue, delegation, denial, revocation) and of updates for the life of the instance, and SHOULD keep at least 90 days of the rest. - **Who reads the audit log.** The owner can read every record of the instance. A member can read in full the records of their own invocations and of what those caused on their own behalf, and the other records in outline; what an invocation of theirs caused for another person, such as a value read for that person or a rule run in that person's session, is among the other records. An agent reads in full only the records of its own invocations, whose input it supplied and whose output it received. The other records it may see, which are those its invocations caused and, for an agent with full access, every record of the instance, are given in outline. A record in outline says what happened, when, and to which action, rule, flow or operation, without inputs, outputs or messages. - **Why.** From any audit record, a user MUST be able to walk the cause chain back to the principal action or trigger that started it. ## 16. Versioning, identity and history - **Spec version.** `oad` is `MAJOR.MINOR`; this document defines `0.2`. Before 1.0 every minor version is its own format: a host or tool declares the versions it reads and refuses a document of any other version, saying which versions it reads (`document.version`, `validation.md`). `changes.md` lists what changed from 0.1. From 1.0 on, minor versions only add; a 1.2 host runs any 1.x document, ignoring nothing silently: unknown constructs are reported as `degraded` or `missing` in the resolution report. - **Definition version.** Semver. Removing or renaming an export, action, action input field or agent-exposed state entry is a breaking change and requires a major bump. - **Instance identity.** An instance runs one definition at a time, identified by `id`; running it with another digest is an update (section 6.4.1). - **Digest.** The digest of a JSON document (a definition, catalog, design system or history) is `sha256-` followed by the base64url (no padding) SHA-256 of its canonical JSON form (RFC 8785, JCS). The digest of any other resource, such as a code module or a control implementation module, is `sha256-` followed by the base64url (no padding) SHA-256 of its bytes. Digests pin exact content in `uses.definitions`, `meta.derivedFrom`, code `module`, catalog `implementations` and history. - **The digest of a definition never covers `data`.** The digest of a definition is taken of the definition without the `data` member of each entry of its `assets` (section 12.5): those members, and nothing else, are left out before the canonical form is made. A definition that carries its pictures and the same definition without them are one definition with one digest, so everything that rests on the digest, such as a pin in `uses.definitions` or `meta.derivedFrom`, a signature, a grant issued for a definition, the definition an instance runs (section 6.4.1) and the digests of a history, holds whichever of the two a host or tool has. Each picture is still covered, through the `digest` member of its entry. - **The digest of a definition never covers `included`.** The member `included` (section 4) is left out before the canonical form is made, exactly as the `data` of each asset is. A definition with its carried copies and the same definition without them are one definition with one digest, and everything that rests on the digest holds for both. A carried copy is covered only where a reference pins its `digest`; each carried copy has its own digest, taken as for any definition or design system. A signature, a grant or an approval that rests on the digest of an app therefore says nothing about its carried copies unless the app's reference pins their digest, and a reference of `uses.design` pins none. What stands for the same app as before is the app's digest together with the digests of the parts it resolved, which is what an instance records (section 6.4.1). - **History.** A definition does not carry its own change log. History is a sidecar document (`*.oad.history.json`) of the form `{ "oadHistory": "0.2", "id", "base", "entries" }`, where `id` is the definition's id and `entries` is an ordered list of `{ "version", "at", "by": { "kind": "person" | "agent", "id" }, "approvedBy", "intent", "patch", "digest" }`. `at` is a UTC `datetime` written with `Z`, `patch` is an RFC 6902 JSON Patch from the previous entry's document, `intent` is the request that led to the change, in the requester's words, and `digest` is the digest of the document after the patch. `approvedBy` is optional: `{ "kind": "person", "id" }`, the person who agreed to the change. A tool that applies a change which widens what the app may do (a new or broader grant request, a new capability, code module or network origin) SHOULD record who agreed. `base` is optional: `{ "version", "digest" }` of the document the first patch applies to. Without `base`, the first patch applies to the empty object, so the history rebuilds the definition from nothing. A history with a `base` can be replayed only by someone who also holds that base document, which the sidecar does not carry; a tool that starts a history for an existing definition SHOULD therefore omit `base` and record the whole definition as the first entry. Edits are undone one at a time by replaying the history up to the entry before; a JSON Patch alone does not carry the values it removed. Keeping it beside the file keeps the definition small and lets a definition be shared without its past. - **Signatures.** Detached signatures over the digest are carried in a sidecar and are specified in `contracts.md` together with catalog signing. ## 17. Errors Failures carry a stable `code` and a human-readable `message`. Codes defined here: | Code | Raised when | | --- | --- | | `action.invalidInput` | An action's input, or a file reference in an agent's tool input, is not valid (sections 5 and 8). | | `action.forbidden` | An action's `allow` is not true, or the caller has no access to the action (sections 6.1 and 8). | | `action.refused` | A `require` entry is not true; carries the entry's message (section 8). | | `action.declined` | A confirmation was declined or not answered (section 8). | | `action.failed` | An action failed for a reason no other code names. | | `instance.forbidden` | A person who holds no access to an instance tried to load it, or someone other than the owner presented a different definition for it (sections 6.4 and 6.4.1). | | `grant.denied` | No issued grant covers an operation (section 6). | | `grant.expired` | The grant that would cover an operation has expired. | | `grant.rateLimited` | An operation would exceed its grant's `rate`. | | `capability.unavailable` | A call names a capability the host could not bind (section 14). | | `capability.failed` | A provider failed, or an operation's input or `once` key is not valid. | | `capability.onceMismatch` | A call repeated a `once` key under the same identity with a different input (section 8.3). | | `code.unsupported` | The host cannot run the module's runtime. | | `code.limit` | A module exceeded its `limits`. | | `code.failed` | A module failed or returned something that is not plain data (section 11). | | `flow.forbidden` | The transition taken has an `allow` that is not true (section 10). | | `flow.noTransition` | A flow event has no element, or no transition to take (section 10). | | `flow.fieldWrite` | A step wrote the state field of a collection flow (section 10). | | `rule.cascade` | A rule would have run, or a sourced entry would have been read, more than 16 levels below the work that started the cascade, counting the capability events that follow from the cascade's own calls; recorded in the audit log (sections 7.1 and 9). | | `state.conflict` | A write under `conflict: "reject"` was based on a stale value (section 7.2). | | `state.readonly` | A write targets a derived or sourced entry, or a part's driven input (sections 8.1 and 13). | | `state.invalidValue` | A value does not conform to its entry's type, or a source's output does not (sections 7 and 7.1). | | `state.noElement` | A write through a selector matched no element (section 8.1). | | `egress.denied` | A remote fetch is not covered by a grant (section 6.3). | | `expression.syntax` | An expression or path does not parse. | | `expression.error` | An expression failed when evaluated (`expressions.md`). | | `resolution.failed` | The definition could not be resolved for loading (section 14). | An app MAY use its own codes in a `fail` step (section 8.1). The diagnostics a validator reports, such as `action.confirmBypassed` or `call.onceEffect`, are listed in `validation.md`. Expression errors are contained where they occur: a failing `derive` yields `null` and a diagnostic; a failing guard or condition (`allow`, a `require` entry's `that`, `if`, the `when` of a node, `where`, `becomes`) counts as not-true and produces a diagnostic; a failing expression in a step fails the step. Elsewhere a failing expression has these effects: - A failing prop or view title is absent, so its default applies; a failing required prop gives the node's placeholder (section 14). A canvas that has already drawn keeps its last picture in the placeholder's place for a short time (`contracts.md` section 8.3). - A failing `each.in` repeats nothing. - A failing binding or selector shows an empty, disabled control and writes nothing. - A failing `source.with` or `source.when` is a failed read with `expression.error`. - A failing `config` member is left unsupplied (section 5). - A failing `done` message, or one that is not text, gives no message, and the action has still succeeded (section 8). - A failing stored `initial` or view state `initial` gives `null`. ## 18. Conformance A **conforming definition** validates against the 0.2 JSON Schema and passes the semantic checks of `validation.md` (references resolve, names are unique and well-formed, expressions parse and agree with the types that can be known, derived state and the action call graph are acyclic, every capability operation used has a scope covered by some grant request, every code module has a grant request). A **conforming host** loads conforming definitions, produces resolution reports, enforces grants as in section 6, implements execution semantics as in sections 7 to 11, and provides explanation and audit as in section 15. A host declares which surfaces and code runtimes it supports. Conformance fixtures live in `conformance/0.2/`. ### 18.1 Sizes A host MUST accept a definition that is within all of these sizes: - the definition, as JSON without insignificant white space and without the `data` of its assets, is at most 2,621,440 bytes in UTF-8; - it has at most 64 assets; - the `data` of each asset is at most 1,048,576 characters, and the `data` of all its assets together at most 2,621,440 characters; - its `localization` (section 12.6) has at most 64 languages, at most 2,000 keys in one language, at most 2,000 code points in one text (each form of an entry counts alone), and at most 24 forms in one entry. All of it counts toward the size of the definition like any other member; - the size of the definition does not count `included` (section 4), which has sizes of its own: it holds at most 16 definitions and at most 17 design systems, and the carried copies together are within the sizes of one definition: each as JSON without insignificant white space and without the `data` of its assets, at most 2,621,440 bytes in UTF-8 in all; at most 64 assets among them; the `data` of each of those assets at most 1,048,576 characters, and of all of them together at most 2,621,440 characters. A host MAY accept more, and MAY let the person who runs it set how many definitions one app may include in all, counting the parts of its parts once each. A host that refuses a document for its size SHOULD say which of these sizes the document passed and by how much. A definition beyond these sizes is still valid; a validator warns that not every host accepts it (`validation.md`, section 9.1). Section 13 gives the deepest include graph every host supports. ## Appendix A. Language tables The five tables that section 12.7 uses, in full. Script codes are those of ISO 15924; region codes are those of ISO 3166 and the areas of UN M49. Table `scripts` follows the likely subtags of Unicode CLDR, with the two differences that section 12.7 names. ### A.1 Old codes (`aliases`) The old language codes a person's device may still send, and the tag each is read as (section 12.7, "Reading a person's tag"). They apply to a person's tags only: an app's own tag never uses one. | Old code | Read as | | --- | --- | | `iw` | `he` | | `in` | `id` | | `ji` | `yi` | | `jw` | `jv` | | `mo` | `ro` | | `tl` | `fil` | | `sh` | `sr-Latn` | | `cmn` | `zh` | ### A.2 One language (`sameLanguage`) Languages that are one language when tags are compared. Both are valid tags of an app. | Language | Compared as | | --- | --- | | `no` | `nb` | ### A.3 Scripts (`scripts`) For each language listed, its usual script and the regions where another script is usual. Listed are the languages written in more than one script and the languages whose usual script runs right to left; for any other language, script is not compared. | Language | Usual script | Another script, and the regions where it is usual | | --- | --- | --- | | `acm` | `Arab` | | | `aeb` | `Arab` | | | `afb` | `Arab` | | | `apc` | `Arab` | | | `ar` | `Arab` | | | `arq` | `Arab` | | | `ars` | `Arab` | | | `ary` | `Arab` | | | `arz` | `Arab` | | | `az` | `Latn` | `Arab`: `IQ`, `IR`; `Cyrl`: `RU` | | `azb` | `Arab` | | | `bal` | `Arab` | | | `bgn` | `Arab` | | | `bm` | `Latn` | | | `bqi` | `Arab` | | | `brh` | `Arab` | | | `bs` | `Latn` | | | `ckb` | `Arab` | | | `dv` | `Thaa` | | | `fa` | `Arab` | | | `ff` | `Latn` | | | `glk` | `Arab` | | | `ha` | `Latn` | `Arab`: `CM`, `SD` | | `hak` | `Hans` | `Hant`: `TW` | | `haz` | `Arab` | | | `he` | `Hebr` | | | `hi` | `Deva` | | | `iu` | `Cans` | | | `khw` | `Arab` | | | `kk` | `Cyrl` | `Arab`: `AF`, `CN`, `IR`, `MN` | | `kok` | `Deva` | | | `ks` | `Arab` | | | `ku` | `Latn` | `Arab`: `IQ`, `IR`, `LB`; `Cyrl`: `AM`, `AZ`, `GE`, `TM` | | `ky` | `Cyrl` | `Arab`: `CN`; `Latn`: `TR` | | `lah` | `Arab` | | | `lrc` | `Arab` | | | `mn` | `Cyrl` | `Mong`: `CN` | | `mni` | `Beng` | | | `ms` | `Latn` | | | `mzn` | `Arab` | | | `nan` | `Hans` | `Hant`: `MO`, `TW` | | `nqo` | `Nkoo` | | | `pa` | `Guru` | `Arab`: `PK` | | `pnb` | `Arab` | | | `ps` | `Arab` | | | `rhg` | `Rohg` | | | `sat` | `Olck` | | | `sd` | `Arab` | `Deva`: `IN` | | `sdh` | `Arab` | | | `shi` | `Tfng` | | | `skr` | `Arab` | | | `sr` | `Cyrl` | `Latn`: `ME` | | `syr` | `Syrc` | | | `tg` | `Cyrl` | `Arab`: `PK` | | `ug` | `Arab` | `Cyrl`: `KZ`, `MN` | | `ur` | `Arab` | | | `uz` | `Latn` | `Arab`: `AF`; `Cyrl`: `CN` | | `vai` | `Vaii` | | | `yi` | `Hebr` | | | `yue` | `Hant` | `Hans`: `CN` | | `zh` | `Hans` | `Hant`: `HK`, `MO`, `TW` | ### A.4 Regional parents (`parents`) For `en`, `es`, `pt` and `zh-Hant`, the regions whose texts fall back to a wider regional form before the plain language, taken from Unicode CLDR 49. Every tag is written `language-Script-REGION` for a language that table `scripts` lists and `language-REGION` for any other, and a parent has the language and the script of the tags whose parent it is. | Parent | The tags whose parent it is | | --- | --- | | `en-001` | `en-150`, `en-AG`, `en-AI`, `en-AU`, `en-BB`, `en-BM`, `en-BS`, `en-BW`, `en-BZ`, `en-CC`, `en-CK`, `en-CM`, `en-CX`, `en-CY`, `en-DG`, `en-DM`, `en-ER`, `en-FJ`, `en-FK`, `en-FM`, `en-GB`, `en-GD`, `en-GG`, `en-GH`, `en-GI`, `en-GM`, `en-GS`, `en-GY`, `en-HK`, `en-ID`, `en-IE`, `en-IL`, `en-IM`, `en-IN`, `en-IO`, `en-JE`, `en-JM`, `en-KE`, `en-KI`, `en-KN`, `en-KY`, `en-LC`, `en-LR`, `en-LS`, `en-MG`, `en-MO`, `en-MS`, `en-MT`, `en-MU`, `en-MV`, `en-MW`, `en-MY`, `en-NA`, `en-NF`, `en-NG`, `en-NR`, `en-NU`, `en-NZ`, `en-PG`, `en-PK`, `en-PN`, `en-PW`, `en-RW`, `en-SB`, `en-SC`, `en-SD`, `en-SG`, `en-SH`, `en-SL`, `en-SS`, `en-SX`, `en-SZ`, `en-TC`, `en-TK`, `en-TO`, `en-TT`, `en-TV`, `en-TZ`, `en-UG`, `en-VC`, `en-VG`, `en-VU`, `en-WS`, `en-ZA`, `en-ZM`, `en-ZW` | | `en-150` | `en-AT`, `en-BE`, `en-CH`, `en-CZ`, `en-DE`, `en-DK`, `en-EE`, `en-ES`, `en-FI`, `en-FR`, `en-GE`, `en-HU`, `en-IT`, `en-LT`, `en-LV`, `en-NL`, `en-NO`, `en-PL`, `en-PT`, `en-RO`, `en-SE`, `en-SI`, `en-SK`, `en-UA` | | `es-419` | `es-AR`, `es-BO`, `es-BR`, `es-BZ`, `es-CL`, `es-CO`, `es-CR`, `es-CU`, `es-DO`, `es-EC`, `es-GT`, `es-HN`, `es-JP`, `es-MX`, `es-NI`, `es-PA`, `es-PE`, `es-PR`, `es-PY`, `es-SV`, `es-US`, `es-UY`, `es-VE` | | `pt-PT` | `pt-AO`, `pt-CH`, `pt-CV`, `pt-FR`, `pt-GQ`, `pt-GW`, `pt-LU`, `pt-MO`, `pt-MZ`, `pt-ST`, `pt-TL` | | `zh-Hant-HK` | `zh-Hant-MO` | ### A.5 Right-to-left scripts (`rtlScripts`) The scripts written right to left, those in use and the historic ones. | Kind | Scripts | | --- | --- | | In use | `Adlm`, `Arab`, `Aran`, `Hebr`, `Mand`, `Nkoo`, `Rohg`, `Syrc`, `Syre`, `Syrj`, `Syrn`, `Thaa` | | Historic | `Armi`, `Avst`, `Chrs`, `Cprt`, `Elym`, `Gara`, `Hatr`, `Hung`, `Khar`, `Lydi`, `Mani`, `Mend`, `Merc`, `Mero`, `Narb`, `Nbat`, `Orkh`, `Ougr`, `Palm`, `Phli`, `Phlp`, `Phnx`, `Prti`, `Samr`, `Sarb`, `Sidt`, `Sogd`, `Sogo`, `Yezi` | --- # Open App Definition (OAD) 0.2: Catalogs and Contracts Status: working draft. Read `core.md` first. ## 1. Catalogs A **catalog** is a versioned, publishable JSON document (`*.oadcatalog.json`) that holds **contracts**. A contract describes one reusable part: a **control** (a building block for visual and voice surfaces) or a **capability** (typed access to the outside world). Anyone can publish a catalog. The standard defines how parts are described, not which parts exist. ```json { "oadCatalog": "0.2", "id": "org.openappdefinition.core", "version": "0.2.0", "meta": { "name": "OAD Core", "description": "Baseline controls and capabilities.", "publisher": "Open App Definition", "license": "Apache-2.0" }, "types": {}, "contracts": {} } ``` `id` and `version` follow the same rules as a definition's. `meta` has `name` and `description` (both required) and optional `publisher`, `license` and `homepage`. `types` is an optional object of shared type definitions, referenced from contracts by name and from definitions as `alias:TypeName`. `contracts` is required and is keyed by contract name. **Using other catalogs.** A catalog MAY carry `uses: { "catalogs": { alias: { "id", "version" } } }`, which names other catalogs by `id` and semver range as a definition's `uses.catalogs` does (core.md section 4). Inside the catalog, a type reference MAY then be `alias:TypeName`, a `requires` entry's `contract` MAY be `alias:contractName`, and `degradeTo` MAY be `alias:contractName`. The graph of catalogs using catalogs MUST be acyclic (`uses.catalogCycle`). This is also how a contract outside the core catalog declares a file input that the host resolves and checks (core.md section 5): it types the field with the core catalog's `FileRef`. ```json { "oadCatalog": "0.2", "id": "com.example.expenses", "version": "1.0.0", "meta": { "name": "Expenses", "description": "Expense claims and policies." }, "uses": { "catalogs": { "core": { "id": "org.openappdefinition.core", "version": "^0.2.0" } } }, "types": { "ClaimLine": { "type": "object", "properties": { "amount": { "type": "number" }, "receipt": { "$ref": "core:FileRef" } }, "required": ["amount"] } }, "contracts": {} } ``` The core catalog, `org.openappdefinition.core` in `catalogs/core/`, is described for readers in `catalogs/core/README.md`, generated from the catalog. It is the reference for the core controls with their props, events and slots, and for the core capabilities with their operations and scopes. Sections 8 and 9 below settle how those controls and capabilities behave where their declarations do not say. **Known values.** A type in a catalog's `types` whose `type` is `string` MAY carry `known`: a list of 1 to 256 distinct strings, each 1 to 64 characters long, that are the values every implementation of the catalog should know. Each of them MUST be a value of the type itself, matching its `pattern` and within its `minLength` and `maxLength` (`type.invalid`). Such a type takes only `type`, `known`, `pattern`, `minLength`, `maxLength`, `default`, `description` and `title`, and `known` appears nowhere else: not inside another type, not on a field's own type, and not in a definition. A contract's field refers to the type by name, as `Name`, or as `alias:Name` from another catalog. `known` never refuses a value. Any string that is a value of the rest of the type is valid wherever the type is expected, and an implementation MAY know more values than the list holds. A host gives each known value its meaning and treats a value it does not know as the type's `description` says. A checker warns where a definition gives a control prop of such a type a literal value outside the list (`value.notKnown`, `validation.md` section 6), and names the known values nearest to it by spelling; the definition stays valid, and a value given by an expression is not checked. A catalog MAY add values to `known` in a minor version, since no value becomes invalid; removing one is breaking. ```json { "oadCatalog": "0.2", "id": "com.example.weather", "version": "1.0.0", "meta": { "name": "Weather", "description": "Forecasts and the words for them." }, "types": { "Sky": { "description": "What the sky does. A host draws each known value with a picture of its own; it shows another value as its words.", "type": "string", "pattern": "^[a-z][a-zA-Z0-9]*$", "known": ["clear", "cloudy", "rain", "snow", "storm"] } }, "contracts": {} } ``` The core catalog's `IconName` is such a type, and its `known` list is the **icon vocabulary**: the names every host draws a symbol for. The core `icon` control's `name`, the core `button`'s `icon`, a definition's `meta.icon` and the `icon` of a main section (core.md section 12.2) all take an `IconName`. **Names.** Contract names, and the names of props, outputs, events, slots, slot scope variables, operations, config fields, token and variant names, follow the name rule of core.md section 3. Scope names are one or more such names joined by dots (`transactions.read`). A catalog MAY be **private**: scoped to an organization and distributed through that organization's host configuration. Private and public catalogs share one format, so a private catalog is published later by changing where it is hosted, not what it contains. ## 2. Contract shape Controls and capabilities share one envelope, so vendors of either face the same rules. ```json { "kind": "control", "intent": "Show progress toward a numeric target.", "since": "0.1.0", "interface": { "props": { "value": { "type": "number", "description": "Current amount." }, "label": { "type": "string", "description": "Accessible name and visible caption." } } }, "surfaces": { "visual": { "support": "full" }, "voice": { "support": "degraded", "note": "Spoken as a percentage." } }, "accessibility": { "role": "progressbar", "labelProp": "label" }, "implementations": [], "requires": [], "distribution": { "license": "Apache-2.0" }, "conformance": [] } ``` | Field | Declares | Required | | --- | --- | --- | | `kind` | `control` or `capability`. | yes | | `intent` | What the part is for, written so an AI can choose it and an agent can understand it. | yes | | `since` | Catalog version that introduced the contract. | no | | `deprecated` | `{ "version", "replacement", "note" }`: the catalog version that deprecated the contract, and optionally the contract in the same catalog that replaces it and a note. | no | | `interface` | The typed surface of the part (sections 3 and 4). | yes | | `surfaces` | For controls: an entry for both `visual` and `voice`, each with `support` of `full`, `degraded` or `none`, a `note` (required when `degraded`), and optional `degradeTo` naming another control contract to use instead when support is `degraded` or `none`: a contract name in the same catalog, or `alias:contractName` for a contract in a catalog this catalog uses (section 1). The host passes the replacement only the props it declares. A control named in the `degradeTo` of a used control is itself used, transitively: its `requires` must be covered, and its pricing is shown, as for any control the definition names. | controls | | `accessibility` | For controls: `role` (a WAI-ARIA role name, required), optional `alternateRoles` (other roles the host may use when it picks a different presentation, such as a `combobox` for a `listbox`, or when prop values make another listed role the correct one, such as `none` for a decorative image), optional `labelProp` (the prop that supplies the accessible name; omitted when the name comes from content or the role takes none), and optional `keyboard` (array of `{ "key", "does" }`). Key names are W3C UI Events `key` values, with `Space` for the space bar. `keyboard` describes the control in its `role`; a host that presents it in one of its `alternateRoles` follows the keyboard conventions of that role instead. Declared here so accessibility does not depend on each renderer. | controls | | `implementations` | Array of `{ "adapter", "module", "digest" }` (all required) naming shipped implementations per adapter (`web`, `skia`, `native-ios`, `mcp`, `http`, and so on). `digest` is the digest of the module's bytes (core.md section 16). The host fetches a module and checks its digest when it installs the app; that is not egress (core.md section 6.3). Empty means descriptor-only: the host supplies its own. | no | | `requires` | Array of `{ "contract", "scopes" }`: capabilities and scopes the part itself needs in order to work. `contract` is a contract name in the same catalog, or `alias:contractName` for a contract in a catalog this catalog uses (section 1). A definition using the part MUST request grants that cover these, so a part can never quietly widen an app's permissions. | no | | `distribution` | `license` (SPDX), optional `pricing` (`{ "model": "free" \| "paid" \| "metered", "terms": uri }`, with `terms` required unless the model is `free`), optional `provenance` (`{ "source": uri, "build": uri }`, with `build` optional). | no | | `conformance` | Array of `{ "suite", "version", "result": "pass" \| "partial", "report": uri }` referencing conformance suite results. `report` is optional. | no | Compatibility within a catalog follows semver on the catalog version: within a major version, a contract MAY gain optional props, optional operation inputs, events and operations. Anything else is breaking. ## 3. Control interface ```json "interface": { "props": { "value": { "type": "number", "description": "Current amount.", "bindable": false }, "max": { "type": "number", "description": "Target amount.", "default": 100 }, "label": { "type": "string", "description": "Accessible name and visible caption." } }, "events": { "press": { "description": "The user activated the control.", "payload": {} } }, "outputs": { "valid": { "type": "boolean", "description": "Whether every input inside currently meets its constraints." } }, "slots": { "item": { "description": "Template for one row.", "scope": { "item": "any", "index": "integer" }, "required": true } }, "children": "none" } ``` All of `props`, `outputs`, `events` and `slots` are optional. - `props` is a field map (core.md section 3.3) with two extra per-field keys. `bindable` (default `false`) marks a prop that may appear in a node's `bind` for a two-way binding; a bound prop counts as supplied when it is required. `remote` (default `false`) marks a prop whose value can make the host fetch from the network, such as an image address; such props fall under the egress rule of core.md section 6.3. A value in such a prop, or a string inside it, MAY instead be `asset:` followed by the name of an asset the definition carries (core.md section 12.5), which the host loads from the definition itself: no fetch, and no grant. - `outputs` is a field map of values the control produces and the app can only read, such as a form's validity. An output MUST NOT share a name with a prop. A node receives one by naming it in `bind`; the host writes the bound state. Only `type` and `description` are meaningful on an output. - `events` maps an event name to a description and a `payload` field map. - `slots` maps a slot name to a description, the `scope` variables the slot's template can read (name to type reference), and `required` (default `false`). A slot without `scope` variables is not a template repeated over data but one node, filled once: it reads what a child at the same place would (state, view state and the names around its node), and its handlers run as any handler does. The host fills such a slot for every control that declares one. - **The `actions` convention.** A control that draws a header of its own (a title line above its content) declares what a person can do with that one control as an optional slot named `actions`, without `scope` variables, which the host draws at the end of the header. A control that gains a header later takes the same slot under the same name, so that authors and models find it in the same place. In the core catalog `group`, `chart`, `table`, `list`, `canvas` and `diagram` have it, and `alert` has it for what to do about what it says (section 8.3). - `children` is `none` (the default), `one` or `many`. - Common props every control accepts without declaring them: `variant` (string, a design-system variant name), `hidden` (boolean) and `disabled` (boolean). Section 8.2 says what `hidden` and `disabled` do. ## 4. Capability interface ```json "interface": { "config": { "accountKind": { "type": "string", "description": "Which kind of account to read.", "required": false } }, "operations": { "listTransactions": { "description": "List transactions, newest first.", "input": { "since": { "type": "date", "required": false } }, "output": "Transaction[]", "scope": "transactions.read", "effect": "read" } }, "events": { "transactionPosted": { "description": "A new transaction appeared.", "payload": { "transaction": { "type": "Transaction" } }, "scope": "transactions.read" } }, "scopes": { "transactions.read": { "description": "Read your transactions.", "sensitivity": "high" } }, "traits": [] } ``` - `operations.` has `description`, optional `input` (field map), optional `output` (type reference), `scope` (the scope a grant must include to call it), `effect`, optional `interactive` and optional `paging`. `effect` is `read` (no outside change, safe to retry), `write` (changes data the capability manages), or `external` (acts in the world: sends, pays, publishes). `interactive: true` marks an operation that asks the person for something, such as picking a file or taking a photo; it cannot be a state `source`. It is asked of the acting principal's person, on a surface of theirs that is active; with none, the call fails with `capability.unavailable`. The host carries it out in its own interface, which says which app is asking and, when an agent started the work, that an agent did. Nothing reaches the app unless the person completes it, and a host never completes one for them. - A `write` or `external` operation receives the `once` key of a call that gives one (core.md section 8.3). A provider that can recognize a repeated effect SHOULD perform the effect once per key and answer a repeat as it answered the first call. - `paging` declares that an operation returns its results in pages: `{ "cursor": inputField, "next": outputField, "items": outputField }`. `cursor` names an optional string input field that asks for the page after a given one, `next` names an output field that holds the cursor for the following page or `null` when there is none, and `items` names the output field that holds the page's list. The output MUST be a map type that declares both fields, the field `items` names MUST be a list, and `cursor` MUST name an optional input field of type `string` or `string?`; anything else is `contract.invalidPaging`. A caller follows the pages while `next` is present and not `null`. A state source can follow the pages (core.md section 7.1). - `events.` has `description`, `payload` (field map) and `scope`. A grant condition written for the operations of a scope is applied to the payload of events under the same scope (core.md section 6), so an event SHOULD carry, under the same names, the fields those operations take as filters. An event that lacks them is withheld from every app whose grant is narrowed by them. - `scopes.` has a plain-language `description`, shown to approvers, `sensitivity` of `low`, `medium` or `high`, and optional `consent`. Hosts SHOULD require stronger confirmation for higher sensitivity. - `consent` is `asked` (the default) or `use`. `use` marks a scope as **given by use**: nothing happens under it unless a person does it themselves at that moment in the host's own interface, or has already handed the app the thing acted on. A request whose scopes are all given by use is not put to anyone; the person's own act each time is the consent (core.md section 6). A contract makes this promise for every operation under the scope, and three parts of it are checked (`contract.invalidConsent`): a capability with the `background` or `egress` trait has no scope given by use, since what those traits permit follows from holding a grant and not from anything a person does; no event has a scope given by use; and an operation under one that is not `interactive` has `effect: "read"`. Such a `read` operation reads only what a person gave the app through the host, such as the contents of a file they chose, and its description says so. A host honours the mark only from a catalog it trusts to make the promise, and treats the scope as `asked` otherwise (core.md section 6). - `traits` is an array of strings that mark cross-cutting properties. The set is closed in 0.2: `background` (holding a grant on this capability permits unattended execution: timers, rules and source refreshes that run with no active surface), `offline` (operations work without a network and are queued or served locally by the provider), `multiUser` (the provider can supply identity and roles for more than one principal), `egress` (the capability's config names one network origin in a field called `origin`, and a grant on it permits the host to fetch `remote` content from that origin, per core.md section 6.3), and `personal` (the provider acts for one person: their device, their accounts, their files; a grant on it is answered by each person for themselves and covers only what is done on their behalf, per core.md section 6.4.2). - Only operations with `effect: "read"` that are not `interactive` MAY be used as a state `source`. - An operation has exactly one scope. Where a permission should depend on an input value, use one scope and let the definition's grant narrow it with `where`. ## 5. Capability identity and equivalent providers A definition references a capability by **contract** (`alias:name` within a catalog `id` and version range). A **provider** is an implementation of that contract registered with a host under a provider id. Two providers that implement the same contract are equivalent as far as the definition is concerned. When several providers match, the host chooses. The choice SHOULD follow, in order: an explicit user choice, host or organization policy, the definition's `prefer` list, and then a host default. Hosts MUST show which provider is bound, and SHOULD disclose when a paid provider was selected and why. **Paid parts.** A part is paid when its `distribution.pricing.model` is `paid` or `metered`. An AI selecting parts on a person's behalf MUST NOT bind a paid capability provider, or use a control whose implementation is paid, without the approver seeing its pricing terms. A host shows those terms in the review the approver answers, beside the grant requests. ## 6. Design systems A design system is a JSON document (`*.oaddesign.json`): ```json { "oadDesign": "0.2", "id": "com.example.brand", "version": "2.0.0", "meta": { "name": "Example Brand", "description": "House style." }, "tokens": { "color": { "surface": "#ffffff", "text": "#1f1f1f", "textMuted": "#5f6368", "outline": "#747775", "accent": "#0b57d0", "onAccent": "#ffffff", "neutral": "#5f6368", "info": "#0b57d0", "success": "#146c2e", "warning": "#8a5300", "danger": "#b3261e", "category1": "#0b57d0", "category2": "#b3261e", "category3": "#146c2e", "category4": "#8a5300", "category5": "#6b3fa0", "category6": "#00687a", "category7": "#a8326b", "category8": "#5f6368" }, "space": { "small": 4, "medium": 12, "large": 24 }, "type": { "body": { "family": "Inter", "size": 16, "weight": 400 }, "title": { "family": "Inter", "size": 24, "weight": 600 } }, "radius": { "medium": 8 }, "motion": { "quick": 120 }, "shadow": { "low": { "offset": 1, "blur": 3, "opacity": 0.14 } } }, "modes": { "dark": { "color": { "surface": "#121212", "text": "#f1f1f1" } } }, "variants": { "org.openappdefinition.core:button": { "primary": { "emphasis": "high" }, "quiet": { "emphasis": "low" } } }, "catalogs": [ { "id": "com.example.brand-controls", "version": "^1.0.0" } ], "agent": { "toolNaming": "camelCase", "errorStyle": "Say what failed and what to try next." } } ``` - `meta` has `name` and `description` (both required) and optional `publisher` and `license`. - `tokens` groups named values. Token group names in 0.2: `color`, `space`, `type`, `radius`, `motion`, `shadow`. Renderers map token names onto their own styling. - `color` values are `#rrggbb` or `#rrggbbaa`. - `space` and `radius` values are non-negative numbers in density-independent units (one unit is a CSS pixel at standard density). - `type` values are `{ "family", "size", "weight" }` with optional `lineHeight`. `family` is a font family name or one of the generic names `system-ui`, `serif`, `sans-serif` and `monospace`; `size` is in the same units as `space`; `weight` is an integer from 1 to 1000; `lineHeight` is a multiple of `size`. - `motion` values are durations in milliseconds, as numbers. - `shadow` values are `{ "offset", "blur", "opacity" }`: how far down a shadow falls and how soft its edge is (the blur radius, as a CSS box shadow's), both in the same units as `space`, and how opaque it is at its darkest, from 0 to 1. The names a canvas uses are `low`, `medium` and `high` (section 8.3); a design system that defines none of them has the default design system's values, and a mode MAY change them, as a dark mode does to keep a shadow as visible on a dark ground. A shadow is drawn in the design's ink, its `text` color, at that opacity; in a mode whose `text` is lighter than its `surface`, a shadow in that color would read as a glow, so it is drawn in black. - `modes` optionally maps a mode name to a partial `tokens` object that overrides the base tokens while that mode is active. `dark` and `highContrast` are the well-known mode names; others are allowed, and a host ignores modes it does not offer. A mode MUST NOT introduce a token the base does not define. - Definitions and catalogs refer to colors by token name, so portability needs a common minimum. Every design system MUST define these `color` tokens: `surface`, `text`, `textMuted`, `outline`, `accent`, `onAccent`, the tones `neutral`, `info`, `success`, `warning` and `danger`, and `category1` to `category8` for data series. It MUST define the `space` tokens `small`, `medium` and `large`. A host that meets an unknown token name uses its nearest default and reports the node as `degraded`. Text, tone and accent colors SHOULD reach a contrast ratio of at least 4.5:1 against the surface colors in every mode. Where a data-series color falls below 3:1 against its surface, hosts SHOULD keep labels or a tabular view of the same data available. - `variants` maps a fully qualified control (`catalogId:contractName`) to named prop presets. A node selects one with the common `variant` prop. Presets MAY set only props the contract declares. The variants of the core catalog's default design system are listed in `catalogs/core/README.md`. - `catalogs` lists catalogs of custom controls that belong to the design system. - `agent` holds conventions for agent surfaces generated under this design system. - A design system MAY restyle and preset any control. It MUST NOT alter a contract's interface, accessibility role or required grants. ## 7. Trust and distribution - **Digest.** As in core.md section 16, over the canonical JSON of the catalog, design system or definition. The digest of a definition leaves out the `data` of its assets and its `included`, so a signature over it says nothing about the definition's carried copies unless the definition's reference pins their digest (a reference of `uses.design` pins none). What stands for the same app as before is the app's digest together with the digests of the parts it resolved (core.md section 6.4.1). - **Signature sidecar.** A file beside the document, named after the document's file name with its final `.json` replaced by `.sig.json` (`com.example.brand.oaddesign.json` is signed by `com.example.brand.oaddesign.sig.json`), holds `{ "oadSignature": "0.2", "digest", "signatures": [ { "keyId", "algorithm", "value", "signedAt", "signer" } ] }`. `algorithm` is `ed25519` in 0.2. The signed message is the UTF-8 bytes of the `digest` string, and `value` is the signature in unpadded base64url. `signedAt` is a UTC `datetime` written with `Z`. `signer` is a reverse-DNS identity that SHOULD match or be a parent of the document `id`. How hosts establish trust in keys (pinned keys, an organization root, a public registry) is host policy and outside 0.2. - **Load policy.** A host MUST verify digests wherever a definition pins one. A host SHOULD verify signatures of catalogs that ship executable `implementations`, and MUST treat executable implementations from unsigned or untrusted catalogs as untrusted code. - **Listing and certification.** Passing the conformance suite is recorded in `conformance`. Whether a registry requires it for listing is registry policy. ## 8. Control behaviour This section settles behaviour that a control's props and events do not show on their own. Sections 8.1 and 8.2 apply to every control; section 8.3 to controls of the core catalog, whose descriptions in the catalog say the same. A **renderer** is the part of a host that draws controls and takes the person's input. ### 8.1 Events and values - A host raises a control's events only for something the person did, or where this section says so. - A renderer identifies what the person picked by position or key, and the host supplies the rest of the payload from the control's current props. In the `select` event of a list, table or chart, `item` is the element of the `items` prop at that position, exactly as the app passed it, so a handler can read any field of it; its type is the element type of the value given to `items`. Payload fields that the host supplies are ignored if a renderer sends them. - A value from the person that the control's own props rule out is not written and raises no event: a number outside a slider's `min` and `max`, or an option that is not among `options`. A `slider` or `numberInput` refuses a value that is not `min` plus a whole number of steps, as it refuses one outside `min` and `max`. A `fileInput` refuses a file whose kind its `accept` prop excludes. - A text input writes its binding and raises `change` at least when the person pauses or leaves the field; a host MAY do so at every keystroke. - A choice option's `value` is a string, a number or a boolean. The bound value has the type of the option picked, and options are compared with `==` (`expressions.md`). - Controls that show numbers take a `NumberFormat` (`plain`, `currency` or `percent`) and, for `currency`, a currency code, which defaults to `env.currency`. With no code and `env.currency` `null`, a currency value is shown as a plain number. `progress` takes a `format`, and each chart series MAY take a `format` of its own, which overrides the chart's. - A date input's `value`, `min` and `max` take the form its `mode` sets: `YYYY-MM-DD` for `date`, the canonical UTC datetime `YYYY-MM-DDTHH:MM:SSZ` for `datetime`, and `HH:MM` on a 24-hour clock, with no date or zone, for `time`. A state entry of type `date` or `datetime` can be bound to it in those modes. - A prop that names a design token, such as a chart series `color`, a canvas shape's `fill` and `stroke`, a canvas `background`, or a choice option's `swatch`, takes a token name. An unknown name falls back to the host's nearest default, and the node is reported as `degraded` (section 6). ### 8.2 Presence: `when`, `hidden` and `disabled` - A node whose `when` is not true does not exist: it is not drawn, raises no events, writes no outputs, loads nothing, and counts toward no form. What the host held for it, such as the text in an unbound input, is discarded. - A node with `hidden: true` keeps its place and whatever the host holds for it, but it is not drawn or announced, loads nothing remote, raises no events, and its inputs count toward no form. Its children and slots are hidden with it. - A node with `disabled: true`, and every node inside it, is shown as unavailable and raises no events from the person, and its inputs count toward no form. A node inside cannot undo this with `disabled: false`. - When a canvas stops raising events while a key it reported pressed is still down, because its `when` is no longer true, it is hidden or disabled, or a dialog makes it unavailable, the host itself raises that key's release at it once, as the node was when it last raised events, with any confirmation the handler asks for answered no and any navigation it makes ignored. - A node repeated with `each` counts as one node per element wherever controls count nodes: each is a panel of `tabs` and an input of a form. #### 8.2.1 Direction and text - A host lays out an app in the direction of the language the app is shown in, and takes it from nothing else: never from the page or window around the app. An app shown in no language of its own is laid out as the page around it is. - A host gives a session the person's languages, in order of preference as the platform gives them, and the language the person chose for the app and the host kept, if any (`core.md` section 12.7). With no list of languages, the person's languages are the one locale the host gives. A kept choice that is not one of the app's own language tags is ignored. Either may change while the app runs: `env.language`, `env.direction` and `env.locale` then change like any other `env` field, and the app keeps its state, the person's place in it, typed text and open dialogs. - What a renderer is told about language, with what it draws: the app's shown language (none for an app without `localization`) and its direction; for an app with `localization`, the locale the app's formats use, so that numbers and dates the host formats agree with the app's words; and the app's own language tags when it carries more than one, which a language switch offers. Each follows a change of the person's languages or of the kept choice. - For each text of a node whose language the host knows, a renderer is told the direction of that language, and the same for a view's title. A text the definition writes as a plain literal is in the default language; a text written as exactly one `t()` call is in the language of the table its entry comes from, so a text that falls back to the default language inside a right-to-left app reads left to right. Any other text (one joined in an expression, a value read from state or typed by the person) has no known language. A node made from a template is judged by the template as the definition writes it. An app without `localization` has no text of known language. - Where a part is shown in another language or direction than the app around it, the renderer is told the part's language and direction for the region of the part. - The host's own sheets, dialogs and notices keep the direction of the host's own words, whatever the app's. - A host that shows an app with more than one language offers the person, in its own interface around the app, the choice among the app's own languages, or to follow the person's own languages. It names each language in that language itself, and keeps the choice for that app on that device. - Alignment follows the app: a text sits at the start edge of the app's direction. The order inside one text follows the text: the direction of its language when the host knows it, else the direction of its first strong character, else left to right. A text in another direction than the app's keeps its place and reads in its own order. - The host's own words inside the app (the pages of a table, the amount of a progress bar, a problem with an input) read in their own direction, apart from the app's. App text inside a sentence of the host is held apart from the host's words, so neither can reorder the other. A number, an amount or a date the host formats is kept in one piece: a sign, a currency symbol or a percent sign never parts from its digits. - An empty text field takes the app's direction and typed text its own. A telephone number, an email address, a web address and a number read left to right in an app of either direction. - What a host removes from app text before showing it depends on where the text goes: - Text the host shows in an element of its own keeps U+200C ZERO WIDTH NON-JOINER and U+200D ZERO WIDTH JOINER, which Persian spelling and joined emoji need; the marks U+200E, U+200F and U+061C; and the isolates U+2066 to U+2069 that are balanced on their line once the text is shortened. It loses the embeddings and overrides U+202A to U+202E, an isolate without its partner, U+200B, U+2060 to U+2065 and U+FEFF. Other control characters become spaces. - Text the host puts into a string (an accessible name, a title, a line it writes as text), an identifier or an address the host shows on a sheet of its own, and a value a person approves or reads back (a confirmation, a record of what was done), keeps the two joiners and loses the marks and the isolates as well. A mark could show the parts of a value, such as the groups of a telephone number, in another order than the value has, and the person would approve what they did not read. ### 8.3 Core controls - **dialog.** Only the app opens a dialog, by making `open` true; the person cannot. When the person dismisses it, the host raises `dismiss` and, when `open` is bound, writes `false`. When `open` is not bound, the dialog stays open until the app makes `open` false, usually in its `dismiss` handler. A host MAY draw a dialog inside the app's own region rather than above everything on the screen; either way the rest of the view is unavailable while it is open. - **form.** An input counts toward the innermost form that contains it, through children and slots, and only while it is present, not hidden and not disabled. Inputs inside an embedded part view do not count toward the parent's forms. A `required` text input holding only white space counts as empty. The checks for `kind` (email, phone, url) are the host's and SHOULD accept any value a person could reasonably mean. When the person submits while some input is not acceptable, the host shows the problems at the inputs and does not raise `submit`; `valid` reports the state at all times. - **list.** A list **takes part** in moving items when it handles `move`, a person may act on it (it is present, not hidden, not disabled, and not behind an open dialog), and it has a `moveGroup`, is `reorderable`, or both. Lists that take part, share a `moveGroup` and are on the same view take items from each other; the same view is one visit of a view, or one part view embedded in it, as it is drawn at that moment, so the lists inside an open dialog move items only among themselves, and a list in a tab that is not selected, or whose `when` is not true, takes no part. A reorderable list also lets a person put an item of it at a place of their choosing; one with no `moveGroup` moves its items only within itself. The host carries out the whole gesture and tells the app once, when the person lets an item go on another list of its group or at another place of a reorderable list, or picks that move among the moves the host offers from the item: it raises `move` on the list the item lands in, whose handler reads that list's names, with `item` the element of the `items` of the list the item came from, exactly as the app passed it there. Its value is computed from what that list was given (core.md section 7.3). When the list the item lands in is reorderable, the event also carries `index`, the place the item takes among that list's items in the new order, counted from 0, and `order`, the `itemKey` of every item of that list in the new order, the moved item among them, each exactly as it is in the item, or `null` for an item whose key is missing or is not a short string, a number or a boolean; both are `null` when that list is not reorderable. Nothing is raised for the list the item is already in, unless that list is reorderable and the item's place in it changes. Where in a list that is not reorderable an item is let go means nothing, also when it comes from a reorderable list: the app orders its lists. A reorderable list shows its items in the order the app passes them, so its handler keeps the order the event gives, as `state.goals.sortBy(g, indexOf(event.order, g.id))` does. A host MUST offer, from each item of a list that takes part, a way to move it to each other list of its group that needs no dragging, naming each list by its `label`, or by `List` followed by its position among the lists of its group, counted from 1, when it has none. For a reorderable list it MUST also offer, from each item that can move, a way without dragging to put it one place earlier and one place later, and SHOULD offer the first and the last place; an item sent by such a way to another list of its group that is reorderable takes the first place there. These ways are how a host meets success criterion 2.5.7 of WCAG 2.2, Dragging Movements, which keyboard use alone does not. A host MAY leave out dragging, and offers those ways alone; it MUST NOT leave them out. A host that lets the person drag an item onto a reorderable list shows where the item will stand there before it is let go. A host with no pointer, such as a voice or a text host, offers the same moves in its own manner. A renderer names the item by the identity the host gives it, its `itemKey`, and, for a reorderable list, the place by its position among that list's items as they are without the item, from 0 up to their number; the host finds the item in the list it comes from as that list is when the move arrives, so a move that arrives after the app's state changed moves the item the person picked or none, and a place beyond the end of the list as it is then is its end. An item with no key of its own, or one that repeats another's, cannot be moved; other items can be put before or after it. Until the app has answered, the host MAY show the item as on its way; what the app's next tree says is what is shown after. - **table.** With `complete` true the host sorts and pages `items` itself. It orders numbers by size and text without regard to case, puts missing and `null` values last, keeps ties in their original order, and returns to page 1 after sorting. With no `pageSize`, a table of more than 100 rows is shown 50 at a time, and a table of 100 or fewer is not paged. With `complete` false, `items` is the current page in display order: the host shows it as given, neither sorts nor slices it, and raises `sort` and `page` for the app to answer; `pageSize` and `total` tell it how many pages to offer, and without `total` it offers a next page while the current one is full. `selected` holds the keys (values of `itemKey`) of the selected rows. When the person picks a row, the host works out the new selection, writes it when `selected` is bound, and raises `select` with the row and the new `selected`; in single selection, picking the selected row again unpicks it. A host that lets people select rows presents the table in the `grid` role. A column whose `format` is `custom` is drawn with the `cell` slot, and without one its value is shown as text. - **tabs.** Panels are counted as drawn, after `when` and `each`. A panel's caption is the child's accessible label: a group's `title`, an embedded part view's title, and otherwise `Tab` followed by its position counted from 1. - **link.** `link` declares the event `activate`, with payload `{}`, raised when the person follows it. For a `view` link the host opens the view with `input` as a `navigate` step would; for a `url` link it shows the destination before leaving the app. - **canvas.** Positions in a scene and in `pointer` events are fractions of the canvas: `x` of its width from the left edge, `y` of its height from the top. Lengths that do not follow one axis (a radius, a stroke width, a text size) are fractions of the width, so hit testing uses `aspect`. `target` is the `id` of the topmost shape with an `id` under the pointer, or `null`. The keys listed in `keys` reach the app while the canvas has the focus; when a canvas that takes keys leaves the drawing while it has the focus and another canvas that takes keys is drawn after it, in its place or in the view shown next, a host SHOULD give that canvas the focus, so that the keyboard stays with the app without a press. A host MUST NOT take the focus from outside its own document for it, such as from the page around the frame the app is drawn in. When a canvas stops taking events while a key it reported pressed is still down (its surface loses the focus, or the canvas leaves the view, is hidden, is disabled, or a dialog is opened over it), the app hears that key's release then, and not again when the key is let go; a release with no press before it is not reported. A `path` is one line through its `points` in order, and a path of one point is a round dot as wide as the line; `closed` joins the last point to the first, a `fill` fills the inside as if it did (by the nonzero rule where the line crosses itself), and with a `fill` the line is drawn only when `stroke` is given. The segment that ends at a point is straight, a quadratic curve when the point also has `cx` and `cy`, or a cubic curve when it has `c1x`, `c1y`, `c2x` and `c2y` (which win over `cx` and `cy`); the first point's control points bend the closing segment of a closed path and mean nothing otherwise, and a path that bends holds a fill with two points. A curved point counts as one point. An element of `points` that is not an object with two finite numbers `x` and `y` is passed over, and a point whose control fields make neither curve is drawn straight; for each the node is reported as degraded, saying how many. A path is under the pointer on its line, with the reach of a `line`, and inside its fill. A `rect`'s `radius` rounds its corners, never by more than half its shorter side, and the rounded corner is under the pointer only inside its curve. An `ellipse` is a circle stretched to `radiusX` and `radiusY`, both fractions of the width, turned by `rotation`. An `arc` is the part of the circle of `radius` around `x`, `y` from `from` to `to`, in degrees clockwise from pointing right: the part it covers is `to - from`, nothing when that is 0 or less and the whole circle when it is 360 or more. It is drawn as a line, under the pointer with the reach of a `line`; with a `fill` it is the wedge between the arc and the center, filled, its outline drawn only when `stroke` is given, and under the pointer inside it. Every shape with a line takes `dash` (`solid`, `dashed`: dashes three widths long with gaps of two, `dotted`: dots one width long with gaps of one, measured with the ends) and `cap` (`round`, `flat`, `square`), and a `rect`, a `path` and an `arc` take `join` (`round`, `sharp`, `bevel`). What a shape leaves out is drawn as before these fields: a `line`, a `path` and an `arc` have round ends, the others flat ones; a `path` and an `arc` have round corners, a `rect` sharp ones; every line is solid. A `text` takes `weight`: `body`, the default, or `emphasis`, the weights of the design's type styles of those names (400 and 600 when the design has none). The `fill` of a `rect`, `circle`, `ellipse`, `arc`, `path` or `text` may be, instead of a color name, a gradient `{ "gradient": "linear" | "radial", "stops": [...], "angle": degrees }` that runs through two to eight stops across the shape's own box: the box of a `rect`, a `circle` and an `ellipse`, turned with the shape; the box of an `arc`'s whole circle; the box around a `path`'s line; and for a `text` its drawn width by its `size`. A `linear` gradient runs along `angle` in degrees clockwise (0 from left to right, 90, the default, from top to bottom), from corner to corner of the box, so that its first and its last stop each touch it; a `radial` one runs from the middle of the box out to its farthest edge, as a circle. A stop is a color name (inside a symbol, `given` takes the placement's color, as a plain fill does) or `{ "color", "opacity", "at" }`, `opacity` and `at` from 0 to 1; stops without `at` are spread evenly between the stops around them that have one, the first at 0 and the last at 1, and a stop never sits before the one ahead of it. A gradient names no color codes and no pixel positions. A stroke is one color. Every shape, `group` and `use` takes `shadow`: `low`, `medium` or `high`, how far it seems lifted, drawn with the design system's `shadow` token of that name in the mode the scene is drawn in (section 6): the shadow falls `offset` down, blurred by `blur`, in the design's ink at `opacity`, both measured in the design's units whatever the scale or the turn of the groups around it. A shape with a fill casts it from its fill, one without from its line, and a `group` or a `use` casts one shadow from everything it holds. A shadow never moves anything and never changes what is under the pointer. A `group` draws its `shapes` in a space of its own: positions are measured from the group's `x` and `y`, both axes in fractions of the width (the one place where `y` is not a fraction of the height), every position and size is multiplied by `scale` (default 1, line widths and text sizes included), the whole is turned by `rotation` degrees clockwise around the group's `x`, `y`, and `opacity` multiplies with each shape's own. The canvas prop `symbols` maps a name to a list of shapes in that space, and a `use` shape places the symbol it names (`symbol`) as a group of its `x`, `y`, `scale`, `rotation` and `opacity` would; a shape of a symbol whose `fill` or `stroke` is `given` is drawn in the `use`'s `color`, or in the color that field has by default when the `use` gives none, and inside a symbol a `use` whose `color` is `given` passes on its placement's. Groups and placements nest at most 4 deep together: a group or `use` inside four others is not drawn. A `use` of a name the symbols do not hold, and one inside a symbol that places that symbol again, directly or through other symbols (the two are in one circle of what places what), is not drawn. For each the node is reported as degraded, saying how many. A pointer on a shape inside a group or a placement is on the outermost group or `use` with an `id` that holds it, or on the shape itself when none has one; the topmost drawn thing still wins, and a group drawn fully transparent is not under the pointer. A host draws at most 5000 shapes and 50000 path points in all, counted in drawing order and each as often as it is drawn (a group and a placement count as one shape each, and what they hold counts again for every placement), a path that crosses the limit up to it; what lies beyond is not drawn, and the node is reported as degraded, saying how many shapes and path points were left out. A presenter that passes on a scene cut at the limit writes the placement it cuts as a group of the same place, size, turn, opacity and shadow, its `given` colors written out. The canvas prop `motion`, and a shape's own `motion` that overrides it, say how a shape that stays in the scene when it changes gets from its old values to its new ones. A shape stays when the new scene has a shape of the same `kind` with its `id` at the same level (the scene, or the shapes of the same group with an `id`, through groups without one); of two with one `id` the first is matched, and a shape without an `id` never moves smoothly. `none`, the default, changes it at once; the name of a motion token of the design moves it over that long, eased so that it starts fast and settles; `{ "over": duration, "ease": "smooth" | "linear" }` over an ISO 8601 duration of hours, minutes and seconds, at most `PT5S` (a longer one is drawn over five seconds and the node reported as degraded). Every number that places or sizes the shape moves (`x`, `y`, `x2`, `y2`, `width`, `height`, `r`, `radius`, `radiusX`, `radiusY`, `from`, `to`, `rotation` the shorter way round, `scale`, `opacity`, `strokeWidth`, `size`), and the points of a path whose number of points stays the same; everything else changes at once. A shape that appears or goes does so at once, and a change while a shape moves starts from where it is drawn. The host is the clock: the app is told nothing of frames, and a `pointer` event reports shapes where the scene puts them. Where the person asks for reduced motion, or the canvas is not shown, every change is drawn at once; once a motion ends the canvas shows exactly what it would without it. Motion, gradients and shadows are the parts of a scene a host MAY leave out, and it then draws something plain and correct: each change at once, a gradient's shape filled with the color of its first stop at that stop's opacity, and no shadow. Groups and symbols every host MUST draw. In a scene, only the `source` of an `image` shape can cause a fetch, and it is the address the egress rule applies to (core.md section 6.3), in the scene and in `symbols` alike. The canvas's `tools` slot holds the drawing's tools (choices drawn as palettes and icon-only buttons) and their settings (any other control, such as a slider for a pen size); its title, its actions, its tools and their settings are drawn outside the surface, so they never change the positions a `pointer` event carries. Every color a scene names, and its `background`, is drawn in the values of the mode the page around it is drawn in, as every other control's colors are, and follows a change of that mode while the app is open; with `mode` (`light` or `dark`) the scene keeps that mode's values whatever the page's, its base values when the design system lacks that mode. A palette among its tools shows each color as the scene draws it. Its title, actions, tools and settings follow the page. A canvas is never mirrored: in an app read from right to left a scene draws the same picture, and positions, `pointer` events and keys are as above. Each `text` is ordered by its own first strong character, and its `align` is physical: `start` is the left end and `end` the right end of the text in every language. A canvas that has drawn a scene in this visit of its view and whose node is then the host's placeholder (its `scene` or another required prop has no value, because its expression failed or the value does not fit; core.md section 17) SHOULD keep showing the last picture it drew, at its size and in the same place, for a short time (a few seconds at most), so an animation whose scene fails on some frames stutters instead of flashing a placeholder and moving what is around it. When the node is a canvas again within that time, it draws from that node in the same place; when it is not, the placeholder is shown. Meanwhile the kept picture raises no events, as the placeholder raises none, and the host tells assistive technology once, in the placeholder's words, that the part cannot be shown, not at each frame, and does not announce the picture's return. The tree still holds the placeholder, and whatever reads the tree reports it. A canvas that has not drawn in this visit shows the placeholder. - **chart.** A `unit`, the chart's or a series' own, which overrides it, is shown after each plain number exactly as written: a host neither translates it nor makes it plural, and the number keeps the person's notation. A value whose format is `currency` or `percent` is shown without it, and the host reports a view diagnostic. `categoryLabel` and `valueLabel` say what the axes show (for `scatter` the category axis is the horizontal number); a `pie` has no axes, so they are only read aloud and head the columns of the data's table. `orientation: "horizontal"` applies to `bar`, stacked or not: the categories run down the side with the first at the top, and the values along the bottom. A host MAY draw only the first categories of a long horizontal chart when it says so to the person and in a view diagnostic, and the data's table holds them all. A `goal` of a `bar`, `line` or `area` chart is drawn across the plot at its value, which the value axis always includes; in a stacked chart it is compared with the whole stack. `orientation` with another kind, and `goal` with `pie` or `scatter`, are ignored with a view diagnostic. The unit, what the axes show and the goal are part of what assistive technology and a voice surface are told. The plot (its axes, its marks, the way bars grow and the turn of a pie) is drawn left to right in every language and never mirrored, and each text drawn in it keeps the order of its own words; the chart's title, actions, legend and data table follow the direction of the app. - **diagram.** A diagram keeps its layout in every language: in an app read from right to left its boxes, groups and connections stand where they would in one read from left to right, and each text on it keeps the order of its own words. A symbol that stands before a box's words, such as a `person` box's, stands before them as the app reads. - **choice.** When every option has a `swatch`, or every option has an `icon` the host draws, and there are at most 12, the host draws the choice as a palette of color dots or symbol buttons, one picked. It stays one radio group named by `label`: one stop for the keyboard, arrow keys move and pick, and each option is named by its `label`, its `description` read with it. An option's symbol or color the host shows in another form is shown before its label. `multiChoice` does not draw them. `required` concerns a form, so a host shows no words saying an input is required when it is in no form. - **icon.** Every host draws a symbol for each name of the icon vocabulary (section 1). An icon whose `name` the host does not know shows no symbol; its `label`, if any, is still given to assistive technology. - **actions.** The `actions` slot of `group`, `chart`, `table`, `list`, `canvas` and `diagram` is drawn on the line of the control's title (a group's `title`, the others' `label`; a `table`, `list` or `canvas` that has actions shows its `label` as that title), at its trailing end, or under the title when the line has no room for both. An `alert` draws its actions after its message, apart from its control to dismiss it. Assistive technology meets them after the title and before the content, as the control's own. A surface without a visual form offers them by their labels after the control's summary. - **button.** With `iconOnly` true and an `icon` the host draws the icon alone; the `label` stays the accessible name and is shown when the pointer rests on the button or keyboard focus is on it. Without an `icon` it draws the label (`prop.iconOnlyWithoutIcon`). While the handler of a press has not finished, the host does not raise `press` again from the same button, and after a short wait shows that the button is working, without changing its size; a form's submit action behaves the same. A label that does not fit the button's place wraps onto more lines. - **text.** `format` is `plain` (the default) or `markdown`. A plain text shows its `value` as it is. A markdown text reads the subset of Markdown below, the same on every host, and shows everything else as the characters it is. `style` sets the size and weight of ordinary text in both formats. **Lines and blocks.** The value is split into lines at `\n`, `\r\n` and `\r`; a tab at the start of a line counts as spaces to the next multiple of four. A line of only spaces is blank. A line indented by four spaces or more starts no block. Blocks are read in the order below; a paragraph is the default. | Construct | Written | Shown | | --- | --- | --- | | Paragraph | `Lines of words`, ending at a blank line or at a line that starts another block | A paragraph. Each line break inside it is kept as a line break. Spaces at the start and end of each line are dropped. | | Heading | `# Title`, `## Part`, `### Detail`: one to six `#`, then a space or the end of the line | A heading of level 1, 2 or 3; four to six `#` are level 3. A closing run of `#` after a space is dropped. `#tag` with no space is a paragraph. | | Rule | `---`, `***` or `___`: three or more of one of these, with spaces between them or not, alone on the line | A horizontal rule. Under a paragraph it is a rule, never a heading. | | Quotation | `> Words`: lines that start with `>`; one space after it is dropped | A quotation holding the blocks read from those lines. It ends at the first line that does not start with `>`. | | List | `- one`, `* one`, or `1. one` (up to nine digits and a `.`), then a space or the end of the line | A list; numbered lists start at the first item's number. An item holds its first line and the lines after it indented by at least two spaces, or to the column of its text, read as blocks; a blank line inside it is kept when the next line is indented so. The next item of the same marker (`-`, `*`, or a number) continues the list, also after blank lines; another marker starts another list. A list inside an item is drawn one level in; a list inside that, and deeper, is drawn at that second level, its items following the item they were in. A numbered item ends a paragraph only when it is numbered 1, and an item with no text never does. | | Block of code | ` ``` ` or more backticks, a language word after them allowed and ignored, then the lines up to a line of at least as many backticks | The lines exactly as written, in a monospaced face, read from left to right. Without a closing line, the block runs to the end of the text. | | Table | A row with `\|`, followed by a row of cells of dashes, each with an optional `:` at either end, with the same number of cells: `\| Name \| Cost \|` then `\| --- \| ---: \|`; then rows up to a blank line or a line without `\|` | A table with that header row; `:---:` centres a column and `---:` aligns it to the end. A pipe at the start and end of a row is optional. A row with fewer cells is filled with empty ones, and cells beyond the header's are dropped. A pipe with a backslash before it, or inside code in a line, does not divide cells. A table ends a paragraph. | **In a line.** Inside paragraphs, headings, list items and table cells: | Construct | Written | Shown | | --- | --- | --- | | Code | `` `code` ``: a run of backticks up to the next run of exactly as many | The characters as written, in a monospaced face; line breaks inside become spaces, and one space at each end is dropped when both are there. Nothing inside is read. Without a closing run the backticks are characters. | | Link | `[words](https://example.com/page)`: an address with no spaces, which may hold one pair of parentheses | The words as a link to the address. A link holds no other link. | | Address | ``: `http://`, `https://`, `mailto:` or `tel:` inside angle brackets | The address as a link to itself. | | Strong | `**words**` | Strong words. | | Emphasis | `*words*` or `_words_` | Emphasized words. `***words***` is both. | | Escape | `\*`: a backslash before an ASCII punctuation character | The character itself, read as nothing else. | A run of `*` or `_` opens when the character after it is not white space and, when it is punctuation, the character before it is white space or punctuation; it closes when the same holds the other way round. A single `*` or `_` neither opens nor closes inside a word, so `2*3*4` and `snake_case` stay as they are; `**` may sit inside a word, but not between two ASCII letters or digits, so `2**10` stays as it is. A `*` or `_` with white space on both sides is a character. A closer pairs with the nearest open run of the same kind (`*`, `**`, `***` or `_`), and runs opened between them stay characters. Runs of four or more `*`, and two or more `_`, are characters. Code, links and addresses are read before emphasis, and emphasis never crosses a link's words. **Shown as its characters:** HTML of any kind and character references such as `&`; images (`![words](address)`, the whole of it); reference links, footnotes and task lists; links whose brackets are not followed at once by `(address)`; underline headings, indented code, `~~~` fences, `+` lists, numbers followed by `)`; and anything else not listed above. **Links.** A link's address is a link only when `core:link` would follow it as a `url` (http, https, mailto or tel, with no user name or password before the host, no spaces or control characters, at most 2048 characters); otherwise its words are shown as text, not as a link. A person must activate it; the host shows where it leads (the address's host, or the address of an email or phone link) before leaving, never fetches it beforehand, and a host that holds links holds these the same way. Nothing in a formatted text is fetched, loaded or run: it never opens a view, runs an action or writes state, and an image is never loaded because of it. **Bounds.** A host reads at most the first 20,000 characters (`characters`), keeps at most 500 blocks and list items (`blocks`), reads quotations and list items at most 5 deep (`nesting`; deeper `>` and list markers are shown as characters), and keeps at most 100 rows (`tableRows`) and 12 columns (`tableColumns`) of each table. What is beyond a bound is not shown, the text says so where it ends, and the node is reported as `degraded` with a view diagnostic. Reading is linear in the length of the text. **Other surfaces.** A heading in a text is exposed to assistive technology below every heading the view itself draws; lists are lists and tables are tables with header cells. A surface that cannot format shows or speaks the text without its markup; markup is never read aloud as symbols, and a table is spoken as a summary of its columns and number of rows. For example, this value: ``` ## Trip We fly on **Friday**; the code is `LX 1234`. 1. Pack 2. Leave > Gates close early. | Day | Cost | | --- | ---: | | Friday | 240 | Details at [the airline](https://example.com/flights). ``` is a heading of level 2, a paragraph with strong words and code, a numbered list of two items, a quotation, a table of one row whose second column is aligned to the end, and a paragraph with a link that shows it leads to `example.com`. - **fileInput.** File references in `value` come only from the host, from its file chooser or a capture. Choosing a file, or taking a photo or a recording, through `fileInput` is the person's own act and needs no grant; reading the file's contents goes through a capability. ## 9. Core capability behaviour The capability contracts of the core catalog settle these points, and their descriptions in the catalog say the same. **Personal capabilities.** `files`, `media`, `location`, `clipboard` and `share` have the `personal` trait; `notify`, `scheduler`, `http`, `directory` and `records` do not (core.md section 6.4.2). **Given by use.** The scopes `files.pick`, `files.read`, `files.save`, `media.camera`, `media.microphone` and `share.send` are given by use (section 4): under each, a person chooses, captures, saves or sends at that moment in the host's interface, or the app reads a file that a person gave it. A request for them alone is not asked. Every other core scope is asked, `clipboard.write`, `clipboard.read` and `location.current` included, since under them the app acts without the person doing anything at the time, unless the host's own provider keeps what is done under it inside the app (core.md section 6, "When a request is asked"). **The current user.** Where a contract speaks of the current user (`notify.send`, `notify.sendTo`, `directory.me`, and `directory.manager` without `of`), it means the person of the acting principal (core.md section 6.1). An agent or the app is never the current user. When the acting principal has no person, the operation fails with `capability.failed`. **notify.** `send` and `sendTo` take an optional `viewInput`, the input for `view`: opening the notification opens that view with that input. When the view does not exist or the input does not fit its `input` field map, the host opens the start view. `sendTo` sends on the current user's behalf. **scheduler.** Its scope lets the app run while nobody has it open: holding a grant on it permits `every` rules, flow `after` timers and timed source refreshes to run unattended, and the scope's description says so plainly to the approver. `wakeAt` with a time that has passed is due at once and returns the current time. A `wakeAt` whose key is already pending replaces the earlier wake. Wakes are kept by the instance, not by a session, and each `wake` is delivered once. A wake belongs to the person on whose behalf it was scheduled: the rules it fires act on that person's behalf, with the values of one of that person's active sessions when there is one, and otherwise with no session, the app running unattended under the scheduler grant (core.md section 6.4.4). Wake keys are per instance, so an app that keeps a wake for each person includes `user.person.id` in the key. Within an instance, wakes belong to the definition whose steps scheduled them, the app itself or one of its parts: each has its own keys, so neither a part nor the app that includes it can replace or cancel a wake of the other or of another part, also when the part's capability is mapped to the including app's, and a `wake` event reaches only the rules of the definition that scheduled it. The event's `at` is the time `wakeAt` returned. A host supports at least 100 pending wakes per instance and times up to ten years ahead; a request beyond what it supports fails with `capability.failed`. **http.** - Paths are taken literally and never normalized, so a grant's `where` sees exactly the path the service receives. A path that contains a dot segment (`.` or `..`, also percent-encoded), an encoded `/`, `\`, `.` or `%`, a `\`, a control character, or any character outside the path characters of RFC 3986 is refused, and the call fails with `capability.failed`. Just before sending, the host checks that the address it built has the configured origin. - Redirects are never followed. A 3xx response is returned to the app as it is; where the platform cannot return it, the call fails with `capability.failed`. - Headers an app may not set are refused, not dropped: the call fails with `capability.failed`. They are `host`, `cookie`, `cookie2`, `set-cookie`, `set-cookie2`, `connection`, `keep-alive`, `transfer-encoding`, `te`, `trailer`, `upgrade`, `content-length`, `expect`, `origin`, `referer`, `via`, `forwarded`, `max-forwards`, `http2-settings`, `accept-encoding`, `accept-charset`, `date`, `dnt`, `access-control-request-headers`, `access-control-request-method`, `x-real-ip`, `x-original-url`, `x-rewrite-url`, any header starting with `proxy-`, `sec-` or `x-forwarded-`, and the method-override headers `x-http-method-override`, `x-http-method` and `x-method-override`, which would let a `get` under `http.read` act as a write. - `set-cookie` headers are removed from responses. A credential the host attached that the service echoes back is replaced with `[withheld]`. - The response `body` is `null` when the response has no content; the parsed value when the response declares a JSON media type (`application/json`, or `application/` followed by a name ending in `+json`) and parses; and otherwise the content decoded as UTF-8 text, with invalid sequences replaced. Binary content therefore cannot be read through `http`. **files.** An instance can read only file references the host issued to it: by `pick`, by `save`, by a capture (`media`, `fileInput`), or for a file an agent handed to the host (core.md section 5). Any other reference fails with `capability.failed`, as if the file were not available. How long a reference stays readable, and what a reference kept in `shared` state shares, is set out in core.md section 5. `as: "records"` reads and writes comma- or tab-separated text, every value as text. **records.** - Field names in `filter`, `sort` and `groupBy` name top-level fields of a record. A missing field reads as `null`. - `eq`, `ne` and `in` compare exactly, with no conversion between kinds; `in` takes a list of values. `lt`, `lte`, `gt` and `gte` hold only between two numbers or two strings. `contains` holds when the field and the value are both strings and the field contains the value once both are mapped to lower case by the Unicode default case conversion with no locale (what ECMAScript's `String.prototype.toLowerCase` gives), with no normalization and no folding of accents: `"Refund for a cancelled booking"` contains `"refund"` and `"REFUND"` but not `"réfund"`. `eq`, `ne`, `in` and the ordering comparisons mind case. - Sorting uses one order across kinds: missing and `null` first, then `false` before `true`, then numbers by size, then strings by code point, then lists and objects. Ties keep the order in which the records were created. - `list` declares `paging` (`cursor`, `next`, `items`). A cursor is good only for the listing that produced it. A record that exists throughout the paging and keeps its sort values is listed exactly once. `total`, when given, counts every record that passes the filter, not only the page. - `count` takes an optional `filter` and returns `{ "count" }`, the number of records that pass it. - `aggregate` takes an optional `filter`, an optional `groupBy` (a list of field names; without it every record is in one group), `measures` (an object from a name to `{ "op", "field" }`, where `op` is `count`, `sum`, `min`, `max` or `avg`, and `field` is required for every `op` except `count`, which counts the records of the group) and an optional `limit` (the most groups returned, 1 to 1000, default 100). It returns `{ "groups": [ { "key", "values" } ], "truncated" }`: `key` maps each `groupBy` field to the group's value, `values` maps each measure name to its result, groups come in ascending order of their keys in the sort order above, and `truncated` is `true` when more groups existed than `limit`. `sum` and `avg` use only number values, and `min` and `max` use the sort order above over values that are not `null`; with no such values `sum` is 0 and the others are `null`. - `count` and `aggregate` are `read` operations under `records.read`. - `changed` is delivered after the write that caused it. --- # Open App Definition (OAD) 0.2: Expressions Status: working draft. The key words MUST, MUST NOT, REQUIRED, SHOULD, SHOULD NOT and MAY are to be read as in RFC 2119. This chapter defines the expression language used throughout an app definition: in fields marked *expression*, in dynamic values (strings that start with `=`), and in paths (`core.md`, section "Values and expressions"). Its syntax is a subset of the Common Expression Language (CEL) plus template strings. Its values are the JSON data model. Section 15 lists every place where it differs from CEL. Section 17 defines the static types a validator infers to find expressions that are certain to fail, and section 18 defines the pattern dialect used by `matches` and by a type's `pattern`. Expressions are side-effect free, have no user-defined functions, assignment, loops or recursion, and every evaluation runs under a cost budget, so every evaluation terminates. ## 1. Values Every value is one of six kinds: | Kind | Description | | --- | --- | | `null` | The null value. | | `boolean` | `true` or `false`. | | `number` | An IEEE 754 binary64 (double) value that is finite. There is a single number kind: an integer is a number with no fractional part. | | `string` | A sequence of Unicode code points. | | `list` | An ordered sequence of values (a JSON array). | | `map` | A set of string keys, each with a value (a JSON object). | - **Numbers.** No expression ever produces NaN or an infinity. An operation whose mathematical result is not finite fails with subcode `range`. Negative zero is never produced: wherever a result would be negative zero, it is zero. Where this chapter says *integer*, it means a number with no fractional part. - **Strings.** Lengths, indexes and positions within strings count Unicode code points, not bytes or UTF-16 code units. Strings are compared by code point. Strings are never normalized: `'é'` and `'é'` are different strings. - **String length limit.** A string built by `+`, a template, `t`, `join`, `replace`, `padStart`, `padEnd`, `upper`, `lower`, or `string()` of a list or map MUST NOT exceed 1,048,576 code points. An operation that would build a longer string fails with subcode `budget`. Where the length of the result can be computed from the operands (`+`, templates, `t`, `join`, `padStart`, `padEnd`, and an upper bound for `replace`), an implementation MUST detect this before building the string. Every other operation returns either a string of small fixed length (such as a formatted number or date) or one no longer than one of its string operands. Strings in the scope are not limited; work on a long string is paid for by the rules of section 10. - **Maps.** Keys are strings, and maps are unordered. Every operation that exposes an order of a map's keys (`keys`, `values`, `entries`, conversion of a map to a string by `string()` or a template, and any other place where an order of iteration is observable) MUST use ascending code point order of the keys. For example `keys({'b': 1, '10': 2, '9': 3})` is `['10', '9', 'b']`. The order of members in a map an evaluation returns to its host is not significant. - **Dates and times** are strings in ISO 8601 form (section 9). There is no separate date kind. A host supplies data to an expression through the scope (section 4). Scope data MUST be made of the six kinds above. Where a host language has an undefined or absent marker distinct from `null`, a map member holding it MUST be treated as absent. Any other value outside the data model (for example a host object or a function) MUST fail with subcode `type` when it is used as an operand. ## 2. Lexical structure Expression source is a sequence of Unicode code points. - **Whitespace** is space, tab, line feed and carriage return. It separates tokens and is otherwise ignored. There are no comments. - **Identifiers** match `[A-Za-z_][A-Za-z0-9_]*`. The reserved words `true`, `false`, `null` and `in` are not identifiers, except directly after a `.`, where any identifier-shaped word is a member name (so `state.in` reads the key `in`). - **Numbers** match `(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?`. A number literal MUST NOT be immediately followed by an identifier character. A literal whose value rounds to a non-finite double is a syntax error. Leading zeros, a leading or trailing `.`, hexadecimal forms and suffixes are syntax errors. A negative number is the unary `-` operator applied to a literal. - **Strings** are enclosed in `'` or `"`. A string MUST NOT contain a raw line feed or carriage return. The escapes are: | Escape | Meaning | | --- | --- | | `\\` `\'` `\"` `` \` `` | The character itself. | | `\n` `\r` `\t` `\b` `\f` `\v` | Line feed, carriage return, tab, backspace, form feed, vertical tab. | | `\uXXXX` | The code point with exactly four hexadecimal digits. | | `\UXXXXXXXX` | The code point with exactly eight hexadecimal digits. | A `\u` or `\U` escape that names a surrogate (U+D800 to U+DFFF) or a value above U+10FFFF is a syntax error, as is any other escape. - **Template strings** are enclosed in backticks. They may contain raw line breaks, the escapes above, and `\$`, which is a literal `$`. A `${` begins an interpolation, which contains one expression and ends at the matching `}`. A `$` not followed by `{` is a literal `$`. An empty interpolation is a syntax error. Templates may nest inside interpolations. - **Punctuators** are `== != <= >= && || < > ! ? : + - * / % . , ( ) [ ] { }`. A lone `=`, `&` or `|` is a syntax error. ## 3. Grammar ``` expr = cond cond = or [ "?" expr ":" cond ] or = and { "||" and } and = rel { "&&" rel } rel = add { ( "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" ) add } add = mul { ( "+" | "-" ) mul } mul = unary { ( "*" | "/" | "%" ) unary } unary = ( "!" | "-" ) unary | postfix postfix = primary { "." NAME [ args ] | "[" expr "]" } primary = NUMBER | STRING | TEMPLATE | "true" | "false" | "null" | IDENT [ args ] | "(" expr ")" | list | map args = "(" [ expr { "," expr } ] ")" list = "[" [ expr { "," expr } [ "," ] ] "]" map = "{" [ entry { "," entry } [ "," ] ] "}" entry = ( STRING | IDENT ) ":" expr ``` Operators by precedence, lowest first: | Level | Operators | Associativity | | --- | --- | --- | | 1 | `? :` | right | | 2 | `\|\|` | left | | 3 | `&&` | left | | 4 | `==` `!=` `<` `<=` `>` `>=` `in` | left | | 5 | `+` `-` | left | | 6 | `*` `/` `%` | left | | 7 | unary `!` `-` | right (prefix) | | 8 | `.name`, `[index]`, `f(args)`, `x.f(args)` | left (postfix) | Further rules that are part of the syntax: - `IDENT [ args ]` is a function call. `x.NAME(args)` is a method call: it calls the function `NAME` with `x` as its first argument, followed by `args`. `has`, `default`, `let`, `can`, `canSend` and `t` are only global calls: written as a method call (`x.has(y)`), each of them is a syntax error. The list macros (section 7.3) are only method calls. - A map key written as a bare identifier is the literal key name; it is not a variable. Reserved words are not allowed as bare keys. Duplicate keys in one map literal are a syntax error. - `has(e)` requires exactly one argument, which is a member access or an index expression. `default(a, b)` requires exactly two arguments. `let(n, v, e)` requires exactly three arguments, and `n` is an identifier. A list macro call `x.m(v, e)` requires exactly two arguments, and `v` is an identifier. Anything else with those names in those positions is a syntax error. - `can(a)` and `can(a, i)` require `a` to be a string literal. `canSend(f, e)` and `canSend(f, e, k)` require `f` and `e` to be string literals. Any other number or form of arguments to `can` or `canSend` is a syntax error. - `t(k)` and `t(k, v)` require `k` to be a string literal that is a key (section 8.7: it matches `^[A-Za-z][A-Za-z0-9_.]{0,79}$`) and `v`, when present, to be a map literal, whose values are any expressions. Any other number or form of arguments to `t` is a syntax error. A variable or member named `t` (`item.t`, the variable of a list macro or of `let`) is not affected: only a call written `t(...)` is the function. - When the pattern argument of `matches` (the second argument of `matches(s, p)`, the only argument of `s.matches(p)`) is a string literal, it MUST be a pattern in the dialect of section 18, or the expression is a syntax error. A pattern computed at run time is checked when it is used (section 8.3). - Chained relations parse left to right (`1 < 2 < 3` is `(1 < 2) < 3`, which then fails with `type`). ### 3.1 Limits To keep hostile definitions from exhausting a host: - Source longer than 10000 code points is a syntax error. - An expression whose nesting depth exceeds 100 is a syntax error. The nesting depth is the height of the syntax tree: a literal, an identifier, an empty list or map, and a template with no interpolations have height 1; every other construct has height one more than its tallest operand, and a parenthesized expression has height one more than its contents. The operands are: the target of a member access; the target and index of an index; the arguments of a call; the receiver and arguments of a method call; the receiver and body of a list macro; the argument of `has`; both arguments of `default`; the value and body of `let`; the elements of a list; the values of a map; the interpolations of a template; and the operands of unary, binary and conditional operators. For example `((1))` has depth 3. Chains of binary operators are not flattened: each operator is one level, so `1 + 1 + ... + 1` with 101 terms has depth 101 and is rejected. Implementations MUST reject exactly the expressions these rules reject, so that a definition that parses on one host parses on every host. ## 4. Scope and identifiers An expression is evaluated against a **scope**: a map from root identifier to value, supplied by the host. - An identifier that is not bound by an enclosing list macro or `let` resolves to the scope member of that name. If the scope has no such member, evaluation fails with subcode `unknownIdentifier`. Only the scope's own members count; names inherited from an implementation's object model never resolve. - These root names are reserved for hosts and have the meanings given in `core.md`, section "Expression scope": `state`, `input`, `env`, `user`, `event`, `flows`, `parts`, `capabilities`, `sources`, `grants`, `view`, `item`, `index`, `error`, `output`. A host supplies only the roots that apply where the expression is evaluated, together with any local names the definition binds there (`as`, `indexAs`, `let` steps and slot scope variables). Which names apply at each position is listed in `validation.md`, section "Expression scope". - A variable bound by a list macro or by `let` is bound only inside the body. Inside the body it shadows any outer name, including reserved roots such as `item` and outer macro variables: `state.items.map(item, item.price)` is valid, and `item` there is the element. ## 5. Evaluation Evaluation is deterministic and has no side effects. The only exceptions are `random()` and `uuid()` (section 8.5). The functions of sections 8.6 to 8.8 are deterministic for a given scope, host locale data, table of texts and app state. - **Order.** Operands and arguments are evaluated left to right, and all of them are evaluated before the operator or function applies, except where this chapter says otherwise: `&&`, `||`, `? :`, `default`, `has`, `let` and the list macros. - **Errors.** An evaluation either produces a value or fails with an error whose `code` is `expression.error` and whose `subcode` is one of those in section 11. The first error raised ends the evaluation unless a construct defined here catches it: only `has` and `default` do, and only for `missing` (section 7). What a host does with a failed expression is defined in `core.md`, section "Errors". - **Results** are values in the data model. Evaluation MUST NOT modify any value in the scope. Lists and maps an expression constructs are new values; values read from the scope may be returned as they are. - **Resources.** If an evaluation exhausts a resource of the implementation that this chapter does not otherwise meter (for example stack depth while comparing deeply nested scope data), it MUST fail with subcode `budget` rather than with any other kind of failure. ### 5.1 Member access and indexing - `x.name` on a map yields the value of key `name`. If the map has no such key, it fails with `missing`. If `x` is `null`, it fails with `missing`. On any other kind, it fails with `type`. - `x[k]` on a map requires a string `k` (else `type`) and behaves like `x.k`. On a list it requires a number `k` (else `type`) that is an integer (else `range`). An index out of range (below zero, or not less than the list's size) fails with `missing`, not `range`, so `has` and `default` treat an absent element like an absent key. On `null` it fails with `missing`. Strings cannot be indexed: use `substring`. On any other kind it fails with `type`. - Only a map's own keys are members. In particular `constructor`, `toString` and `__proto__` are ordinary keys: absent unless the data contains them. ### 5.2 Logical and conditional operators - `a && b` evaluates `a`, which MUST be a boolean (else `type`). If `a` is `false`, the result is `false` and `b` is not evaluated. Otherwise `b` is evaluated and MUST be a boolean (else `type`), and is the result. - `a || b` is the same with the roles of `true` and `false` exchanged. - `!a` requires a boolean. - `c ? a : b` evaluates `c`, which MUST be a boolean (else `type`), then evaluates and returns only the chosen branch. There is no truthiness: `null`, `0`, `''` and empty collections are never treated as booleans. ### 5.3 Equality `a == b` is deep structural equality and never fails. Values of different kinds are unequal. Numbers are equal when numerically equal (`1 == 1.0`, `0 == -0`). Strings are equal when they have the same code points. Lists are equal when they have the same size and pairwise equal elements. Maps are equal when they have the same set of keys and equal values for each key. `a != b` is `!(a == b)`. ### 5.4 Ordering `<`, `<=`, `>` and `>=` require two numbers or two strings, else they fail with `type`. Numbers compare numerically. Strings compare lexicographically by code point. ISO 8601 dates and datetimes in the canonical forms of section 9 therefore compare chronologically. ### 5.5 Membership `a in b`: if `b` is a list, the result is `true` when some element equals `a` (section 5.3). If `b` is a map, `a` MUST be a string (else `type`) and the result is `true` when `b` has the key `a` (a key whose value is `null` is present). Any other `b` fails with `type`. ### 5.6 Arithmetic - `a + b` adds two numbers, concatenates two strings, or concatenates two lists into a new list. Any other combination fails with `type`; there is no implicit conversion (use `string()` or a template). - `a - b`, `a * b`, `a / b` and `a % b` require two numbers (else `type`). `/` is true division: `7 / 2` is `3.5`. `%` is the remainder of truncating division and has the sign of the dividend: `-7 % 3` is `-1`, `7.5 % 2` is `1.5`. Division or remainder by zero fails with `divideByZero`, including `0 / 0`. - Unary `-` requires a number. - Arithmetic is IEEE 754 binary64 with round-to-nearest-even. A non-finite result fails with `range`. A negative zero result is zero. ### 5.7 Templates and string conversion A template evaluates to its literal text with each interpolation replaced by its value converted to a string. Conversion follows `string()`: - `null`, `true` and `false` become `null`, `true` and `false`. - A number becomes the string produced by ECMAScript `Number::toString` in radix 10 (ECMA-262): the shortest decimal that round-trips, without exponent for magnitudes from 1e-6 up to but excluding 1e21 (`100`, `1.5`, `0.000001`), with exponent otherwise (`1e+21`, `1e-7`). Zero, including negative zero, is `0`. - A string is itself. - A list or map becomes compact JSON text (RFC 8259) with no whitespace, map members in ascending code point order of keys, numbers as above, and strings escaped as follows: `"` and `\` are escaped with a backslash; U+0008, U+0009, U+000A, U+000C and U+000D become `\b`, `\t`, `\n`, `\f`, `\r`; other code points below U+0020 become `\u00XX` with lowercase hexadecimal digits; everything else, including non-ASCII characters, is written as is. For text meant for people, use the formatting functions of section 8.6 instead. ## 6. Dynamic values A **dynamic value** (`core.md`, section "Values and expressions") is a JSON value in which strings may be expressions: - A string that starts with `==` is a literal string: the first `=` is removed (`"==x"` is `=x`, `"=="` is `=`). - Any other string that starts with `=` is an expression: the rest of the string is the source. `"="` alone is an expression with empty source, which is a syntax error. - Any other string, and every number, boolean and null, is a literal. - Arrays and objects are walked recursively. Object keys are never expressions. A host MUST parse every expression in a dynamic value when it loads the definition, and MUST report a syntax error together with the JSON Pointer (RFC 6901) of the offending string, relative to the dynamic value. Evaluation produces a new value of the same shape. Expressions are evaluated depth first, array elements in index order and object members in ascending code point order of their keys, so every host reports the same first error; each expression is evaluated with its own budget. An evaluation error is reported with the JSON Pointer of the expression that failed. ## 7. Macros Macros are written like calls but control how and whether their arguments are evaluated. ### 7.1 `has(path)` `path` is a member access or index chain, such as `has(state.form.amount)` or `has(state.items[0].name)`. The innermost operand of the chain (usually a root identifier) is evaluated normally, so an unknown root identifier still fails with `unknownIdentifier`. Then each step is applied in turn: - If the current value is `null`, the result is `false`. - If the step would fail with `missing` (an absent key, or a list index out of range), the result is `false`. - Any other error, including `type` for stepping into a number, and any error raised while evaluating an index expression, propagates. If every step succeeds, the result is `true`. A path whose final value is `null` is present: `has(state.x)` is `true` when `state.x` is `null`. ### 7.2 `default(value, fallback)` Evaluates `value`. If that evaluation fails with subcode `missing` (anywhere inside it), or produces `null`, the result is the evaluation of `fallback`. Otherwise the result is the value, and `fallback` is not evaluated. Errors with any other subcode propagate. `default(state.form.note, '')` reads an optional field; `default(false, true)` is `false`. ### 7.3 List macros A list macro has the form `list.m(v, body)`. `list` MUST evaluate to a list (else `type`; maps and strings are not iterated). For each element visited, `body` is evaluated with the identifier `v` bound to the element. Elements are visited in order. | Macro | Result | | --- | --- | | `l.map(x, e)` | New list of `e` for each element. | | `l.filter(x, p)` | New list of the elements for which `p` is `true`. | | `l.all(x, p)` | `true` if `p` is `true` for every element. Stops at the first `false`. `true` for an empty list. | | `l.exists(x, p)` | `true` if `p` is `true` for some element. Stops at the first `true`. `false` for an empty list. | | `l.find(x, p)` | The first element for which `p` is `true`, or `null`. Stops at the first match. | | `l.count(x, p)` | The number of elements for which `p` is `true`. | | `l.sortBy(x, k)` | New list sorted ascending by key `k`, stable. | | `l.groupBy(x, k)` | Map from each key `k` to the list of elements with that key, in element order. | | `l.indexBy(x, k)` | Map from each key `k` to the element with that key. When several elements have the same key, the last one is kept. | | `l.sumBy(x, e)` | Sum of `e` over the elements, added left to right. `0` for an empty list. | | `l.minBy(x, k)` | The element with the smallest key, the first one on ties, or `null` for an empty list. | | `l.maxBy(x, k)` | The element with the largest key, the first one on ties, or `null` for an empty list. | | `l.distinctBy(x, k)` | New list of the first element for each distinct key (keys compared with section 5.3). | Predicates (`p`) MUST be booleans, else `type`. The keys of `sortBy`, `minBy` and `maxBy` MUST be all numbers or all strings, else `type`. `groupBy` and `indexBy` keys MUST be strings, else `type`. `sumBy` values MUST be numbers, else `type`. `state.answers.indexBy(a, a.itemId)` builds a lookup map once; `m[item.id]` then reads one element without scanning the list again. To visit elements together with their positions, iterate `enumerate(list)` (section 8.1): `enumerate(state.tiles).map(e, {id: e.value.id, pos: e.index})`. ### 7.4 `let(name, value, body)` Evaluates `value`, then evaluates `body` with the identifier `name` bound to the result, and returns the result of `body`. `name` is bound only inside `body`, not inside `value`, and shadows any outer name there as a list macro variable does (section 4). `let` names a sub-result once instead of repeating it: ``` let(limit, state.limits[e.category][0], e.amount > limit.max ? limit.max : e.amount) let(open, state.tickets.filter(t, t.status == 'open'), size(open) == 0 ? 'none' : open[0].subject) ``` `let` calls nest: `let(a, 1, let(b, a + 1, a + b))` is `3`. An error raised by `value` propagates and `body` is not evaluated. ## 8. Functions Every function can be called globally, `f(a, b)`, or as a method on its first argument, `a.f(b)`, except `can` and `canSend`, which are global only (section 3). Calling a name that is not a function fails with `unknownFunction`; this check happens before the arguments are evaluated. Calling with the wrong number of arguments fails with `arity`, also before the arguments are evaluated. A wrong argument kind fails with `type`. A right kind with a value the function does not accept fails with `range`; this includes a non-integer number where an integer is required and a string that is not in the format the function requires. Section 17.5 gives the signature of every function and macro. ### 8.1 Collections and aggregates | Function | Result | | --- | --- | | `size(x)` | Code points of a string, elements of a list, or keys of a map. | | `sum(list)` or `sum(n, ...)` | Sum of numbers, added left to right. `0` for an empty list. | | `avg(list)` or `avg(n, ...)` | Arithmetic mean, or `null` for an empty list. | | `min(list)` or `min(v, ...)` | Smallest value, or `null` for an empty list. Values MUST be all numbers or all strings. | | `max(list)` or `max(v, ...)` | Largest value, or `null` for an empty list. Same rule as `min`. | | `keys(map)` | List of keys, in ascending code point order. | | `values(map)` | List of values, in ascending code point order of their keys. | | `entries(map)` | List of `{ "key": k, "value": v }` maps, in ascending code point order of keys. | | `merge(a, b)` | New map with the members of both maps. Where both have a key, the value from `b` is kept. Only the top level is merged. | | `compact(map)` | New map with the members whose value is not `null`. Only the top level is examined. | | `reverse(x)` | New list in reverse order, or a string with its code points reversed. | | `slice(x, start, end?)` | New list (or string) of the elements from `start` up to but excluding `end` (default: the size). Negative indexes count from the end. Indexes are then clamped to the range 0 to size; if `end` is not greater than `start`, the result is empty. | | `first(list)` | First element, or `null` when empty. | | `last(list)` | Last element, or `null` when empty. | | `flatten(list)` | New list in which each element that is a list is replaced by its elements (one level). | | `distinct(list)` | New list of the first occurrence of each distinct element (section 5.3). | | `enumerate(list)` | New list of `{ "index": i, "value": v }` maps, one for each element in order, with `i` counting from 0. | | `range(n)` | The list `0, 1, ..., n - 1`. `n` MUST be a non-negative integer (else `range`). | | `contains(x, y)` | For a list: `true` if some element equals `y`. For strings: `true` if `y` occurs in `x`. | | `indexOf(x, y)` | For a list: the index of the first element equal to `y`. For strings: the code point index of the first occurrence of `y`. `-1` when not found. | In the variadic forms, a call with exactly one argument that is a list uses that list; any other call uses its arguments. `merge` and `compact` together build a map with optional members: `compact(merge(base, {receipt: input.receipt, note: default(input.note, null)}))` drops the members that are `null`. ### 8.2 Numbers and conversions | Function | Result | | --- | --- | | `abs(n)`, `floor(n)`, `ceil(n)` | As in mathematics. | | `round(n, digits?)` | `n` rounded to a multiple of 10 to the power `-digits` (default 0), with ties away from zero. `digits` is an integer from -15 to 15. The decision is made on the shortest decimal form of `n` that round-trips, so `round(1.005, 2)` is `1.01` and `round(-2.5)` is `-3`. | | `int(x)` | A number truncated toward zero, or a numeric string (as for `number`) parsed and truncated. | | `number(x)` | A number unchanged, or a string parsed as a decimal number matching `[+-]?([0-9]+(\.[0-9]*)?\|\.[0-9]+)([eE][+-]?[0-9]+)?`, with no surrounding whitespace. Other strings fail with `range`. | | `string(x)` | Conversion as in section 5.7. | | `bool(x)` | A boolean unchanged, or the string `"true"` or `"false"`. Other strings fail with `range`. | | `type(x)` | One of `"null"`, `"boolean"`, `"number"`, `"string"`, `"list"`, `"map"`. | ### 8.3 Strings | Function | Result | | --- | --- | | `startsWith(s, prefix)`, `endsWith(s, suffix)` | Booleans. | | `lower(s)`, `upper(s)` | Full Unicode default case conversion, without locale tailoring (`upper('straße')` is `STRASSE`). | | `trim(s)` | `s` without leading and trailing code points that have the Unicode `White_Space` property. | | `split(s, sep)` | List of the parts of `s` between occurrences of `sep`. An empty `sep` splits into code points. `split('', ',')` is `['']`. | | `join(list, sep?)` | The elements, which MUST all be strings, joined with `sep` (default `''`). | | `replace(s, from, to)` | `s` with every non-overlapping occurrence of `from`, scanning left to right, replaced by `to`. Both are literal text. An empty `from` fails with `range`. | | `substring(s, start, end?)` | Code points of `s` selected as in `slice`. | | `padStart(s, length, pad?)`, `padEnd(s, length, pad?)` | `s` extended to `length` code points by repeating `pad` (default `' '`), truncating the last repetition. Unchanged if `s` is already at least `length` long or `pad` is empty. | | `matches(s, pattern)` | `true` if some part of `s` matches `pattern`, a pattern in the dialect of section 18. Anchor the pattern with `^` and `$` to test the whole string. A pattern outside the dialect fails with `range`. | `join`, `replace`, `padStart`, `padEnd`, `upper` and `lower` are subject to the string length limit (section 1). A pattern is a string, so its backslashes are escaped once for the expression's string literal and, inside a JSON document, once more for JSON: the expression `matches(input.code, '^[A-Z]{3}\\d{4}$')` is written in a definition as `"=matches(input.code, '^[A-Z]{3}\\\\d{4}$')"`. Classes such as `[0-9]` need no backslash. ### 8.4 Dates and times In this table, *date* means a calendar date or a datetime, and the result has the same form as the argument unless stated. Formats are defined in section 9. | Function | Result | | --- | --- | | `addDays(date, n)` | `n` (an integer) calendar days later. For a datetime, `n` times 86400 seconds later. | | `addMonths(date, n)` | `n` (an integer) calendar months later, with the day clamped to the last day of the resulting month: `addMonths('2024-01-31', 1)` is `2024-02-29`. The time of day is kept. | | `addDuration(datetime, duration)` | Applies years and months as in `addMonths`, then weeks and days as 86400 seconds each, then hours, minutes and seconds. A calendar date argument fails with `range`. | | `daysBetween(a, b)` | Integer number of calendar days from `a` to `b` (negative if `b` is earlier). A datetime counts as its UTC calendar date. | | `durationBetween(a, b)` | Seconds from `a` to `b`, which may be fractional. A calendar date counts as midnight UTC. | | `datePart(date, part)` | An integer: `year`, `month` (1 to 12), `day`, `weekday` (1 = Monday to 7 = Sunday), `hour`, `minute`, `second` (whole seconds). Time parts of a calendar date, and any other `part`, fail with `range`. | | `startOf(date, unit)` | The first instant of the `day`, `week` (starting Monday), `month` or `year` containing `date`. Any other `unit` fails with `range`. | | `toDate(date)` | The UTC calendar date of a datetime, or a calendar date unchanged. | | `seconds(duration)` | The length of a duration in seconds. Durations with a non-zero year or month component have no fixed length and fail with `range`. | | `atTime(date, time, zone?)` | The datetime, in canonical UTC form, at which the clocks in time zone `zone` show the calendar date `date` and the time of day `time` (section 9). `zone` defaults to `env.timezone`. A datetime as `date` fails with `range`. | | `dateIn(datetime, zone?)` | The calendar date in time zone `zone` at the instant `datetime`. `zone` defaults to `env.timezone`. A calendar date is returned unchanged, and `env.timezone` is then not read; a `zone` argument is checked all the same. | Apart from `atTime` and `dateIn`, these functions work in UTC. There is no function for the current time. Hosts expose it as `env.now`, and the current date in the person's time zone as `env.today` (`core.md`, section "Environment"). **Time zones.** A `zone` is a time zone name of the IANA time zone database, such as `Europe/Paris` or `UTC`, matched exactly (case-sensitive). A name the host does not know fails with `range`; so does a `zone` taken from `env.timezone` when that is not a known name. A local time that occurs twice (when clocks go back) gives the earlier of the two instants. A local time that does not occur (when clocks go forward) is moved forward by the length of the gap: in a zone that moves from 02:00 to 03:00, `02:30` gives the instant shown as `03:30`. Hosts use their own copy of the time zone database, so results for instants whose rules changed recently may differ between hosts; conformance vectors use zones and instants whose rules are long settled. `atTime(addDays(state.deadline, -3), '09:00')` is nine in the morning, local time, three days before the deadline, as a UTC datetime that a scheduler can use. `dateIn(env.now, 'Asia/Tokyo')` is today's date in Tokyo. ### 8.5 Effectful functions | Function | Result | | --- | --- | | `random()` | A number in the range 0 (inclusive) to 1 (exclusive). | | `uuid()` | A UUID in lowercase canonical form (8, 4, 4, 4 and 12 hexadecimal digits separated by `-`). Hosts SHOULD generate random (version 4) UUIDs as defined in RFC 9562. | These are the only functions whose results are not determined by their arguments, the scope, the host's locale data and the app's state. A host makes them available only where effects are allowed: in step expressions (`core.md`, section "Execution semantics"; `validation.md`, section "Expression scope"). Elsewhere, calling either fails with subcode `effect`. An implementation MUST also fail with `effect` if the host's source of randomness returns a value outside the stated result. ### 8.6 Formatting for people | Function | Result | | --- | --- | | `formatNumber(n, options?)` | Text showing the number `n`. | | `formatDate(d, style?)` | Text showing the calendar date or datetime `d`. | | `relativeTime(d)` | Text saying how far the calendar date or datetime `d` is from now, such as "12 minutes ago" or "in 3 days". | | `plural(n, forms)` | The member of `forms` for the plural category of the number `n`. | Their results are for display only. They depend on the host's locale data, so an app MUST NOT parse them, compare them, or store them as data, and two hosts may return different text for the same call. Each reads, from the scope, `env.locale` (a BCP 47 language tag) and the other `env` fields named below, exactly as the expression `env.locale` would read them: a scope without `env` fails with `unknownIdentifier`, a missing field with `missing`, and a field of the wrong kind with `type`. A host that has no data for `env.locale` uses the nearest locale it has (such as `fr` for `fr-CA`), and otherwise a default of its choosing. **`formatNumber(n, options?)`.** `options` is a map with these optional members; a member whose value is `null` counts as absent, any other member name fails with `range`, and a member of the wrong kind fails with `type`: | Option | Meaning | | --- | --- | | `style` | `decimal` (default), `percent`, `currency` or `compact`. Any other string fails with `range`. | | `currency` | An ISO 4217 code of three uppercase letters A to Z, else `range`. Defaults to `env.currency`. Used only with `currency` style. | | `digits` | An integer from 0 to 6 (else `range`): the number of digits after the decimal separator. | - `decimal` shows `n` with grouping. With `digits`, exactly that many fraction digits are shown; without it, up to 3, with trailing zeros dropped. - `percent` shows `n` times 100 with a percent sign, with `digits` fraction digits (default 0). The multiplication is exact: it moves the decimal point of the shortest round-trip decimal form of `n` two places, so `formatNumber(0.285, {style: 'percent'})` shows 29. - `currency` shows `n` as an amount of `currency`, with `digits` fraction digits, by default the currency's minor unit (2 for `USD` and `EUR`, 0 for `JPY`; 2 for a code the host does not know). When neither `currency` nor `env.currency` gives a code, the number is formatted as `decimal` with `digits` (default 2) fraction digits. - `compact` shows `n` scaled to the locale's short form, such as `1.2M` or `12K`, with at most `digits` fraction digits (default 1) in the scaled number. The number shown is `n` rounded as `round` does (ties away from zero, decided on the shortest decimal form) to the number of fraction digits stated, after scaling for `percent` and `compact`. A decimal, percent or currency result never uses exponent notation. **`formatDate(d, style?)`.** `style` is `short`, `medium` (default), `long` or `time`; any other string fails with `range`. A calendar date is shown as it is, with no time zone. A datetime is first converted to the local date and time in `env.timezone` (section 8.4). `short` shows the date in numeric form, `medium` with an abbreviated month name, and `long` with the full month name; for a datetime each of them also shows the hour and minute. `time` shows only the hour and minute of a datetime, and fails with `range` for a calendar date. Seconds and the time zone are never shown. **`relativeTime(d)`.** For a datetime, the difference is `durationBetween(env.now, d)` in seconds. Its size is expressed in the largest of these units it reaches: year (365 days), month (30 days), week (7 days), day (86400 seconds), hour, minute and second. The count is the size divided by the unit, rounded toward zero. A size under one second is shown as the present moment ("now"). For a calendar date, the difference is `daysBetween(env.today, d)` in days, expressed in years, months, weeks or days in the same way, and a difference of zero is shown as the present day ("today"). A negative difference is in the past ("3 days ago") and a positive one in the future ("in 3 days"). A host MAY use the locale's words for a count of one day ("yesterday", "tomorrow"). **`plural(n, forms)`.** `forms` is a map whose members are strings: `other` is required, and `zero`, `one`, `two`, `few` and `many` are optional. A missing `other`, or any other member name, fails with `range`; a member that is not a string fails with `type`. The result is the member for the cardinal plural category of `n` in `env.locale`, as the Unicode CLDR plural rules define it for the shortest decimal form of `n`, or `other` when `forms` has no member for that category. Categories belong to the locale: in English, 0 is in category `other`, so a `zero` form is never chosen there; to say something special for none, test `n == 0`. `` `${n} ${plural(n, {one: 'check', other: 'checks'})} left` `` gives "1 check left" and "3 checks left" in English. What every host shows the same, and what may vary: | Fixed by this section | Varies with the host's locale data | | --- | --- | | The number after rounding, its sign and its count of fraction digits; the currency; the percentage after scaling. | Digit shapes, grouping and decimal separators, the minus sign, the form and position of the currency symbol and the percent sign, compact scaling and abbreviations. | | The calendar date and local time after conversion to `env.timezone`; which parts each style shows. | Month names, the order of the parts, separators, a 12-hour or 24-hour clock. | | For `relativeTime`, the unit, the count, and whether it is past or future. | The wording. | | For `plural`, that the result is one of the strings in `forms`. | Which category a number falls in. | These functions fail with `type` when `n` is not a number, `d` is not a string or `options` or `forms` is not a map, and with `range` when `d` is not a calendar date or a datetime (section 9). ### 8.7 Texts of the app | Function | Result | | --- | --- | | `t(key, values?)` | The app's text named `key`, in the language the host shows, with its blanks filled from the map `values`. | An app keeps the texts it shows to people in a table of texts, one table per language; `core.md` defines the table, its languages and how a host chooses the language it shows. `t` points at a text of that table from any expression. It may stand wherever an expression may stand. Where its result is stored (in a state entry's `initial`, by a step, in a notification sent or an audit record), it is stored as a plain string in the language of that moment and does not change when the language changes afterwards. **Keys.** A key is an ASCII letter followed by at most 79 ASCII letters, digits, `_` or `.`: it matches `^[A-Za-z][A-Za-z0-9_.]{0,79}$`. Case matters. Dots only group keys for a reader; the table is flat. **Entries.** The entry of a key is a text, or forms. - **A text** is read from its start. `{`, a blank name and `}` is a **blank**, where a blank name is an ASCII letter or `_` followed by ASCII letters, digits or `_`. `{{` writes one `{`, and `}}` writes one `}`. Any other `{` or `}` makes the text malformed. There is no other syntax. The empty text is a text. - **Forms** are an object `{ "by": name, "forms": { key: text, ... } }` with no other member. `by` is a blank name: the value passed for that blank chooses the form. Every form is a text, and may hold blanks, the `by` blank among them. The form keys are `other`, which is required; the plural category names `zero`, `one`, `two`, `few` and `many`; `=` followed by a finite number exactly as `string(n)` writes it (`=0`, `=1`, `=12`, `=-1`, `=1.5`); and any other non-empty string that does not begin with `=`, which is an **exact text**. The empty key, and a key that begins with `=` without being `=` and such a number (`=`, `=1.0`, `=01`, `=+1`, `=-0`, `=abc`), make the entry malformed: they could never be chosen. **What the host gives.** An implementation of this chapter evaluates `t` through a provider of texts the host gives it, as it does `can` (section 8.8). For a key, the host looks the key up in the app's table for the language it shows, as `core.md` defines, and answers with four things: the entry; the language of the table the entry was taken from; the **locale of the text**, which writes its numbers and gives their plural categories; and the **direction of the text**, `ltr` or `rtl`. When the entry is taken from the table of the language shown, the locale of the text is `env.locale` and its direction is `env.direction`; when it is taken from another language's table, they are that language's own. A key the host does not know fails with `missing`. Where the host gives no provider, `t` fails with `effect`. **Evaluation.** `t(key, values)` evaluates its arguments (`values` defaults to `{}`), asks the host for the entry of `key`, and then: 1. **Checks the entry.** A malformed entry, in any of its forms, fails with `range`, whichever form the values would choose. Validation reports a malformed entry before the app runs (`validation.md`), so a host meets one only in a table that was not validated. 2. **Chooses the form**, for forms. Let `v` be the member of `values` named by `by`. When `values` has no such member, `t` fails with `missing`. - `v` is a number: the form `=N` where `N` is `string(v)`; else the form named by the cardinal plural category of `v` in the locale of the text, exactly as `plural` defines the category (section 8.6); else `other`. A category the language never yields is simply never chosen: in English a `zero` form is never chosen, and it is not an error. - `v` is a string: the form whose key equals `v`, except that a string never matches the keys `other`, `zero`, `one`, `two`, `few` and `many` or a key that begins with `=`; else `other`. - `v` is `true` or `false`: the form `true` or `false`; else `other`. - `v` is `null`: `other`. - `v` is a list or a map: `t` fails with `type`. The form is chosen from the value passed, not from the digits its blank then shows. `formatNumber` shows at most three fraction digits, so `1.0004` is shown as `1` in the form chosen for `1.0004`, which in English is `other`: an app that passes such a number rounds it first. 3. **Fills the blanks** of the chosen text (of the entry, when it is a text). Each blank is replaced by the member of `values` of its name: a string as it is; a number as `formatNumber(n)` with no options writes it, in the locale of the text; `null` as nothing. A boolean, a list or a map fails with `type`, so a boolean is a value only for a `by` blank that the chosen form does not insert. A blank whose name `values` has no member for fails with `missing`. Only the blanks of the chosen form need values. A member of `values` that no blank names is ignored. A value is inserted once and never read again: braces inside it are characters, not blanks. 4. **Keeps each inserted value in one piece.** In a text whose direction is `rtl`, every inserted value that is not empty is wrapped in U+2068 FIRST STRONG ISOLATE and U+2069 POP DIRECTIONAL ISOLATE. In a text whose direction is `ltr`, only an inserted value that holds a right-to-left character is wrapped so. A **right-to-left character** is a code point from U+0590 to U+08FF, U+FB1D to U+FDFF, U+FE70 to U+FEFC, U+10800 to U+10FFF or U+1E800 to U+1EFFF; digits and punctuation in those ranges count. The characters of the entry itself are never wrapped, and the table does not store these characters for this purpose. The result is a string, subject to the length limit of section 1. Like the functions of section 8.6, a number in it depends on the host's locale data, so an app MUST NOT parse it, compare it or store it as data. With a table whose language `en` holds ```json { "appName": "Trip planner", "welcome": "Welcome back, {name}", "nights": { "by": "count", "forms": { "one": "{count} night", "other": "{count} nights" } } } ``` and `ar` holds `"welcome": "مرحبًا بعودتك يا {name}"` and no `nights`: | Shown | Expression | Result | | --- | --- | --- | | `en`, `env.locale` `en-US` | `t('appName')` | `Trip planner` | | `en`, `env.locale` `en-US` | `t('welcome', {name: 'Ana'})` | `Welcome back, Ana` | | `en`, `env.locale` `en-US` | `t('welcome', {name: 'دانة'})` | `Welcome back, ` + U+2068 + `دانة` + U+2069 | | `en`, `env.locale` `en-US` | `t('nights', {count: 1})` | `1 night` | | `en`, `env.locale` `en-US` | `t('nights', {count: 3})` | `3 nights` | | `en`, `env.locale` `en-US` | `t('nights', {count: 1250})` | `1,250 nights` | | `ar`, the person's languages `ar-EG`, `env.locale` `ar-EG` | `t('welcome', {name: 'Ana'})` | `مرحبًا بعودتك يا ` + U+2068 + `Ana` + U+2069 | | `ar`, the person's languages `ar-EG`, `env.locale` `ar-EG` | `t('nights', {count: 3})` | `3 nights`: there is no Arabic entry, so the English one is used, with the English plural rule, its number written as `en-EG` writes it and its direction `ltr` | `t` fails with `effect` without a provider, `missing` for a key the host does not know or a blank or `by` without a value, `type` for a value of the wrong kind, and `range` for a malformed entry. ### 8.8 Questions about the app | Function | Result | | --- | --- | | `can(action, input?)` | `true` when invoking the action `action` with `input` now would pass its checks; otherwise `false`. | | `canSend(flow, event, key?)` | `true` when sending `event` to the flow `flow` now would take a transition; otherwise `false`. | These let a view or a step ask in advance what an invocation would answer, instead of repeating its guards. Both are answered by the host from the loaded definition and the app's current state; an implementation of this chapter evaluates them through a provider the host gives it, as it does `random()` and `uuid()`. Where the host provides neither, calling them fails with `effect`. Where they may be used is listed in `validation.md`, section "Expression scope". **`can(action, input?)`.** `action` is a string literal naming an action as a `run` step does: an action of this definition, or `part.action` for an exported action of a part. `input` defaults to `{}`. The host: 1. validates `input` against the action's `input` field map after applying field defaults, as an invocation does; if it does not conform, the result is `false`; 2. evaluates the action's `allow`, if any; if it is not `true`, the result is `false`; 3. evaluates each entry of the action's `require` in order; if one's condition is not `true`, the result is `false` (`core.md`, section "Actions"). Otherwise the result is `true`. Confirmation, grants, the caller's access to the action, and the guards of anything the action's steps would do are not considered. **`canSend(flow, event, key?)`.** `flow` is a string literal naming a flow of this definition and `event` a string literal naming an event. `key` identifies the element of a collection flow and is given exactly when the flow is a collection flow. The host finds the flow instance (for a collection flow, the first element of the collection whose key field equals `key`; if there is none, the result is `false`), takes its current state, and walks the transitions for `event` in that state as a `send` would: the first transition whose `if` is absent or `true` is the one that would be taken. If there is none, the result is `false`. Otherwise the result is that transition's `allow` (`true` when it has none). In these conditions `event` is `null`, and in a collection flow `item` and `index` are the element and its position (`core.md`, section "Flows"). Both functions: - evaluate the guards with the scope the calling expression has (the same `user`, `env` and state, including the pending writes of the current action) except for `input`, `event`, `item` and `index`, which are set as stated above; - treat a guard that fails with an error as not `true`, except for `budget` errors (section 10); - never run steps, never call a capability or code module, never raise events and never change anything. ## 9. Date, datetime and duration formats All dates use the proleptic Gregorian calendar with years 0000 to 9999. A result outside that range fails with `range`. - **Calendar date:** `YYYY-MM-DD`. It has no time zone. - **Datetime:** `YYYY-MM-DDTHH:MM:SS`, optionally followed by `.` and 1 to 9 fractional digits, followed by `Z` or an offset `+HH:MM` or `-HH:MM`. `T` and `Z` are uppercase. Hours are 00 to 23, minutes and seconds 00 to 59 (no leap seconds). A datetime denotes an instant; offsets are applied to obtain UTC. Precision is milliseconds: further fractional digits are truncated. Functions that return a datetime always return the canonical UTC form `YYYY-MM-DDTHH:MM:SSZ`, with `.mmm` (exactly three digits) before the `Z` when the milliseconds are not zero. - **Duration:** `[-]P[nY][nM][nW][nD][T[nH][nM][nS]]`, where each `n` is a non-negative integer, except that seconds may have a fraction of 1 to 9 digits. At least one component is required, and `T` must be followed by at least one time component. A leading `-` negates every component. - **Time of day:** `HH:MM`, with hours 00 to 23 and minutes 00 to 59, as taken by `atTime`. It has no time zone. A string argument that is not in the form a function requires fails with `range`; an argument that is not a string fails with `type`. ## 10. Cost budget Every evaluation has a budget of cost units. For expressions in a definition the budget is fixed at 100000: hosts MUST NOT use a different budget, so that an expression that evaluates on one host evaluates on every host. Each expression in a dynamic value has its own budget. When the total cost of an evaluation exceeds its budget, the evaluation fails with subcode `budget`. The **blocks** of a string are its number of code points divided by 1,024, rounded down, so a string shorter than 1,024 code points has none. The **deep size** of a value is 0 for `null`, a boolean or a number, the blocks of a string, and for a list or map its number of elements or keys plus the deep sizes of its members. Costs are: 1. **Nodes.** Each time a syntax node is evaluated: 1. This includes literals and identifiers, every node of a macro body each time the body is evaluated, and every member or index node in the argument of `has`. Parentheses are not nodes. The variable named by a list macro or by `let` is not a node. 2. **Macro iteration.** Each element a list macro visits: 1, in addition to the cost of evaluating its body. `all`, `exists` and `find` count only the elements they visit before stopping. 3. **Function arguments.** Each function call: the number of elements of every list argument, the number of keys of every map argument and the blocks of every string argument (the receiver of a method call is an argument), charged after the arguments are evaluated. 4. **Built collections.** `range(n)` costs `n`; `split` costs the number of parts; `flatten` and `enumerate` cost the size of their result; `+` on two lists costs the size of the result. Each is charged before the result is built. 5. **Built strings.** `+` on two strings, a template, `t`, `join`, `replace`, `padStart`, `padEnd`, `upper`, `lower`, and `string()` of a list or map each cost 1 per 1,024 code points of the string they return, rounded down. A string shorter than 1,024 code points costs 0. Converting a list or map inside a template also costs its number of elements or keys. 6. **Equality.** Each comparison of two values for equality costs the smaller of their deep sizes. This applies to `==` and `!=`, to every element compared by `in` on a list, `contains` on a list and `indexOf` on a list, which also cost the size of the list (by rule 3, or for `in` directly), and to nothing else. Comparing with `null`, a boolean, a number or a string shorter than 1,024 code points therefore costs 0. 7. **Distinct values.** `distinct` costs the deep size of each element, and `distinctBy` the deep size of each key, in addition to rules 2 and 3. These functions compare elements by a canonical form whose construction is proportional to that deep size, rather than pairwise, so their charge does not depend on the other elements. 8. **Patterns.** `matches(s, p)` costs the weight of `p` (section 18.3, and at least 1) times the number of code points of `s`, divided by 256 and rounded down, charged before matching. When `p` is not a string literal, the call costs 40 more, for compiling a pattern that is known only when it is used. 9. **Questions.** `can` costs the deep size of its input, and `can` and `canSend` cost every guard expression they evaluate, counted by these rules as though it were part of the calling expression. They are charged to the calling evaluation's budget; when that budget is exhausted inside a guard, the calling evaluation fails with `budget`. 10. **Ordering and keys.** Each comparison of two strings by `<`, `<=`, `>` or `>=` costs the smaller of their blocks. `min` and `max` given a list cost the deep size of each element, and `sortBy`, `minBy`, `maxBy`, `groupBy` and `indexBy` the deep size of each key, in addition to rules 2 and 3. Indexing a map with a string key (`m[k]`, also inside `has`) and `in` on a map cost the blocks of the key. For example: `1 + 2` costs 3; `size([1, 2])` costs 6 (four nodes plus two elements); `[1, 2, 3].map(x, x)` costs 11 (five nodes for the call and the list, and two per element); `'a' in ['a', 'b']` costs 7 (five nodes, two for the list, and 0 for comparing two scalars); `[[1, 2]] == [[1, 2]]` costs 12 (nine nodes plus the deep size 3); `padStart('', 2048)` costs 5 (three nodes plus 2 for 2,048 code points); `size(state.note)` costs 3 for a short note and 7 for one of 5,000 code points (three nodes plus 4 blocks). Every expression has finite size, every macro visits a finite list, every list is paid for when it is built, work on a long string is paid for in proportion to its length, no string an expression builds can exceed the length limit, and every pattern matches in time proportional to its weight times the length of its input, so every evaluation terminates, and the time and memory it can use are bounded. ### 10.1 Typical costs The table shows what common shapes cost by the rules above, for a list of `n` elements and the largest `n` the budget of 100000 allows. Use it to judge what fits; where a check is quadratic, build a lookup map once with `indexBy` or `groupBy`, or name a repeated sub-result with `let`. | Expression | Cost | Largest `n` | | --- | --- | --- | | `state.goal - state.saved` | 5 | | | `` `Saved ${state.saved} of ${state.goal}` `` | 5 | | | `formatNumber(state.total, {style: 'currency'})` | 6 | | | `t('nights', {count: state.nights})` | 6 | | | `state.deposits.sumBy(d, d.amount)` | 3n + 3 | 33,332 | | `sum(state.deposits.map(d, d.amount))` | 4n + 4 | 24,999 | | `state.tiles.sortBy(t, t.pos)` | 3n + 3 | 33,332 | | `state.items.indexBy(i, i.id)` | 3n + 3 | 33,332 | | `state.items.count(i, i.status == 'open')` | 5n + 3 | 19,999 | | `state.items.find(i, i.id == input.id)` (no match) | 6n + 3 | 16,666 | | `state.e.map(a, state.e.count(b, b.day == a.day))` | 6n² + 4n + 3 | 128 | | `let(m, state.e.indexBy(x, x.id), state.o.map(o, m[o.itemId].price))`, with `n` elements in each list | 9n + 7 | 11,110 | | `matches(input.code, '^[A-Z]{3}-[0-9]{4}$')` on a short string | 4 | | ## 11. Errors A syntax error has `code` `expression.syntax` and a position in the source. An evaluation error has `code` `expression.error`, a position, and one of these subcodes: | Subcode | Raised when | | --- | --- | | `missing` | A map has no such key, a member or index is applied to `null`, a list index is out of range, or `t` names a key the host does not know or leaves a blank without a value (section 8.7). | | `type` | An operand or argument has the wrong kind, a condition or predicate is not a boolean, or a value is outside the data model. | | `divideByZero` | The right operand of `/` or `%` is zero. | | `budget` | The evaluation exceeded its cost budget, would have built a string longer than the length limit (section 1), or exhausted a resource of the implementation (section 5). | | `unknownFunction` | A call names no function. | | `unknownIdentifier` | A root identifier is not in the scope. | | `arity` | A function was called with the wrong number of arguments. | | `effect` | A function that the host provides only at some positions (`random`, `uuid`, `can`, `canSend`) was called where it is not provided, or `t` was called where the host gives no texts. | | `range` | A value has the right kind but is not accepted: a non-integer where an integer is required, a malformed date, datetime, time of day, duration or number string, an unknown part, unit, style or option name, an unknown time zone, a pattern outside the dialect of section 18, a numeric result that is not finite, a date outside years 0000 to 9999, or a malformed entry of the app's texts (section 8.7). | Positions and messages are informative. The `code` and `subcode` are normative. ## 12. Paths A **path** names a writable location, such as the target of a `set` step or a two-way binding (`core.md`, sections "Steps" and "Visual surface"). A path is a root name followed by names separated by `.`, and, where this section allows them, by **selectors** that pick one element of a list: ``` path = IDENT { "." NAME | selector } selector = "[" NAME "=" expr "]" ``` `IDENT` and `NAME` are as in section 2: the first name MUST NOT be a reserved word, and later names may be. Outside selectors a path has no whitespace. Inside a selector, whitespace may surround the field name, the `=` and the expression. The `=` is a single `=`; the expression after it is any expression of section 3, read with the lexical rules of section 2, and ends at the first `]` that is not part of it: a `]` inside a string or template literal, or one that closes a `[` inside the expression, does not end it (`state.lines[id=input.ids[0]]`, `state.tags[name='a]b']`). A selector expression is subject to the limits of section 3.1 as an expression of its own, and a whole path MUST NOT be longer than 10000 code points. A path that does not match is a syntax error. ``` state.form.amount state.answers[id=item.id].note state.inspections[id=input.inspectionId].checks[key=input.check].result view.draft.title ``` Selectors are allowed only in the targets of `set`, `append`, `remove` and `patch` steps and in `bind`. A path with a selector anywhere else (a `changes` trigger, a flow's `over.collection`, an exported input, a `refresh` step) is a syntax error. **What a path selects.** Starting from the root, each `.name` selects the member of that name as in section 5.1. A selector `[f=e]` applies to a list: it selects the first element that is a map with a member `f` equal (section 5.3) to the value of `e`. Elements that are not maps, or have no member `f`, never match. When no element matches, the path selects nothing: a write through it fails with `state.noElement`, and a binding through it shows an empty, disabled control (`core.md`, sections "Steps" and "Visual surface"). A selector applied to a value that is not a list selects nothing in the same way. **Evaluating selectors.** Selector expressions are evaluated in the scope of the step or node that holds the path, before the step writes or the binding reads, from left to right, each with its own budget. They see the roots and local names of that step or node, but not the `item` and `index` that a `remove` or `patch` binds for its `where` (`validation.md`, section "Expression scope"). An error in a selector expression fails the step; in a binding, the control is shown empty and disabled and nothing is written. How a host writes through a path is otherwise defined by the step or binding that uses it. ## 13. Static analysis Hosts need to know what an expression reads, for example to recompute derived state when its inputs change (`core.md`, section "State"). The **references** of an expression are the root-anchored static paths it may read: - A chain of member accesses and string-literal indexes starting at a free root identifier is one path: `state.m['k'].z` reads `state`, `m`, `k`, `z`. - A chain stops at the first index that is not a string literal; the path read so far is reported and the index expression is analyzed on its own. `state.items[input.i].name` reads `state.items` and `input.i`. - Identifiers bound by a list macro or by `let` are not references. Paths are reported once each, in the order they first appear. - A function that reads `env` (section 8.6, and `atTime` and `dateIn` without a `zone` argument) adds the `env` fields it may read, after the references of its arguments: `formatNumber` adds `env.locale` and `env.currency`; `formatDate` adds `env.locale` and `env.timezone`; `relativeTime` adds `env.now`, `env.today` and `env.locale`; `plural` adds `env.locale`; `atTime` and `dateIn` add `env.timezone`. - `t` adds `env.language` and `env.locale`, after the references of its arguments. Its text depends on the language shown and on the person's languages, which these two fields follow. A host that changes the person's languages, or the language the person chose for the app, MUST treat both fields as changed even where a value stays the same, because a text taken from another language's table follows the person's languages directly. A reference to a path means the expression may depend on any value at or below that path. The references of `can` and `canSend` calls are those of their arguments. Their results also depend on the guards they evaluate, which this analysis cannot see; a host that recomputes values when their inputs change MUST also treat a `can` or `canSend` call as reading what those guards read (other than `input`, `event`, `item` and `index`), the collection of a collection flow, and `flows.` of a singleton flow. The references of a path are the path with its selectors removed, up to the first selector (`state.answers` for `state.answers[id=item.id].note`), together with the references of each selector expression. ## 14. Examples ``` state.goal - state.saved sum(state.deposits.map(d, d.amount)) state.deposits.filter(d, d.date >= startOf(toDate(env.now), 'month')).sumBy(d, d.amount) 'manager' in user.roles has(state.profile.email) && state.profile.email.endsWith('@example.com') default(state.form.note, '') `You saved ${round(state.saved / state.goal * 100)}% of ${state.goal}` state.tasks.groupBy(t, t.status) daysBetween(toDate(env.now), state.trip.departs) <= 7 ? 'soon' : 'later' `Put aside ${formatNumber(state.weekly, {style: 'currency'})} a week` `Updated ${relativeTime(sources.tickets.updatedAt)}` let(byItem, state.answers.indexBy(a, a.itemId), state.items.filter(i, !(i.id in byItem))) merge(item, {done: true, doneAt: env.now}) matches(trim(input.word), '^[a-z]+$') atTime(addDays(state.deadline, -3), '09:00') can('approveRequest', {id: item.id}) t('nights', {count: state.trip.nights}) ``` ## 15. Differences from CEL The syntax is a subset of CEL with template strings added. The semantics follow the JSON data model. Concretely: - **One number kind.** There are no separate `int`, `uint` and `double` types and no integer overflow: every number is a double. `int()` truncates to an integral number rather than converting to an integer type. - **True division.** `/` always divides exactly (`7 / 2` is `3.5`), where CEL truncates integer division. `%` accepts non-integers. - **Errors instead of special values.** Results that would be infinite or NaN fail with `range`. - **Left-to-right logic.** `&&` and `||` short-circuit from left to right and require booleans. CEL's commutative error absorption (`error || true` is `true`) does not apply: an error on the left side propagates. - **Equality and `+`.** `==` compares deeply across kinds and never fails. `+` does not mix kinds. - **Map literals.** A bare identifier key is the literal key name (`{goal: 1}` has key `goal`), where CEL evaluates it as an expression. Keys are limited to string literals and names. - **Template strings** with `${...}` interpolation are not part of CEL. - **`has()`** accepts index steps and whole chains, and returns `false` when any step is absent or passes through `null`, where CEL's `has()` tests one field and fails if an earlier step is absent. - **Local names.** `let(name, value, body)` plays the part of CEL's `cel.bind(name, value, body)`. - **Patterns.** `matches` takes a pattern in the restricted dialect of section 18, not full RE2 syntax, and the dialect is also used by a type's `pattern`. - **Added macros and functions.** `default`, `let`, `find`, `count`, `sortBy`, `groupBy`, `indexBy`, `sumBy`, `minBy`, `maxBy` and `distinctBy` are not CEL macros, and most functions in section 8 are not in CEL's standard library. CEL's `exists_one` and three-argument `map` are not provided. - **Not supported:** bytes, `uint`, `timestamp` and `duration` types (dates and durations are ISO 8601 strings); protocol buffer messages; type values (`type()` returns a string); optional values and `.?`; raw, triple-quoted and byte string literals; octal and hexadecimal escapes; hexadecimal and unsigned number literals; number literals starting with `.`; comments. - **Reserved words.** Only `true`, `false`, `null` and `in` are reserved. CEL's other reserved words (`if`, `package`, `return` and so on) are ordinary identifiers, because they can be names in a definition. - **Membership** with `in` on lists and maps is as in CEL and is not a difference. - **Limits.** Strings built by an evaluation are limited to 1,048,576 code points (section 1). - **Cost budget.** Every evaluation is bounded by the cost model of section 10. - **Static types.** CEL type-checks against declared types and rejects an expression that may fail. The checks of section 17 report only what is certain to fail, and treat anything not known as acceptable. ## 16. Conformance A conforming implementation MUST produce, for every vector in `conformance/0.2/expressions/`, exactly the result or error that vector states. Each file is a JSON array of vectors, grouped by topic. A vector has a `name` and one of these shapes: | Shape | Meaning | | --- | --- | | `{ "expr", "scope"?, "budget"?, "effects"?, "texts"?, "expect" }` | Evaluating `expr` against `scope` (default `{}`) yields `expect`, compared with section 5.3: lists in order, maps structurally. | | `{ "expr", ..., "expectPattern" }` | Evaluating `expr` yields a string that `expectPattern`, a pattern in the dialect of section 18, matches. Used for the functions of section 8.6, and for `t` with a number, whose text varies between hosts. | | `{ "expr", ..., "error": subcode }` | Evaluation fails with `expression.error` and that subcode. | | `{ "expr", ..., "syntaxError": true }` | Parsing fails with `expression.syntax`. | | `{ "value", "scope"?, ... }` | As above, for a dynamic value (section 6). An optional `pointer` is the JSON Pointer the error must carry. | | `{ "path", "expect" \| "syntaxError" }` | Parsing a path (section 12) yields the list `expect`, in which a name is a string and a selector is `{ "field": name, "expr": source }`, with `source` the text of the selector expression without surrounding whitespace; or parsing fails. | | `{ "expr", "references", "functions", "identifiers" }` | Static analysis (section 13): the references, the distinct names of functions and macros called, and the distinct free root identifiers, each in first-appearance order. | | `{ "expr", "types", "typeErrors", "resultType"? }` | Static types (section 17): with each root name in `types` given the static type of the type reference beside it (section 17.2; references are inline JSON Schema objects or primitive shorthands), checking `expr` reports exactly the codes in `typeErrors` (`expression.unknownMember` or `expression.typeMismatch`), compared as a multiset, and its type is the static type of the type reference `resultType`. | `budget` overrides the default budget for that vector. `effects` supplies a provider whose `random()` always returns `effects.random` and whose `uuid()` always returns `effects.uuid`; without it, effects are not allowed. Vectors for the functions of section 8.6 set `env.locale` to `en-US` and `env.timezone` in their scope; a conforming implementation MUST have locale data for `en-US`, and the patterns accept the variation that locale data for `en-US` allows. `can` and `canSend` need a loaded definition and are tested by the semantic fixtures of `validation.md`, not by these vectors. An evaluation vector may carry `texts`, the answers of a provider of texts (section 8.7): a map from each key the provider knows to the answer it gives for that key, `{ "entry", "language", "locale", "direction" }`. A key not in `texts` is one the host does not know, and a vector without `texts` has no provider, so its `t` fails with `effect`. The vectors so do not depend on how a host chooses a language. They write numbers only in the locale `en-US` (one of them gives `en-EG` for the number 3, which every English locale writes the same), and test a right-to-left text by giving the direction `rtl`. ## 17. Static types Before a definition runs, a validator infers a **static type** for every expression whose types can be known, and reports operations that are certain to fail (`validation.md`, section "Static types in a definition"). This section defines those types and the rules, so that every validator reports the same diagnostics for the same definition. Static types play no part in evaluation: a host evaluates by sections 1 to 12 alone. The governing principle is that a diagnostic is reported only when it is certain. Anything whose type is `any`, `null` or not known, and any member of an open map that the map does not name, passes. ### 17.1 Types | Static type | Describes | | --- | --- | | `any` | Nothing is known about the value. | | `null` | The value `null`. | | `boolean`, `number`, `string` | A value of that kind. | | `list` | A list whose elements have type `T`. | | map type | A map. It has zero or more **named members**, each with a type, and is either **closed** (it has no other members) or **open**, with a **rest type** for members it does not name (`any` when nothing is known of them). | `map` stands for the open map type with no named members and rest type `T`. A type is **known** when it is neither `any` nor `null`. The **kind** of a known type is `boolean`, `number`, `string`, `list` or `map`. A static type records kinds and shapes only. Whether a number is an integer, a string's `format` (such as `date`), `enum` and `const` values, `pattern`, and length and range limits are not part of it; they are checked on literal values by validation and on every value at run time. Absence and `null` are not tracked. A named member is assumed to be present, and a type reference marked nullable gives the same static type as the reference without `?`. Reading an optional field, or a member of a value that may be `null`, is therefore never reported, and neither is passing `null` where a value is expected. ### 17.2 Types from type references A type reference (`core.md`, section "Types") gives a static type as follows. For a JSON Schema object, the first row that applies is used. | Type reference | Static type | | --- | --- | | `string`, `date`, `datetime`, `duration` | `string` | | `number`, `integer` | `number` | | `boolean` | `boolean` | | `any` | `any` | | A type name, `alias:TypeName`, or a schema with `$ref` | The static type of the schema referred to. | | `T[]` | `list` | | `T?` | The static type of `T`. | | Schema with `type` `"object"` | A map type with a named member for each entry of `properties`, typed by its schema. It is closed when `additionalProperties` is `false`, and otherwise open with rest type from `additionalProperties` when that is a schema, else `any`. `required` is ignored. | | Schema with `type` `"array"` | `list` with `T` from `items`, or `list` without `items`. | | Schema with `type` `"string"`, `"number"`, `"integer"`, `"boolean"` or `"null"` | `string`, `number`, `number`, `boolean` or `null`. | | Schema with `type` given as a list | Without `"null"`, a single remaining entry is read as above; otherwise `any`. | | Schema with `enum` | The union (section 17.3) of the static types of its values. | | Schema with `const` | The static type of its value. | | Schema with `oneOf` | The union of the static types of its members. | | Any other schema | `any` | | A reference that does not resolve | `any` | The static type of a JSON value is `null`, `boolean`, `number` or `string` for a scalar; `list` for an array, with `U` the union of its elements' types (`list` when empty); and for an object, a closed map type with a named member for each key, typed by its value. A dynamic value has the same static type, except that each expression in it has its inferred type. A **field map** gives a closed map type with a named member for each field, typed by the field's `type`. A named type may refer to itself; its members are expanded only as far as an expression reads them, so inference always ends. ### 17.3 Union The union of two types `A` and `B` is: 1. `any`, when either is `any`; 2. the other, when one is `null`; 3. that kind, when both are `boolean`, both `number` or both `string`; 4. `list`, when both are lists, with `U` the union of their element types; 5. when both are map types, a map type that names every member either names. A member's type is the union of its type in each map that names it and the rest type of each open map that does not. The result is closed when both are closed, and otherwise open with a rest type that is the union of the rest types of the open ones; 6. `any` otherwise. The union of more than two types is taken from left to right. The members of a union of map types are computed when an expression reads them. `[1, 2]` is `list`; `[1, 'a']` is `list`; `c ? {a: 1} : {b: 'x'}` is a closed map naming `a` (a number) and `b` (a string). A `oneOf` of closed object types gives a closed map naming every property of every member, so a property that no member has is reported, and one that some member has is not. ### 17.4 Inference | Expression | Static type | | --- | --- | | `null`, `true`, `false`, a number or string literal | `null`, `boolean`, `number`, `string` | | A template | `string` | | `[e1, e2, ...]` | `list`, with `U` the union of the elements' types; `[]` is `list` | | `{k1: e1, ...}` | A closed map type with a named member for each key, typed by its value | | An identifier bound by a list macro | The element type of the macro's receiver (`any` when the receiver is not a known list) | | An identifier bound by `let` | The type of `let`'s value | | Any other identifier | The type of that root or local name at the expression's position (`validation.md`, section "Static types in a definition"); `any` for a name that is not in scope | | `x.n`, `x['n']`, `x[k]` | Section 17.6 | | `has(p)` | `boolean` | | `default(a, b)` | The union of the types of `a` and `b` | | `let(n, v, e)` | The type of `e` | | `!a`, `a == b`, `a != b`, `a < b`, `a <= b`, `a > b`, `a >= b`, `a in b`, `a && b`, `a \|\| b` | `boolean` | | `-a`, `a - b`, `a * b`, `a / b`, `a % b` | `number` | | `a + b` | `number` when either operand is a number, `string` when either is a string, `list` when both are lists (`U` the union of their element types), `list` when one is a list and the other is not known, otherwise `any` | | `c ? a : b` | The union of the types of `a` and `b` | | A function call or list macro | Its result type (section 17.5) | Static types are not narrowed by conditions or by `has`: in `type(x) == 'number' ? x + 1 : 0`, `x` keeps its own type in both branches. Every part of an expression is checked, including the branch of a conditional that is not taken and the body of a list macro, which is checked as though the list had an element. ### 17.5 Signatures In this table, `T` stands for one static type throughout a row, `U` for another, `map` for any map type, `A | B` for a parameter that accepts either, `?` marks an optional parameter and `...` repetition. A parameter accepts the kind it names; `list` accepts a list whose element type is `number` or not known. | Function | Parameters and result | | --- | --- | | `size` | `(string \| list \| map) -> number` | | `sum`, `avg` | `(list) -> number`; `(number, ...) -> number` | | `min`, `max` | `(list) -> T` with `T` `number` or `string`; `(T, ...) -> T` with every argument of one kind, `number` or `string` | | `keys` | `(map) -> list` | | `values` | `(map) -> list`, with `V` the union of the map's named member types and, when open, its rest type | | `entries` | `(map) -> list<{key: string, value: V}>`, closed, with `V` as for `values` | | `merge` | `(map, map) -> map`: see below | | `compact` | `(map M) -> M` | | `reverse` | `(list) -> list`; `(string) -> string` | | `slice` | `(list, number, number?) -> list`; `(string, number, number?) -> string` | | `first`, `last` | `(list) -> T` | | `flatten` | `(list>) -> list`; `(list) -> list` when `T` is known and not a list; `(list) -> list` | | `distinct` | `(list) -> list` | | `enumerate` | `(list) -> list<{index: number, value: T}>`, closed | | `range` | `(number) -> list` | | `contains` | `(list, any) -> boolean`; `(string, string) -> boolean` | | `indexOf` | `(list, any) -> number`; `(string, string) -> number` | | `abs`, `floor`, `ceil` | `(number) -> number` | | `round` | `(number, number?) -> number` | | `int`, `number` | `(number \| string) -> number` | | `string` | `(any) -> string` | | `bool` | `(boolean \| string) -> boolean` | | `type` | `(any) -> string` | | `startsWith`, `endsWith` | `(string, string) -> boolean` | | `lower`, `upper`, `trim` | `(string) -> string` | | `split` | `(string, string) -> list` | | `join` | `(list, string?) -> string` | | `replace` | `(string, string, string) -> string` | | `substring` | `(string, number, number?) -> string` | | `padStart`, `padEnd` | `(string, number, string?) -> string` | | `matches` | `(string, string) -> boolean` | | `addDays`, `addMonths` | `(string, number) -> string` | | `addDuration` | `(string, string) -> string` | | `daysBetween`, `durationBetween` | `(string, string) -> number` | | `datePart` | `(string, string) -> number` | | `startOf` | `(string, string) -> string` | | `toDate` | `(string) -> string` | | `seconds` | `(string) -> number` | | `atTime` | `(string, string, string?) -> string` | | `dateIn` | `(string, string?) -> string` | | `formatNumber` | `(number, map?) -> string` | | `formatDate` | `(string, string?) -> string` | | `relativeTime` | `(string) -> string` | | `plural` | `(number, map) -> string` | | `random` | `() -> number` | | `uuid` | `() -> string` | | `can` | `(string, map?) -> boolean` | | `canSend` | `(string, string, any?) -> boolean` | | `t` | `(string, map?) -> string`: see below | When an argument is not known, a function whose result depends on it (`reverse`, `slice`, `first`, `last`, `min`, `max`) returns `any`. The result of `merge(a, b)` is, when both are map types, a map type naming every member either names: a member `b` names has its type in `b`; any other member has its type in `a`, joined (section 17.3) with `b`'s rest type when `b` is open. It is closed when both are closed, and otherwise open with the union of the open ones' rest types. When either argument is not known, the result is `map`. Each member of the map given to `t` is a string, a number, a boolean or `null`: a member that is known and a list or a map is reported. A boolean passes, because it may be the `by` blank of the entry, which the static types cannot see; whether the entry inserts it is checked by validation, which knows the table (`validation.md`). | Macro | Receiver, body and result | | --- | --- | | `l.map(x, e)` | `list`, any `e` → `list`, `E` the type of `e` | | `l.filter(x, p)` | `list`, `p` boolean → `list` | | `l.all(x, p)`, `l.exists(x, p)` | `list`, `p` boolean → `boolean` | | `l.find(x, p)` | `list`, `p` boolean → `T` | | `l.count(x, p)` | `list`, `p` boolean → `number` | | `l.sortBy(x, k)`, `l.distinctBy(x, k)` | `list`, `k` number or string (any for `distinctBy`) → `list` | | `l.minBy(x, k)`, `l.maxBy(x, k)` | `list`, `k` number or string → `T` | | `l.groupBy(x, k)` | `list`, `k` string → `map>` | | `l.indexBy(x, k)` | `list`, `k` string → `map` | | `l.sumBy(x, e)` | `list`, `e` number → `number` | | `has(p)` | any path → `boolean` | | `default(a, b)` | any, any → the union of their types | | `let(n, v, e)` | any `v`, any `e` → the type of `e` | When the receiver of a list macro is not a known list, `T` is `any`, and the result is `list`, `any`, `boolean` or `number` as the row says. ### 17.6 What is reported Two diagnostics come from these rules (`validation.md`, section "Expressions and references"). Each operation is reported at most once. **`expression.unknownMember`** is reported for a member access `x.n`, or an index `x['n']` with a string literal, when the type of `x` is a closed map type that does not name `n`. Its type is then `any`. A validator reports a more specific diagnostic instead where `validation.md` names one (such as `reference.unknownState` for `state.n`). Member access and indexing are typed as follows: | Target type | `x.n` and `x['n']` | `x[k]`, `k` not a string literal | | --- | --- | --- | | `any` or `null` | `any` | `any` | | A map type | The member's type if named; otherwise the rest type if open; otherwise reported as `expression.unknownMember` | `expression.typeMismatch` if `k` is known and not a string; the rest type when the map names no members; otherwise `any` | | `list` | `expression.typeMismatch`; `any` | `expression.typeMismatch` if `k` is known and not a number; `T` | | `boolean`, `number` or `string` | `expression.typeMismatch`; `any` | `expression.typeMismatch`; `any` | The same rules apply to every step of the path inside `has(...)` and `default(...)`. **`expression.typeMismatch`** is also reported, at the operation, when: - the operand of `!` is known and not a boolean, or the operand of unary `-` is known and not a number; - an operand of `&&` or `||`, or the condition of `? :`, is known and not a boolean; - an operand of `<`, `<=`, `>` or `>=` is known and neither a number nor a string, or both are known and one is a number and the other a string; - the right operand of `in` is known and neither a list nor a map, or it is a map type and the left operand is known and not a string; - an operand of `+` is known and is a boolean or a map, or both are known and of different kinds; - an operand of `-`, `*`, `/` or `%` is known and not a number; - a function is called with a number of arguments its signature does not allow; - an argument is known and of a kind its parameter does not accept, or a list argument has a known element type of a kind the parameter does not accept; for the variadic forms of `min` and `max`, the known arguments are not all numbers or all strings; for `contains` and `indexOf` on a string, the second argument is known and not a string; for `t`, a member of its map is known and a list or a map; - the receiver of a list macro is known and not a list; the predicate of `filter`, `all`, `exists`, `find` or `count` is known and not a boolean; the key of `sortBy`, `minBy` or `maxBy` is known and neither a number nor a string; the key of `groupBy` or `indexBy` is known and not a string; the body of `sumBy` is known and not a number. Nothing else is reported. In particular `==`, `!=`, template interpolations, `string()` and `type()` accept every type, and a call to an unknown function is reported only as `expression.unknownFunction` (a warning), with type `any`. An operation that is reported has the type its row in section 17.4 gives when that row does not depend on the operands, and `any` otherwise, so one fault does not cause others. ### 17.7 Compatible types Where a computed value must conform to a declared type, validation reports `expression.typeMismatch` when the value's static type is **incompatible** with the declared one. A type `V` is incompatible with a type `D` when: - both are known and of different kinds; - both are lists, and `V`'s element type is incompatible with `D`'s; - both are map types, and a member named by `V` is incompatible with the member of that name in `D`; or `D` does not name it and is closed; or `D` does not name it, is open, and the member is incompatible with `D`'s rest type. Otherwise the types are compatible. A comparison that reaches a pair of types already being compared, as happens with a type that refers to itself, takes that pair as compatible, so every comparison ends. `any` and `null` are compatible with every type, as is anything with `any`. Since refinements are not part of static types, a `number` is compatible with `integer` and a `string` with `date`; such values are checked when they are written. ### 17.8 Worked examples The scope types are `state: { goal: number, note: string?, deposits: Transaction[], extra: any, settings: { "type": "object" } }`, with `Transaction` a closed object type with `id` and `memo` (strings, `memo` not required), `amount` (number) and `date` (date), and `input` the closed field map `{ amount: number }`. | Expression | Reported | Why | | --- | --- | --- | | `state.deposits.map(d, d.amont)` | `expression.unknownMember` | `Transaction` is closed and has no `amont`. | | `state.goal + ' left'` | `expression.typeMismatch` | `+` with a number and a string. | | `state.deposits.sumBy(d, d.memo)` | `expression.typeMismatch` | The body of `sumBy` is a string. | | `state.deposits.filter(d, d.amount)` | `expression.typeMismatch` | The predicate is a number. | | `size(state.goal)` | `expression.typeMismatch` | `size` does not accept a number. | | `{a: 1}.b` | `expression.unknownMember` | A map literal is closed. | | `input.amount > 0 && input.amount` | `expression.typeMismatch` | The right operand of `&&` is a number. | | `state.deposits[0].memo.size() > 0` | none | `memo` is optional, but absence is not tracked. | | `state.note + '!'` | none | `note` is nullable, but `null` is not tracked. | | `state.extra.anything + 1` | none | `extra` is `any`. | | `state.settings.theme` | none | `settings` is an open map. | | `state.goal + state.extra` | none | One operand is not known; the type is `number`. | | `type(state.extra) == 'string' ? state.extra.size() : 0` | none | `extra` is `any` in both branches. | | `` `${state.goal} left` `` | none | Interpolation accepts every type. | ## 18. Patterns `matches` (section 8.3) and the `pattern` keyword of a type schema (`core.md`, section "Types") use one **pattern dialect**. Its syntax is a subset of ECMAScript's regular expression syntax with the `u` flag; its meaning is defined by section 18.2 alone, and every pattern in it can be matched in time proportional to the length of the input. An implementation that matches with another engine, such as RE2, MUST translate the constructs whose meaning there differs, among them `.`, `\s`, `\S` and the `\u` escapes. Backreferences, lookaround, word boundaries, flags, named groups and Unicode property classes are not part of it. ### 18.1 Syntax ``` pattern = alternative { "|" alternative } alternative = { term } term = "^" | "$" | atom [ quantifier ] atom = char | "." | escape | class | "(" pattern ")" | "(?:" pattern ")" quantifier = "*" | "+" | "?" | "{" count "}" | "{" count ",}" | "{" count "," count "}" count = DIGIT { DIGIT } class = "[" [ "^" ] item { item } "]" item = classchar [ "-" classchar ] | classescape | "-" escape = "\d" | "\D" | "\w" | "\W" | "\s" | "\S" | charescape | "\" ( syntaxchar | "/" ) classescape = "\d" | "\D" | "\w" | "\W" | "\s" | "\S" classchar = any code point except "\", "]", "[" and "-" | charescape | "\" ( syntaxchar | "/" | "-" ) charescape = "\t" | "\n" | "\v" | "\f" | "\r" | "\u" HEX HEX HEX HEX | "\u{" HEX { HEX } "}" char = any code point except syntaxchar syntaxchar = "^" | "$" | "\" | "." | "*" | "+" | "?" | "(" | ")" | "[" | "]" | "{" | "}" | "|" ``` Further rules: - A slash is an ordinary character, and `\/` also stands for it. - In a class, a bare `-` item is allowed only as the first item (after any `^`) or the last, where it is a literal; elsewhere a `-` joins two `classchar`s into a range, whose first code point MUST NOT be greater than its last. A class escape such as `\d` cannot be the end of a range. A class has at least one item: `[]` and `[^]` are outside the dialect. - `\u` escapes name a code point: exactly four hexadecimal digits, or one to six in braces with a value up to 10FFFF. Surrogates (D800 to DFFF) are outside the dialect. - In a quantifier, each count is at most 1000, and in `{m,n}`, `m` MUST NOT be greater than `n`. A quantifier cannot follow `^`, `$` or another quantifier: lazy forms such as `+?` and repeated quantifiers such as `a**` are outside the dialect. - `(?` followed by anything other than `:` is outside the dialect. - A pattern MUST NOT be longer than 1000 code points, and its weight (section 18.3) MUST NOT exceed 10000. Anything else, such as `\b`, `\1`, `\p{L}`, `\x41`, `(?=`, `(?`, `(?i)` or an unescaped `{`, is outside the dialect. ### 18.2 Meaning A pattern and its input are sequences of code points. A pattern describes a set of strings: | Construct | Matches | | --- | --- | | `char`, `\/` and the other escaped syntax characters | That code point. | | `\t` `\n` `\v` `\f` `\r` | U+0009, U+000A, U+000B, U+000C, U+000D. | | `\uXXXX`, `\u{X...}` | The code point with that value. | | `.` | Any one code point except U+000A, U+000D, U+2028 and U+2029. | | `\d`, `\D` | One of `0` to `9`; any other code point. | | `\w`, `\W` | One of `A` to `Z`, `a` to `z`, `0` to `9` and `_`; any other code point. | | `\s`, `\S` | One of U+0009 to U+000D, U+0020, U+00A0, U+1680, U+2000 to U+200A, U+2028, U+2029, U+202F, U+205F, U+3000 and U+FEFF; any other code point. | | `[...]` | One code point that is one of the class's items: a code point, every code point in a range (inclusive), or a code point in a class escape's set. | | `[^...]` | One code point that is none of them. | | `^`, `$` | The empty string at the start, or at the end, of the input. | | `a b` (a sequence) | A string matched by `a` followed by one matched by `b`. An empty alternative matches the empty string. | | `a \| b` | A string matched by either. | | `( p )`, `(?: p )` | What `p` matches. Groups only group: nothing is captured. | | `a*`, `a+`, `a?` | Zero or more, one or more, zero or one strings matched by `a`, one after another. | | `a{m}`, `a{m,}`, `a{m,n}` | Exactly `m`, at least `m`, from `m` to `n` strings matched by `a`. | Matching is exact by code point: there is no case folding and no normalization, and `\d`, `\w` and `\s` are the fixed sets above whatever the locale. A pattern **matches** a string when it matches some part of the string, with `^` and `$` standing only for the start and the end of the whole string. Since only whether a match exists is observable, which part matches is never defined. The empty pattern matches every string. ### 18.3 Weight and time The **weight** of a pattern bounds the work of matching it: - a `char`, escape, `.` or class weighs 1, and so does `^` or `$`; - an alternative weighs the sum of its terms, and a pattern the sum of its alternatives; - a group weighs what its contents weigh; - `a*`, `a+` and `a?` weigh what `a` weighs; `a{m}` and `a{m,}` weigh `max(m, 1)` times what `a` weighs, and `a{m,n}` `n` times. `^[A-Z]{3}-[0-9]{4}$` weighs 10. A host MUST match patterns in time bounded by a constant times the weight times the length of the input, for example with an automaton; a backtracking matcher, whose time can grow exponentially, does not meet this requirement. A pattern outside the dialect is a syntax error when it is a string literal argument of `matches` (section 3), fails with `range` when `matches` receives it at run time, and is `type.invalid` in a type schema (`validation.md`, section "Types and values"). --- # Open App Definition (OAD) 0.2: Validation Status: working draft. The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are to be read as in RFC 2119. This chapter lists the semantic checks that a definition, a catalog and a design system pass in addition to their JSON Schemas. Each check has a stable diagnostic code, a severity and a one-line statement. A **conforming definition** validates against the 0.2 definition schema and produces no error from the checks below; the same holds for catalogs and design systems with their own schemas and checks. ## 1. Diagnostics A validator reports every problem it finds as a **diagnostic**: | Field | Meaning | | --- | --- | | `code` | A stable code from the tables below, written `.`. | | `severity` | `error` or `warning`. An error makes the document non-conforming. A warning marks something legal that probably does not do what the author meant. | | `pointer` | JSON Pointer (RFC 6901) to the offending value: the key, string or object that breaks the rule. A missing member is reported at the object that lacks it. | | `message` | Human-readable explanation. Informative only. | - A validator MUST report the code and severity given here, and the pointer given in the conformance fixtures. Messages MAY differ. - A validator MUST collect all diagnostics rather than stop at the first. - A validator MUST NOT fail on malformed input. A document that is not JSON data, or that is nested more than 256 levels deep, is reported as `document.invalid`. - A document whose version marker is not `0.2` is reported as `document.version` and not checked further. - Checks run after schema validation. A validator MAY still run them on a document that fails the schema, and SHOULD then expect some overlap. - Rules marked *schema* in the tables are also enforced by the JSON Schema, so no schema-valid document can break them. They are listed so that a validator running the checks on a schema-invalid document reports them consistently. ## 2. Terms - **Resolve.** Catalogs and included definitions are located by `id` and semver range; the highest version that satisfies the range is used. A definition or design system is looked up first among the carried copies of the file the referring document came in (`core.md`, section 4), and a carried copy that fits is used whatever else is found. How a host finds them otherwise is outside this chapter. A reference into something that did not resolve is not checked further and produces no additional diagnostic; the static type of anything read from it is `any`. - **Literal.** A dynamic value with no expression in it. Its value is the JSON value with each leading `==` replaced by `=`. Checks on values apply only to literals. - **Literal input object.** The `with` of a `call`, `run`, `code`, `navigate` or state `source`, the `config` of a capability, the `with` of a part, when it is a JSON object (its members may still be expressions), and the input argument of a `can` call when it is a map literal. An absent `with`, and a `can` call without an input argument, is an empty literal input object. - **Used.** An operation is used by every `call` step and every state `source` that names it. A capability event is used by every rule trigger and refresh occasion that names it. A contract is used by every capability and node that names it, and a control contract named in the `degradeTo` of a used control is used too, and so on transitively. - **Covered.** An operation or capability event of capability `a` is covered when some grant request with `capability: a` lists its scope in `scopes` and either has no `operations` or names it in `operations`. A scope is covered when some grant request with `capability: a` lists it in `scopes` and has no `operations`. - **Static type.** The type inferred for an expression, or given by a declaration, as defined in `expressions.md`, section "Static types", with the types of roots and local names given in section 7.1. A static type is **known** when it is neither `any` nor `null`. ## 3. Expression scope Each expression sees only the root names below, and the local names in scope at its position. The **base roots** are `env`, `state`, `sources`, `capabilities`, `flows`, `parts`, `grants` and `user`. | Position | Roots | | --- | --- | | State `initial`, capability `config` | `env` | | Grant `where`, part grant `where` | `input`, `env` | | `derive`, state `source.with` and `source.when`, rule `when.becomes`, part `with`, voice `greeting` | the base roots | | Action `allow`, `require` (`that` and `message`), `confirm.message` | the base roots and `input` | | Action `done.message` | the base roots, `input` and `output` | | Action steps | the base roots and `input`; plus `error` in `onError` steps and in `orElse` | | Rule `if` and `do` | the base roots and `event`; plus `error` in `onError` steps and in `orElse` | | Flow transitions (`if`, `allow`, `do`), `enter`, `exit` | the base roots and `event`; plus `item` and `index` in a collection flow, and `error` in `onError` steps and in `orElse` | | View state `initial` | `env`, `state`, `user` and `view` | | Navigation section `label`, `when`, `with`, `count` and `each`; navigation group `group` and `when` | the base roots | | View `title`, node `when`, `props`, `each` and `bind` | the base roots and `view` | | Visual event handlers | the view roots and `event`; plus `error` in `onError` steps and in `orElse` | | Voice intent `reply` | the base roots, `input` and `output` | | Voice `announce` values | the base roots and `event` | | `where` of `remove` and `patch`, and `with` of a `patch` that has `where` | the enclosing roots and `item`, `index`, which hide any outer `item` and `index` | | Steps inside an `each` step, nodes inside a node with `each` (with their props, bindings and handlers), and the `label`, `when`, `with`, `count` and `each.key` of a navigation section with `each` | the enclosing roots; plus `item` when `as` is not given, and `index` when `indexAs` is not given | In a view state `initial`, `view` holds only the view's inputs. In a voice `reply`, `state` is the state after the action has committed; for an intent without an action, `input` is `{}` and `output` is `null`. In an action's `done.message`, `state` is the state as the action's steps left it, and `output` is the value the action produced. Which principal `user` is at each position, including `derive`, `becomes`, `source.with`, `source.when` and a part's `with`, is given in `core.md`, section "Who acts". A path's selectors (`expressions.md`, section "Paths") see the roots and local names of the step or node that holds the path, but not the `item` and `index` that a `remove` or `patch` binds for its `where` and `with`. **Local names.** These bind a local name: - `as` on a `call`, `run` or `code` step, and a `let` step: visible to the steps after the binding step in the same list, including steps nested inside them. A step's own `as` is not visible in its own `with`, `onError` or `orElse`. A local name bound inside a nested list (such as the `then` of an `if`) is visible only in that list. - `as` and `indexAs` on an `each` step: visible in its `do` steps. On a node's `each`: visible in the node itself (its `when`, `each.key`, `props`, `bind` and handlers) and in every node inside it, with their handlers. On a navigation section's `each`: visible in the section's `label`, `when`, `with`, `count` and `each.key`. - Variables a contract declares in a slot's `scope`: visible inside that slot's template. A later binding of a name hides an earlier one. Variables bound by list macros and `let` calls are local to the macro body. **Functions limited by position.** | Function | Allowed in | | --- | --- | | `random()`, `uuid()` | Step expressions: expressions inside action steps, rule `do`, transition `do`, `enter`, `exit` and visual event handlers, including a `call` step's `once`, the `orElse` of a `call`, `run` or `code` step, and a `let` step's `to`, but not path selectors. | | `can()`, `canSend()` | Every position where `user` is a root, except `derive`, an action's `allow`, the `that` of its `require` entries, and a transition's `if` and `allow`. | | Every other function | Everywhere. | The guards that `can` and `canSend` evaluate are excluded so that a question can never ask itself. ## 4. Documents and names | Code | Severity | Rule | | --- | --- | --- | | `document.invalid` | error | A document MUST be JSON data (plain objects, arrays, strings, finite numbers, booleans and null) nested at most 256 levels deep. | | `document.version` | error | A document's version marker (`oad`, `oadCatalog` or `oadDesign`) MUST be `0.2`. The message SHOULD say which version the validator reads. | | `schema.invalid` | error | A document MUST validate against the OAD 0.2 JSON Schema for its kind. | | `name.reserved` | error | No name MAY be `true`, `false`, `null` or `in`, no scope segment MAY be one of them, and no view MAY be named `back`. *schema* | | `name.collision` | error | Capability aliases and part names MUST be distinct. A view's input fields and state entries MUST have distinct names. The `as` and `indexAs` of one `each` MUST differ. | | `name.shadowsRoot` | error | A local name bound by `as`, `indexAs` or a `let` step MUST NOT be an expression root name. *schema* | | `view.duplicateNodeId` | error | Node `id`s MUST be unique within a view, including nodes in slots and fallbacks. | ## 5. Uses and parts | Code | Severity | Rule | | --- | --- | --- | | `uses.catalogNotFound` | error | Every entry of `uses.catalogs`, in a definition or a catalog, MUST resolve to a catalog with that `id` and a version in the range. A host can still load a definition whose catalog it lacks (`core.md`, section "Resolution and graceful degradation"); a validator needs the catalog to check it. | | `uses.catalogCycle` | error | The graph of catalogs using catalogs through `uses.catalogs` MUST be acyclic. | | `uses.definitionNotFound` | error | Every entry of `uses.definitions` MUST resolve to a definition with that `id` and a version in the range. | | `uses.designNotFound` | warning | `uses.design` SHOULD resolve to a design system; otherwise the host default applies. | | `uses.digestMismatch` | error | A definition reference with `digest` MUST resolve to a document whose digest is exactly that value. | | `part.cycle` | error | The include graph of definitions MUST be acyclic. | | `part.tooDeep` | error | Included definitions MUST NOT nest more than 8 levels below the root definition. | | `part.invalid` | error | Every included definition MUST itself be a conforming definition. | | `part.unknownDefinition` | error | A part's `definition` MUST be an alias in `uses.definitions`. | | `part.unknown` | error | Every reference to a part (part nodes, `run` and `can` of `part.action`, `parts.` in expressions, `part.name` in agent surface lists) MUST name a declared part. | | `part.notExported` | error | A parent MUST use only what a part exports: `with` keys are exported inputs, `parts.

.state.` names exported state, `run` and `can` name exported actions, triggers name exported events, part nodes name exported views, and agent `tools`, `resources` and `events` lists name exported actions, state entries and events. | | `part.capabilityUnknown` | error | Each key of a part's `capabilities` MUST be a capability alias of the part, and each value a capability alias of the parent. | | `part.capabilityMismatch` | error | Mapped capabilities MUST reference the same contract name in catalogs with the same `id` and major version. | | `part.grantUnknown` | error | Each key of a part's `grants` MUST name a grant request of the part. | | `part.grantWidens` | error | A part grant adjustment MUST only narrow: `scopes` a subset of those requested, `operations` a subset of those the part's request names (or, when it names none, of the operations and events under its scopes), `rate` no higher, `duration` no longer, and `scopes`, `operations` or `where` only on capability requests. | | `included.kind` | error | Every entry of `included` MUST be a definition or a design system of this version of the format (`oad` or `oadDesign` is `0.2`) with a string `id` and a semantic `version`. A catalog is never carried. Reported at the entry, or at `included` when it is not an array. *schema* | | `included.duplicate` | error | No two entries of `included` MAY be of one kind with the same `id` and `version`. Reported at the later entry. | | `included.nested` | error | A carried definition MUST NOT have an `included` of its own. Reported at its `included`. *schema* | | `included.reserved` | error | An entry of `included` MUST NOT have an `id` that begins with `org.openappdefinition.`: such an `id` names a document of the format itself, which every host provides and no file carries (`core.md`, section 4). Such an entry is not looked up and not checked further. Reported at its `id`. *schema* | | `included.unused` | warning | Every entry of `included` SHOULD be what some reference resolves to: a reference of the definition, or of a carried copy that a reference of the definition reaches. A copy nothing reaches is not checked further. Reported at the entry. | The entries of `included` are the **carried copies** (`core.md`, section 4). A carried definition that a part resolves to is checked like any included definition (`part.invalid`), with its own references looked up among the copies of the file that carries it; the definition's other rules do not read the copies. A definition found elsewhere is checked as a file of its own, with its own `included`. ## 6. Types and values | Code | Severity | Rule | | --- | --- | --- | | `type.unresolved` | error | Every type reference MUST resolve: a primitive, a name in `types`, or `alias:TypeName` with `alias` a key of the document's `uses.catalogs` and `TypeName` a type of that catalog; every `$ref` likewise. | | `type.invalid` | error | A type schema's `format` MUST be `date`, `date-time`, `duration` or `uri`; its `pattern` MUST be a pattern in the dialect of `expressions.md`, section "Patterns"; `minItems` and `maxItems` MUST be non-negative integers with `minItems` not greater than `maxItems`; every value in a catalog type's `known` MUST be a value of that type (`contracts.md` section 1). | | `type.cycle` | error | A named type MUST NOT consist only of `$ref`s that lead back to itself. | | `value.typeMismatch` | error | Literal state `initial` values, literal view state `initial` values, field `default`s, literal capability `config` members, literal input members, literal control props, a literal `once`, and literal `set` `to`, `append` `value`, `patch` `with` and `return` values MUST conform to their declared types. A `once` is declared as a string of 1 to 200 code points. A written value's declared type is the one section 7.1 gives its place; a literal `patch` `with` is compared member by member, as section 7.1 says. | | `value.notKnown` | warning | A literal value of a control prop whose type lists `known` values (`contracts.md`, section 1) SHOULD be one of them, and so SHOULD a literal `meta.icon` and a main section's `icon` in a definition that uses the core catalog, which take a name of its `IconName` (`core.md`, sections 3.1 and 12.2). Another value is valid, but a host need not know it, and a host that does not know an icon name shows no symbol. A value given by an expression is not checked, nor one the type does not accept (`value.typeMismatch`). The message names the three known values nearest to it by spelling. | A value conforms to `date` when it is a calendar date `YYYY-MM-DD`, to `datetime` when it is `YYYY-MM-DDTHH:MM:SS` with optional fraction and `Z` or an offset, and to `duration` when it is an ISO 8601 duration as defined in `expressions.md`, section "Date, datetime and duration formats". A list conforms to `minItems`, `maxItems` and `uniqueItems` as in JSON Schema, with elements compared as in `expressions.md`, section "Equality". ## 7. Expressions and references | Code | Severity | Rule | | --- | --- | --- | | `expression.syntax` | error | Every expression, every expression inside a dynamic value, and every path MUST parse. This includes the rules on `let`, `can`, `canSend`, `t` and literal `matches` patterns, and the rule that selectors appear only in the paths that allow them (`expressions.md`, sections "Grammar" and "Paths"). | | `expression.unknownRoot` | error | Every free identifier of an expression MUST be a root present at its position (section 3) or a local name in scope there. | | `expression.effectNotAllowed` | error | A function limited by position (section 3) MUST be called only where it is allowed: `random()` and `uuid()` in step expressions, `can()` and `canSend()` where section 3 allows them. | | `expression.unknownFunction` | warning | Every function an expression calls SHOULD exist; a call to an unknown function always fails when evaluated. | | `expression.unknownMember` | error | A member access, or an index with a string literal, MUST NOT name a member that the closed map type of its target does not name (`expressions.md`, section "What is reported"). Under a root this covers every unknown name for which this table names no more specific code, such as `grants.`, `env.`, `user.`, `error.`, a typed `event.`, and a member below a known entry. | | `expression.typeMismatch` | error | An operator, function or list macro MUST NOT be applied to operands whose known types it cannot accept (`expressions.md`, section "What is reported"), and a computed value MUST NOT have a static type incompatible with the type of the place it goes (section 7.1). | | `reference.unknownState` | error | `state.` in an expression, the path of a `changes` trigger and the path of a `refresh` step MUST name a declared state entry. | | `reference.notSourced` | error | `sources.` MUST name a sourced state entry. | | `reference.unknownFlow` | error | `flows.` MUST name a singleton flow. | | `reference.unknownCapability` | error | `capabilities.` MUST name a declared capability. | | `reference.unknownViewInput` | error | `view.` MUST name an input field or a state entry of the view the expression belongs to; in a view state `initial`, an input field. | | `reference.unknownInput` | error | `input.` MUST name a field of the input in scope: the action's input field map (in an action, its guards, steps and `done.message`, and a voice `reply`), or, in a grant `where`, a field of an operation input or event payload the request covers. | The `reference.*` rules apply to a member access and to an index with a string literal (`state['goal']`), and each replaces `expression.unknownMember` for the name it covers. ### 7.1 Static types in a definition A validator infers the static type of every expression, dynamic value and path in a definition by `expressions.md`, section "Static types", and reports the operations that chapter's section "What is reported" names, and the incompatible values the rules below find. An expression that does not parse is not typed. **Roots.** At each position, the roots have these static types. Every map type in this table is closed. | Root | Static type | | --- | --- | | `state` | A member for each state entry, typed by its `type`. | | `sources` | A member for each sourced entry: `{ status: string, error: { code: string, message: string }, updatedAt: string, partial: boolean }`. | | `capabilities` | A member for each capability alias: `{ available: boolean }`. | | `flows` | A member for each singleton flow: `{ state: string }`. | | `parts` | A member for each part: `{ state: S }`, with `S` a member for each state entry the part exports, typed by its `type` in the part. | | `grants` | A member for each grant request of this definition: `{ held: boolean, declined: boolean }`. | | `user` | `{ id: string, kind: string, name: string, roles: list, onBehalfOf: U, person: { id: string, name: string } }`, with `U` this same type. | | `env` | `{ now, today, timezone, locale, currency, surface, invocation, direction: string, language: string?, online: boolean, host: { name: string, version: string } }`. `language` is the shown language, `null` for a definition without `localization` (`core.md` section 12.7). | | `input` | In an action's guards, steps and `done.message`, and a voice `reply`, the action's input field map. In a grant `where`, the union (`expressions.md`, section "Union") of the input field maps of the operations, and the payload field maps of the events, the request covers. In a part grant `where`, the same for the part's request. | | `output` | The action's `output` type. When it declares none: `null` if no step of the action is a `return`, at any depth, and unknown (`any`) otherwise, since such a `return` is not checked. | | `view` | A member for each input field and state entry of the view, typed by its `type`. | | `item`, `index` | The element type of the list concerned (the target of `remove` or `patch`, a collection flow's collection, or the list an `each` iterates), and `number`. | | `error` | `{ code: string, message: string }`. | | `event` | As in the next table. | | Where `event` is in scope | Static type of `event` | | --- | --- | | A rule with a `changes` trigger | `{ previous: T, current: T }`, with `T` the type at the trigger's path. | | A rule triggered by a capability event `alias.event` | The event's payload field map. | | A rule triggered by `action:` | `{ input: I, output: O }`, with `I` the action's input field map and `O` what the root `output` is for that action (the first table). | | A rule triggered by `flow:`, or a voice `announce` of `flow:` | `{ from: string, to: string, event: string, key: any }`. | | A visual event handler | The control event's payload field map. | | Anywhere else (an emitted app event, a part's event, `becomes`, `every` and `lifecycle` triggers, flow transitions, `enter` and `exit`) | `any` | **Local names.** | Local name | Static type | | --- | --- | | `as` on `call` | The operation's `output` type, or `null` when it declares none. | | `as` on `run` | The action's `output` type (for `part.action`, as declared in the part). When it declares none: `null` if no step of the action is a `return`, at any depth, and unknown (`any`) otherwise. | | `as` on `code` | The module's `output` type, or unknown (`any`) when it declares none: a module's result is checked only against a declared type. | | `as` on a step that has `orElse` | The union of the type above and the type of `orElse`. | | `as` on an `each` step or a node's `each` | The element type of the list it iterates. | | `indexAs` | `number` | | A `let` step | The type of its `to`. | | A slot scope variable | The type the contract declares for it. | **Path types.** A path is typed from its root: a name is a member access and a selector `[f=e]` gives the element type of the list before it. A selector applied to a type that is known and not a list is `write.notList`; a selector field that the element's closed map type does not name is `expression.unknownMember`. The selector expression is typed and checked as any expression, and is not compared with the field. **Where values go.** A computed value at each place below MUST have a static type compatible with the type beside it (`expressions.md`, section "Compatible types"); otherwise the validator reports `expression.typeMismatch` at the place's pointer. A place whose value is a literal is checked by `value.typeMismatch` instead (section 6). A place whose declared type does not resolve, or a path whose type is `any`, is not checked. For a part's `with`, this is how a driven input's type is checked against what the parent can drive: a known type that cannot be accepted is reported, a value that may be `null` is not, and a driven value that does not conform at run time is handled as `core.md`, section "Parts: building apps from apps", says. | Place (pointer) | Type it must be compatible with | | --- | --- | | `derive` | The entry's `type`. | | A stored entry's computed `initial` | The entry's `type`. | | A sourced entry's `source` (the output of its operation) | The entry's `type`. | | A view state entry's computed `initial` | The entry's `type`. | | `set` `to` | The type at the target path. | | `append` `value` | The element type of the target. | | `patch` `with` | The element type of the target when the step has `where` or the target ends in a selector, otherwise the type at the target. The `with` is a partial value: only the members it names are compared. | | Each member of the `with` of `call`, `run`, `code`, `navigate`, `source`, a navigation section and a part, and of a `can` input map literal; and a computed `with` as a whole | The field's type in the target's field map (operation input, action input, code input, view input, or the type at the path a part's exported input names); a whole `with`, the closed map type of the field map. | | Each computed member of a capability `config` | The config field's type. | | `return` | The action's `output`, when it declares one. | | Each node prop | The prop's type; `boolean` for `hidden` and `disabled`, `string` for `variant`. | | Each `bind` | For a bindable prop, which the binding both reads and writes, the type at the target path MUST be compatible with the prop's type and the prop's type with the type at the target path. For an output, which the control only writes, the output's type MUST be compatible with the type at the target path. | | `once` | `string` | | A navigation section's computed `label`, and a navigation group's computed `group` | `string` | | A navigation section's computed `count` | `integer?` | | `allow`, `if`, `when`, `where`, `becomes`, `source.when`, a `require` entry's `that`, and transition `if` and `allow` | `boolean` | | An `each` step's expression, and the `each.in` of a node or a navigation section | `list` | ### 7.2 Worked cases In these cases `goal` is a state entry of type `number`, `deposits` of type `finance:Transaction[]` (a closed object type with `id`, `amount`, `date` and `memo`), `policy` of a closed catalog type `expenses:Policy` with a member `version`, and `label` an action input field of type `string`. | Definition fragment | Diagnostic | Why | | --- | --- | --- | | `/state/saved/derive`: `sum(state.deposits.map(d, d.amont))` | `expression.unknownMember` | `Transaction` is closed and has no `amont`. | | An action `allow`: `state.policy.versoin == 2` | `expression.unknownMember` | `Policy` is closed. | | `/state/total` with `type` `number` and `derive` `state.deposits.map(d, d.amount)` | `expression.typeMismatch` at `/state/total/derive` | A `list` is not compatible with `number`. | | A step `{ "set": "state.goal", "to": "=input.label" }` | `expression.typeMismatch` at `.../to` | A `string` is not compatible with `number`. | | A step `{ "call": "bank.listTransactions", "with": { "since": "=state.goal" } }` with `since` of type `date` | `expression.typeMismatch` at `.../with/since` | A `number` is not compatible with `date`, whose static type is `string`. | | A node prop `"value": "=state.deposits"` on a control whose `value` is a `number` | `expression.typeMismatch` at `.../props/value` | A list is not compatible with `number`. | | `grants.readSavings.held` with no request `readSavings` | `expression.unknownMember` | `grants` names only the declared requests. | | `{ "set": "state.lastDate", "to": "=input.label" }` with `lastDate` of type `date` | none | `string` is compatible with `date`; the value is checked when it is written. | | `{ "set": "state.goal", "to": "=null" }` | none | `null` is not tracked. | | `/state/half` with `type` `integer` and `derive` `state.goal / 2` | none | `number` is compatible with `integer`. | | A `bind` of a `date` entry to a `string?` prop | none | `date` and `string` are both strings. | | `state.settings.theme` with `settings` of type `{ "type": "object" }` | none | The map is open. | | `/state/page` sourced from an operation whose output is a map type, with `type` a different closed map type that names the same members | none | The types are compatible; a read whose output does not conform to `type` fails at run time. | ## 8. State, writes and actions | Code | Severity | Rule | | --- | --- | --- | | `state.cycle` | error | Derived entries MUST NOT read each other, directly or through other derived entries, in a cycle. | | `state.sourceNotRead` | error | A state `source` MUST call an operation whose `effect` is `read` and that is not `interactive`. | | `state.sourceNotPaged` | error | A state `source` that sets `pages` above 1 MUST call an operation that declares `paging`. | | `state.notSourced` | error | The path of a `refresh` step MUST be `state.` followed by the name of a sourced entry, and nothing more. A declared entry that is not sourced, or a path longer than `state.`, is `state.notSourced`; an undeclared name is `reference.unknownState` only; a selector is `expression.syntax` only. | | `state.readonly` | error | Steps, bindings and exported inputs MUST NOT target a derived or sourced entry. | | `state.internal` | error | A state entry with `internal: true` MUST NOT appear in `exports.state` or be named in an agent `resources.include` list. Naming one in `resources.exclude` is allowed. | | `state.sensitivityUnstated` | warning | A sourced entry whose operation's scope has `sensitivity` `high` SHOULD set `sensitive`, to `true` or to `false`. | | `write.invalidTarget` | error | The target of `set`, `append`, `remove`, `patch` and `bind` MUST be `state.` followed by a declared stored entry; `item` in the steps of a collection flow; or `view.` followed by a state entry of the view, in an event handler or `bind` of a node of that view. Selectors may follow any name. | | `write.notList` | error | The target of `append`, `remove`, and `patch` with `where`, and the value before each selector of a path, MUST be a list wherever its static type is known. | | `write.sharedDirect` | error | A `bind`, and a `set`, `append`, `remove` or `patch` step written in a visual event handler (directly or nested in its `if`, `each` and `onError` steps), MUST NOT target a stored entry whose `scope` is `shared`. Shared state changes only through actions, which a handler runs with `run`. The steps of an action a handler runs are not affected. | | `view.handlerStep` | error | A visual event handler MUST hold only `set`, `append`, `remove`, `patch`, `let`, `if`, `each`, `navigate`, `refresh` and `run` steps. A `call`, `code`, `send`, `emit` or `return` step in a handler, at any depth (also inside its `if` and `each` steps and the `onError` steps of its `run` steps), is reported. Outside effects, flow events and app events start in an action, which a handler runs with `run`. | | `action.unknown` | error | `run`, `can`, a voice intent's `action` and an `action:name` trigger MUST name a declared action. | | `action.cycle` | error | The static call graph that `run` steps form between actions MUST be acyclic. | | `action.internal` | error | An `internal` action MUST NOT appear in `exports.actions`, in agent `tools.include` or `tools.describe`, or as a voice intent action. Naming one in `tools.exclude` is allowed. | | `action.confirmBypassed` | error | A `run` step MUST NOT target an action whose `confirm` is `true` or an object when the step is in a rule's `do`, in a flow's transition `do`, `enter` or `exit`, or in the steps of an action whose `confirm` is absent or `false`. Steps nested in `if`, `each` and `onError` count where their enclosing step is. A `run` in a visual event handler is not reported. | | `action.waitsOnPerson` | error | A step that waits on a person, a `call` of an operation that is `interactive` or a `run` in a visual event handler of an action whose `confirm` is `true` or an object, MUST come before every step of its work that changes anything: a `set`, `append`, `remove` or `patch` of stored state, a `send`, an `emit`, a `call` of an operation whose `effect` is not `read`, or a `run` of an action whose steps can do any of these. Writes to view state in a visual event handler are not changes. Several steps that wait may stand in a row. Such a step MUST NOT be in a rule's `do` (a lifecycle rule's included), in a flow's transition `do`, `enter` or `exit`, or in an action any of those reaches with `run`. Steps nested in `if`, `each` and `onError` are judged on every path: a step that some path reaches after a change, a later pass of an `each` body included, is reported, and a path that ended with `return` or `fail` reaches nothing after it. A `run` whose action (an exported action of a part included) reaches such a step before it changes anything is reported at the `run`. A `run` that `action.confirmBypassed` reports is not reported again. | | `action.doneTooLong` | warning | A literal `done.message` SHOULD be at most 200 characters once cleaned to one line, as a host cleans it (`core.md`, section "Actions"): a host cuts a longer message. | | `call.onceEffect` | error | A `call` step with `once` MUST call an operation whose `effect` is `write` or `external`. | | `code.unknown` | error | A `code` step MUST name a declared code module. | | `field.unknown` | error | A literal input object MUST name only fields its target declares. | | `field.missing` | error | A literal input object MUST supply every required field of its target. A capability `config` is exempt: a required config field it leaves out is supplied when the capability is bound. | ## 9. Capabilities, grants and controls | Code | Severity | Rule | | --- | --- | --- | | `contract.unknown` | error | Every `alias:name` contract reference MUST use an alias of `uses.catalogs` and name a contract of that catalog. | | `contract.wrongKind` | error | Capabilities MUST reference capability contracts and nodes MUST reference control contracts. | | `operation.unknown` | error | `call` steps and state sources MUST name a declared capability and an operation of its contract. | | `event.unknown` | error | Event names MUST resolve: a bare trigger name to an event some `emit` step raises, `alias.event` to a capability event, `action:name` to an action, `flow:name` to a flow, refresh occasions to capability events, node `on` keys to control events, and voice `announce` keys to an event some `emit` step raises or to `flow:name` of a declared flow. | | `event.moveWithoutGroup` | warning | A `core:list` that handles `move` SHOULD name a `moveGroup` or be `reorderable`. With neither it takes no part in moving items, and no item is moved onto it. A list whose `reorderable` is an expression is not reported. | | `grant.unknownTarget` | error | A grant request's `capability` or `code` MUST name a declared capability or code module. | | `grant.unknownScope` | error | Every scope of a capability grant request MUST be declared by the contract. | | `grant.operationUnknown` | error | Every name in a grant request's `operations` MUST be an operation or event of the capability's contract whose scope is one of the request's `scopes`. | | `grant.uncovered` | error | Every used operation, and every capability event used in a rule trigger or a `refresh.on` list, MUST be covered (section 2). | | `grant.eventWithheld` | warning | A capability event used in a rule trigger or a `refresh.on` list SHOULD be able to pass the `where` of at least one grant request covering it. It cannot when every such `where` reads an `input` field the event payload does not carry, because a condition that cannot be evaluated withholds the event (`core.md`, section "Grants"). A `where` that uses `has` or `default` is not reported. | | `grant.requiresUncovered` | error | For every used contract, each `requires` entry MUST be covered: some capability whose contract has the required contract's catalog `id` and name has grant requests that cover all the required scopes (section 2). | | `code.noGrant` | error | Every code module MUST have a grant request naming it. | | `egress.ungranted` | error | A control prop the contract marks `remote` MAY be set to a literal absolute `http` or `https` address only when some capability whose contract has the `egress` trait has a grant request that either carries no `operations` or names in `operations` an operation whose `effect` is `read`. A computed value, or a reference to content the host already holds, is not reported: the host settles it when it loads the content (`core.md`, section "Egress"). | | `egress.originMismatch` | error | When a `remote` prop is a literal absolute http or https URL and every granted egress capability has a literal `origin`, the URL's origin MUST equal one of them. | | `trigger.noBackground` | warning | An `every` trigger that does not set `foreground: true`, and a flow `after` timer, SHOULD come with a grant request on a capability whose contract has the `background` trait; without one it runs only while a person has a surface of the app open. An agent's connection alone does not count. `foreground: true` states that running only then is intended. | | `duration.invalid` | error | `every`, `refresh.every`, flow `after` keys, grant `duration` and `rate.per` MUST be durations longer than zero. | | `prop.unknown` | error | Node `props` MUST be declared by the contract or be a common prop: `variant`, `hidden`, `disabled`. | | `prop.missing` | error | Every required prop MUST be set in `props` or bound in `bind`. | | `prop.iconOnlyWithoutIcon` | warning | A node that sets `iconOnly` to `true` SHOULD set `icon`, when its control declares both. Without an icon the host shows the label. | | `prop.markdownInPlainText` | warning | A `core:text` whose `format` is absent or `plain` SHOULD NOT have a literal `value` that is plainly written in Markdown: a pair of `**` around words, a link written `[words](http...)`, `[words](https...)` or `[words](mailto...)`, a line that starts with `#` to `###` and a space, or two or more lines that start with `- `. A host shows such a value with its markup. A lone asterisk, a minus sign or brackets alone are not reported, nor is a value computed by an expression. Reported at the `value`. | | `prop.moveGroupUnhandled` | warning | A `core:list` that names a `moveGroup` SHOULD handle `move`. Without a handler it takes no part in moving items, and its items cannot be moved. | | `prop.moveGroupAlone` | warning | A `core:list` that takes part in moving items (it names a `moveGroup` and handles `move`) SHOULD share its group with another `core:list` of its view: one whose `moveGroup` is the same literal or an expression. A list whose own `moveGroup` is an expression, a list repeated by `each` or drawn in a slot once per item, and a `reorderable` list, whose items move within it, is not reported. | | `prop.reorderableUnhandled` | warning | A `core:list` that is `reorderable` SHOULD handle `move`. Without a handler it takes no part in moving items, and a person cannot put its items in order. A `reorderable` that is the literal `false` is not reported; one that is an expression is. | | `prop.moveListUnnamed` | warning | A `core:list` that takes part in moving items SHOULD set `label` to an expression or a text that is not blank: hosts name the list by it where they offer to move an item to it. | | `bind.invalid` | error | `bind` MUST name a prop the contract marks `bindable`, or an output. | | `slot.unknown` | error | `slots` MUST name slots the contract declares. | | `slot.missing` | error | Every slot the contract marks `required` MUST be filled. | | `node.children` | error | `children` MUST respect the contract: none for `none`, at most one for `one`. | | `view.unknown` | error | `start`, every navigation section's `view` and every `navigate` target other than `back` MUST name a declared view. | | `view.invalidNavigation` | error | A navigation section without `with` MUST name a view whose `input` has no required field, and two sections that have neither `each` nor `with` MUST NOT name the same view. Reported at the section's `view`; for a view named twice, at each such section after the first. A section's `with` is checked as a `navigate` step's is (`field.unknown`, `field.missing`, `value.typeMismatch`). | | `view.headingRepeatsTitle` | warning | The first node a view's `body` draws SHOULD NOT be a `core:heading` whose `value` says what the view's `title` says: two literal texts equal after trimming and without regard to case, or the same expression. A host draws the title as the heading of the page, or of the card an app of one view is drawn as (`core.md` section 12.2), so the words would show twice. The first node drawn is the `body`, or, while that is a `core:stack`, its first child, followed through first children that are stacks. Reported at the heading. | | `view.tabUnnamed` | warning | Every child of a `core:tabs` SHOULD name its tab: a control whose contract's `labelProp` is set by the node to an expression or a text that is not blank (or has such a default), such as a `core:group` with a `title`, or a part view whose `title` is set. A tab with nothing to name it is captioned by its position alone. Reported at the child. | ### 9.1 Assets These checks apply to the `assets` of a definition (`core.md`, section 12.5). The rules on the bytes apply only to an entry that carries `data`; an entry without it is checked by the schema alone. An **asset reference** is a literal string that starts with `asset:`, the whole value of a prop that the contract marks `remote` or a string anywhere inside such a value. A string in such a prop that is an expression could name any asset. | Code | Severity | Rule | | --- | --- | --- | | `asset.dataInvalid` | error | An asset's `data` MUST be base64 in its one form: the standard alphabet, with padding, no line break and no other character, and zero in the bits that padding leaves unused. *schema* | | `asset.digestMismatch` | error | The digest of the bytes of an asset's `data` MUST equal its `digest`. Reported at `digest`. | | `asset.unrecognized` | error | The bytes of an asset's `data` MUST be a PNG, JPEG, WebP or GIF picture whose header can be read as `core.md` section 12.5 sets out. Reported at `data`. | | `asset.typeMismatch` | error | The bytes of an asset's `data` MUST be a picture of the type its `type` gives. Reported at `type`. | | `asset.tooLarge` | error | The picture an asset's `data` holds MUST be at most 4096 pixels wide and at most 4096 pixels high, as its header gives them. Reported at `data`. | | `asset.sizeMismatch` | error | An asset's `width` and `height`, where given, MUST be the size its picture shows at: those its header gives, swapped when its EXIF orientation turns it a quarter (`core.md` section 12.5). Reported at the member that differs. | | `asset.unknown` | error | An asset reference MUST be `asset:` followed by the name of an entry of the definition's own `assets`. Reported at the string. | | `asset.unused` | warning | Every asset SHOULD be named by an asset reference. It is not reported when any `remote` prop of the definition holds an expression, which could name it. | | `document.beyondFloor` | warning | A definition, as JSON without insignificant white space and without the `data` of its assets, SHOULD be at most 2,621,440 bytes in UTF-8, which every host accepts (`core.md`, section 18.1). Reported at the document. | | `asset.countBeyondFloor` | warning | A definition SHOULD have at most 64 assets, which every host accepts. Reported at `assets`. | | `asset.dataBeyondFloor` | warning | The `data` of an asset SHOULD be at most 1,048,576 characters, which every host accepts. Reported at the `data`. | | `asset.totalBeyondFloor` | warning | The `data` of all assets together SHOULD be at most 2,621,440 characters, which every host accepts. Reported at `assets`. | | `included.countBeyondFloor` | warning | `included` SHOULD hold at most 16 definitions and at most 17 design systems, which every host accepts (`core.md`, section 18.1). Reported at `included`, once for each kind beyond. | | `included.sizeBeyondFloor` | warning | The carried copies, each as JSON without insignificant white space and without the `data` of its assets, SHOULD be at most 2,621,440 bytes in UTF-8 together, which every host accepts. Reported at `included`. | | `included.assetCountBeyondFloor` | warning | The carried copies SHOULD have at most 64 assets together, which every host accepts. Reported at `included`. | | `included.assetDataBeyondFloor` | warning | The `data` of an asset of a carried copy SHOULD be at most 1,048,576 characters, which every host accepts. Reported at the `data`. | | `included.assetTotalBeyondFloor` | warning | The `data` of all assets of the carried copies together SHOULD be at most 2,621,440 characters, which every host accepts. Reported at `included`. | The size of the definition itself (`document.beyondFloor`) does not count `included`, and the rules above on assets apply to the definition's own `assets` only: the pictures of a carried copy count toward the sizes of `included`. A message about an asset never repeats a value of the document, such as any part of a `data` text or of a reference: it names the asset by its key, or the place by its pointer. ### 9.2 Texts in several languages These checks apply to a definition's `localization` (`core.md` section 12.6) and to every use of its keys: each call of `t` in an expression (`expressions.md` section 8.7), wherever an expression, a dynamic value or a path selector stands, and each **fixed-text reference**, a value that is exactly `=t('key')` at one of the fixed-text places `core.md` section 12.6 lists. The **default table** is the member of `strings` named by `default`. A **translation** is the table of any other language. An entry's **blanks** are the blank names of all its texts, its forms together; the names an entry **takes** are its blanks and its `by`. | Code | Severity | Rule | | --- | --- | --- | | `localization.tagInvalid` | error | `default` and every key of `strings` MUST be a language tag in its one spelling: it matches `^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}\|[0-9]{3}))?$`, and its language is not `und` and not an old code of table `aliases` (`core.md` Appendix A). Reported at the tag. The message SHOULD give the valid spelling where there is one: `en-US` for `en-us` or `en_US`, `he` for `iw`. | | `localization.defaultMissing` | error | When `strings` is present, it MUST have a member for `default`. Reported at `strings`. | | `localization.entryInvalid` | error | Every entry MUST be a well-formed text (`expressions.md` section 8.7), or forms whose `by` is a blank name, which have an `other` form, whose form keys are not empty, each key that begins with `=` being `=` and a finite number exactly as `string` writes it, and whose forms are well-formed texts. Reported at the entry, or at the form at fault. | | `localization.keyUnknown` | error | Every `t` call and every fixed-text reference MUST name a key of the default table. A definition with no `strings`, or with no `localization`, has no keys, so every use is reported. Reported at the expression or the place. The message SHOULD name the nearest keys by spelling. | | `localization.valuesMismatch` | error | A `t` call MUST give a value for exactly the names the entry of its key in the default table takes: none that the entry does not take, none of them left out. It MUST NOT give a value whose static type is `boolean` for a name the entry shows in a text that such a value could choose (a blank other than `by` shown in any form; the `by` itself shown in the form `true`, the form `false` or, where either is missing, `other`). Reported at the expression. | | `localization.blankUnknown` | error | A translation's entry of a key the default table has MUST NOT show a blank, nor choose its form by a `by`, that the default entry does not take. A translation MAY leave out a blank of the default entry. Reported at the translation's entry. | | `localization.fixedNeedsPlainText` | error | The key of a fixed-text reference MUST be, in every table that has it, a text without blanks that is not empty. Reported at the place. | | `localization.untranslated` | warning | Every translation SHOULD give a text in its own language for every key of the default table: its own entry, or that of a table of the same language and script earlier in its text chain (`core.md` section 12.7), including the default table when that is of the same language and script. Reported once for each translation, at its table, with the count and the first five keys. | | `localization.keyNotInDefault` | warning | Every key of a translation, and of `notes`, SHOULD be a key of the default table: no use can name another. Reported once for each translation, at its table, and once for `notes`, with the count and the first five keys. | | `localization.keyUnused` | warning | Every key of the default table SHOULD be named by a `t` call or a fixed-text reference. Reported once, at the default table, with the count and the first five keys. It is not reported when an expression or a path of the definition does not parse, since the uses it holds are not known. | | `localization.sameAsDefault` | warning | A translation's text SHOULD differ from the default table's text of the same key. Only a default text of more than 3 code points that holds a letter (Unicode category L) is compared, and only with a translation's entry that is a text. Reported once for each translation, at its table, with the count and the first five keys. | | `localization.scriptUnclear` | warning | A tag whose language is `zh` or `sr` SHOULD name its script (`zh-Hans`, `zh-Hant`, `sr-Cyrl`, `sr-Latn`): without one, the script follows the region. Reported once for each such tag, at its table, or at `default` when no table has it. | | `localization.fixedTextForm` | warning | A value at a fixed-text place that begins with `=t(` SHOULD be exactly a reference `=t('key')`: anything else is shown as its characters. Reported at the place. | | `localization.directionUndeclared` | warning | A definition without `localization` whose literal texts people see mostly begin in a right-to-left script SHOULD declare its language (`"localization": { "default": "ar" }`), so that a host lays the app out right to left. The texts counted are the literal `meta.name` and `meta.description`, view titles, navigation section labels, `confirm` and `done` messages of actions, and node props whose declared type is a string with no `enum`, `const`, `pattern`, `format` or `known` values, each counted when it has a first strong character (`expressions.md` section 8.7). Reported at the document when at least 5 are counted and more than half of them have a right-to-left first strong character. | | `localization.languagesBeyondFloor` | warning | `strings` SHOULD have at most 64 languages, which every host accepts (`core.md` section 18.1). Reported at `strings`. | | `localization.keysBeyondFloor` | warning | A table SHOULD have at most 2,000 keys, which every host accepts. Reported once, at the first such table. | | `localization.textBeyondFloor` | warning | A text of a table SHOULD be at most 2,000 code points, each form counted alone, and an entry SHOULD have at most 24 forms, which every host accepts. Reported once, at the first such entry, with the count of the others. | **Order.** These checks run with the other checks of a definition, after the schema. A use is checked against the default table only when that table exists: when `strings` lacks it, `localization.defaultMissing` is reported once and no use is reported. The values of a `t` call are checked only when its key is in the default table and the default entry is well formed, and a translation's entry only when both it and the default entry are well formed, so that one mistake gives one diagnostic. The warnings on translations and on unused keys follow, once every use has been found. **Texts read by other checks.** The checks that read a literal text, such as the type of a literal prop with its length limits (a chart's `unit`, the `label` of its `goal`), a literal `initial`, input member or written value against its type (`value.typeMismatch`), Markdown in a plain `core:text` (`prop.markdownInPlainText`), the length of a done message (`action.doneTooLong`) and a heading that repeats its view's title (`view.headingRepeatsTitle`), also read each language's text where a value, or a string within it, is exactly the expression `t('key')` with no values and the key's entry in that language's own table is a text without blanks. They read the text as it is shown, `{{` as `{` and `}}` as `}`, and a diagnostic they report for it names the language. At a fixed-text place that holds a reference, every rule on the place reads the text of each language the same way: an asset's `credit` is one line of at most 300 code points in every language, reported as `schema.invalid` at the place. **Without the schema.** A tool that runs these checks on a document without validating it against the schema also misses what only the schema holds: the shape of `localization` (no member but `default`, `strings` and `notes`; an entry is a string or an object with exactly `by` and `forms`; every form a string), the pattern of a key of a table and of `notes`, and a note of 1 to 300 characters. The language tag is not in the schema: `localization.tagInvalid` is its only report. ## 10. Flows, exports and surfaces | Code | Severity | Rule | | --- | --- | --- | | `flow.unknown` | error | A `send` step and a `canSend` call MUST name a declared flow. | | `flow.unknownState` | error | A flow's `initial` and every transition `to` MUST name a state of that flow. | | `flow.unknownEvent` | error | A `send` step and a `canSend` call MUST name an event that some state of the flow handles. | | `flow.keyMismatch` | error | A `send` step and a `canSend` call MUST carry a key exactly when the flow is a collection flow. | | `flow.invalidCollection` | error | `over.collection` MUST be a path to stored state that is a list wherever its static type is known. | | `flow.fieldWrite` | error | A step or binding MUST NOT write the `field` of a collection flow where this can be seen from the definition: a target path that is the flow's collection path followed by a selector and `.field` (and possibly more names); in the flow's own steps, a target path `item.field`; a `patch` of the collection, of an element of it selected by a selector, or of `item`, whose `with` is a JSON object or a map literal with a member named `field`; or an `append` to the collection whose value is a JSON object with a literal member `field` that is not the flow's `initial`. | | `flow.unreachable` | warning | Every state of a flow SHOULD be reachable from `initial`. | | `export.unknown` | error | `exports` MUST name existing state entries, actions and views, events some `emit` step raises, and inputs pointing at declared state entries. | | `export.notStored` | error | Every exported input MUST be a path into a stored state entry. | | `surface.unknownName` | error | Agent `tools` lists and `describe` keys MUST name actions (an `exclude` list MAY name internal actions), `resources` lists MUST name state entries (an `exclude` list MAY name entries that are not exposed), and `events.include` MUST name emitted events or `flow:` of a declared flow. An `include` list MAY also name `part.name` for an action, state entry or event the part exports. | | `voice.unknownSlot` | error | Every `{slot}` placeholder in a voice example MUST name an input field of the intent's action. An intent without an action has no slots. | ## 11. Catalogs | Code | Severity | Rule | | --- | --- | --- | | `scope.undeclared` | error | Every operation and event `scope` MUST be declared in the contract's `scopes`. | | `contract.unknownReference` | error | `labelProp` MUST name a declared prop; `degradeTo` MUST name another control contract of the same catalog, or, written `alias:contractName`, a control contract of a catalog this catalog uses, with `alias` a key of its `uses.catalogs`; `deprecated.replacement` MUST name another contract of the same kind in the same catalog. | | `contract.invalidRequires` | error | A `requires` entry's `contract` MUST name a capability contract of the same catalog, or, written `alias:contractName`, of a catalog this catalog uses, with `alias` a key of its `uses.catalogs`; and its `scopes` MUST be scopes that contract declares. | | `contract.invalidPaging` | error | An operation that declares `paging` MUST have an `output` that is a map type naming both the `paging.next` and the `paging.items` member; the member `paging.items` names MUST be a list; and `paging.cursor` MUST name an optional field of its `input` whose type is `string` or `string?`. An operation with no `output`, or whose known output type is not a map, is reported. An output type that does not resolve, or a member whose static type is not known, is not checked further. | | `contract.invalidConsent` | error | A capability whose `traits` include `background` or `egress` MUST NOT have a scope with `consent: "use"`. Such a scope MUST NOT be the scope of an event, and every operation under it that is not `interactive` MUST have `effect: "read"`. Reported once for each scope, event or operation at fault. | | `contract.egressWithoutOrigin` | error | A capability contract with the `egress` trait MUST declare a config field named `origin`. *schema* | | `contract.outputShadowsProp` | error | A control output MUST NOT share a name with a prop of the same control. | | `contract.valueChangeMismatch` | warning | When a control has a bindable prop `value` and a `change` event, the event payload SHOULD have a field `value` of the same type. | The type, value and name rules of sections 4 and 6 also apply to catalogs: a type reference resolves to a name in the catalog's own `types` or, written `alias:TypeName`, to a type of a catalog it uses, with `alias` a key of its `uses.catalogs` (`type.unresolved` otherwise), and defaults conform to their field types. `uses.catalogNotFound` (section 5) applies to a catalog's `uses.catalogs`. A reference through an alias whose catalog did not resolve is not checked further (section 2). ## 12. Design systems | Code | Severity | Rule | | --- | --- | --- | | `design.missingToken` | error | A design system MUST define the color tokens `surface`, `text`, `textMuted`, `outline`, `accent`, `onAccent`, `neutral`, `info`, `success`, `warning`, `danger` and `category1` to `category8`, and the space tokens `small`, `medium` and `large`. *schema* | | `design.unknownModeToken` | error | A `modes` entry MUST override only tokens that the base `tokens` define, group by group. | | `design.unknownContract` | error | When the catalog a `variants` key names can be resolved, the key MUST name a control contract of it. | | `design.unknownVariantProp` | error | A variant preset MUST set only props the control contract declares; literal values MUST conform to the prop types (`value.typeMismatch`). | ## 13. Conformance fixtures `conformance/0.2/semantic/` holds fixtures for these checks: - `valid/` holds definitions that produce no diagnostic at all. - `invalid/` holds definitions (`*.oad.json`), catalogs (`*.oadcatalog.json`) and design systems (`*.oaddesign.json`) that each validate against their schema and break exactly one rule. `invalid/manifest.json` lists `{ "file", "code", "pointer", "violates" }` for each, where `violates` is a sentence that says what the file breaks (informative, like a message); a conforming validator reports exactly one diagnostic for the file, with that code and pointer. - `registry/` holds the catalogs, included definitions and design systems the fixtures resolve against, beside the core catalog, which every validator has. A fixture that carries copies in its `included` resolves against them first: where the registry also holds a version that fits, the carried copy is still the one checked. Every code in this chapter has at least one invalid fixture, except `document.invalid`, `schema.invalid` and the rules marked *schema*, which no schema-valid file can break, and `document.beyondFloor`, `asset.dataBeyondFloor`, `asset.totalBeyondFloor`, `included.sizeBeyondFloor`, `included.assetDataBeyondFloor` and `included.assetTotalBeyondFloor`, whose fixtures would each be megabytes long. `document.version` is tested with a file whose version marker is `0.1`. The static type rules of section 7.1 have invalid fixtures for each kind of place in its last table, and valid fixtures for the cases that section 7.2 shows are not reported. --- # Open App Definition (OAD) 0.2: Changes from 0.1 Status: working draft. This document lists what changed in OAD from draft 0.1 to draft 0.2, and why, for a reader who knows 0.1. It is grouped by subject. Each entry says what the change is, what it replaces, and whether a 0.1 definition has to change. Section numbers refer to the 0.2 chapters, `core.md`, `contracts.md`, `expressions.md` and `validation.md`, unless a reference says "above" or "below", in which case it means a section of this document. Most of 0.2 answers questions that 0.1 left to each host: who acts when an app is shared, what a refusal says, what happens when a call is retried, how a source pages, what a control's events carry. Some answers are new features; many are behaviour that 0.1 implied and 0.2 now states. ## 1. Version and documents **The version is 0.2.** Documents say `"oad": "0.2"`, `"oadCatalog": "0.2"`, `"oadDesign": "0.2"`, `"oadHistory": "0.2"` and `"oadSignature": "0.2"`. The core catalog is version `0.2.0`, and conformance fixtures live in `conformance/0.2/`. Before 1.0 every minor version is its own format: a host or tool states which versions it reads and refuses others with `document.version`, saying which versions it reads (`core.md` section 16). This replaces the 0.1 rule that a host rejects only a higher minor version. *0.1 definitions* must change their `oad` value, and their core catalog range (`^0.1.0` becomes `^0.2.0`), together with the changes marked below. **`changes.md`** is this document. It is new. **New reserved root names.** `grants` and `output` are new expression roots (`core.md` section 3.4), and a local name bound by `as`, `let` or `indexAs` may not be a root name. *0.1 definitions* that used `grants` or `output` as a local name must rename it. ## 2. Checking expressions **Static types.** Validation now infers the type of every expression where it can be known: from state entry types, field maps, catalog types, operation outputs, view inputs and view state, macro variables and function signatures. It reports only what is certain; `any` and unknown types pass, and nullability is not reported. Two new errors: - `expression.unknownMember`: a member access, or an index with a literal string, on a value whose type has no such property (an object with `additionalProperties: false`, or a field map), and an unknown name under a root (`grants.x`, `env.x`, `user.x`, `error.x` and a typed `event.x`) where no more specific diagnostic exists. Unknown names under `state`, `input`, `view`, `sources`, `capabilities`, `flows` and a part's state keep their own `reference.*` and `part.notExported` codes. - `expression.typeMismatch`: an operator or function applied to operands whose known types cannot be right, and a computed value whose known type cannot fit where it goes: a `derive` against its entry's `type`, a `return` against `output`, a written value against its target, a `with` field against the field map it feeds, a prop value against the prop's type, a part's driven input against what the parent can drive, a binding, a `once` key and a capability `config`; and conditions and guards that are not boolean (`allow`, `if`, `when`, `where`, `becomes`, a `require` entry's `that`) and `each` values that are not lists. A 0.1 definition with, say, `"when": "state.count"` or a misspelt `env.tz` now fails. `expressions.md` gives every function and macro a signature and says how types flow through operators, conditionals, `default`, member access and list macros (section "Static types"). Why: in 0.1 a definition with a misspelled field inside an expression validated cleanly and failed only at run time, sometimes after a person had confirmed the action. *0.1 definitions* that validated may now report errors where an expression was in fact wrong; correct definitions need no change. ## 3. Instances, people and who acts 0.1 described one person using one app. 0.2 says what happens when an app is shared (`core.md` section 6.4). **Instances, owners and members.** An app instance is one installation of a definition on a host: its state, its issued grants and its audit log. It has one owner (the person who installed it, or the person or organization host policy names); other people who use it are members. How people join is host policy; unless it says otherwise, a member holds access to every action that is not `internal`. A person with no access to an instance cannot load it (`instance.forbidden`), and sees nothing of its state or audit log. A principal holds full access when it holds access to every action; access names an action that is not `internal` or, as `part.action`, one a part exports, and an action that cannot be named is reached only through its own definition's steps and handlers and needs no access of its own; an instance grant is revoked by the owner, a personal grant by its person or the owner. A session is one principal's use of an instance on one device; locking the device or moving the app to the background does not end it. Replaces the 0.1 wording "a person who installs an app", and settles what `session` scope means. *No change to definitions.* **When a surface is active.** A surface is active while a person has it open. An agent's connection alone does not make the app active: `every` rules, flow `after` timers and timed refreshes need a person's surface open or a `background` grant, while an agent's own calls run whenever it makes them. 0.1 used "active" without defining it. *No change to definitions.* **Updates.** Running an instance with a definition of the same `id` and a different digest is an update, and so is a change in any part the instance resolves. Only the owner may update; anyone else is refused with the new code `instance.forbidden`. The host records each update in the audit log, with each part whose definition changed, applies the rule that a kept grant answers only the request it was asked for, and SHOULD show the owner what changed. A stored value that no longer conforms to its entry's `type` is replaced by `initial`, and the host SHOULD keep the old value, and the values of entries no longer declared, for the person they belong to: `shared` values for the owner, a `user` value for its person. Members SHOULD be told at their next use that the definition changed, also when only a part changed. Likewise a flow instance whose state the new definition no longer declares is put in the flow's `initial` state without running `enter` steps, and the resolution report says so. A host MAY refuse an update that does not descend from the running definition, by its history or signer. Why: in 0.1, two files with the same `id` silently shared stored state, and a member opening a changed shared app could not withdraw grants the owner had answered. *No change to definitions.* **Personal and instance grants.** A new capability trait, `personal`, marks a provider that acts for one person (their device, accounts or files). A request on a personal capability is answered by each person for themselves and covers only what is done on their behalf, with its `rate` counted per person. Every other request, code included, is an instance request: answered once by the owner, covering the instance whoever uses it, with its `rate` counted per instance. Members are shown instance grants and are not asked. A member whose required personal request is declined cannot load the app; a required instance request the owner declines fails the load for everyone. A request declined only because nobody entitled was present is declined for that use and asked again later. With one person nothing changes. In the core catalog `files`, `media`, `location`, `clipboard` and `share` are personal; in the example finance catalog, `accounts` is. Replaces the 0.1 rule that every grant is approved by "a person who holds full access". *No change to definitions.* **Roles.** The owner assigns roles and holds every declared role unless host policy says otherwise. A member holds the roles the host assigns and none by default. A person who delegates access to an agent MAY include roles they hold; the agent holds exactly those, and none by default. A directory's roles are not assumed to be the app's. Replaces "a person who installs an app for their own use holds every declared role". *No change to definitions*, but see the flow example below. **Who acts.** One table (`core.md` section 6.4.4) replaces statements scattered across 0.1. An action from a surface runs as the invoking principal; a flow transition caused by a `send` runs as the principal who sent it, which is the `user` its `allow` sees. A `becomes` or `changes` trigger is tested where a change happens, with the values of that place, and there are three kinds of change: a write by work that has an acting principal (tested once, on behalf of that principal's person), the result of a source read (once, on behalf of the person the value belongs to), and a change of a session's environment (in that session, on behalf of its person, so the same rule can fire in several sessions; with no active session and a `background` grant held, once for the instance on behalf of the owner). A change made in one place fires no rule in another: one person's write never makes the app act for another person. With `"initial": true`, a `becomes` fires when a session opens while it is true, in that session. An `every` rule fires once per interval in each active session for its person, or once for the instance on behalf of the owner when no session is active and a `background` grant is held. A flow `after` transition runs once per flow instance: for a singleton flow or a flow over a `shared` collection on behalf of the owner, and for a flow over a collection that is not `shared` on behalf of the person whose collection holds the element. A rule fired by an event of a personal capability, or by an event its contract says belongs to a person, runs once for that person; any other capability event fires in each active session, or once for the owner with a `background` grant and no session. For the app principal, `user.kind` is `app`, `user.id` the definition's `id`, `user.roles` empty and `user.onBehalfOf` the person. A principal with no person stands in for its person: values are kept for it, and it holds no personal grant, so a personal call fails with `grant.denied`. A rule runs after the transaction that triggered it commits, in its own transaction; a rule beyond the cascade limit does not run, and `rule.cascade` is recorded against the work that started it, instead of failing an action that has already committed. Why: 0.1 did not say who `user` is in a flow transition or a timer, nor where a trigger with no invoking person fires, and every approval guard depends on it. *No change to definitions*, but an effect meant to happen once for each person needs `user.person.id` in its `once` key (section 5 below). **Access that ends.** Access that is taken away or runs out ends at once: the host ends the sessions of a principal that no longer holds access, shows it nothing further, asks it nothing and runs nothing on its behalf (`core.md` section 6.4). Delegated access MAY name the resources an agent may read as well as the actions it may run; such limits bind agents, and a person who holds access to an instance sees what its surfaces show them. Why: 0.1 had one person for each app and never had to say what becomes of someone who is removed while they have the app open. *No change.* **Events are observed where they are raised.** An app event is observed by rules at the place where it was raised, and by the surfaces of the person on whose behalf the work ran, that person's agents included; other people learn what changed through the state they can read (`core.md` sections 8.2 and 12.1). Why: on an instance that people share, an event is one person's work, and delivering it everywhere would run every person's rules on it and tell every person's agents of it. *No change* for an app that one person uses. **Principals with no person.** A principal that acts for no person, such as an agent a host admits on its own account, stands in a person's place for the values kept for it, holds no personal grant, and cannot load an instance that has a required personal request (`core.md` sections 6.4.2 and 6.4.4). *No change.* **The person behind the principal.** `user.person` is `{ "id", "name" }` of the person the acting principal is or acts for, or `null`. A definition that records who owns something, or compares a stored person id with the caller, uses `user.person.id`, so work an agent does for a person belongs to the person. *0.1 definitions* that compared stored ids with `user.id` work as before for people acting themselves; to let agents act for them, compare with `user.person.id`. **`user` in `derive`.** Inside `derive`, `user` is the principal the value is read for: the acting principal during an action, rule, transition or `can` evaluation, the person using a visual or voice surface, or the agent reading a resource. A derived entry that reads `user` has one value per principal; to follow the person, read `user.person`. `env.surface` and `env.invocation` are `null` there. 0.1 did not say. *No change.* **Shared state is written only by actions.** A binding, or a step written directly in a visual handler, may not target a `shared` stored entry (`write.sharedDirect`). Shared state changes through actions run from the handler, so every change passes an `allow` and an agent can make it on the same terms. Entries of other scopes may still be written directly. Why: with members, a binding to shared state let anyone who could open a view change any record with no guard. *0.1 definitions* that bind to, or write from a handler to, a `shared` entry must move the write into an action. **Steps in a visual handler.** A visual event handler holds only steps that stay with the person and the view: `set`, `append`, `remove` and `patch` (never on `shared` state), `let`, `if`, `each`, `navigate`, `refresh` and `run`. A `call`, `code`, `send`, `emit` or `return` step in a handler, at any depth, is an error (`view.handlerStep`). Every outside effect, flow event and app event therefore starts in an action, passes an `allow`, and can be done by an agent on the same terms. Replaces the 0.1 statement that a handler has the same semantics as an action body. *0.1 definitions* whose handlers call capabilities, run code, send flow events, emit events or return must move those steps into an action and `run` it from the handler. **Confirmation cannot be bypassed.** A `run` of an action with `confirm` from a rule, from a flow's steps, or from an action without `confirm` is now an error, `action.confirmBypassed`. A `run` from a visual handler or a voice intent is the person's own invocation and is allowed, and a confirmed action that runs another is not asked about twice. *0.1 definitions* that ran a confirmed action from a rule, a flow or an unconfirmed action must change: give the calling action `confirm`, or invoke the confirmed action from a surface. **Confirmation says more.** `confirm` may be `{ "message": dynamic value }` as well as `true` or `false`. The message is shown beside the action, its input and who is asking, marked as the app's own words, and sees the roots `allow` sees. Confirmation is asked of the person of the calling principal, and an invocation with no person to ask fails with `action.declined`. When the answer arrives, access, input, `allow` and `require` are checked again. Why: a person confirming saw only the input, not what the app knew about it. *No change.* **Order of an invocation.** An invocation is checked in a fixed order: that the action exists, is not internal, is exposed by the surface used and is covered by the caller's access (all refused alike with `action.forbidden`); its input; `allow`; `require`; confirmation; then the steps. In 0.1 a host could validate input before access and so tell an agent that a hidden action exists. *No change.* **Requirements with reasons.** A new action field, `require`, lists `{ "that", "message" }` entries checked after input validation and `allow`, and before confirmation and any step. The first that is not true fails the invocation with the new code `action.refused` and that entry's message. `allow` keeps the question of who may act; a refusal for `allow` (`action.forbidden`, `flow.forbidden`) MUST NOT carry the guard's text. A declined or unanswered confirmation now fails with the new code `action.declined`. Why: 0.1 had no readable refusal, so authors moved checks into `fail` steps that ran after the person had confirmed, and hosts showed raw guard expressions to agents. *0.1 definitions* need not change, but an `allow` that tests the input or the state rather than the principal reads better as a `require`. **Asking in advance.** New functions `can(actionName, input?)` and `canSend(flowName, event, key?)` tell a view or a step whether an invocation or a flow event would pass its checks, without running anything. They are not available in `derive`, nor in the guards they evaluate (`allow`, a `require` entry's `that`, a transition's `if` and `allow`), where they would recurse. Why: views copied guards from actions and flows, and the copies drifted. *No change.* ## 4. Grants **Narrowing to operations.** A capability grant request MAY carry `operations`, a list of operation and event names; the grant then covers only those, within its scopes. A parent may shorten a part's list. A name that is not an operation or event under one of the request's scopes is `grant.operationUnknown`. A request with `operations` on a capability with the `egress` trait permits egress only if the list names a `read` operation. Why: one scope often covers several operations (`directory.read` covers `find` as well as `manager`), and 0.1 could narrow them only by testing which input fields were present. *No change.* **`where` sees defaults.** A grant's `where` is evaluated on the operation input after the contract's defaults are applied. 0.1 did not say, and a call that left out a defaulted field could be silently denied. *No change.* **Knowing what was granted.** A new expression root, `grants`, gives for each request `grants..held`, whether a grant for it is in force for the person or instance acting, and `grants..declined`, whether a decline of it stands. A request that has not been answered yet is neither. Why: an app could not tell that an optional request was declined, so it offered features that would fail; and it must tell "said no" from "not asked yet", so that it keeps offering what a person has not refused. *0.1 definitions* that used `grants` as a local name must rename it (section 1 above). **Asking less.** Three rules say when a request is put to a person (core.md section 6, "When a request is asked"). A request whose scopes are all *given by use* is not asked: under such a scope nothing happens unless the person does it themselves at that moment in the host's interface (choosing a file, taking a photo, sharing), or has already handed the app the thing acted on (reading a file they chose), so the act is the consent, and the host issues the grant without a question and records that. The mark counts only from a catalog the host trusts. A required request is asked before the load completes. An optional request MAY wait: the host asks it later, and at the latest when the person's own work first needs it, holding that call for the answer. An answer stands, so a host never asks again for a request whose decline stands, and a revoked grant leaves its request declined; a request that was put to nobody, or got no decision, is declined for that use only. A host MAY take one act as the answer to all the requests it shows together, setting apart those that deserve a closer look. A person's confirmation of their own act MAY be asked at the control they activated. Why: 0.1 put every request to the person as its own question before the app opened, including permission to show a file picker that asks again by its nature, and people who are asked too often stop reading. *No change* to definitions; an app that hid an optional feature with `grants..held` should hide it with `!grants..declined`, or a host that asks later never gets to ask. **Contained requests are not asked.** A request is *contained* when everything done under it stays inside the app (core.md section 6, "When a request is asked"), and it needs no answer: the host issues its grant without a question and records that nobody was asked, at the moments it issues a grant given by use. Every code request is contained, since its module runs in the host's sandbox and reaches nothing. A capability request is contained when the provider the host binds promises, for each scope requested, that it gives the app nothing of anyone's, changes nothing outside the instance, reaches no network, program or person, costs nothing and stops with the app, as a demonstration service with sample data does. Only the host makes that promise; a definition or a catalog cannot. The grant is otherwise like any other: limited as requested, shown with the app's other grants, revocable, and not issued again while a decline stands. A host MAY ask all the same. Why: 0.1 asked for every request, among them code a person cannot judge and sample data that is nobody's; an answer to those protects nothing, and people who meet such questions while trying a sample are put off. *No change* to definitions: a module still needs its request. **Part and parent requests.** A call made by a part's steps is covered only by that part's requests, as the parent attenuated them, and a call by the parent's steps only by the parent's. Each request has its own rate. 0.1 did not say which of two requests on one capability covered a call. *No change.* **Code grants check the text at use.** A host refuses to run a module whose text is not the text the grant was issued for, at the moment it runs it. 0.1 implied this through the rule on kept grants. *No change.* **Configuration left to the host.** `config` is evaluated once, when the capability is bound for the instance, with the owner's `env`, and kept until an update. A required capability `config` field MAY be left out of a definition; the owner or host policy supplies it when the capability is bound (for a personal capability, each person when they answer, or host policy), the resolution report shows it, and it is part of what the approver answered. A host with no value reports the capability as `missing`. Why: 0.1 forced organization-specific values (a collection name) into a file meant to be shared. *No change*, though such values can now be removed. **Paid parts.** The rule that an approver sees pricing before a paid provider is bound now covers paid control implementations too, and the host shows the terms in the review the approver answers (`contracts.md` section 5). *No change.* **Consent in history.** A history entry MAY carry `approvedBy: { "kind": "person", "id" }`. A tool that applies a change widening what the app may do SHOULD record who agreed. *No change.* ## 5. Outside effects **`once`.** A `call` step MAY carry `once`, a key of 1 to 200 code points naming the effect. Within an instance, a call takes effect at most once per effect record, identified by the definition that made the call (root or part instance), the capability alias, the operation, the key and, for a personal capability, the person. A repeat with an equal input produces the recorded output, is audited as repeated, and does not count against `rate`; a repeat with a different input fails with the new code `capability.onceMismatch`; a call made while another with the same identity is in progress waits for its outcome. Failed calls are not recorded. The record is kept outside the action's transaction for at least 30 days, and the key is passed to the provider. `once` is allowed only on `write` and `external` operations (`call.onceEffect`). Why: an action that filed a report and then failed on a later step filed it again when retried, and nothing let an app prevent that. A key names the effect for the whole instance, so an effect that should happen once for each person includes `user.person.id` in its key. *No change*, but retried effects should gain `once`. **`env.invocation`.** The id of the audit record of the outermost invocation, so app records can point at the audit log. *No change.* **Failure handling.** `call`, `run` and `code` MAY carry `orElse`, the value bound to `as` when the step fails. A step with `onError` or `orElse` handles its own failure: after the `onError` steps finish normally, the action continues with the next step and `as` is `orElse` or `null`. `return` and `fail` end the whole action from any depth. When a `run` step fails, only the writes of the action it ran are discarded. 0.1 did not say whether the action continued after `onError`, and left `as` unbound. *No change* for definitions that relied on the reference host, which continued; helper actions that existed only to supply a fallback value can be replaced by `orElse`. **`let` step.** `{ "let": name, "to": value }` binds a local name for the steps that follow. Why: a value used twice (one `uuid()` for both an `append` and a `send`) needed a helper action. *No change.* **`refresh` step.** `{ "refresh": "state." }` asks for a sourced entry to be read again without waiting. Naming an entry that is not sourced is `state.notSourced`. Why: a "Try again" button could not be written. *No change.* **Sources.** Several changes to sourced state (`core.md` section 7.1): - `source.when` reads the entry only while it is true; otherwise its status is `idle` and its value is kept. - `source.pages` (1 to 50, default 1) follows an operation's paging, joins the pages, and sets the new `sources..partial` when pages remained. It needs an operation that declares `paging` (`state.sourceNotPaged` otherwise). - `refresh.on` defaults to `["open", "change"]` whenever it is absent, also when `every` is given. In 0.1 it was unclear whether `every` alone dropped them. - `refresh.every` needs a `background` grant to run with no surface active, like an `every` rule. - A sourced entry has one value per person, read on that person's behalf: `open` reads the value of the person whose session opens, `change` the value of each person whose `with` or `when` changed, `refresh.every` the value of each person with an active session (or the owner's, with no session and a `background` grant), a capability event the values of the persons it reaches, and a `refresh` step the acting person's value. - Following pages continues while `next` is present and not `null`. - At most one read per entry and person is in flight, a trigger during a read causes exactly one more, and a read that would exceed `rate` waits rather than fails. - The last value read is kept, per person, across restarts; values restored at load make no `becomes` edge. - The value is `null` until the first successful read whatever `type` says, and an output that does not conform to `type` is a failed read with `state.invalidValue`. `type` may be narrower than the operation's output. - `sources..error` is `{ "code", "message" }` or `null`. *0.1 definitions* that listed `["open", "change"]` beside `every` only to keep the defaults may drop them; others need no change. **Environment changes.** A change to `env.online`, `env.today` or a refresh of `env.now` re-evaluates the derived values, bindings, `becomes` triggers and source inputs that read it; a source whose input changes this way is read again when its `refresh.on` includes `change`. Each session has its own environment. *No change.* **Offline and scopes.** `session` and `device` values are always available. A host that synchronizes `user` and `shared` values keeps a local copy and applies offline writes on reconnection under the entry's `conflict` policy. `conflict` and `key` are sibling fields of the state entry. `merge` works on the top level of the value, matching list elements by `key`, and an element changed on both sides is taken whole from the later write. `device` entries always use last write wins, and under `reject` a stale write whose base still equals what storage holds is not a conflict. *No change.* **Files across boundaries.** A file reference's `id` must be unguessable (at least 128 random bits). A reference stays readable as long as stored state holds it, and a host that cannot keep the file makes reading it fail rather than leave it looking valid. A reference kept in `shared` state shares the file with every member whose grant covers reading it. A file reference in an operation input typed as the core catalog's `FileRef`, at any depth, is resolved by the host so the provider can read it; a vendor catalog names that type through its own `uses` (section 10 below). A file reference in an agent's tool input, at any depth, must be one the host issued to that agent for this instance, or the call is refused as invalid input; a host SHOULD check any value in its own reference form whatever its declared type. Hosts SHOULD let agents hand files to the host. Why: an agent-only app could not attach a file, and nothing stopped an agent from passing a made-up handle. *No change.* ## 6. State, steps and flows **`device` scope and people.** A `device` value belongs to one person on one device; another person using the same device does not see it. *No change.* **`initial` is evaluated once.** A stored entry's `initial` is evaluated when the instance is created and the result is stored, so a later load sees the same value: a start date stays the day the app was installed. An entry an update adds is evaluated at that update. 0.1 said "evaluated once" without saying when. *No change.* **`internal` state.** A state entry with `internal: true` is never an agent resource and never an export (`state.internal` if listed). Why: helper values leaked as agent resources unless every one was excluded by hand. *No change.* **Sensitivity follows data.** A derived entry that reads a sensitive entry is itself sensitive, for agent resources, the audit log and the explanation alike, unless it sets `sensitive: false` to say the computed value may be shown. A new warning, `state.sensitivityUnstated`, flags a sourced entry on a high-sensitivity scope that does not state `sensitive`. Why: 0.1 redacted values computed from sensitive data in the audit log but exposed them to agents. *0.1 definitions* whose derived entries read sensitive data and were meant to be readable by agents must add `sensitive: false` to them. **Redaction follows the value.** In the audit log, a recorded input, output or message is redacted when it was computed from a sensitive value, and recorded in full when it was not, even if the same invocation read sensitive values elsewhere. "Computed from" is defined by references, not conditions: a value is so computed when the expression producing it refers to a sensitive entry, or to a local name, `input` field or `event` field that was so computed; a `call` or `code` output when its input was. A derived entry with `sensitive: false`, and a stored entry without `sensitive: true`, stop it. A message returned to an agent that was computed from a sensitive value the agent cannot read is replaced by the host's own words; a tool's output is returned as computed, so returning a sensitive value makes it readable by every principal that may call the action. *No change.* **Derived values in a transaction.** A derived entry read during an action reflects that action's pending writes. 0.1 implied it. *No change.* **Optional inputs.** An optional field with no default that the caller left out is absent from `input`; read it with `has` or `default`. 0.1 did not say. *No change.* **Keyed paths.** A path may select one list element with `[field=expression]`, as in `state.answers[id=item.id].note`, in the targets of `set`, `append`, `remove` and `patch` and in `bind`. A write that matches nothing fails with the new code `state.noElement`; a binding that matches nothing shows an empty, disabled control. Why: a row of a repeated list could not bind to its own element, so every editable list needed a change handler and an action per edit. *No change.* **`patch` and `remove` scope.** In `where`, `item` and `index` are the element under test; in the `with` of a `patch` that has `where`, they are the element being patched. Both hide outer names. `each` steps and a node's `each` may name the position with `indexAs`. In 0.1, `with` could not see the element, and `index` meant two things in one step. *0.1 definitions* whose `patch ... with` read an outer `item` or `index` must name the outer element with `as` or `indexAs`. **Flow state belongs to the flow.** The state field of a collection flow is written only by the flow; a step that writes it fails with `flow.fieldWrite`. At run time the host compares the collection's elements by key before and after each write, so a computed write, a whole-collection `set`, a re-added element or a changed key cannot change a state either. An appended element may omit the field or give `initial`, and the host writes `initial` into elements appended without it. No `enter` steps run for a new element's initial state. Why: any action could set an approval's status to `approved` and skip every guard. *0.1 definitions* that set the field to anything other than `initial`, or changed it outside the flow, must change. **Rule edges.** The text now explains that a condition the edge depends on belongs inside `becomes`, because `if` is tested only when the edge happens. An `every` trigger may say `"foreground": true`: the rule then runs only while a surface is active, also when the app holds a `background` grant, and `trigger.noBackground` is not reported for it. Cascade depth counts only rules whose `if` held. An app that waits for a condition of the environment that may already hold when a session opens sets `"initial": true`, which then fires in that session. A schedule (`every`, `refresh.every`) that fell due several times while the app was not running, or across a clock jump, fires once when it resumes. *No change*, though rules that guard a `becomes` with `if` should be checked. **Work never waits on a person while it holds the app.** Work on an instance is serial, and `core.md` section 8.2 now says so. A wait on a person (a call of an `interactive` operation, a confirmation, a request asked at the moment of a call) MUST NOT hold the instance: the work waits only while it has changed nothing, its turn then ends with nothing to commit while other work goes on, and it continues where it stopped once the person answered, with `allow` and `require` of the actions it is inside checked again against the state of that moment, the names it bound kept and `env.now` the time of continuing. It is not run again. A new error, `action.waitsOnPerson`, places such steps: a call of an `interactive` operation, and a visual handler's `run` of an action with `confirm`, come before every step of their work that changes anything, and are never in a rule, a flow's steps or an action those run. At run time, work that reaches such a step after a change, or in a rule or a flow, fails it (`capability.unavailable`, or `action.declined` for a confirmation) instead of waiting; a request asked at a call made after a change holds the instance no longer than a call's limit and then fails with `grant.denied`, while the question stays open for the next try. A schedule that fell due several times while other work ran fires once, and its audit record says how many times it fell due. This replaces the 0.1 sentence that a host SHOULD ask a confirmation before the work starts. Why: one person choosing a photo or answering a question held the app for everyone who shared it, for agents and for timers, for up to ten minutes. *0.1 definitions* that write before taking a person's step, or ask a person in a rule or a flow, must take the person's step first, in an action a person or an agent starts, and move what must still hold after the answer into `require`. **A minimum for `after`.** A host may hold a flow's `after` to the minimum interval it enforces for `every`. 0.1 gave hosts a minimum for `every` only, so two states that lead to each other after a very short time could keep a host busy without end. *No change.* **Parts.** A driven input is read-only inside the part (a write fails with `state.readonly`), and its type must accept every value the parent can drive; at run time a driven value that does not conform is not written and the host reports `state.invalidValue`. An agent surface's `include` lists may name a part's exported action, state entry or event as `part.name`. A host may let a person start a part from a copy of an instance they own: only `shared` entries and that person's own `user` entries are copied, and the copy is recorded in the source instance's audit log. *No change*, though wrapper actions and re-emitted events that existed only to reach a part from an agent can go. **The resolution report.** A declared surface is `satisfied` only when the host serves it. A part's request the parent declines with `false` is not put to the approver and is listed as declined by the including definition, not as `missing`; a request the parent attenuated and the approver granted as shown is `satisfied`, and `degraded` is kept for a grant narrower than what was shown. A type from a catalog the host cannot find is treated as `any` at run time and marked `degraded`. When `meta.derivedFrom` has a `digest` and the host holds the definition it names, the host verifies it and fails the load on a mismatch; otherwise the report says the origin is unverified. A part node's `id` addresses the node that stands for the embedded view, and the ids of nodes inside an embedded view are qualified by the part's name and a dot (`savings.total`). *No change*, except that a definition whose `derivedFrom` digest is wrong now fails to load where the host can check it. **Behaviour now stated.** These were the reference host's readings and are now in the text: a singleton flow's bookkeeping lives with the instance and a collection flow's with the collection; `action:` is raised on success, nested runs included, with `{ "input", "output" }`; rules fire only in the session that made the write; `install` is an instance's first load, `open` runs when a session's first surface opens and `close` when its last closes; a failing `if` or `where` counts as false; `each` over a value that is not a list is `expression.error`; a `return` value is checked against `output` only when a return ran, and an action without one produces `null`; a request for an unavailable capability, or for code the host cannot run, is not asked and does not fail the load; a flow event for a missing element is `flow.noTransition`; an app may use its own codes in `fail`. *No change.* **The flow example.** The flow example in `core.md` section 10 modelled "my manager" as a role, which let any manager approve anyone's request, and used an undeclared `director` role. It now stores `requesterId` and `managerId` on each request, lets only the requester (or their agent) submit, takes `managerId` from the directory rather than from input, compares it with `user.id` because the manager must approve in person, and declares every role the flow uses. `state.requests` is a `shared` list. Elsewhere a stored person id is compared with `user.person.id`, so an agent acting for the person passes. *No change*, but definitions copied from the old example have the same fault. **An action can say it was done.** An action may carry `done: { "message": dynamic value }`, what the app says once the action has been done. Whoever invoked it from outside hears it, and nobody else: a person through a visual handler's `run`, for whom the host shows it for a moment outside the view; a person through a voice intent without its own `reply`; and an agent, whose tool result carries it beside the output. An action run by another action, a rule or a flow says nothing, and a parent that runs a part's action gets its output only. The message is evaluated once, after the steps succeeded, with the roots `allow` sees, the state as the steps left it, and `output`, the value the action produced; a message that cannot be evaluated is no message and the action still succeeds. A host cleans it to one line of plain text and cuts it at 200 characters, and validation warns about a longer literal message (`action.doneTooLong`). Why: almost every app says "Saved" or "Request sent" after a press whose result is not where the person looks, and 0.2 had no way to say it, so apps kept a text in state that never went away. *No change*: a definition without `done` behaves as before. ## 7. Audit log **Record kinds.** The audit log gains kinds for a delivered capability event (`event`), a visual handler (`handler`), a timer (`timer`) and an update (`update`); `core.md` section 15 lists every kind. A declined grant request is recorded (which request, who declined, when), and so is a load that failed because of it. A state change names as its cause the action whose step wrote it; an `after` transition names the transition that entered its state; a timed source read names its timer. Members read their own records in full and the rest in outline; the owner reads all. *No change.* **What the log holds and keeps.** Routine refreshes of the environment, such as the minute tick of `env.now`, are not recorded. `every` firings under one minute apart are recorded as one record per minute with a count; writes to view state are not recorded, and successive keystroke writes from one binding form one record. A host may bound the log's size, but keeps the records of grants and updates for the life of the instance and SHOULD keep at least 90 days of the rest. *No change.* ## 8. Views **View state.** A view MAY declare `state`: entries of `{ "type", "initial", "description" }`, read and written as `view.`, evaluated when the view opens and gone when it leaves the navigation stack. Actions never see `view`, and view state is never a resource. Why: every form needed a session state entry per field, each of which was also an agent resource. *No change*, but form drafts in session state can move to view state. **Main navigation.** The visual surface MAY carry `navigation`: 1 to 12 entries of `{ "view", "label", "icon", "when" }` naming the app's main sections in order (and the forms of the next entry). A host draws the sections that are offered as the app's own navigation and marks the current one; choosing a section replaces the navigation stack with its view. A section's view takes no required input unless the section gives it, and two plain sections never name the same view (`view.invalidNavigation`). `when` decides what is offered, never what is allowed. A host MAY show more than one view of the stack at a time, such as a record beside the list it was opened from, and a `navigate` step of a handler that runs in a view below the top then first closes the views above it, while a handler that does not navigate closes nothing. Choosing the section that is already at the bottom of the stack returns to it. Why: 0.1 gave a host only a start view and a stack, so a host could not tell an app's sections from its forms, and every app looked like pages inside someone else's frame. *No change*; an app with several sections should list them. **Main sections from the app's data.** A navigation entry MAY also be a repeated section, a section with `each` (the shape of a node's `each`) that offers one section for each element of a list, or a group, `{ "group", "when", "sections" }`, a heading over 1 to 12 sections or repeated sections. A section MAY carry `with`, the input its view opens with, checked as a `navigate` step's `with`, and `count`, a whole number shown beside its label, such as unread messages. A section with `with` or `each` may name a view another section names; plain sections still name a view once. The host marks the section whose view and input are at the bottom of the stack, tells sections apart by keys that stay the same while an element keeps its `each` key, and offers at most 200 sections, saying how many a repeated section left out. Why: channels, folders, notebooks and projects are data, so a chat, mail, notes or planner app could not list them in its navigation and had to draw a list inside a view instead. *No change*; a section's view that takes a required input is now allowed when the section gives it with `with`. **An app of one view is a card.** An app whose visual surface has exactly one view and no `navigation` is drawn as one card headed by the view's title (`core.md` section 12.2): with no bar and no page heading above it and the host's own parts outside it; when the body is one canvas, chart, table, list, diagram or group, that control is the card itself. The form follows from the definition, not from the host or a field of its own. Why: most small tools an assistant writes have one view, and a page around them said the app's name three times around something that is one card. *No change*; give the view a `title`, which heads the card. **Navigation returns to an open view.** A `navigate` to a view already on the stack with equal input returns to it and closes the views above, instead of pushing a second copy; `navigate: "back"` followed by a named `navigate` replaces the current view. Why: going "home" after deleting an item pushed a copy, and Back then showed the deleted item. *No change*, though handlers that worked around it can be simplified. **A link to a main section goes to that section.** A `navigate` to a view that the navigation offers as a section at that moment, with an input equal to the one that section opens with, chooses the section (`core.md` section 12.2): the navigation stack is replaced with that view, or returns to it and closes the views above when it is already at the bottom, as when the person chooses the section in the navigation. This holds for a handler's `navigate` step, a `core:link` with `view` and a host that opens a view for the person. A `navigate` to any other view, or to a section's view with another input, or to a section that is not offered, pushes the view or returns to it as before. Why: a home page whose links lead to the app's sections opened each one on top of the home page, often beside it in a narrow pane, with the home page still marked in the navigation, while choosing the same section in the navigation showed it in full. An author who lists a view as a main section has said it is a place of the app, and going there means the same from a link as from the navigation. *No change* to a definition; a link to a section no longer leaves a way back to the view it was followed from. **Failed expressions in views and elsewhere.** A failing prop or title is absent (a required one gives the placeholder), a failing `each.in` repeats nothing, a failing binding shows an empty, disabled control, a failing source `with` or `when` is a failed read (not an idle source), a failing `config` member is left unsupplied, and a failing `initial` gives `null`. 0.1 said nothing for these positions. *No change.* **Handler failures.** When a handler fails without handling the failure, the host SHOULD show the error's message at the control that raised the event, or in the form for a `submit`, and the handler's later steps do not run. *No change.* **Fallbacks.** A `fallback` is a complete node: it takes nothing from the node it replaces but its place, and the outer `when` and `each` apply to whichever is drawn. A catalog the host cannot find no longer fails the load: its controls fall back and its capabilities are missing, which fails the load only if one is required. Validation still needs the catalog. `degradeTo` may name a contract in a catalog that the control's catalog uses (section 10 below). Why: a fallback could not save an app on a host that never installed the vendor's catalog. *0.1 definitions* whose fallbacks relied on inheriting props or handlers must repeat them; the reference host never inherited them. **Actions of one control.** A slot without `scope` variables is one node filled once with the names around it, and a control that draws a header of its own takes what a person can do with it as a slot named `actions` (`contracts.md` section 3). In the core catalog `group`, `chart`, `table`, `list`, `canvas`, `diagram` and `alert` have it, and `button` gains `iconOnly`, which draws its icon alone and keeps its label as its name; `iconOnly` without `icon` is `prop.iconOnlyWithoutIcon`. A host takes one press of a button at a time while its handler runs. Why: a button at the end of a chart's header, as apps commonly have, could only be drawn as a row above the chart, which reads as a separate thing. *No change.* **Control behaviour.** A new section, `contracts.md` section 8, settles what the core controls left open: a `select` event's `item` is the app's own element at the picked position, and chart, table and list `select` payloads are typed; `hidden` keeps a node while `when` removes it, and `disabled` passes down; only the app opens a dialog, and a dialog may be drawn inside the app's region; table paging, sorting and selection; which inputs count toward a form; canvas coordinates and lengths; an unknown icon shows nothing; `link` declares `activate`; `progress` and chart series take a `format`; choice values may be strings, numbers or booleans; the format of a date input's value in each mode; keyboard descriptions follow an alternate role when the host uses one; `slider` and `numberInput` refuse a value off their `step`, and `fileInput` refuses a file its `accept` excludes. *0.1 definitions* whose chart `select` handlers read only the plotted fields need no change; those that relied on choice values being strings still work. **Two warnings about how a view reads.** A view whose body begins with a `core:heading` saying what the view's `title` says is reported (`view.headingRepeatsTitle`), because a host draws the title as the page's heading and the words would show twice. A child of `core:tabs` with nothing to name its tab, such as a plain `core:stack`, is reported (`view.tabUnnamed`), because its tab would be captioned by its position alone. Both are warnings: the definition stays valid. *0.1 definitions* that do either should remove the heading, or wrap the panel in a `core:group` with a `title`. **A diagram control.** The core catalog gains `diagram`, for explaining how parts connect: an architecture, a flow or a process. The app gives `boxes` (`DiagramBox`: `id`, `label`, `detail`, `group`, and a `kind` of `box`, `person`, `store` or `outside`), `connections` (`DiagramConnection`: `from`, `to`, `label`, `id`, a `style` of `solid` or `dashed`, and `arrows` `forward`, `both` or `none`) and optional `groups` (`DiagramGroup`), never positions, sizes or colours; the host lays the boxes out in bands, routes the lines and fits the drawing to the width it has. `selected` is bound and reported as a table's selection is: pressing a box raises `select` with `{ box, selected }` and selects it, pressing it again or pressing empty space clears it. `highlight` names boxes and connections to keep strong while the rest is dimmed; a connection without an id counts as named when both its boxes are. A connection to a box the diagram does not have, a repeated box id, a group nobody declared and a highlight that names nothing are left out or drawn without the missing part, with a view diagnostic. At most 60 boxes, 120 connections and 12 groups are drawn; beyond that the rest is left out and the node is reported as degraded. Why: an app could only draw a diagram by placing shapes on a `canvas` by hand, which a model gets wrong and which never fits both a phone and a desktop. *No change.* **Charts say what their numbers are.** `chart` gains `unit` (such as `hours` or `kg`, which a series may override with its own), `categoryLabel` and `valueLabel` (what the axes show), `orientation` (`vertical`, or `horizontal` for bars on their side, first category at the top) and `goal` (`ChartGoal`: a `value` and an optional `label`, drawn as a dashed line across a bar, line or area chart, with the value axis always reaching it). A unit is shown after plain numbers only, as written; `orientation` with a kind other than `bar`, and `goal` with `pie` or `scatter`, are ignored with a view diagnostic (`contracts.md` section 8.3). Why: only money and percentages could be said, bars could not lie on their side for a ranking or long names, and a target could not be shown, so models invented props such as `yLabel` and `target` that the check refused. *No change.* **A chart keeps what was selected where the app can clear it.** `chart` gains `selected`, bindable, a `ChartValue` (`{ item, series }`: the value of the record's key field and the field of its series) or `null`, and `itemKey`, the field that names a record, else the category field. Pressing a bar, a point or a slice selects it, pressing it again or Escape clears it, and pressing empty space changes nothing; the host works out the new selection, writes it to `selected` when that is bound and keeps it in the view otherwise, as a diagram does, and `select` gains `selected`, the selection after it, `null` when the press or Escape cleared it. `item` and `series` always name the value the event is about, the one pressed or the one whose selection Escape cleared, and are never `null`; Escape is heard only by an app that gives `selected`, and for one that does not, the host clears its own mark without calling the handler. A chart that neither handles `select` nor binds `selected` offers no selection. A selection that names a record or a series the chart does not draw now marks nothing and is kept. The host outlines the selected value and says it is selected in the words of the point and the table of the data, and shows the place of the keys apart from it, only while the keyboard is in the plot. Why: a pressed value stayed outlined, and the app had no way to take the outline away when it forgot what was picked. *0.1 definitions* that handle `select` hear every press as before, and never Escape, since they give no `selected`. **Formatted text.** `core:text` gains `format`: `plain`, the default, or `markdown`, which reads a small subset of Markdown that every host reads the same way (`contracts.md` section 8.3): paragraphs and line breaks, strong, emphasis and code in a line, headings of levels 1 to 3, lists with one level inside an item, fenced blocks of code, quotations, rules, links and pipe tables. Everything else, HTML and images included, is shown as its characters. A link in it follows the rules of `core:link` with a `url`; nothing in it is fetched, and it never opens a view, runs an action or writes state. A host reads at most 20,000 characters, 500 blocks and list items, nesting 5 deep, and 100 rows and 12 columns of each table, and reports a text beyond them as degraded. The new warning `prop.markdownInPlainText` reports a literal plain text that is plainly written in Markdown (`validation.md` section 9). Why: replies from models, notes people write and descriptions from services commonly arrive in Markdown, and a plain text showed `**`, `- ` and `[words](address)` literally. *No change*; a plain text is drawn as before. **Colors and tools in a choice.** A `ChoiceOption` MAY carry `icon`, an `IconName`, and `swatch`, a color token name as a canvas shape's `fill` takes. A host draws a `core:choice` whose options all carry a `swatch`, or all an `icon` it draws, at most 12 of them, as a palette: small color dots or symbol buttons, one picked, still one radio group named by the choice's `label`, each option named by its own. A swatch whose name the design lacks falls back to `accent` and the node is reported as `degraded`, as a canvas fill is. `core:multiChoice` takes the same options and does not draw either. `core:canvas` gains a slot `tools`: such choices and icon-only buttons, which a host draws beside the surface, or above it where there is little width, outside the area that takes the pointer. A host shows no words saying an input is `required` when it is in no form, since nothing is submitted there. Why: apps drew color and tool pickers as shapes on a canvas, which grew with the column and were neither one tab stop nor announced as options. *No change.* **A path shape, and the limits of a scene.** The core catalog's `Shape` gains `path`: `points`, a list of `{ x, y }`, drawn as one line through them with round ends and joins, one point alone as a dot, with optional `closed`, `fill`, `stroke`, `strokeWidth` and `opacity`. A path is under the pointer on its line and inside its fill, and a point that is not two finite numbers is passed over. A host draws at most 5000 shapes and 50000 path points of a scene and reports a scene beyond them as degraded, saying how many were left out (`contracts.md` section 8.3). Why: a pen stroke had to be one `line` for each move of the pointer, so a whiteboard built from its strokes' points ran out of its expression budget after about 2500 points, some 40 seconds of drawing, and lost its canvas, tools and actions with it, and one that kept the lines met the 5000 shapes the reference host drew, which it left out without a word. A stroke is now one shape, and the cost of a scene follows the number of strokes, not of points. *No change*; the reference host already drew at most 5000 shapes. **Curves and round shapes on a canvas.** The core catalog's `Shape` gains `ellipse` (`radiusX`, `radiusY`, `rotation`) and `arc` (`radius`, `from` and `to` in degrees clockwise from pointing right; with a `fill`, the wedge between the arc and its center), `rect` gains `radius` for rounded corners, and a point of a `path` may carry control points: `cx` and `cy` for a quadratic curve, or `c1x`, `c1y`, `c2x` and `c2y` for a cubic one (the type `PathPoint`). A curved point counts as one point against the limit of a scene. Every shape with a line gains `dash` (`solid`, `dashed`, `dotted`) and `cap` (`round`, `flat`, `square`), and `rect`, `path` and `arc` gain `join` (`round`, `sharp`, `bevel`); `text` gains `weight` (`body` or `emphasis`, as the design's type styles). What a shape leaves out is drawn as before, and the pointer finds each shape where it is drawn (`contracts.md` section 8.3). Why: a stretched circle, a rounded tile, a gauge or a smooth line had to be approximated with many points, which used up the canvas's points, cost expression budget and was not crisp on a large canvas. *No change*: a scene that uses none of these is drawn exactly as before. **A canvas follows the page's mode.** Every color a `core:canvas` scene names, and its `background`, is drawn in the values of the page's mode, as every other control's colors are, and follows a change of mode while the app is open; a palette among its tools shows each color as the scene draws it. The canvas gains `mode`, `light` or `dark`, which keeps the scene in that mode's values whatever the page's, for a drawing whose colors mean something by themselves, such as one that must print as it shows (`contracts.md` section 8.3). Its card, title, tools and settings follow the page either way. Why: a scene kept the light values on a dark page, so a game board, a gauge or a whiteboard was a white panel in a dark app, while a token names a role, and a role has a color in each mode. *No change* on a light page, or where the design system has no dark mode. **Groups, symbols and motion on a canvas.** The core catalog's `Shape` gains `group` (`x`, `y`, `scale`, `rotation`, `opacity` and `shapes`, drawn in a space of their own whose both axes are fractions of the width) and `use`, which places a drawing of the canvas's new prop `symbols` (a map from a name to shapes) as a group would, with one `color` of its own for the shapes of the symbol that name `given`. Groups and placements nest four deep; a placement of an unknown name or of a symbol inside itself is not drawn. The limits of a scene count every shape and point as often as it is drawn, and a pointer on a shape inside a group or a placement reports the outermost `id`. The canvas and every shape gain `motion` (the type `Motion`): `none`, a motion token's name, or `{ over, ease }`, by which a shape that stays in the scene with the same `id` glides from its old values to its new ones, drawn by the host on its own clock, and at once for a person who asks for reduced motion (`contracts.md` section 8.3). Why: a game wrote a figure of several shapes out again wherever it appeared, sending the same rectangles on every tick, and made motion look smooth with a rule that fired twenty times a second. *No change*: a scene that uses none of these is drawn exactly as before. **Gradients and shadows on a canvas.** A shape's `fill` may be a gradient (the type `Fill`): `{ "gradient": "linear" | "radial", "stops", "angle" }`, two to eight color names or `{ color, opacity, at }` stops across the shape's own box. Every shape, `group` and `use` gains `shadow` (`low`, `medium`, `high`), drawn from a new optional token group of design systems, `shadow`, whose levels give `offset`, `blur` and `opacity`; a design system that names none has the default design system's (`contracts.md` sections 6 and 8.3). A host may leave both out: it fills a gradient's shape with its first stop's color at that stop's opacity and draws no shadow. Why: a game drawn on a canvas looked plotted rather than made, as every fill was one flat color and nothing stood above the ground. *No change*: a scene that uses neither is drawn exactly as before, and a design system without `shadow` stays valid. **The keys of a canvas follow the game and are always released.** When a canvas that takes keys leaves the drawing while it has the focus and another canvas that takes keys is drawn after it, a host SHOULD give that canvas the focus, and MUST NOT take the focus from outside its own document for it. When a canvas stops taking events while a key it reported pressed is still down (its surface loses the focus, or the canvas leaves the view, is hidden, is disabled, or a dialog is opened over it), the app hears that key's release then, once, and a release with no press before it is not reported; for a canvas that no longer raises events the host raises the release itself (`contracts.md` sections 8.2 and 8.3). Why: a game whose screens are separate canvases lost the keyboard at each change of screen until the person clicked, and a key held when its canvas went away stayed pressed for the app forever. *No change*. **A canvas keeps its picture through a frame that cannot be drawn.** When a `core:canvas` that has drawn a scene in this visit of its view becomes the host's placeholder (its `scene` failed or does not fit), a host SHOULD keep showing the last picture it drew, at its size and in the same place, for a short time, and show the placeholder when no scene can be drawn within it; the kept picture raises no events, assistive technology is told once that the part cannot be shown, and the tree still holds the placeholder (`contracts.md` section 8.3). **Items that move between lists, and lists a person orders.** `core:list` gains `moveGroup`, a name the app chooses, `reorderable`, and the event `move`. Lists of one view that share a `moveGroup` and handle `move` take items from each other: the host carries out the whole gesture, lets the person drag an item onto another list of the group, and MUST offer from each item a way to move it to each other list that needs no dragging, named by that list's `label`. A list that is `reorderable` and handles `move` lets a person put an item at a place of their choosing, within the list and, with a `moveGroup`, from another list of the group; the host MUST offer from each item a way without dragging to put it one place earlier and one place later, SHOULD offer the first and the last place, and, where it lets the person drag, shows where the item will stand. When an item is let go on another list or at another place, or that move is chosen, the host raises `move` on the list it lands in with `{ item, index, order }`: `item` the element of the list it came from, and, when the list it lands in is reorderable, `index` its place there and `order` the `itemKey` of every item of that list in the new order, which the handler keeps with `sortBy` and `indexOf`; both are `null` for a list that is not reorderable. The item is found by its `itemKey`, so one without a key of its own stays where it is (`contracts.md` section 8.3). The new warnings `prop.moveGroupUnhandled`, `event.moveWithoutGroup`, `prop.moveGroupAlone`, `prop.moveListUnnamed` and `prop.reorderableUnhandled` report a list that names a group without handling `move`, handles it with neither a group nor `reorderable`, is alone in its group and not reorderable, has no label to be named by, or is reorderable without handling `move` (`validation.md` section 9). Why: a task board moved its cards with two arrow buttons on each, and people expect to drag them; a to-do list, a list of priorities and the cards of one column are kept in an order their owner chooses; a way without dragging keeps both moves open to everyone. *No change*: a list with neither `moveGroup` nor `reorderable` is drawn as before. **Pictures the app carries.** A definition MAY carry its pictures in a new top-level member, `assets`: an object from asset name to an entry with `type` (PNG, JPEG, WebP or GIF), `digest`, and optionally `data` (the bytes as base64 in one canonical form), `width`, `height`, `source` and `credit` (`core.md` section 12.5). A `remote` prop refers to one as `asset:logo`, which is a third kind of value beside a web address and a reference the host issued (`core.md` section 6.3): loading it is not egress and needs no grant, and for a view of a part it names the part's own asset. An entry without `data` is valid, and the digest of a definition leaves `data` out (`core.md` section 16), so a host or tool can keep the bytes apart and put them back without changing the definition or anything pinned to its digest. Carried bytes are checked: canonical base64, the digest, the type read from the picture's header, at most 4096 pixels on a side, and `width` and `height` where given (`validation.md` section 9.1). Why: an app could show a picture only from the web, so a header photo asked the person a permission question, showed nothing on a host that loads nothing from the internet, and was lost when its address died. *0.1 definitions* need no change. **Sizes every host accepts.** `core.md` section 18.1 names the sizes every host MUST accept: 2,621,440 bytes for a definition without the `data` of its assets, 64 assets, and 1,048,576 characters of `data` for one asset and 2,621,440 for all of them. A larger definition is valid, and a validator warns about it. Why: 0.1 named no size, so an author could not know what every host would load. *No change.* **Where a carried picture was taken.** A tool that adds a picture to a definition removes the location its metadata holds (EXIF GPS data and XMP GPS properties) before the digest is taken; a validator warns about a carried picture that still holds one; a host shows pictures as they are (`core.md` section 12.5). Why: a photo from a phone says where it was taken, and carried in an app that place went to everyone who received the file, unseen. *No change.* **A place named in words is part of where a picture was taken.** Beside coordinates, the location a tool removes and a validator warns about includes the place a photo manager writes as words: the XMP properties `photoshop:City`, `photoshop:State`, `photoshop:Country`, `Iptc4xmpCore:Location`, `Iptc4xmpCore:CountryCode`, `Iptc4xmpExt:LocationCreated` and `Iptc4xmpExt:LocationShown`, and the IPTC datasets 2:26, 2:27, 2:90, 2:92, 2:95, 2:100 and 2:101; a title, caption, keywords, credit, author and copyright stay (`core.md` section 12.5). Why: with the coordinates gone, a photo that went through a photo manager still told its city and country. *No change to definitions.* **The size of a turned picture is the size it shows at.** An asset's `width` and `height` are the size the picture shows at: for a JPEG or a PNG whose EXIF orientation is 5 to 8, the sides its header gives, swapped. A host shows a JPEG or a PNG turned as its orientation says; a WebP and a GIF show as stored (`core.md` section 12.5, "Orientation"). Why: a photo taken upright on a phone is stored on its side and every browser shows it upright, so the stored size told a host the wrong shape to keep room for. *An entry that gives the stored size of a turned picture is now `asset.sizeMismatch`: give the two numbers the other way round, or leave both out.* ## 9. Expressions These are defined in `expressions.md`. - **`let(name, value, body)`** binds a name inside an expression. - **`merge(a, b)`** and **`compact(map)`** combine maps and drop `null` members, so optional fields need no duplicated literals. - **`list.indexBy(x, key)`**, a list macro in method form, and **`enumerate(list)`** build lookups and give positions. - **`formatNumber`**, **`formatDate`** and **`relativeTime`** format for people, using `env.locale` and `env.timezone`. Their results are for display only and vary between hosts. - **`plural(n, forms)`** picks the plural form for `n` in `env.locale`, for display. - **`atTime(date, "HH:MM", timezone?)`** and **`dateIn(datetime, timezone?)`** convert between local and UTC time. - **`matches(string, pattern)`** tests a pattern. Patterns here and in a type's `pattern` use a restricted dialect that matches in linear time; a pattern outside it is `type.invalid` or `expression.syntax`. Its meaning is defined by `expressions.md` alone, so an implementation that uses another engine translates `.`, `\s`, `\S` and `\u`. This replaces the 0.1 rule that a type's `pattern` is any ECMAScript regular expression. *0.1 definitions and catalogs* whose patterns use backreferences, lookaround or other features outside the dialect must rewrite them. - **Typical costs** are tabulated so authors can judge what fits the budget. - **Long strings are paid for.** A function call costs 1 for every 1,024 code points of each string argument, comparing or ordering two strings costs the same for the shorter of them, and a pattern that is not a string literal costs a fixed 40 to compile. In 0.1 reading a long string cost nothing, so an expression within its budget could still keep a host busy for a long time. *0.1 definitions* are affected only where they work on strings of 1,024 code points or more. - **Macros in method form.** `x.has(...)`, `x.default(...)` and `x.let(...)` are syntax errors, as `x.can(...)` and `x.canSend(...)` are. In 0.1 the first two parsed and always failed when evaluated. - **`t(key, values?)`** gives the app's own text named `key` in the language the host shows, with its blanks filled from the map `values` (section 8.7). A text holds blanks written `{name}`, with `{{` and `}}` for the braces themselves. An entry may instead be forms chosen by the value of one blank: `=N` for an exact number, a plural category, an exact text, `true` or `false`, and otherwise `other`. A number is written as `formatNumber` writes it, and an inserted value is kept in one piece inside text that reads the other way. `t` is only a global call with a string literal key and an optional map literal, so every use can be found without running the app; anything else is `expression.syntax`, and a variable or member named `t` is unaffected. It reads `env.language` and `env.locale`, and its result is for display only. Section 12 below describes the table of texts. New in 0.2. - **`can`** and **`canSend`** (section 3 above). *0.1 definitions* that use any of these names as local names in list macros are unaffected; a macro variable may shadow anything. ## 10. Catalogs and contracts **`personal` trait.** Added to the closed set of traits (section 3 above). **Scopes given by use.** A scope MAY carry `consent: "use"` (the default is `asked`): the contract's promise that nothing happens under the scope unless a person does it themselves at that moment in the host's interface, or has already handed the app the thing acted on. A capability with the `background` or `egress` trait may have no such scope, no event may have one, and an operation under one that is not `interactive` must have `effect: "read"` (`contract.invalidConsent`). In the core catalog `files.pick`, `files.read`, `files.save`, `media.camera`, `media.microphone` and `share.send` are given by use. An interactive operation is carried out in the host's own interface, which says which app is asking, and a host never completes one for the person. A host honours the mark only from a catalog it trusts, the core catalog among them, and treats the scope as asked otherwise (section 4 above). *No change.* **Paging and aggregates.** An operation MAY declare `paging: { "cursor", "next", "items" }`, where the output is a map type declaring both fields, `items` is a list and `cursor` an optional `string` or `string?` input (`contract.invalidPaging` otherwise). `core:records` `list` declares it, and `core:records` gains `count` and `aggregate` (grouped `count`, `sum`, `min`, `max` and `avg` with a group limit and a `truncated` flag), both `read` under `records.read`. Why: a dashboard over a few thousand records could neither count them nor page through them. *No change.* **`contains` ignores letter case.** A `core:records` condition with `contains` holds when the field contains the value once both are mapped to lower case by the Unicode default case conversion with no locale, with no normalization and no folding of accents (`contracts.md` section 9): `"Refund for a cancelled booking"` contains `"refund"`. `eq`, `ne`, `in` and the ordering comparisons stay exact. 0.1 did not say whether case counted. Why: a search by the words a person types that minds capitals misses most of what they look for. *0.1 definitions* that relied on a search minding capitals find more records. **Capability behaviour.** A new section, `contracts.md` section 9, settles what the core capabilities left open: http paths are literal and never normalized, redirects are never followed, forbidden headers are refused and listed, and the response body for empty, binary and malformed content is defined; scheduler behaviour for past times, sessions and limits, and a wake belongs to the person on whose behalf it was scheduled, its rules acting for that person in one of their active sessions or, with none, unattended under the scheduler grant, with wake keys per instance (so a per-person wake includes `user.person.id` in its key) and a part's keys its own, and its scope says plainly that it lets the app run while closed; the current user for `notify.send` and `directory.me` is the person of the acting principal; record filter, sort, paging and aggregate semantics; who may read a file reference; an `interactive` operation is asked of the acting principal's person on an active surface of theirs, and fails with `capability.unavailable` when there is none. `notify.send` and `notify.sendTo` gain `viewInput`, so a notification can open a particular record. *No change.* **Catalogs may use other catalogs.** A catalog MAY carry `uses: { "catalogs": { alias: { "id", "version" } } }`, as a definition does. Inside it, a type reference may be `alias:TypeName`, a `requires` entry's `contract` may be `alias:contractName`, and `degradeTo` may be `alias:contractName`, each with a version range. The graph of catalogs using catalogs must be acyclic (`uses.catalogCycle`). A control named in a used control's `degradeTo` is itself used, so its `requires` and pricing count. This is how a vendor contract declares a file input the host resolves and checks: it types the field with the core `FileRef`. Why: vendor catalogs copied core types such as `FileRef` and `ChartSeries`, and a host could not tell a copied file handle from plain data. Replaces the 0.1 `catalogId:contractName` form in `requires`. *0.1 catalogs* that used that form must declare the other catalog in `uses` and refer to it by alias; catalogs with copied types should replace them with references. **Type schemas** gain `minItems`, `maxItems` and `uniqueItems`. *No change.* **Known values and the icon vocabulary.** A string type in a catalog's `types` MAY list `known`, the values every implementation should know (`contracts.md` section 1). It never refuses a value: a checker warns about a literal value outside the list (`value.notKnown`) and names the nearest known values by spelling. The core catalog's `IconName` is such a type, and its list is the icon vocabulary that `meta.icon`, a main section's `icon`, the `icon` control's `name` and a `button`'s `icon` take; the vocabulary gains `chart`, `dashboard`, `list`, `table`, `folder`, `tag`, `inbox` and `money`, and for drawing apps `undo`, `redo`, `eraser`, `line`, `rectangle`, `ellipse`, `text`, `pointer`, `hand` and `fill`. A `known` type is checked wherever a prop's value holds it, such as the `icon` of each option of a choice. *No change needed: a name outside the list is still valid, shows no symbol as before, and is now told.* **Digests and sidecars.** The digest of a resource that is not JSON, such as a code module or a control implementation, is `sha256-` and the base64url SHA-256 of its bytes; 0.1 defined digests only for JSON. A signature sidecar is named after the document's file name with `.json` replaced by `.sig.json`. Fetching a control's implementation module, or a code module's `module.uri`, is the host's act at install, checked against its digest, and is not egress. *0.1 sidecars* named otherwise must be renamed; digests of JSON documents are unchanged. **The core catalog README** is now named by the specification as the reference for core controls, their props and the core capabilities. **Smaller additions to the core controls.** `core:toggle` takes an optional `hint`, a line of guidance shown with the setting, as `core:choice` and the other inputs do. The `direction` of `core:stack` now says what hosts already did: in a horizontal stack the first child, when it is a text, a heading or a stack, takes the room the others leave, and children that one `each` repeats are laid out alike. *No change.* ## 11. Voice The voice surface is now fully described (`core.md` section 12.3), though still marked as less proven than the others: - `greeting` is spoken when a voice session starts. - An intent has `examples` (required, with `{slot}` placeholders naming input fields of the action), an optional `action` (without one the intent only replies), and `reply`, spoken after success with the state after the action, `input`, the new root `output`, `env` and `user` in scope. - `announce` maps an app event (an `emit` name or `flow:`) to words spoken when it is raised during a voice session. - Recognition is the host's job and examples are guidance, with a stated minimum: each example is recognized as written, slots are converted to their field's type, a host asks again when it cannot convert, never runs an action whose required input it could not fill, and says so when nothing fits. - When the action fails the host speaks the error's message, not the reply; for a `confirm` action it asks aloud and proceeds only on a clear yes. - A control's `surfaces.voice` support level is about reading views aloud and is independent of intents. Why: 0.1 gave one example and a sentence, so replies could not see results, questions needed dummy actions and nothing could be announced. *0.1 definitions* need no change, though actions that existed only to answer a question can become intents without `action`, and replies can read `output`. ## 12. An app's texts in several languages **A `localization` table.** A definition may carry its own texts in several languages in a top-level `localization` member: `default`, the language its plain texts are written in; `strings`, for each language a table from key to entry; and `notes` for whoever translates later (`core.md` section 12.6). An entry is a text with blanks written `{name}`, or forms chosen by the value of one blank. An expression shows an entry with `t('key', { name: value })` (section 9 above). The default language is complete; the other languages may be partial, and a text one of them lacks is taken from a wider regional form of the same language and then from the default. **References in fixed places.** In the places that hold plain text and never an expression (`meta.name`, `meta.description`, a grant request's `reason`, the descriptions, and the other places `core.md` section 12.6 lists), a value that is exactly `=t('key')` shows that key's text. Any other value is the literal text, as before. **The host chooses the language; direction and formats follow.** A host shows the app in one of the app's own languages, chosen from the person's languages and from a choice the host keeps for the person. The rules use only five small tables printed in `core.md` Appendix A, so every host chooses alike (section 12.7). A script is never crossed: a reader of Traditional Chinese is not shown Simplified. The direction of the app, left-to-right or right-to-left, comes from the shown language and from nothing else: a definition cannot set it apart. `env.language` and `env.direction` are new, and `env.locale` is now the locale that formats numbers and dates beside the words shown, the shown language written for the person's region (section 3.5). **Kept grants.** A kept grant whose reason is a reference holds while the reason's text, in the language the approver read, is unchanged (section 6, rule 5). Adding a language does not ask again. **Parts.** A part has its own table and its own shown language (section 13). **Sizes.** Every host accepts 64 languages, 2,000 keys in one language, 2,000 code points in one text and 24 forms in one entry (section 18.1). **An app read from right to left.** A host lays out an app in the direction of its shown language and takes that direction from nothing else, never from the page or window around the app; the host's own sheets, dialogs and notices keep the direction of the host's words (`contracts.md` section 8.2.1). Alignment follows the app, and the order inside one text follows the text: the direction of its language where the host knows it, else the direction of its first strong character. A number, an amount or a date the host formats stays in one piece, and a telephone number, an email address, a web address and a number field read left to right in every app. **What never turns.** A chart's plot, a diagram's layout and a canvas are the same in every language: axes, bars and lines keep their places, the boxes and connections of a diagram stand where they stood, and on a canvas `x` grows to the right and `start` is the left end of a text (`contracts.md` section 8.3). The words around them, such as a chart's title, legend and data table, follow the app. **Hidden characters in an app's text.** What a host removes from an app's text before showing it depends on where the text goes (`contracts.md` section 8.2.1). Text shown in an element of its own keeps the joiners U+200C and U+200D, the direction marks and the isolates that are balanced on their line, and loses embeddings and overrides. Text put into a string, an identifier or an address on a sheet of the host, and a value a person approves or reads back keep only the two joiners, so a hidden mark cannot show the groups of a telephone number in another order than the value has. **What a host gives a session, and what a renderer is told.** A host gives a session the person's languages, in order of preference, and the choice of language it kept for the person; with no list, the person's languages are the one locale the host gives (`contracts.md` section 8.2.1). Either may change while the app runs: `env.language`, `env.direction` and `env.locale` then change like any other `env` field, what reads them or calls `t` is worked out again, and the app keeps its state, the person's place in it, typed text and open dialogs. A text taken from another table than the shown language's is written with that table's formats and reads in that table's direction. A renderer is told the app's shown language and its direction, the locale the host's own figures are written in, the app's language tags when it carries more than one, the direction of each text whose language is known (a plain literal, or exactly one `t` call) and of a view's title, and the language and direction of a part that differ from those of the app around it. A fixed text is shown to a person in the language the app is shown to them in; where no person in a session reads it, such as an agent's tool descriptions and the name of the app's own principal, it is in the default language. *No change for an app without `localization`: its `env` gains `language`, which is null, and `direction`, which is `ltr`.* **The person chooses.** A host that shows an app with more than one language offers the person, in its own interface around the app, the choice among the app's own languages or to follow their own languages again. It names each language in that language itself and keeps the choice for that app on that device (`contracts.md` section 8.2.1). The app is not asked: a definition cannot open, close or set that choice. **Validation.** A validator checks the table and every use of its keys (`validation.md` section 9.2). Seven mistakes are errors, because the app would fail or show the wrong thing: a language tag that is not one (`localization.tagInvalid`, whose message gives the valid spelling), a `strings` without a table for the default language (`localization.defaultMissing`), a malformed entry (`localization.entryInvalid`), a `t` call or a reference that names a key the default language lacks (`localization.keyUnknown`, with the nearest keys), a `t` call whose values are not the blanks of its entry (`localization.valuesMismatch`), a translation that shows a blank the default entry lacks (`localization.blankUnknown`), and a reference in a fixed place to an entry that is not a plain text (`localization.fixedNeedsPlainText`). Ten more are warnings, each given once for a language or once for the document with a count and the first five keys, so an app with hundreds of missing translations gets one line for each language: `localization.untranslated`, `localization.keyNotInDefault`, `localization.keyUnused`, `localization.sameAsDefault`, `localization.scriptUnclear`, `localization.fixedTextForm`, `localization.directionUndeclared` (an app without `localization` whose texts mostly begin in a right-to-left script) and the three sizes above. A regional table may stay partial where a table of the same language gives the other texts. The checks that read a literal text, such as the length of a chart's `unit` or of a done message, Markdown in a plain text and a heading that repeats its view's title, also read each language's text where a value is exactly `=t('key')`, and name the language. The static type of `env` gains `language` (a string or null) and `direction` (a string). The explanation and the agent manifest show a reference in a fixed place as its text in the default language, and the explanation says which languages the app carries. **Conformance.** `conformance/0.2/languages/` holds rows for choosing the language, the formatting locale, direction, the tables a text is looked for in, and tags. `conformance/0.2/expressions/texts.json` holds vectors for `t`. `conformance/0.2/semantic/` holds a valid document that names a key from every kind of place and an invalid document for each of the new codes. Why: a 0.1 app was written in one language and could not say which, so a host could neither show it to a reader of another language nor know which way it reads. *0.1 definitions* need no change: a definition without `localization` behaves as before, shown left-to-right with `env.locale` as the host gives it. ## 13. One file that holds what it includes **Carried copies.** A definition may carry whole copies of the definitions and design systems it refers to in a new top-level member, `included` (`core.md` section 4), so that one file opens alone wherever it is handed. In 0.1 a definition held only references, and a file whose parts lay elsewhere did not open alone. **Where a reference is looked up.** A reference of `uses.definitions` or `uses.design` is looked up first among the carried copies of the file the referring document came in, then where the host looks otherwise. When a copy fits, it is used even where another place holds a higher version that fits, so the same file opens as the same app everywhere. A pinned `digest` is checked against the chosen copy as against any definition. The copies a file carries serve that file only: a definition found elsewhere does not see them, and a host never adds them to a registry or takes one for the definition of an instance because its `id` matches (`core.md` section 13). Nothing else changes: a part whose definition is carried is a part like any other. **Flat, and outside the digest.** A carried definition has no `included` of its own; a tool that writes the carried form lifts the copies of copies to the one list, sets it to exactly what the references reach, in a fixed order, and changes no other member. The digest of a definition leaves out `included` as it leaves out the `data` of assets (section 16), so a pin, a signature, a grant and the digests of a history hold for a definition with its copies and without them. **The format's own documents are never carried.** An `id` that begins with `org.openappdefinition.` belongs to the format: the core catalog and the default design system, which every host provides. A carried copy never has such an `id`, a reference to one is never looked up among the carried copies, and a tool that writes the carried form leaves such a document out, so a file cannot bring its own default look or hold the look to the default of the day it was written. **Sizes.** The size of a definition does not count `included`. Every host accepts 16 carried definitions and 17 carried design systems, and carried copies that together are within the sizes of one definition (section 18.1). **Validation.** Four errors and one warning are new (`validation.md` section 5): an entry that is not a definition or a design system of 0.2 with an `id` and a version (`included.kind`), two entries that are one document (`included.duplicate`), a carried definition with copies of its own (`included.nested`), a copy whose `id` begins with `org.openappdefinition.` (`included.reserved`), and a copy nothing resolves to (`included.unused`). Five warnings give the sizes above (`validation.md` section 9.1). A carried definition a part resolves to is checked as any included definition is. Why: one file is the unit an app is handed over in, and a file that names what it includes without holding it does not open for the person it was handed to. *0.1 definitions* need no change. ## 14. Reference tools These are not part of the standard, but they help with the move to 0.2. The reference implementation reads 0.2 only. `oad upgrade ` rewrites a 0.1 document to 0.2 where the change is mechanical and lists what needs a decision. `oad catalog [contract]` prints a readable summary of a catalog or one contract. `run`, `approve` and `serve-mcp` accept `--roles` and `--config alias.field=value`. A sample document can give the records a `core:records` collection starts with, under `$records`; the reference records provider then answers every read of it, with its filters, sorting, paging, counts and aggregates, and keeps what the app writes. A sample cannot script a failure or an offline host: `run` takes `--without ` to leave a capability unbound and `--offline` to start with no network connection. `explain` mentions the flow guards an action is subject to, `require` messages, the schedules of sourced entries and effective sensitivity. For an app that carries its texts in several languages (section 12 above): `run` and `approve` take `--language `, the languages of the person in front of the host in order of preference, and `look` takes the same, the languages of the person it looks as. A page in a browser says the languages of its browser, and the app is shown in the one chosen from them; an agent's session is given none and reads the app's default language. `validate` prints, for a definition with several languages, how many of the default language's keys each language has a text for. The authoring tools say the same count after every change, name the translations a new default text left behind, show only the default language's table in a whole read unless asked for others, and can look at the app as a reader of given languages. The reference shell draws the person's choice as a `Language` button beside App info in its bar (its globe alone where the bar is compact) and a `Language` row in App info, each the browser's own list of `Match my device` and the app's languages; an app drawn as a card is changed in App info. The frame that shows an app in a chat conversation says the person's languages and time zone to the tools that run the app, so the app is in the person's language there too, and it has one entry for the choice in its own line under the app. ## 15. Not in 0.2 These were considered and left out of 0.2. They remain open. - Install-time parameters beyond capability `config`. - Per-person visibility of rows in shared state. - Sources scoped to a view. - An app event for a rejected conflicting write. - Grant lifetimes tied to app data, such as "until the trip". - Timers whose duration is an expression. - `send` with a computed event name. - Listing the holders of an app role. - A cell template per table column. - More required color tokens. - Contracts that extend a contract, generic record types, and asking for provider traits (such as offline queueing). - Event payloads for agents. - Not asking for a grant that only a control's fallback would have needed. - Sharing a live instance as a part. - A start time for `every`. - Currency conversion. - Which of an app's capabilities a control's `requires` is wired to, and whose rate its calls use. - How a signature's `keyId` leads to a key. - The words of a host itself in other languages: its hints, its sheets and its messages. - Carrying catalogs in `included`, fetching a definition from the address of a `source` hint, and one picture shared by an app and its carried copies. --- # The example apps of the repository Each is a whole definition in `examples//.oad.json` of the repository, with a sample document so that it runs without live services, and opens in the playground at https://openappdefinition.org/playground/?example=. - `trip-savings`, Trip savings: Tracks money arriving in your savings accounts toward a trip goal and a date, tells you how much to put aside each week to get there, and celebrates when you pass the halfway mark and the goal. - `book-club`, Book club: A club's reading list: the book being read now, the books up next and the books finished, with who picked each. Includes Goal, which counts the books finished toward the club's goal for the year. - `goal`, Goal: A count toward a goal on one card: how far along, how many to go, and the number to reach. On its own you step the count yourself; an app that includes the card gives it the count instead. - `trip-planner`, Trip planner: Plans a trip: where and when, what it will cost, and what still needs doing. Includes Trip savings, whose goal follows the trip's total cost and whose deadline is the departure date. - `support-dashboard`, Support dashboard: Shows the team's open support tickets with their counts, a searchable, sortable list with each ticket opened beside it, and an overview by priority, refreshed every hour. - `purchase-approval`, Purchase approvals: Routes purchase requests over the approval limit to the requester's manager and then to finance, escalates to the manager's own manager after three days without an answer, and keeps a record of every decision. Requests at or under the limit are approved straight away. - `expense-agent`, Expense filing: Files receipts as expenses, checks each one against your organization's expense policy, flags anything outside it for a justification, and submits claims once you say so. Built to be used by an agent, with a small screen where you see what was filed, what waits for you, and what was paid. - `site-inspection`, Site inspection: A safety checklist for site inspections that works with no signal. Answer each item, photograph problems, attach documents, and finish; finished inspections wait on the device and are sent as soon as there is a connection. - `front-desk`, Front desk: The sign-in book at the entrance of an office: each visitor signs in in their own language and is given a badge number, and the desk sees who is in the building today. - `table-for-two`, Table for two: Ask a small restaurant, Trattoria Esempio, for a table: choose a day, a time and how many people, and the card says what was asked for. The photo at the top travels inside the app's own file. - `stackfall`, Stackfall: A falling-blocks game of stars, pairs, rods, corners and five-block pieces in a well nine cells wide. Full rows clear, a star in a cleared row clears its column above it, and the pace rises every eight rows. - `five-in-a-row`, Five in a row: The old board game against the computer: take turns placing stones where the lines cross, and the first to make an unbroken line of five, across, down or diagonally, wins. - `word-game`, Word builder: A quick word game for car rides. Each round deals the letters of a hidden word; find as many words in them as you can before the clock runs out. Play by tapping letters, typing, or saying words out loud. - `slide`, Slide: The traditional sliding tile puzzle: square tiles in a frame with one gap. Slide the tiles back into order, three by three or four by four, in as few moves as you can. - `grid-sketch`, Grid Sketch: Draw small pictures square by square: a pencil, an eraser, a fill and a colour picker, thirty-two colours, layers, undo, and saving the picture as an SVG file. - `rosette`, Rosette: A small studio for one kind of picture: move a few sliders and pick a palette, and the canvas draws a rosette, one petal repeated round a middle in rings, the way such ornaments are drawn in tiles, lace and rose windows. - `orrery`, Orrery: A small moving model of the Solar System: the eight planets go round the Sun at their true pace against each other. Play and pause, make time run faster or slower, set the planets where they are today, and press a planet to read a few facts about it. - `support-dashboard-premium`, Support plus: The support dashboard with its priority chart drawn by a commercial chart control that adds a target line, value labels and export. On a host without that control it falls back to the core chart and works the same. - `component-gallery`, Component gallery: Every built-in control of the core catalog on eight pages, each with a live example to try. It runs on a page of its own, https://openappdefinition.org/components/.