# AGENT.md — Basel bootstrap

This guide describes the whole Basel engine, not any tenant's data. It is assembled from embedded authoring guidance and tables generated from the engine itself, so it changes only when Basel itself changes.

Basel's user and its developer are the same kind of thing: an agent. This guide is what you read once, on arrival, to learn the system.

- **Engine version:** 0.4.36
- **Metadata format version:** 2

## Contents

- [Start here](#start-here)
  - [From nothing to a running app](#from-nothing-to-a-running-app)
  - [Format 2](#format-2)
  - [Converting from format 1](#converting-from-format-1)
  - [Which server a command talks to](#which-server-a-command-talks-to)
  - [Server settings](#server-settings)
- [Designing an app](#designing-an-app)
  - [Modeling principles](#modeling-principles)
  - [The rules in brief](#the-rules-in-brief)
  - [Reuse before you build](#reuse-before-you-build)
  - [Start with the business, not the files](#start-with-the-business-not-the-files)
  - [Choose the right construct](#choose-the-right-construct)
  - [Integrity and derived values](#integrity-and-derived-values)
  - [Operations and authority, designed together](#operations-and-authority-designed-together)
  - [Recommended patterns](#recommended-patterns)
  - [Pattern: one-to-many, a document, and many-to-many with facts on the link](#pattern-one-to-many-a-document-and-many-to-many-with-facts-on-the-link)
  - [Pattern: cardinality in both directions](#pattern-cardinality-in-both-directions)
  - [Pattern: contact details, a field first](#pattern-contact-details-a-field-first)
  - [Pattern: least privilege for one role](#pattern-least-privilege-for-one-role)
- [Profile boundary](#profile-boundary)
  - [What is refused, not silently degraded](#what-is-refused-not-silently-degraded)
- [Endpoints](#endpoints)
  - [Control mutations](#control-mutations)
  - [Raw proposals](#raw-proposals)
  - [Save by key](#save-by-key)
  - [Status code vocabulary](#status-code-vocabulary)
- [Authentication](#authentication)
  - [Open endpoints](#open-endpoints)
  - [The exchange](#the-exchange)
  - [Audiences and token prefixes](#audiences-and-token-prefixes)
  - [Who you are, and logging out](#who-you-are-and-logging-out)
  - [Invitations: where an account comes from](#invitations-where-an-account-comes-from)
  - [Agents and services](#agents-and-services)
  - [The first member of a new tenant](#the-first-member-of-a-new-tenant)
  - [The rest of the identity lifecycle](#the-rest-of-the-identity-lifecycle)
  - [Invitations by email](#invitations-by-email)
  - [Sign-up with an access code](#sign-up-with-an-access-code)
  - [Signing the CLI in through the browser](#signing-the-cli-in-through-the-browser)
  - [Delegation](#delegation)
  - [The control plane and elevation](#the-control-plane-and-elevation)
  - [Development mode](#development-mode)
  - [Refusals, and finding out why](#refusals-and-finding-out-why)
  - [Trace ids and the attempt log](#trace-ids-and-the-attempt-log)
  - [Secrets never echo](#secrets-never-echo)
- [Policy](#policy)
  - [The `policies/` tier](#the-policies-tier)
  - [Roles and permits](#roles-and-permits)
  - [Role grants](#role-grants)
  - [Permits](#permits)
  - [The readable fields](#the-readable-fields)
  - [Conditions: the actor root and `IN <path>`](#conditions-the-actor-root-and-in-path)
  - [Reads and explicit writes are checked](#reads-and-explicit-writes-are-checked)
  - [Existing row targets require visibility](#existing-row-targets-require-visibility)
  - [Relationship writes](#relationship-writes)
  - [What write refusals disclose](#what-write-refusals-disclose)
  - [What the read filter does to a caller](#what-the-read-filter-does-to-a-caller)
  - [Operator endpoints and the metadata tier](#operator-endpoints-and-the-metadata-tier)
  - [What a push grants](#what-a-push-grants)
  - [Assertions](#assertions)
  - [`/tenants/{key}/reflect/authority`](#tenantskeyreflectauthority)
  - [Explaining a decision](#explaining-a-decision)
  - [Who can do this](#who-can-do-this)
  - [Exports](#exports)
  - [`permitted`](#permitted)
  - [`create` on a surface document](#create-on-a-surface-document)
- [Ids: TypeID on the wire](#ids-typeid-on-the-wire)
- [Error shape](#error-shape)
  - [Every error at once](#every-error-at-once)
  - [A model that changed under the request (`409 model_changed`)](#a-model-that-changed-under-the-request-409-model_changed)
  - [Guard and invariant failures](#guard-and-invariant-failures)
  - [A write that collided with a concurrent one](#a-write-that-collided-with-a-concurrent-one)
  - [A tenant waiting for a metadata migration](#a-tenant-waiting-for-a-metadata-migration)
  - [Name clashes](#name-clashes)
  - [Rule owner](#rule-owner)
- [Metadata files at a glance](#metadata-files-at-a-glance)
  - [File rules](#file-rules)
  - [Paths](#paths)
  - [Keys and their shapes](#keys-and-their-shapes)
  - [One repository with every common file kind](#one-repository-with-every-common-file-kind)
- [Metadata grammar and type table](#metadata-grammar-and-type-table)
  - [Values on the wire](#values-on-the-wire)
  - [Email, Url and Phone](#email-url-and-phone)
  - [Text length](#text-length)
  - [Multi-select (`set` of `enum`)](#multi-select-set-of-enum)
  - [Money](#money)
  - [Display](#display)
  - [Creation defaults (`default`)](#creation-defaults-default)
  - [Expression defaults (`{"expr": ...}`)](#expression-defaults-expr-)
  - [Stamps (`stamp`)](#stamps-stamp)
  - [Filling existing rows (`backfill`)](#filling-existing-rows-backfill)
  - [Record numbering (`numbering`)](#record-numbering-numbering)
  - [Named scalar types (`types/`)](#named-scalar-types-types)
  - [Queries (`queries/`)](#queries-queries)
  - [Grouped queries](#grouped-queries)
  - [Reference selectors](#reference-selectors)
  - [Tasks and triggers](#tasks-and-triggers)
  - [Conditional uniqueness and interval exclusion (`constraints`)](#conditional-uniqueness-and-interval-exclusion-constraints)
  - [Structured types and `list` params](#structured-types-and-list-params)
  - [Tagged references (`reference_choice`)](#tagged-references-reference_choice)
  - [Declared action results (`result`)](#declared-action-results-result)
- [Subtypes and interfaces](#subtypes-and-interfaces)
  - [`$type`: the concrete kind](#type-the-concrete-kind)
  - [Querying a family](#querying-a-family)
  - [Interfaces](#interfaces)
- [User interface](#user-interface)
  - [The UI definition (`ui/app.json`)](#the-ui-definition-uiappjson)
  - [Several apps (`ui/apps/<name>/`)](#several-apps-uiappsname)
  - [Objects and pages](#objects-and-pages)
  - [Row versions and optimistic concurrency](#row-versions-and-optimistic-concurrency)
  - [Assets](#assets)
  - [Tenant components](#tenant-components)
  - [Presentation release batches](#presentation-release-batches)
  - [Independent UI releases](#independent-ui-releases)
  - [Isolated pages](#isolated-pages)
  - [Surfaces](#surfaces)
  - [Rendering, caching, and preconditions](#rendering-caching-and-preconditions)
  - [The standard UI (`?ui=standard`)](#the-standard-ui-uistandard)
  - [Limits and installed components](#limits-and-installed-components)
  - [Link-only traversal](#link-only-traversal)
  - [Related-list edit mode](#related-list-edit-mode)
  - [Related records on generated surfaces](#related-records-on-generated-surfaces)
  - [The styling contract](#the-styling-contract)
- [Object views](#object-views)
  - [A worked example](#a-worked-example)
  - [Record layout: sections, `hidden` and `remaining`](#record-layout-sections-hidden-and-remaining)
  - [Field widgets](#field-widgets)
  - [Wide fields and `columns: 1`](#wide-fields-and-columns-1)
  - [Conditional sections: `visible_when`](#conditional-sections-visible_when)
  - [Component sections](#component-sections)
  - [The create form](#the-create-form)
  - [The list](#the-list)
  - [Search](#search)
  - [Actions](#actions)
  - [Related lists](#related-lists)
  - [Subtypes inherit key by key](#subtypes-inherit-key-by-key)
  - [App-scoped views](#app-scoped-views)
  - [Which declaration wins](#which-declaration-wins)
  - [Why does this page look like this?](#why-does-this-page-look-like-this)
  - [Custom screens are app pages](#custom-screens-are-app-pages)
- [Page templates](#page-templates)
  - [A worked example](#a-worked-example-1)
  - [Lists and forms](#lists-and-forms)
  - [Parts](#parts)
  - [Where parts go](#where-parts-go)
  - [Empty containers are dropped](#empty-containers-are-dropped)
  - [Which template draws a record](#which-template-draws-a-record)
  - [What a template can't do](#what-a-template-cant-do)
  - [Seeing which template drew a page](#seeing-which-template-drew-a-page)
- [Relationships](#relationships)
  - [Declaring a relationship](#declaring-a-relationship)
  - [Links as rows](#links-as-rows)
  - [Reflection](#reflection-3)
  - [`cardinality`](#cardinality)
  - [`on_delete` and `reparent`](#on_delete-and-reparent)
  - [`document_lock`](#document_lock)
  - [`revision`](#revision)
  - [`shape`](#shape)
- [Nested create and update](#nested-create-and-update)
  - [Vocabulary](#vocabulary)
  - [On create: plain values](#on-create-plain-values)
  - [On update: an explicit envelope](#on-update-an-explicit-envelope)
  - [Refusals](#refusals)
  - [Limits](#limits)
  - [Reflection](#reflection-4)
  - [The honest boundary](#the-honest-boundary)
- [Guards](#guards)
  - [Guard fields](#guard-fields)
  - [The clock in a guard](#the-clock-in-a-guard)
  - [Binding by verb](#binding-by-verb)
  - [What a create guard sees](#what-a-create-guard-sees)
  - [Enforcement](#enforcement)
  - [Reflecting guards](#reflecting-guards)
  - [`locks`](#locks)
  - [Which rule construct](#which-rule-construct)
  - [Rule-selection advisories](#rule-selection-advisories)
- [Aggregates, rollups, and invariants](#aggregates-rollups-and-invariants)
  - [Rollups](#rollups)
  - [Recomputing rollups](#recomputing-rollups)
  - [Invariants](#invariants)
  - [Link aggregates](#link-aggregates)
  - [Read the live shape, don't assume it](#read-the-live-shape-dont-assume-it)
  - [Refused, flagged, or instrumented](#refused-flagged-or-instrumented)
- [Formulas](#formulas)
  - [Nullability and writes](#nullability-and-writes)
  - [Read parity](#read-parity)
  - [Formulas in invariants](#formulas-in-invariants)
  - [Correlated aggregates](#correlated-aggregates)
  - [History functions in reads](#history-functions-in-reads)
  - [Formula limits](#formula-limits)
- [Functions](#functions)
  - [Validators](#validators)
  - [Pure functions](#pure-functions)
  - [Functions on actions](#functions-on-actions)
  - [The JSON mapping](#the-json-mapping)
  - [Budgets](#budgets)
  - [Supported ABI](#supported-abi)
  - [Reserved](#reserved)
- [Actions](#actions-1)
  - [Discovering what a tenant declares](#discovering-what-a-tenant-declares)
  - [Effect vocabulary](#effect-vocabulary)
  - [What an action's guards see](#what-an-actions-guards-see)
  - [Sibling transitions](#sibling-transitions)
  - [Effect budget](#effect-budget)
  - [Read bindings (`bindings`)](#read-bindings-bindings)
  - [The transaction instant and Duration arithmetic](#the-transaction-instant-and-duration-arithmetic)
  - [One audit event per invocation](#one-audit-event-per-invocation)
  - [Invoking an action](#invoking-an-action)
  - [Optional and default params](#optional-and-default-params)
  - [Refusals](#refusals-2)
  - [Reading history](#reading-history)
- [BQL](#bql)
- [Using /reflect](#using-reflect)
  - [Scoping by path](#scoping-by-path)
  - [`_links`/`_href` traversal](#_links_href-traversal)
  - [Full names](#full-names)
  - [`kind` on every node](#kind-on-every-node)
  - [An object's fields: one catalog](#an-objects-fields-one-catalog)
  - [The authors' descriptions](#the-authors-descriptions)
  - [No stub scopes remain](#no-stub-scopes-remain)
  - [One source, one honest caveat](#one-source-one-honest-caveat)
- [Apps from packages](#apps-from-packages)
  - [Themes](#themes)
  - [An app's own components](#an-apps-own-components)
  - [Installing an app](#installing-an-app)
  - [Sample records](#sample-records)
  - [Namespaces, app routes, and `?app=`](#namespaces-app-routes-and-app)
  - [Elevated reads and approvals](#elevated-reads-and-approvals)
  - [Adding to a package's object (`additions/`)](#adding-to-a-packages-object-additions)
  - [What a package's code can and cannot see](#what-a-packages-code-can-and-cannot-see)
- [Worked metadata examples](#worked-metadata-examples)
  - [Lifecycle with a guarded transition and an effect](#lifecycle-with-a-guarded-transition-and-an-effect)
  - [Relationship rollups and decimal division](#relationship-rollups-and-decimal-division)
  - [Member edits only while the parent is open](#member-edits-only-while-the-parent-is-open)
  - [Creating a parent with its members in one request, as a non-admin](#creating-a-parent-with-its-members-in-one-request-as-a-non-admin)
  - [Counting a many-to-many relationship by a far-record field](#counting-a-many-to-many-relationship-by-a-far-record-field)
  - [API and authoring details](#api-and-authoring-details)
- [Tenants](#tenants)

## Start here

This guide is long because it is the whole reference. Use the contents above to jump, or ask for one section at a time: `GET /?section=<slug>` with the slug the contents link to (`guards`, `metadata-files-at-a-glance`). The short version, with this server's origin and version filled in, is `GET /start.md` (`basel agent-md --start`): install the CLI, sign in, add the MCP connection, then build, reading the Basel Catalog before writing any object by hand. If you are building an app, read these in order:

1. This section: the command-line path from nothing to a running app, and the rules of metadata format 2.
2. "Designing an app": the judgment before the files. Its "Modeling principles", "Reuse before you build" (the Basel Catalog comes before any object written by hand) and "Choose the right construct" before you write an object; the pattern that matches your problem before you write a relationship.
3. "Metadata files at a glance": every file, key and shape, with one repository that validates.
4. "Worked metadata examples": complete examples of the constructs builders most often get wrong.
5. "Object views" when you arrange record pages, forms and lists.
6. The construct sections ("Relationships", "Guards", "Policy" and so on) when you need the full rules.

If you are writing a client that calls the HTTP API, start with "Endpoints" and "Authentication".

### From nothing to a running app

1. **Sign in.** `basel auth login` prints a link and a code and waits while a person approves in their browser. An AI agent runs `basel auth login --no-browser --server <url>` and shows the person the link and the code. The CLI stores its own credential and offers to become Git's credential helper for the server (see "Signing the CLI in through the browser").
2. **Find or create a tenant.** `basel tenants list` shows the tenants your account created; `basel tenants create <key>` makes one you administer, once your email is verified.
3. **Clone the tenant's metadata repository.** `git clone <server>/git/<tenant>`. The remote is `/git/<tenant>`, not `/tenants/<tenant>/git`.
4. **Write the metadata.** Read the Basel Catalog first and install the data model that fits ("Reuse before you build"); then design before you write ("Designing an app"); then start from "Metadata files at a glance".
5. **Check it.** `basel validate` (in the repository) is the quick offline check: it compiles the model, policy and UI without contacting the server, and its last line is `OK` or `FAILED: <n> errors`. It does not run every check a push runs. Before you deploy, run `basel plan --worktree`: the server runs the push's own checks on what `basel deploy` would push (your files, uncommitted changes included, as one commit on the remote's `main`), including existing rows that break a new rule, and changes nothing, your branch included. `basel plan` with no flag plans a commit you made instead, which must be one commit on top of the remote's `main`.
6. **Deploy.** `basel deploy --reason "<why>"` pushes the metadata to the clone's `origin` remote, uploads UI artifacts and activates them. A change with a flagged operation on stored data (a field or object that holds data archived, a rule added over existing rows, a choice value removed, a currency opened) is not applied: deploy prints the plan, applies nothing and stops, naming its `plan_hash`. Show the person the plan; if they approve it, `basel deploy --reason "<why>" --approve <plan_hash>` applies that plan and no other, and is refused, applying nothing, if the change or the tenant's `main` has moved since. Flagged `authority:` operations alone (an object, its operations, a role, a derived value or an action that is new or widened, which the server admits only for a pusher holding that authority) deploy acknowledges itself and lists.
7. **Look at what is running.** `basel reflect <tenant>` shows what the tenant's metadata declares; `basel query <tenant> "SELECT id FROM <Object>"` reads rows.

### Format 2

A tenant's metadata is written in **metadata format 2**: one object per file, recognized by the root manifest, `basel.json` (`{"format": 2, "name": "<app>"}`) or `basel.yaml` (`format: 2`). Format 2 is one data model with two spellings, strict JSON (`.json`) and strict YAML (`.yaml` or `.yml`), chosen file by file. The guide's examples are JSON, and Basel's own tests compile each complete one; everything they show reads the same in YAML.

- **Strict JSON, with comments.** No trailing commas, byte-order mark or duplicate member names (`invalid_json`, `duplicate_key`). `// …` and `/* … */` comments are allowed anywhere whitespace is; they are for the file's next reader and never reach the server. A property the grammar does not know is refused `unknown_property`, and every refusal names `file#/json/pointer`, such as `objects/invoice.json#/fields/total/rollup`.
- **Or strict YAML.** One mapping per file, `#` comments, block text (`|`) for long prose, and no quotes needed around keys or expressions. Refused (`invalid_yaml`, with line and column): anchors, aliases, tags, merge keys, several documents, and number-like text JSON does not write (`0x1F`, `+5`, `007`, `.5`). `yes`, `on` and dates are text. Quote a value to mean text: `default: "12"` is the decimal-string literal. A refusal names the YAML file with the same pointer, `objects/invoice.yaml#/fields/total/rollup`.
- **One spelling per file.** The same declaration in both spellings (`objects/invoice.json` beside `objects/invoice.yaml`) is `duplicate_spelling`; both manifests, `duplicate_manifest`. A tree may mix spellings across files. `basel.lock` and package releases are generated JSON.
- **Order is an array; a catalog is an object.** Anything whose order is observable is an array (guards, locks, effects, bindings, lifecycle states, enum values, sections, slot children, stylesheets). Anything keyed by name is an object (fields, actions, invariants, permits, roles).
- **Values are typed literals.** `int`, `decimal` and Money amounts are decimal strings (`"12"`, `"0.25"`, `"12.50"`); an open-currency amount is `{"amount": "12.50", "currency": "USD"}`; `bool` is `true`/`false`; a `set` is an array of strings; every other scalar is a string. A literal that does not fit its type is `invalid_literal`. Structural settings (`format`, page sizes, heights) are JSON numbers.
- **An evaluated value says so.** A value slot (a default, an effect value, a stamp) holds a literal or `{"expr": "<expression>"}`; a plain string is never evaluated. `{"literal": {...}}` escapes an object literal whose only key is `expr`. A slot that only ever holds an expression (`assert`, `where`, `formula`, `rollup`, `unless`, `when`, `editable_when`, `visible_when`) holds the expression text directly.
- **`description`** (a string) is accepted on every declaration and member worth explaining: the manifest and its dependencies, objects, fields, lifecycles and states, actions, params, results, guards, locks, invariants, validators, constraints, bindings, each effect, relationships and their ends, roles, permits, assertions, queries and their params, tasks and their input, triggers, types and their fields, arms and members, functions, and in UI files object views, field settings, sections, lists, related lists, pages, nodes and presentations. It records intent; it is never behavior, and changing one moves no checksum and plans no schema change. (An object view's own top-level `description` is also the description users see for that view.)

The same object in either spelling:

```yaml basel-repository
# file: basel.yaml
format: 2
name: billing
default_currency: USD
# file: objects/invoice.yaml
# Notes like this one stay in the file.
name: Invoice
description: |
  A bill sent to one customer.
  Posted invoices are never edited.
operations: [create, update]
fields:
  number: {type: text}
  quantity: {type: int, default: "1"}
  unit_price: {type: Money}
  total:
    type: Money
    formula: row.unit_price * row.quantity
```

```json basel-repository
# file: basel.json
{"format": 2, "name": "billing", "default_currency": "USD"}
# file: objects/invoice.json
{
  // Notes like this one stay in the file.
  "name": "Invoice",
  "description": "A bill sent to one customer.\nPosted invoices are never edited.\n",
  "operations": ["create", "update"],
  "fields": {
    "number": {"type": "text"},
    "quantity": {"type": "int", "default": "1"},
    "unit_price": {"type": "Money"},
    "total": {"type": "Money", "formula": "row.unit_price * row.quantity"}
  }
}
```

**Leave hints for the next reader.** Whoever changes this app next, person or agent, may see it only through the API. Put the why of a declaration in its `description`: what it is for, what must stay true, what not to change casually. Reflection serves it beside the declaration (`/reflect/objects/<Object>`, its fields, actions, params, guards and effects, `/reflect/queries`, `/reflect/authority`, `/reflect/types`, and an object view's or page's `descriptions`). A `//` or `/* */` comment is for whoever reads the file: it is dropped when the file is read and never reaches the server.

#### Expression roots

Every name in an authored expression starts from a root. A bare name is refused `unrooted_name`, and a root the slot does not offer is `unknown_root`.

| Root | Names | Where |
|---|---|---|
| `row.` | the record; inside an aggregate's or quantifier's `WHERE`, the contributing record | every record expression |
| `before.` | the record's state before the write | guards, locks, update permits, document locks |
| `outer.` | the enclosing record inside a correlated aggregate's `WHERE` | correlated aggregates |
| `args.` | the action's or query's parameters | actions, queries |
| `bindings.` | a record the action's `bindings` resolved | action guards and effects |
| `created.` | a record created earlier in the same effect list | effects (`via`, values) |
| `actor` | the effective principal | permits; action effect values (bare `actor` only) |
| `acting` | the actual caller | defaults and stamps only |
| `value` | the value a named type checks | a named type's `check` |

Three places stay bare because they name declarations, not values: the object of a correlated aggregate or `LOOKUP` (`COUNT(Line WHERE row.invoice = outer.id)`), the lifecycle and state of a history call (`entered_at(status, posted)`), and the projection after an aggregate's `->` or `=>` (`SUM(row.lines -> amount)`). Inside an aggregate's `WHERE`, `row.` is the related record being counted, not the record that declares the aggregate.

**Authored metadata versus runtime queries.** Roots belong to metadata files. A BQL query sent at runtime (`POST /tenants/{key}/query`, `basel query`) is not metadata and keeps its own syntax: `SELECT title FROM WorkItem WHERE status = 'open'`, with bare field names (see "BQL"). The same is true of a request body: it is plain JSON data, with amounts as strings and no `{"expr"}`.

**What reflection and diagnostics show.** Reflection (`/reflect`) shows every expression as format 2 writes it, roots included (`row.amount > 0`, `args.reason != ''`, `before.state`, `acting`), and names every file by the path it was written at (`objects/invoice.json`, or `objects/invoice.yaml` for a YAML file). An object's reflection lists its fields as one catalog, `fields`, each entry naming its `supplier` (`stored`, `rollup`, `formula` or `engine`); it also keeps the by-kind lists `attributes`, `formulas` and `rollups`.

**Where a refusal points.** Refusals name the authored source as `file#/pointer` (`objects/invoice.json#/fields/total/rollup`, `policies/invoice.json#/permits/clerk_update/write`), including those raised while resolving the model rather than while reading a file; such a refusal's detail ends with the compiler's internal element, `(internal element: Invoice.rollups.total.value)`. A refusal points at the declaration or member that holds the problem, not always at the exact key inside it. Behavior is the same either way.

### Converting from format 1

Format 1 (the old YAML grammar: a `basel.yaml` with `metadata_format: 1`) is no longer an authoring format. It is not format 2's YAML spelling. `basel convert` turns a format-1 repository into format 2:

- `basel convert [path]` (or `--check`) reports what it would write and writes nothing;
- `basel convert --in-place` writes the JSON files beside the sources and deletes the converted YAML files;
- `basel convert --out <dir>` writes the whole converted tree into a new or empty directory;
- `--yaml` (or `--to yaml`) with any of these writes format 2 in YAML instead of JSON.

`basel convert --to yaml` or `--to json` on a format-2 repository re-spells it, with the same `--check`, `--in-place` and `--out`. It leaves `vendor/` as installed, and it checks that the result compiles to the same app before writing. Comments do not carry across a re-spelling.

The source must compile first. The converter then proves its own output: the converted tree must compile to the same model, policy, UI and apps, or nothing is written and the first difference is printed (`conversion_mismatch`). Expressions gain their roots, `attributes`/`formulas`/`rollups` join one `fields` catalog, lifecycle transitions become actions, role row grants become permits, and inline UI query plans move to `queries/`.

A few format-1 constructs have no exact format-2 spelling and are refused with what to use instead, naming the file: an object view's `surfaces` overlays other than a plain widget swap, hide or list query, and a custom screen, which becomes an app page (see "Object views"). Converting a tenant is one ordinary commit that replaces the format-1 files. Basel does not re-read the commits before it as source, so a tenant cannot roll back past its conversion.

### Which server a command talks to

Every `basel` command that calls the server uses, in this order: `--server`, then `$BASEL_SERVER`, then the server `basel auth login` last signed in to through the browser, then `http://127.0.0.1:4600`. So after one browser sign-in you need neither `--server` nor `$BASEL_SERVER`. The bearer follows the same order: `--token`, then `$BASEL_TOKEN`, then the credential stored for that server. An empty `$BASEL_SERVER` or `$BASEL_TOKEN` counts as unset. `basel --verbose <command>` prints which server and which kind of token it chose and where each came from, showing only the token's prefix (`bss_…`).

- **Uses that rule:** `agent-md`, `reflect`, `query`, `create`, `update`, `delete`, `metadata`, `tenants`, `token`, every `auth` subcommand, and `deploy`'s own API calls.
- **Needs `--server` (or `$BASEL_SERVER`) the first time:** `basel auth login` and `basel auth accept-invitation` before anything has been stored, since nothing names the server yet.
- **Uses the Git remote instead:** `basel plan`, and `basel deploy`'s push, go to the clone's remote (`--remote`, default `origin`).
- **Offline:** `validate`, `build`, `sync` and `upgrade` never call the server (`sync` and `upgrade` fetch packages from their Git sources).
- **Its own configuration:** `basel work` takes `--config`, and refuses `--server` and `--token`.

The password sign-in, `basel auth login --login <email>`, stores nothing, so it does not set the default server either.

### Server settings

An operator configures `basel-server` with environment variables only; there is no settings file. `basel-server --print-settings` prints every setting the server would run with: its value (secrets redacted, a connection string without its password), where the value came from, its kind, and when a change takes effect. It then exits, so it also checks a configuration before deploying it.

- A boolean is exactly `1` or `0`; empty or unset is its default. Any other spelling (`true`, `yes`) refuses startup, and the message says the value used to mean off and what to write.
- A whole number is ASCII digits within the setting's bounds, with no sign or surrounding spaces.
- Every malformed value is reported at once, each naming its variable. A variable that is one or two edits away from a real setting's name is warned about as a likely misspelling.
- At startup the server logs each setting it took from the environment, redacted.

`BASEL_TASKS=1` turns on tasks v1: metadata may then declare `tasks/` and `triggers/` (see "Tasks and triggers"). It is off by default, and a push declaring either is refused `tasks_disabled` until an operator sets it; `/reflect` reports it as `tasks.enabled`.

## Designing an app

The sections before this one say how to reach a running tenant; the sections after it give every construct's exact rules. This one is about judgment: how to decide what the model is before any file exists, which construct expresses each decision, and the shapes that come up in every app. An agent building an app should read "Modeling principles", "Reuse before you build" and "Choose the right construct" before writing an object, and the pattern that matches its problem before writing a relationship. Each heading here is one section at `GET /?section=<slug>` (`modeling-principles`, `reuse-before-you-build`, `choose-the-right-construct`, `integrity-and-derived-values`, `operations-and-authority-designed-together`, and the patterns), so a builder can fetch one at a time.

### Modeling principles

1. **Use established data-modeling practice.** Give each concept a clear identity and meaning. Separate entities, relationships and attributes. Avoid duplicated facts and unclear ownership. State cardinality and integrity rules explicitly. Normalize where it prevents update anomalies, and make exceptions only for a real workflow or performance need. Test the model against real examples and counterexamples, not only a diagram.
2. **Design for maintenance and change.** Prefer Basel's declarations to code whenever they can express a rule or operation clearly. Declarations are validated, visible through reflection and enforced by the platform. Write code only when the logic truly needs it.
3. **Choose simplicity.** Build the smallest model that captures the business truth and supports the workflow. Add entities, abstraction and special cases only when they earn their cost.
4. **Conserve entities.** An entity is something with its own identity, state or lifecycle. A fact that belongs *between* two entities goes on a relationship, not as another field on one of them.
5. **Use subtypes sparingly.** Use one only when the kinds share an identity and need their own structure or behavior. A plain entity, a relationship or an interface is usually enough.
6. **Get the core model right, then go broad.** Settle the central entities, relationships, identity and integrity rules first; mistakes there are expensive to carry. Then give each main workflow a minimal working path before you deepen any one of them. Record a requirement that is not essential yet, and move on.
7. **Leave hints for the next reader.** Whoever changes the app next, person or agent, may see it only through the API. Put the *why* of a declaration in its `description`: what it is for, what must stay true, what not to change casually. Every object, field, action, param, guard, permit, query, section and page takes one, and reflection serves it beside the declaration. A `//` comment is for whoever reads the file and never reaches the server.

Removing a field after it has been pushed is refused, and so is making a required field nullable. Try uncertain modeling in a throwaway tenant first.

### The rules in brief

The same judgment as a checklist, one line per rule. Basel's in-app assistant works from this list verbatim; apply it whenever you add or change the model, rules, policies or screens, and read the sections below for the reasoning and the shapes.

- One object per real thing, found and acted on independently. A short fixed list of values with no facts of its own is an enum; a value with its own facts (a region with a capital) is an object. Never numbered repeats (contact1_name): link records instead.
- Connect things with a relationship file, not a ref field: only a relationship gives a related list, a picker, a traversal in queries (account.name), rollups and link policy. A ref field is a plain pointer with no list behind it (a Principal, a lookup).
- Facts about how two things relate (a person's role at a company, a partnership and when it began) go on the relationship as properties, never on either object. Name relationships and traversals for the role: EmployeeOf with employer/employees, PartnerOf, AllyOf.
- Shapes: one-to-many is cardinality {max: 1} on the child end; many-to-many is the default; unique: true stops duplicate links; min: 1 requires participation. A parent whose members form one document (an invoice and its lines): nested create/update on the parent end, on_delete: delete_members, and document_lock when the parent itself freezes.
- Cardinality both ways: for every ref and relationship end, say how many in each direction and whether either side may be empty, then declare it. A ref limits one direction only: a nullable ref that must be one-to-one (a Person's principal) takes unique: true, which still allows any number of empty values. Anything that picks "the" matching record (the first row, LIMIT 1, a LOOKUP) rests on a declared unique rule or a max: 1 end, never on how the data looks today.
- Contact details on the person's own objects start as a plain field: email: {type: Email, nullable: true} on Contact is one line and is the default. Use member records (EmailAddress owned by Contact) only when a record really has several, each with facts of its own (a label, a purpose). Decide before data lands: no supported change yet turns a populated stored field into a collection (the extraction path is planned, not built), and a field holding data cannot be dropped. For a full CRM model (contacts and organisations as one Party family, emails, phones, addresses and profiles with primaries, affiliations), offer to install the crm-core data model from the Catalog instead of rebuilding it.
- One of many as "the primary" (a contact's primary email, an account's primary contact, a default address) is one field on the parent: primary_email: {primary: {of: emails, project: address}}. It generates primary_email_ref (nullable pointer), primary_email (formula reading address through it), the guard primary_email_is_own (the pointer names one of this record's own emails) and the action set_primary_email with one parameter, member; call and grant them by those names (action.set_primary_email.invoke).
- The primary's requirements: without project the field itself is the pointer. The far end of emails needs cardinality {max: 1}; declare it in the object's own file, not an addition. A related list over that end shows the primary first and offers Make primary. Never a bool flag on the child. A fallback for a record with one email and no choice: any_email: {type: Email, rollup: "MIN(row.emails -> address)", nullable: true} and a formula CASE WHEN row.primary_email_ref IS NOT NULL THEN row.primary_email_ref.address ELSE row.any_email END.
- Owned members (contact points, lines) go with their parent: on_delete: delete_members on the parent's end and cardinality {min: 1, max: 1} on the member's. Removing a contact or its emails is a delete, not an archived flag. The current primary cannot be deleted (delete_blocked_by_reference): make another primary first; deleting the parent takes it with the rest.
- Subtypes (extends) very rarely: only kinds that are truly the same thing, share nearly all fields and must appear in one list. Something playing several roles is one object with several relationships.
- Every object gets a record_label in its view so references, related lists and search read as words, never as an id chip. An object with no natural name (a booking, a check-in, a line) gets a text formula field that combines its key facts, and that field is the record_label.
- Derive, don't copy. Read through a link (account.name) instead of duplicating. A count or total that rules must trust is a rollup (stored, exact, over a relationship whose far end is max: 1); a value that depends on today or on other read-time facts is a formula (computed on read, always nullable); a report or a list is a query.
- A number's meaning goes on the field, not the screen: a year, a code or an outside id is an int with display: {grouping: false} (numbering and unique give it for free), a ratio is a decimal with display: {style: percent}. A view or metric may only make a value more compact (fewer decimals, currency, units: auto).
- Rules, in this order: a fact true of every record is an invariant (own fields and rollups only, no clock, no before.); a condition on one write, or one comparing to the prior state, is a guard (before. in update guards); fields that freeze after a point are locks; two writers racing on uniqueness or a time range is a constraint (unique or exclude); who may do it is a permit, never a guard. Guards cannot read formulas: use a rollup. A create guard that reads through a relationship sees NULL for a parent created in the same request: write row.deal.stage IS NULL OR row.deal.stage = 'open'.
- Statuses with rules about how they change are lifecycles; every change of state is an action with transition, guards and effects; what the server should decide (who, when, a number) is a stamp, default, numbering or an effect (closed_on: {expr: "TODAY()"}), never a value the client sends. Business operations are named actions (submit, approve, cancel), with params when they need input.
- Policy is explicit: roles carry readable fields and tenant rights; every row grant is a permit with one action; nothing is allowed until declared, operations included (an object without delete in operations cannot be deleted by anyone). Seeing, referencing and changing are three permissions. A nested write (a record plus its link) needs proposal.submit, link on the near end and reference on the far end.
- Screens: start from the generated pages, arranged by the object view (sections, create, list, related lists, compact key fields, icon); a fixed filter lives in a query bound to the list; a chart, metric or picker is a component section; a different screen is an app page placed by record_pages/list_pages/edit_pages/create_pages or a template in defaults; a page of its own (a dashboard) is ui/pages with a route; more apps over the same model are ui/apps/<name>/. Views decide what appears, the presentation decides how it looks; visible_when is presentation, not authority.
- Basel refuses renames and will not drop fields or values that hold data, so get the shape right first. Put a description on what you add (object, field, action, permit, query, section): other agents read it from /reflect; # comments stay in the file.

Before you place a component, read what it accepts rather than learning it from refusals: `basel reflect <tenant> ui/components/<id>@<major>` or the MCP tool `basel_components` answers its config, bindings, slots, modes and frame, for Basel's standard components and the tenant's own or installed ones alike.

### Reuse before you build

Before you write any object by hand, read the Basel Catalog, every time: `GET /catalog.json` lists every published package with its kind, summary and exported objects, roles and components. From the CLI, `basel catalog` lists it and `basel catalog <words>` searches it; the MCP tool is `basel_search_catalog`; both rank a keyword search the same way and mark a listing the tenant's names would refuse. Install with `basel packages install <name>` or `basel_install_package` (the "Apps from packages" section has the doors they use). A package may already bring the objects, roles, components or theme you need.

How to search it, and when to install:

- Catalog first: before you build a new object, an app area, a list component or a look by hand, call basel_search_catalog for it, every time, even if you installed something earlier in this conversation.
- Search by the kind of thing (people, customers, companies, products, orders, cases), never by the business: "pet store" finds nothing, "customers" finds the CRM data model, and a pet store's customers are its contacts.
- A package that models the generic part fits even when the business is different: install it and build the domain objects on top, linked to its objects (an Order's customer is a crm-core Contact; a Pet is new), rather than recreating a contact or an organisation record under another name.
- When a listing fits and its plan installs on this tenant, recommend installing it rather than building, and say what it brings with it (an app may also install a grid or a theme).
- If it brings more than was asked for, do not decide for the person: say in two or three sentences what it would add and what building it by hand would leave out (the listing's pages, roles, boards and links already work together), then ask which they want, and build or install nothing until they answer.
- The exception is a request to set up a whole app in a new or empty tenant: there the fitting data model is the reasonable choice, so say in one sentence that you are installing it and proceed (the plan still waits for their approval).
- Build by hand only when nothing fits, the plan is refused, or the person chooses it; say which.

For people and organisations, install `@rosetta/crm-core` rather than rebuilding it. It is the worked example of modeling on relationships: contacts and organisations as one `Party` family, emails, phones, postal addresses and online profiles as records each party owns, a `primary` email and phone, and dated affiliations between contacts and accounts. A gym's members, a clinic's patients and a shop's customers are all `crm:Contact`s; build the domain objects (a class, an appointment, an order) on top and link them to the package's objects by full name (`"object": "crm:Contact"`). Fields on a package's family cannot be removed or retyped once pushed, so read its listing before you add to it. For your own objects, start simpler: see "Pattern: contact details, a field first".

### Start with the business, not the files

Write these down before any files:

1. **Records:** the records people recognize, how each is identified, and which ones exist on their own.
2. **Relationships:** a plain reference, a connection with its own facts, or a parent with members that form one document.
3. **States and operations:** the valid states, and the named operations that move a record between them.
4. **Integrity:** the facts that must stay true after every transaction, including when two people write at once.
5. **People:** who may see, reference, create, change and invoke what.
6. **Screens:** the lists, pickers and screens the real workflows need.

### Choose the right construct

| Need | Basel construct | When |
|---|---|---|
| A durable business record | `objects/<name>.json` | Users find, audit or act on it independently. |
| A plain pointer to one record | a `ref` field | The link has no identity, facts, list or picker of its own (a `Principal`, a lookup). |
| A connection between records | `relationships/<name>.json` | Anything that needs a related list, a picker, a traversal in queries, a rollup, or link/unlink authority. Facts about the connection go on it as `properties`. |
| A parent with editable members | a relationship with member `"cardinality": {"max": 1}`; consider `min: 1`, the parent end's `nested`, `on_delete`, `document_lock`, `revision` | The parent and members form one document, created or changed together. |
| One member of a to-many named as "the primary" | a `primary` field on the parent: `{"primary": {"of": "<end>", "project": "<field>"}}` | The member is chosen by a person (primary email, default address, primary contact). One line; see "Pattern: contact details, a field first". |
| A short fixed list of values | an `enum` field, or a `set` of `enum` for several at once | The values have no facts of their own. A value with facts (a region with a capital) is an object. |
| Kinds that share an identity | `extends`, optionally `abstract` | One family, one table; `$type` names the concrete kind. Rare. |
| A shared contract across unrelated objects | an interface with explicit `implements` | Objects promise the same fields and actions without sharing identity. |
| A value with reusable validation | a named scalar type in `types/` (`{"name", "base", "check"}`, the check reads `value`) | The same check applies wherever the value is used. |
| A state-changing business operation | an entry in the object's `actions` map, with `transition` when it moves a lifecycle | A named, typed operation with guards and atomic effects. Leave out `transition` when no state changes. |
| A reusable read or picker | a query in `queries/` (`exposure` public or internal) | A worklist, a filtered list, a picker whose eligible choices differ from what a person can read. |
| A different screen | a page in `ui/pages/`, placed by `record_pages`/`list_pages`/`edit_pages`/`create_pages`, or a template under `defaults` | The generated page, arranged by the object view, cannot express it. |

Start with the generated behavior. Move to a relationship as soon as the connection needs a list, a picker, a count or facts of its own: a `ref` gives none of those. Guards can't read formulas, so counting needs a stored rollup, and a rollup needs a declared relationship whose far end is `max: 1` (or the link form, `COUNT(row.<end>=>)`, for many-to-many).

### Integrity and derived values

| Question | Put it here |
|---|---|
| Is the record valid, however it was changed? | `invariants` (own fields and rollups only; checked against existing data when added) |
| May this create, update or delete go ahead? | `guards` (`before.` compares with the prior state; update guards only) |
| Should some fields freeze after a condition? | `locks` |
| May members change only while the parent is open? | a guard on the member that reads the parent (`row.matter.status = 'open'`); the parent end's `document_lock` only if the parent's own fields should freeze too (below) |
| Could two writers break uniqueness or double-book a time range? | `constraints` (`unique` or `exclude`) |
| An aggregate that a rule must trust? | a field with a `rollup` (stored, kept exact in each write) |
| Depends on today's date or another read-time value? | a field with a `formula` (computed on read, always nullable) |
| Depends on who is acting? | a policy permit, not a guard |
| Needs code? | a validator (to admit a write) or a function on an action (to propose one) |

Details that trip people up:

- **Clocks.** Never put a date-dependent condition in an invariant: it could become false with no write. Formulas can't read the audit `created_at`, so a record whose start time matters needs its own timestamp field, filled by the server: a `stamp` (`{"on": "create", "value": {"expr": "NOW()"}}`), a `"default": {"expr": "NOW()"}`, or an action's effect.
- **NULL refuses.** A guard or invariant permits a write only on `true`: `false` and `NULL` both refuse. A rule over a nullable field admits the empty case explicitly: `row.amount IS NULL OR row.amount >= 0`.
- **Guards and formulas.** A guard never sees a formula; use a rollup.
- **Guards on new records.** A create guard that reads through a relationship sees an empty value when the related record is created in the same request. Write it to accept that (`row.ticket.stage IS NULL OR …`), and let cardinality enforce the link.
- **Counting across a many-to-many relationship.** A formula or rollup can't count or sum the far records of a relationship whose far end has no `cardinality: {max: 1}` when it filters on a far-record field: `COUNT(row.people WHERE row.active = true)` is refused. It can count the links (`COUNT(row.people=>)`) and filter on the relationship's own properties (`COUNT(row.people=> WHERE row.role = 'lead')`). To filter on the far record, make that end `max: 1`, keep the count in a query, or model the link as an object with two `ref` fields and use a correlated aggregate (`COUNT(ItemTag WHERE row.item = outer.id AND row.tag.priority = 'hot')`).

**`document_lock` freezes the parent.** `document_lock` on a parent's end stops its members changing while `editable_when` is false. It also stops the parent's own fields changing, and the parent being deleted, while `editable_when` is false. In `editable_when`, `row.` is the parent: as it was *before* the write when the parent's own fields change or it is deleted, and as it is *after* the write when a member or a link changes. Basel adds two guards named `edits_<relationship>` to the parent: an update passes only if `editable_when` held before the write or none of the parent's fields change; a delete passes only while it holds.

```json
"from": {
  "object": "Matter",
  "name": "entries",
  "document_lock": {
    "editable_when": "row.status = 'open'",
    "message": "A closed matter's entries can't change"
  }
}
```

So with `"editable_when": "row.status = 'open'"` on a matter, once the matter is closed you can't correct its title, a transition out of `closed` that sets a field (an `archive` that stamps `archived_at`) is refused, and a closed matter can't be deleted. Closing still works, even with an effect that sets a field, because the matter was open before the write. A transition that sets no field also still works.

Use `document_lock` only when the parent really is finished once `editable_when` turns false, as a posted invoice is. If only a field or two must stay editable (notes), keep the lock and list them in `"editable_fields": ["notes"]`. To allow member changes only while the parent is open, and still let the parent change after it closes, leave `document_lock` off and guard the member:

```json
// objects/time_entry.json
"guards": [
  {
    "name": "matter_open",
    "on": ["create", "update", "delete"],
    "assert": "row.matter.status IS NULL OR row.matter.status = 'open'",
    "message": "Time entries change only while the matter is open"
  }
]
```

`matter` is the member's end of the relationship (`"cardinality": {"max": 1}`), so the guard reads the parent through it. `IS NULL` lets a matter and its entries be created in one request. This guard doesn't cover moving an existing entry to another matter; for that, add a guard on the relationship itself (`"assert": "row.from.status = 'open'"`), or withhold `relationship.<end>.link` and `unlink` from roles.

### Operations and authority, designed together

- **Name the operations.** Expose meaningful operations (`submit`, `approve`, `cancel`) as entries in the object's `actions` map; one that moves a lifecycle says so with `transition`. Use declarative effects when they suffice. Reach for a function (`"run": "<function>"`) only when the logic can't be expressed declaratively; it proposes changes, and Basel checks and commits them like any other write.
- **Let the server decide what it should decide.** Who created a record and when are stamps (`"stamp": {"on": "create", "value": {"expr": "acting"}}`, `{"expr": "NOW()"}`); a running number is `numbering`. The client never sends them. Anything more, such as where a record routes, goes in an action rather than a create the client fills in; then refuse direct creation with an assertion.
- **Stamping time with a state change.** An effect can: `{"op": "set", "values": {"closed_at": {"expr": "NOW()"}}}` on the transition writes the write's own time, and `{"op": "set", "values": {"closed_on": {"expr": "TODAY()"}}}` its date in the tenant's time zone. A function on a transition may also update other fields of its own record, but not a field the transition itself sets.
- **Parameters.** A param is required and non-null unless it declares both `"optional": true` and `"nullable": true`; a `default` needs `optional`. An omitted optional param binds `NULL`, so a guard that reads it checks `IS NULL` first. A param may share a field's name: `args.note` and `row.note` stay distinct.
- **Nothing is available until declared.** An object's operations are listed in `operations` (an object without `delete` there cannot be deleted by anyone, admins included), and every role's reach is declared in `policies/`.
- **Write a role matrix for each workflow:** which fields each role can read; which rows it can see; which fields it can write; what it can reference; what it can link and unlink; what it can invoke. Seeing a record, choosing it as a reference and changing it are three separate permissions. A field outside a role's readable fields is left out of responses.
- **Where authority goes:** roles, readable fields and tenant rights in `policies/roles.json`; every row grant as a named permit in `policies/<object>.json`; structural expectations in `policies/assertions.json`. A role grants no rows by itself. A condition in the UI is presentation, never authority.

Authority facts that surprise people:

- A write that commits more than one change (a record plus its link) needs the tenant action `proposal.submit`.
- A function may propose a transition its caller cannot invoke directly. A review that reads only transition rules under-counts who can move a record.
- A role needs `metadata.read` before any screen loads for it. That also shows the role the model and policy through reflection.
- The built-in `admin` role can do everything, and the built-in `member` role reads and writes every record without any developer authority. Test as a less-privileged person; declare a role only when someone needs less than `member`.

### Recommended patterns

The designs that come up in every app, as the files that express them. Most of them are one small sales app (`Company`, `Deal`, `Task`, `Contact`); the cardinality pattern is a small project app (`Person`, `Project`, `Task`). Every file passes `basel validate` in either spelling. Copy a pattern, rename it, keep its shape. "Worked metadata examples", later in this guide, has complete examples of the constructs builders most often get wrong; "Metadata files at a glance" has every file and key.

### Pattern: one-to-many, a document, and many-to-many with facts on the link

Three relationships: a company's deals (a plain one-to-many, linked when a deal is created or edited), a deal's tasks (a document: created with the deal, deleted with it, each task belonging to exactly one deal), and partnerships between companies (many-to-many, one link per pair, with the partnership's facts on the link).

```json
// relationships/company_deals.json
{
  "name": "CompanyDeals",
  "operations": ["create", "delete"],
  "from": {"object": "Company", "name": "deals"},
  "to": {"object": "Deal", "name": "company", "cardinality": {"max": 1}, "nested": {"create": ["link"], "update": ["link", "unlink"]}}
}
// relationships/deal_tasks.json
{
  "name": "DealTasks",
  "operations": ["create", "delete"],
  "from": {"object": "Deal", "name": "tasks", "nested": {"create": ["create"], "update": ["create", "update", "delete"]}, "on_delete": "delete_members"},
  "to": {"object": "Task", "name": "deal", "cardinality": {"max": 1, "min": 1}}
}
// relationships/partner_of.json
{
  "name": "PartnerOf",
  "description": "Two accounts that work together, with the terms of the partnership on the link.",
  "operations": ["create", "update", "delete"],
  "unique": true,
  "from": {"object": "Company", "name": "partners", "nested": {"update": ["link", "unlink"]}},
  "to": {"object": "Company", "name": "partner_of", "nested": {"update": ["link", "unlink"]}},
  "properties": {"since": {"type": "Date", "nullable": true}, "terms": {"type": "text", "nullable": true}}
}
```

Without `nested` on an end, records cannot be linked through it when they are created or edited; the generated forms then show no picker there. The company's rollups read these relationships:

```json
// objects/company.json, fields
"deal_count": {"type": "int", "rollup": "COUNT(row.deals)"},
"open_total": {"type": "Money", "rollup": "SUM(row.deals -> amount WHERE row.stage = 'open')"},
"partner_count": {"type": "int", "rollup": "COUNT(row.partners=>)"},
"big": {"type": "bool", "formula": "CASE WHEN row.open_total > 100000 THEN true ELSE false END"}
```

And a member guard keeps tasks editable only while their deal is open, admitting the deal created in the same request:

```json
// objects/task.json
{
  "name": "Task",
  "operations": ["create", "update", "delete"],
  "fields": {"title": {"type": "text"}, "due_on": {"type": "Date", "nullable": true}, "done": {"type": "bool", "default": false}},
  "guards": [
    {"name": "deal_open", "on": ["create", "update", "delete"], "assert": "row.deal.stage IS NULL OR row.deal.stage = 'open'", "message": "Tasks change only while the deal is open."}
  ]
}
```

The same shape serves a booking (a relationship from `crm:Contact` to a class, or a `Booking` object with two required links, each `min: 1, max: 1`), an order and its lines, or a membership with a role on the link.

### Pattern: cardinality in both directions

Before you write a `ref` field or a relationship, say its cardinality in both directions, and whether either side may be empty. "A task belongs to at most one project; a project has any number of tasks." "A principal is at most one person; a person may have no principal." Then declare each direction. A direction you only assume is a rule nothing enforces.

A `ref` limits one direction only. Each record points at one target, but nothing stops many records pointing at the same target.

The mistake this prevents comes from a real build. A `Person` got a nullable `principal` ref so that a "My tasks" page could find the signed-in person, and the page took the first `Person` whose `principal` was the caller. Nothing stopped two people linking the same principal, so a second link would quietly show someone else's tasks. Asked about it, the builder said it had not thought about the reverse direction.

Three shapes, in one small project app:

```json basel-repository
# file: basel.json
{"format": 2, "name": "cardinality_example"}
# file: objects/person.json
{
  "name": "Person",
  "description": "Someone who works on projects; principal is their sign-in, when they have one.",
  "fields": {
    "name": {"type": "text"},
    "principal": {"type": "ref", "to": "Principal", "nullable": true, "unique": true, "description": "At most one Person per principal, so My tasks finds exactly one. Many people may have none."}
  }
}
# file: objects/project.json
{
  "name": "Project",
  "fields": {"name": {"type": "text"}}
}
# file: objects/task.json
{
  "name": "Task",
  "fields": {
    "title": {"type": "text"},
    "assignee": {"type": "ref", "to": "Person", "nullable": true, "default": {"expr": "LOOKUP(Person WHERE row.principal = acting)"}}
  }
}
# file: relationships/project_tasks.json
{
  "name": "ProjectTasks",
  "description": "A task belongs to at most one project; a project has any number of tasks.",
  "from": {"object": "Project", "name": "tasks"},
  "to": {"object": "Task", "name": "project", "cardinality": {"max": 1}}
}
# file: relationships/task_dependencies.json
{
  "name": "TaskDependencies",
  "description": "Any task may wait on any number of others; each pair is linked once.",
  "unique": true,
  "from": {"object": "Task", "name": "depends_on"},
  "to": {"object": "Task", "name": "required_by"}
}
```

- **Optional one-to-one on a ref.** `"unique": true` on the nullable `principal` lets each principal belong to at most one `Person`. Empty values are not compared, so any number of people may have no principal. For a rule that applies only to some rows (active people only), declare a `constraints` entry with `unique` and `when`; see "Conditional uniqueness and interval exclusion (`constraints`)".
- **Many-to-one.** `"cardinality": {"max": 1}` on the `Task` end of `ProjectTasks` gives each task at most one project. Add `"min": 1` when every task must have one.
- **Many-to-many with unique pairs.** `TaskDependencies` leaves both ends unbounded, and `"unique": true` stops the same pair being linked twice.

Then check every reader that picks "the" matching record: a page or query that takes the first row or ends in `LIMIT 1`, and every `LOOKUP`. Each must rest on a declared uniqueness rule or a `max: 1` end, not on how the data looks today. `LOOKUP` enforces this itself: the `assignee` default above is refused unless `principal` is unique with no condition.

### Pattern: contact details, a field first

**Start with a plain field.** For your own objects, "a contact has an email" is one line, and most apps never need more:

```json
// objects/contact.json, fields
"email": {"type": "Email", "nullable": true},
"phone": {"type": "Phone", "nullable": true}
```

**Move to records only when a record really has several, each with facts of its own**: a label, a purpose, its own uniqueness or consent. Then each email is an `EmailAddress` the contact owns, and one of them is the primary. Decide this before the object holds data: no supported change yet turns a stored `email` into a collection with the name kept, and a field that holds data cannot be dropped. If you need the full CRM shape, install `@rosetta/crm-core` (see "Reuse before you build") instead of building this yourself.

The owned members:

```json
// objects/contact.json
{
  "name": "Contact",
  "description": "A person we deal with. Their email addresses are records of their own; one is the primary.",
  "operations": ["create", "update", "delete"],
  "fields": {
    "name": {"type": "text"},
    "primary_email": {
      "primary": {"of": "emails", "project": "address"},
      "description": "The contact's chosen email, one of its own `emails`. Change it with set_primary_email(member)."
    },
    "any_email": {"type": "Email", "rollup": "MIN(row.emails -> address)", "nullable": true,
                  "description": "Some email of this contact, so a contact with one address shows it without choosing."},
    "email": {"type": "Email", "formula": "CASE WHEN row.primary_email_ref IS NOT NULL THEN row.primary_email_ref.address ELSE row.any_email END",
              "description": "The email to show: the primary, else any. Read-only: change the EmailAddress records."}
  }
}
// objects/email_address.json
{
  "name": "EmailAddress",
  "description": "One email address of one contact.",
  "operations": ["create", "update", "delete"],
  "fields": {"address": {"type": "Email", "unique": true}, "label": {"type": "text", "nullable": true}}
}
// relationships/contact_emails.json
{
  "name": "ContactEmails",
  "description": "A contact owns its emails: each belongs to exactly one contact and is deleted with it.",
  "operations": ["create", "delete"],
  "from": {"object": "Contact", "name": "emails",
           "nested": {"create": ["create"], "update": ["create", "delete"]},
           "on_delete": "delete_members"},
  "to": {"object": "EmailAddress", "name": "contact", "cardinality": {"min": 1, "max": 1}}
}
```

The one `primary` line stands for four ordinary declarations with fixed names. Reflection lists them under the object's `primaries`, so agents and scripts can find and call them:

| Name | What it is |
|---|---|
| `primary_email_ref` | A nullable `ref` to the member (the pointer). Without `project`, `primary_email` itself is the pointer. |
| `primary_email` | A formula, `row.primary_email_ref.address`, typed like the member's field. |
| `primary_email_is_own` | A create/update guard: the pointer is empty or names one of this contact's own `emails`. |
| `set_primary_email` | An action with one `ref` parameter, `member`. It switches the primary in one write. |

- **Requirements.** The far end of `of` is named and declares `"cardinality": {"max": 1}`. Declare `primary` in the object's own file, not in `additions/`. A model that already has one of the four names is refused `name_collision`.
- **Authority.** Grant the action like any other: `{"roles": ["rep"], "action": "action.set_primary_email.invoke"}` in `policies/contact.json`.
- **Writing.** Create members nested through the parent: `POST /objects/Contact {"name": "Jo", "emails": [{"address": "jo@example.org"}]}`, later `PATCH … {"emails": {"create": [...]}}` or `{"emails": {"delete": ["<id>"]}}`. Then `set_primary_email` with `{"member": "<EmailAddress id>"}`. A write cannot make a member it creates primary, so "add and make primary" is two steps. `any_email` covers the single-email case, so a contact with one address needs no choice.
- **Deleting.** Owned members are deleted, not hidden behind an `archived` flag. `on_delete: delete_members` deletes a contact's emails with it, the primary included. The current primary cannot be deleted on its own: a direct delete is refused `delete_blocked_by_reference`, a nested delete by the guard `primary_email_is_own`. Make another primary first. Because the member's own end is `min: 1, max: 1`, a direct `DELETE` of any other member also removes its one link (the caller needs `delete` on the relationship and `relationship.emails.unlink` on `Contact`).
- **Screens.** The record page's related list for `emails` shows the primary first, marked, and each other row's menu offers **Make primary**; a `basel.inline_collection@1` section does the same in place of the list. The reference picker is not narrowed to the contact's own emails; the guard refuses a wrong pick on save.
- **Formulas.** A formula declares no `nullable` (it is already nullable; `invalid_field`). The generated projection reads one `ref` hop, so it can be a related-list column on another object.

**Which shape for "the primary".** Use `primary` (a pointer on the parent) when a person chooses the member: primary email, default address, an account's primary contact. Use a flag on the child only when there is no parent to hold a pointer, or the primary is per pair (a contact's primary affiliation, which `crm-core` keeps as a flag on the `Affiliation` link): it needs an invariant or rule for "at most one", and switching touches two rows. A member that follows from the data (the current employer, the address in force today) wants a filtered to-one link, which Basel does not have yet.

### Pattern: least privilege for one role

A role carries readable fields and tenant rights; every row grant is a permit with exactly one action. The relationship's own permits make linking possible, and an assertion keeps a door shut on purpose. The deal's actions (`win`, `lose`, `add_task`) are the sales app's own; the shape is what matters.

```json
// policies/roles.json
{"roles": {"rep": {"id": "role_rep",
  "read_fields": {"Company": ["*"], "Deal": ["*"], "Task": ["*"], "CompanyDeals": ["*"], "DealTasks": ["*"], "PartnerOf": ["*"]},
  "tenant": ["metadata.read", "proposal.submit"]}}}
// policies/deal.json
{"object": "Deal",
 "permits": {
   "read_all": {"roles": ["rep"], "action": "read"},
   "reference_all": {"roles": ["rep"], "action": "reference"},
   "create": {"roles": ["rep"], "action": "create", "write": ["*"]},
   "edit_open": {"roles": ["rep"], "action": "update", "write": ["name", "amount", "probability", "expected_close", "notes"],
                 "before": "row.stage = 'open'", "after": "row.stage = 'open'"},
   "win": {"roles": ["rep"], "action": "action.win.invoke", "before": "row.stage = 'open'"},
   "lose": {"roles": ["rep"], "action": "action.lose.invoke"},
   "add_task": {"roles": ["rep"], "action": "action.add_task.invoke"},
   "company_link": {"roles": ["rep"], "action": "relationship.company.link"},
   "company_unlink": {"roles": ["rep"], "action": "relationship.company.unlink"},
   "company_reference": {"roles": ["rep"], "action": "relationship.company.reference"},
   "tasks_link": {"roles": ["rep"], "action": "relationship.tasks.link"},
   "tasks_reference": {"roles": ["rep"], "action": "relationship.tasks.reference"}
 }}
// policies/company_deals.json
{"object": "CompanyDeals",
 "permits": {"create": {"roles": ["rep"], "action": "create", "write": ["from", "to"]},
             "delete": {"roles": ["rep"], "action": "delete"}}}
// policies/assertions.json
{"assertions": [{"roles": ["rep"], "cannot": "delete", "on": "Deal"}]}
```

Permits on `Company` mirror these (`read`, `reference`, `create`, an `update` with `"before": "row.owner = actor", "after": "row.owner = actor"`, and `relationship.deals.link`/`reference`, `relationship.partners.link`/`unlink`/`reference`). One `action` per permit; `read` and `reference` take `where`, `create` takes `after`, `update` takes `before` and `after`, every other action takes `before`; `write` belongs to `create` and `update` only.

## Profile boundary

Basel measures itself against six foundational principles: `GP-01`, `GP-02`, `GP-05`, `GP-06`, `GP-08`, and `GP-11`. An implementation that violates one is not an early version of the platform; it is a different product.

The earliest engine was deliberately non-conformant. Later releases closed the model, transaction and authority gaps described below. Current status, stated plainly rather than implied:

| Principle | Status |
|---|---|
| `GP-01`, `GP-02` | Upheld. Metadata is the sole source of truth and the only way to change the system. |
| `GP-05` — models propose; deterministic systems commit | **Closed.** Every write passes one pipeline: type validation, guard evaluation over a consistent snapshot, rollup recompute, invariant checks, then the write plus exactly one audit event in the same transaction. Functions on actions propose; only `commit()` commits. The boundary also checks current authorization and policy; see "Policy" for the rules on explicit operations and admitted consequences. |
| `GP-08` — state carries history, evidence, epistemic status | **Closed.** Every successful write records a transactional audit event; row history is queryable (`GET .../objects/{Object}/{id}/history`, see "Actions"). |
| `GP-11` — capabilities, not raw primitives | **Still violated.** Declared actions (plain actions and lifecycle transitions) exist as capabilities, but generic record mutation — `GP-11`'s named anti-example — remains the working surface. Closes once actions replace generic CRUD. |
| `GP-06` — intelligence distinct from authority | Implemented: agents and people act through authenticated principals; functions propose operations, and the engine checks authority and commits them. |

Authentication, sessions, tenant memberships, roles and policy enforcement are implemented. General destructive schema changes remain restricted (see below).

### What is refused, not silently degraded

A construct outside the supported profile is an authoring-time error, never a runtime degradation, and Basel applies this literally. `lifecycles`, `actions`, `invariants`, rollups, formulas, and `guards` are implemented constructs; see their sections below.

Every property the format-2 grammar does not declare is **refused** `unknown_property` at its JSON pointer, so nothing is silently ignored. That covers keys from other systems and retired spellings alike: a field-level `derived`, an object-level `computed`, `derivations` or `policies` (policy lives under `policies/`; see "Policy"), and an action's `body` or `grant` (an action names its code with `run` and its reach with `scope`; see "Functions on actions" below). A few retired spellings get a refusal that names the replacement, such as a query's `parameters` (`params`), a permit's `actions` or `when` (one `action`, with `where`, `before` or `after`), and an object view's `surfaces`.

The `create`/`update`/`link`/`unlink` effect operations are supported; see "Nested create and update" and "Actions" below. `default` (a literal, or one of the `{"expr": ...}` forms) is real field vocabulary, and so are the independent `backfill` and `stamp` beside it (see "Metadata grammar and type table" below).

#### Destructive change is refused, not performed

Removing a field, an object or a relationship you own is supported (see "Removing a field, object or relationship" below), and so is a declared rename (see "Renaming a field, object or relationship") and some type changes (see "Changing a field's type"). Other physical retyping remains restricted.

Supported operations such as removing declared `constraints` and removing an eligible package follow their own admission rules. There is no blanket ban on every `DROP CONSTRAINT` or `DROP TABLE` generated by those operations.

Removing a declared element from a document does not silently drop it. It fails:

```
refused: Widget.legacy_code
  declared previously, absent in submitted document; removing elements is not supported in M1
```

These are all allowed: `ADD COLUMN`, `CREATE TABLE`, `CREATE INDEX`, adding an enum value, and `ADD CONSTRAINT` (flagged, since it can fail against existing rows).

#### Removing a field, object or relationship

Deleting a field from an object's file, an object's file, or a relationship's file removes it. What happens to its data depends on whether it holds any:

- **Empty** (no record holds a value for the field; no rows or edges in the table): it is dropped. A field's plan records a `removed_field_empty` check.
- **Holding data:** it is **archived**, a flagged step, so the push needs the plan's approval. The data leaves the model, the API, BQL and the UI, but it is kept, not deleted. An archived field's new records leave it empty. An archived object's or relationship's table moves out of the tenant's schema, and its references to records you keep are released, so those records can still be deleted.

Removing an object also means removing every field and relationship that refers to it, in the same push; each is archived or dropped the same way. A reference left behind refuses `removal_referenced`, naming the table that still holds it; so does renaming an object a reference-choice arm points at, since a rename is a removal plus an addition.

Adding a field, object or relationship back exactly as it was archived (a revert) starts it empty. The plan carries an `archive_not_restored` advisory naming the archive, for example `Task.note@12` (the element, and the version that archived it). A `backfill` the re-add needs is not a difference. Adding it back any other way refuses `archived_name_reused` until you restore the archive or destroy it.

To bring a field's archived data back, add the field with `"restore": true` (the most recent archive) or `"restore": <version>` (the archive that version made, a number). It is a flagged step. The archive's column becomes the field's column again, and anything the definition requires is checked against the data as when it is first added: a required field some record left empty refuses `constraint_apply_failed`. A type different from the archived one refuses as a retype. `restore` naming no archive refuses `archive_not_found`; once the field is back, the key does nothing (`restore_unused` advisory) and can be removed. An object or relationship takes `"restore": true` (or a version) at the top of its file the same way:

- Its table comes back with its rows.
- The references the archive released are rebuilt and checked against the data; a reference to a record deleted meanwhile refuses `constraint_apply_failed`.
- It must be declared exactly as archived (`restore_definition_changed` otherwise); change it in a later push.
- Restore its fields and relationships in the same push to bring everything back.

`archives.json` at the repository root holds two arrays of archives. `restore` brings an archive back when its element is declared again, exactly as a `restore` key on the element would; it is how you restore something whose files you do not edit, such as a reinstalled package's object. To destroy an archive for good, list it under `destroy`:

```json basel-fragment
{"destroy": ["Task.note@12"]}
```

Each entry is a flagged step that drops the archived column or table; the data is gone. An archive the same push creates can't be destroyed by it (`archive_destroy_same_push`); push the removal first. An entry naming no archive refuses `archive_not_found`. Once destroyed, the entry does nothing (`archive_destroy_unused` advisory), so you can delete the line whenever you like. A malformed entry refuses `invalid_archives`. Destroying an archive and declaring its name again can share one push.

#### Renaming a field, object or relationship

A name is an element's identity, so changing it without saying so is a removal plus an addition. Declare the rename with `renamed_from` on the new name, and the data stays where it is. Here `id_prefix` keeps the record IDs already issued:

```json basel-fragment
{
  "name": "Supplier",
  "renamed_from": "Vendor",
  "id_prefix": "vendor",
  "fields": {"memo": {"type": "text", "renamed_from": "note"}}
}
```

- The column or table is renamed in place, as a flagged step, with the constraints whose names carry the old name. Shares and counters follow.
- Record IDs never change. An object's IDs start with its table name, so renaming an object refuses `rename_needs_id_prefix` until it declares `id_prefix` with the old prefix.
- Every reference to the old name breaks at once: formulas, rollups, permissions, queries and views that still name it fail resolution, and each error says what the name was renamed to. Update them in the same push.
- References to a renamed object (a `ref` field, a relationship end) follow it without change.
- A relationship takes `renamed_from` the same way: its junction table is renamed in place, edges kept.
- Leave `renamed_from` in place; once the previous version has the new name it does nothing. A package keeps it in its releases, and `basel build` treats a declared rename as compatible.
- Not yet: subtype families, open-currency Money and reference-choice fields, references to a subtype family, an object a reference choice targets, and a relationship with an end in a subtype family (`rename_not_supported`). A new name already taken refuses `rename_target_taken`.

#### Changing a field's type

Some changes to a field you own are planned on live data. Each runs inside the apply, so a row the change cannot hold refuses the push and nothing changes:

- **Required to nullable** widens the field: an ordinary step.
- **Removing enum values** narrows it: a flagged step that fails while any record still holds a removed value (`constraint_apply_failed`). Change those records first.
- **`int` to `decimal`** is flagged, and refuses a whole number too large for a decimal field.
- **`decimal` to `int`** is flagged, and refuses any value with a fractional part.

- **Removing a lifecycle state** narrows the state column the same way: flagged, and it fails while any record is in a removed state. Move those records first.
- **Removing a whole lifecycle** drops its state column when the table is empty, and archives it (flagged) when it holds rows.
- **Turning a field into a lifecycle** of the same name is refused `field_to_lifecycle`: a lifecycle cannot take over an existing field's column in place. Declare the lifecycle under a new name, and copy the old field's values across with an update if they should carry over.

- **Any other change between text, numbers, booleans, dates and timestamps** converts the existing values when the field declares `"retype": {"from": "<its previous type>"}`, for example `"code": {"type": "int", "retype": {"from": "text"}}`. It is flagged. The old values are archived first, so they stay restorable, and each is converted as the new type reads it. A value that will not convert refuses the push, unless the field is nullable and declares `"on_fail": null` in its `retype`, which leaves it empty. A `from` that is not the field's previous type refuses `retype_from_mismatch`. Once the type has changed, the key does nothing.

Other type changes, conversion formulas (`using` in `retype`), and these changes on subtype families and reference choices still refuse (`retype_not_supported`, `retype_conversion_not_supported` or `removal_not_supported`).

Changing what supplies a field is not a type change. A stored field may not become a `formula` or `rollup` of the same name, and a formula or rollup may not become a stored field of that name: the push refuses `projection_replaced`, naming the field, because the stored values would leave the model, the new stored field would start empty, or a rollup's last values would stop being recomputed. Give the new field a different name, or keep the field as it is. A stored field that brings its own archive back with `restore` may take a formula's name again.

#### How long a change takes

An apply runs in one brief pause: writers wait while it holds the tenant, a statement may run 30 s, the whole apply 60 s, and it waits at most 5 s for a table lock. The plan's `estimates` list each operation's cost, in operation order: `instant` (a catalog change, such as an archive, a rename or a drop) or `scan` (it reads or rewrites every row, such as making a field required), with the table's row estimate. A scan over about a million rows carries a `slow_step` advisory. A step that runs past a limit, or cannot get its lock because a long query holds the table, stops the apply, and nothing is applied: it is refused `apply_pause_exceeded` at that step, naming the limit.

Basel indexes every reference field and every list's sort field itself; you declare nothing. The plan's `indexes` list says what the push does about them, one entry per index (`element`, `reason` `reference` or `order_key`, `table`, `index`, `action` `create`, `rebuild` or `drop`, `when`, `ddl`). On a new or empty table an index is built inside the apply (`when: in_apply`). On a table that holds rows it is built after the apply, without blocking writes (`when: after_apply`): reads use it once it is ready, and nothing waits for it. Indexes are not part of the plan hash, and applying the same model twice lists none.

Your additions to a package's object are fields you own, and are removed the same way; removing the last one unpins the package.

Removing a package works the same way for its objects and relationships: empty ones are dropped, and ones holding data are archived (a flagged step). An object your additions pin, or that one of your fields still references, still refuses. Reinstalling the package starts its objects empty unless you restore their archives; since you do not edit a package's files, list the archives under `restore` in `archives.json` (see above).

Still refused (`removal_not_supported`): a package's own fields (its objects and relationships leave with the package); subtype families and their members; open-currency Money and reference-choice fields, and references to a subtype family. A numbered field's counter is kept, so a field re-added under its name continues the numbering.

Tenant deletion is the one destructive operation the engine permits. It is an explicit control-plane call with its own confirmation, never something a metadata apply can reach.

## Endpoints

Bodies are JSON unless the table says otherwise. Git smart-HTTP routes use Git protocol bytes, and this document is `text/markdown`. `{key}` is a tenant key; `{Object}`/`{attr}` are authored metadata names.

Every `/tenants/{key}/...`, `/accounts/...`, and `/control/...` route authenticates, except the few the next section names. Read "Authentication" before calling anything below `GET /health`.

| Method | Path | Body | Success | Notes |
|---|---|---|---|---|
| GET | `/` | — | 200 `text/markdown` / 404 | this document; `?section=<slug>` answers one section alone, by the anchor the contents list links to (a `###` heading's slug answers that subsection), and an unknown slug is `404 unknown_section` naming the sections |
| GET | `/start.md` | — | 200 `text/markdown` | the start document: one small page to read first, with this server's origin and version filled in — install the CLI from `/downloads`, add the MCP connection, sign in without a browser, the build loop, and the UI SDK for a tenant component; `basel agent-md --start` prints it |
| GET | `/downloads/{name}` | — | 307 / 404 | the client archive for exactly this server's version: `{name}` is a target (`aarch64-apple-darwin`, `x86_64-unknown-linux-gnu`), answered with a redirect to `basel-<version>-<target>.tar.gz` on the release bucket (`BASEL_DOWNLOADS_URL`), `ui-sdk` for the packaged UI SDK `basel-ui-sdk-<version>.tgz`, one of this version's archive, SDK or `.sha256` file names, or `install.sh`; `404 unknown_download` for another version or name, `404 downloads_not_configured` on a server without a bucket (`/health` says: `downloads.configured`) |
| GET | `/health` | — | 200 json / 503 | liveness + engine version, `sdk_contract` — the SDK contract (`<major>.<minor>`) trusted UI bundles are checked against — and `mail` — `{configured, provider}`, whether this server can send account email (`none`, `log` or `cloudflare`); `feed` — the event feed's lag condition (`{status: off | ok | lagging, since?, lag_seconds?, oldest_transaction?: {pid, age_seconds}, paged?}`) and `alerts` — `{configured}`, whether a page has a channel (`BASEL_ALERT_URL`); `503 superseded` once another instance has claimed the singleton epoch — this instance is shutting down |
| GET | `/catalog.json` | — | 200 json / 503 | the Basel Catalog, without a session: `{listings, fetched_at, stale}`, one listing per published package (`name`, `listing_kind` app, data_model, component or theme, `title`, `summary`, `description`, `category`, `tags`, `latest`, `latest_format`, `versions`, `dependencies`, `exports`, `screenshots`, `source`), read from `BASEL_CATALOG_URL`; `503 catalog_unavailable` when the index was never read |
| GET | `/catalog-media/{path}` | — | 200 image / 404 | one catalog screenshot, without a session: only a path the cached index names as a screenshot (a listing's `screenshots[].url`); anything else is `404` |
| GET | `/abi` | — | 200 json | the served function ABI package versions, each linking its WIT and contract schema (see "Functions") |
| GET | `/abi/basel-function/{version}/function.wit` | — | 200 `text/plain` / 404 | the normative WIT for that package version, content ETag; `404 unknown_abi_version` outside the served set |
| GET | `/abi/basel-function/{version}/contract.schema.json` | — | 200 json / 404 | JSON Schema of the `basel-contract` custom section for that package version |
| POST | `/accounts/sessions` | `{"login", "password"}` or `{"token"}`, `"profile": "ui"`? | 201 json / 401 / 429 | the account session exchange (see "Authentication") — one of the four endpoints that is itself unauthenticated; `profile: "ui"` answers with cookies instead of a token |
| DELETE | `/accounts/sessions/current` | — | 204 | revoke the session this request authenticated with; a `ui` session's two cookies are cleared |
| POST | `/accounts/dev/sessions` | `{"login"}`, `"audience": "ui"|"api"|"control"`?, `"profile": "ui"`? | 201 json / 404 | **development only** — open a real session for a login with no password and no token (see "Development mode"); answers in `POST /accounts/sessions`' own two shapes |
| GET | `/accounts/me` | — | 200 json | the authenticated account, minus every secret; carries `memberships_href` and `features` (what the operator has switched on, e.g. `ask_basel`) |
| GET | `/accounts/me/memberships` | — | 200 json | every tenant this ONE session reaches, oldest tenant key first — the endpoint that resolves which `/tenants/{key}/...` paths the token opens |
| POST | `/accounts/me/mcp` | one JSON-RPC 2.0 object | 200 json / 202 / 400 / 401 / 403 / 413 | the account-level hosted MCP endpoint: the same contract as `/tenants/{key}/mcp` for every tenant the caller reaches — `basel_list_tenants`, and each tenant tool with a required `tenant` argument. A credential scoped to one tenant reaches only that tenant here; any other is refused `tenant_out_of_scope` before a door is called |
| GET | `/accounts/me/credentials` | — | 200 json | the caller's own live token credentials; never a secret |
| POST | `/accounts/me/credentials` | `{"audience", "tenant_scope", "label", "expires_at"?}` | 201 json | mint a bearer credential for the caller's own account; the plaintext token is returned once |
| DELETE | `/accounts/me/credentials/{id}` | — | 204 / 404 | revoke one of the caller's own credentials and every live session it authenticated |
| POST | `/accounts/me/credentials/{id}/rotate` | — | 201 json / 404 | replace one of the caller's own credentials with a successor carrying its terms; the predecessor and every session it authenticated are revoked in the same transaction |
| POST | `/accounts/me/agents` | `{"login", "display_name"}` | 201 json / 403 / 409 / 422 / 429 | mint an agent account owned by the caller; only a `human` account under direct live authority may create one; rate-limited per account and per address |
| GET | `/accounts/me/agents` | — | 200 json | the agent accounts the caller owns; never a secret |
| DELETE | `/accounts/me/agents/{id}` | — | 204 / 403 / 404 / 422 | delete an agent the caller owns, with its credentials, sessions and elevations; direct authority only; another owner's agent is 404; refused (`account_has_memberships`) while it is a member of any tenant |
| POST | `/accounts/me/quota-notices` | `{"quota": "ask_basel", "spent_usd", "cap_usd"}` | 200 json / 401 / 422 | the Ask Basel Worker reports, as the person, that it refused a chat at their monthly cap; Basel emails the account's verified address once a calendar month (`notice`: `sent`, `already_sent`, `no_address`, `refused`) |
| POST | `/accounts/me/password` | `{"current", "new"}` | 204 | change the caller's own password; every other session of this account is closed |
| POST | `/accounts/password-resets/complete` | `{"secret": "bse_...", "password": "..."}` | 201 json / 400 | redeem a one-time password-reset secret into a new password; the account's other passwords and every session it holds are revoked; unauthenticated, because the secret is the authentication |
| POST | `/accounts/password-resets` | `{"email"}` | 202 json / 400 / 422 / 429 / 503 | ask for a password-reset link by email; the answer is the same for every address; unauthenticated |
| GET | `/forgot` | — | 200 `text/html` | the page that asks for a reset link; posts to `POST /accounts/password-resets` |
| POST | `/accounts/invitations/accept` | `{"secret"}` (with a credential) or `{"secret", "login", "password", "display_name"}` (without one) | 201 json / 400 / 401 / 409 / 422 | accept a tenant invitation — the caller's own account joins, or a new one is created and joined, in one transaction; the secret rides in the BODY, never the path |
| GET | `/accounts/me/invitations` | — | 200 json | the caller's live tenant invitations — addressed to their account, their login or their VERIFIED email address — into tenants they are not a member of: `{count, invitations: [{id, tenant, kind, roles, invited_by, issued_at, expires_at}]}` |
| POST | `/accounts/me/invitations/{id}/accept` | — | 201 json / 403 / 404 / 409 / 422 | join the tenant of one of the caller's own invitations without its secret; `404` for any id that is not theirs |
| POST | `/accounts/me/invitations/{id}/decline` | — | 204 / 403 / 404 / 422 | withdraw one of the caller's own invitations |
| GET | `/reset` | — | 200 `text/html` | the page a set-password link opens (an operator's account invitation, or any reset secret): it reads the `bse_` secret from the link's fragment, asks for the new password twice and posts it to `POST /accounts/password-resets/complete` |
| GET | `/invite` | — | 200 `text/html` | the page an emailed invitation opens: it reads the secret from the link's fragment and joins, creates an account, or signs in and joins; see "Invitations by email" |
| POST | `/accounts/invitations/preview` | `{"secret"}` | 200 json / 400 / 422 | what an invitation secret is for — tenant, roles, whether accepting it signed out creates an account; unauthenticated (the secret is the proof), changes nothing |
| POST | `/accounts/device/authorizations` | `{"client_name"?, "client_host"?}` | 201 json / 429 | start a CLI's browser sign-in: a device code for the CLI, a user code and link for the person; unauthenticated; see "Signing the CLI in through the browser" |
| POST | `/accounts/device/token` | `{"device_code"}` | 200 json / 202 json / 422 / 429 | poll a sign-in: pending or slow down (`202`), then once the new `api` credential (`200`); unauthenticated (the device code is the proof) |
| POST | `/accounts/device/lookup` | `{"user_code"}` | 200 json / 422 / 429 | what a pending sign-in is — client, host, address — for the signed-in person deciding it |
| POST | `/accounts/device/approve` | `{"user_code"}` | 200 json / 403 / 422 / 429 | approve a pending sign-in as the caller |
| POST | `/accounts/device/deny` | `{"user_code"}` | 200 json / 403 / 422 / 429 | deny a pending sign-in |
| GET | `/device` | — | 200 `text/html` | the page a person approves a CLI sign-in on; it reads the user code from the link's fragment |
| GET | `/signup` | — | 200 `text/html` | the sign-up page: access code, email (the login), display name, password; posts to `POST /accounts/signup` |
| GET | `/accounts/assets/{name}` | — | 200 `text/css` or `font/woff2` / 404 | the account pages' one stylesheet (`basel.css`, the console's shared base and the account-page design) and its fonts; no credential |
| POST | `/accounts/signup` | `{"code", "email", "password", "display_name", "device"?}` | 201 json / 409 / 422 / 429 / 503 | redeem an operator's access code for a new, UNVERIFIED account and mail it a verification link; unauthenticated (the code is the authorization); see "Sign-up with an access code" |
| GET | `/verify` | — | 200 `text/html` | the page the emailed link opens: it reads the token from the link's fragment and posts it to `POST /accounts/verify` |
| POST | `/accounts/verify` | `{"token"}` | 200 json / 409 / 422 | mark the emailed address as the account's own (and a person's login, when it changes); answers `next`, the app's origin; unauthenticated (the token is the proof) |
| POST | `/accounts/me/email` | `{"email"}` | 202 json / 403 / 409 / 422 / 429 / 503 | change the caller's email address — and so its login — once the link mailed to the new address is opened |
| POST | `/accounts/me/email-verification` | — | 202 json / 409 / 422 / 429 / 503 | send the caller a new verification link, withdrawing the old |
| GET | `/accounts/me/tenants` | — | 200 json | `{tenants, tenant_allowance, tenants_used, email_verified}` — the tenants the caller created for itself |
| POST | `/accounts/me/tenants` | `{"key"}` | 201 json / 403 / 409 / 422 | create a tenant the caller administers, within its allowance, once its email is verified; answers with its `api` base and `git_remote` |
| DELETE | `/accounts/me/tenants/{key}` | `{"confirm": "<key>"}` | 204 / 400 / 404 | permanently delete a tenant the caller created (the deletion `DELETE /tenants/{key}` runs), freeing its place in the allowance; any other tenant is `404` |
| GET | `/.well-known/oauth-protected-resource/tenants/{key}/mcp` | — | 200 json | RFC 9728 metadata for that tenant's hosted MCP endpoint: its `resource` and this server as `authorization_servers` |
| GET | `/.well-known/oauth-protected-resource/accounts/me/mcp` | — | 200 json | RFC 9728 metadata for the account's hosted MCP endpoint |
| GET | `/.well-known/oauth-authorization-server` | — | 200 json | RFC 8414 metadata: authorize, token, registration and revocation endpoints; PKCE `S256` only; public clients only |
| POST | `/oauth/register` | `{"client_name", "redirect_uris": [...]}` | 201 json / 400 / 429 | register a public MCP client (RFC 7591); redirects must be https or loopback http (any port) |
| GET | `/oauth/authorize` | query | 200 html | the consent page: the person signs in and allows the client the whole account or one tenant; it sends the browser back with a one-time `code` |
| POST | `/oauth/token` | form: `grant_type`, `client_id`, … | 200 json / 400 | `authorization_code` (with `code_verifier`) or `refresh_token` (rotated; reuse revokes the grant) → `{access_token, refresh_token, expires_in}`; the access token is an `api` session (`bss_`), scoped as allowed, one hour |
| POST | `/oauth/revoke` | form: `token` | 200 | RFC 7009: a refresh token revokes its grant, an access token its session; always `200` |
| POST | `/accounts/oauth/describe` | `{"request": {...}}` | 200 json / 401 / 422 | what the consent page shows about an authorization request |
| POST | `/accounts/oauth/decide` | `{"request", "approve", "tenant_scope"?}` | 200 json / 401 / 403 / 422 | allow or deny; answers `{redirect}` with the code or `error=access_denied` |
| GET | `/accounts/me/oauth-grants` | — | 200 json | the MCP clients this account allowed, still live |
| DELETE | `/accounts/me/oauth-grants/{id}` | — | 204 / 404 | revoke one: its refresh tokens, credentials and sessions end |
| GET | `/tenants` | — | 200 json | excludes tombstoned by default |
| DELETE | `/tenants/{key}` | `{"confirm": "<key>"}` | 204 | deletes the tenant, its history and the service accounts it manages; other accounts keep only their identity; the key is free again; nothing destroys data on a verb alone |
| POST | `/control/sessions` | `{"login", "password"}` | 201 json / 401 / 429 | open a `bcs_` control session — unauthenticated, since it is where control authentication comes from |
| DELETE | `/control/sessions/current` | — | 204 | revoke the control session this request authenticated with |
| GET | `/control/whoami` | — | 200 json | the authenticated control caller, minus every secret |
| POST | `/control/accounts` | `{"kind", "display_name", "email"?, "login"?, "invite"?}` | 201 json | create a new account; holds no instance role and belongs to no tenant. A `human` needs `email`, which is its login; an `agent` needs a `login` that is not an email address, and so does a `runner` (a worker's account; see its runner credentials). `invite: true` (a `human` only) also emails a 7-day set-password link (`/reset#<bse_ secret>`) and answers `invite: {secret, expires_at, delivery}` |
| GET | `/control/accounts?q=&kind=&active=&limit=&after=` | — | 200 json | every account on the instance, oldest first, one page at a time; `q` matches login, email and display name |
| GET | `/control/accounts/{id}` | — | 200 json / 404 | one account with its lifecycle stamps and every active membership |
| DELETE | `/control/accounts/{id}` | — | 204 / 403 / 404 / 422 | delete an account outright with its credentials, sessions and audit rows; refused for the caller, an instance-role holder, a service account whose tenant is live (it goes with its tenant), an owner of other accounts, or an active member of any tenant; a service left behind by a tenant an older engine tombstoned is removed |
| POST | `/control/accounts/{id}/instance-roles` | `{"role": "operator", "held": true|false}` | 204 / 400 / 403 / 404 / 422 | grant or revoke the `operator` instance role; revoking also ends the account's live control sessions and credentials |
| POST | `/control/accounts/{id}/active` | `{"active": true|false}` | 204 / 400 / 403 / 404 / 409 / 422 | activate or deactivate an account instance-wide; deactivation ends every membership, grant, and session it holds in one transaction |
| POST | `/control/accounts/{id}/password-resets` | — | 201 json / 403 / 404 | a one-time `bse_` password-reset secret for the account; this is the only response that ever carries it |
| PUT | `/control/accounts/{id}/tenant-allowance` | `{"tenant_allowance"}` | 200 json / 403 / 404 / 422 | set how many tenants the account may create for itself (0–100); lowering it deletes nothing |
| PUT | `/control/accounts/{id}/login` | `{"login"}` | 200 json / 403 / 404 / 409 / 422 | set an account's login: a person's must be an email address, an agent's or service's must not be; the email and its verification are untouched |
| PUT | `/control/accounts/{id}/features/{feature}` | `{"enabled", "monthly_cap_usd"}` | 200 json / 403 / 404 / 422 | switch a feature on or off for an account (`ask_basel`, the only one), with a monthly cap in dollars across every tenant (`null` for none) |
| GET | `/control/accounts/{id}/ask-basel/usage` | `?month=YYYY-MM` | 200 json / 400 / 404 / 502 / 503 | an account's Ask Basel calls, tokens and cost for the month, by tenant and session, read from the Ask Basel Worker; `503` when this server has no link to it |
| POST | `/control/accounts/{id}/runner-credentials` | `{"label"?, "expires_at"?}` | 201 json / 403 / 404 / 422 | issue a runner account's `bsr_` credential (audience `runner`): accepted only by `GET /runner/runs` and `claim`, never exchanged for a session; the token is in this response and nowhere else |
| GET | `/control/accounts/{id}/runner-credentials` | — | 200 json / 403 | a runner account's credentials, without secrets |
| DELETE | `/control/accounts/{id}/runner-credentials/{credential}` | — | 204 / 403 / 404 | revoke a runner credential at once |
| GET | `/control/tenants/{key}/features/runs` | — | 200 json / 403 / 404 | the tenant's monthly cap on run spending, `{monthly_cap_usd}` (`null`: the Ask Basel Worker's default) |
| PUT | `/control/tenants/{key}/features/runs` | `{"monthly_cap_usd"}` | 200 json / 403 / 404 / 422 | set or clear the tenant's monthly run-spending cap; the Worker enforces it at claim and before every model call |
| POST | `/control/access-codes` | `{"label"?, "max_uses"?, "tenant_allowance"?, "expires_at"?}` | 201 json / 403 / 422 | mint a two-word access code (single use and one tenant unless told otherwise); the code is in this response and nowhere else; `template` names an account template every sign-up with the code is stamped from, and replaces `tenant_allowance` |
| GET | `/control/access-codes` | — | 200 json | every code, newest first: hint, label, uses, expiry, allowance, revocation — never the code; `GET /control/accounts?access_code=<id>` lists the accounts one made |
| DELETE | `/control/access-codes/{id}` | — | 204 / 403 / 404 / 422 | revoke a code; accounts it made are untouched. `?purge=true` removes a revoked, expired or used-up code's row instead (accounts it made stay); a code still redeemable is refused (`access_code_usable`) |
| GET | `/control/account-templates` | — | 200 json / 403 | every account template, by name: tenant allowance, Ask Basel switch and monthly cap, runs cap, and how many codes and accounts name it |
| POST | `/control/account-templates` | `{"name", "description"?, "tenant_allowance"?, "ask_basel"?: {"enabled", "monthly_cap_usd"}, "runs"?: {"monthly_cap_usd"}}` | 201 json / 403 / 422 | create a template: what every account signed up with a code naming it starts with (`template_name_taken` for a repeated name) |
| PUT | `/control/account-templates/{id}` | the same body | 200 json / 403 / 404 / 422 | replace a template's fields; accounts already stamped from it are untouched, codes naming it hand out the new values from their next redemption |
| DELETE | `/control/account-templates/{id}` | — | 204 / 403 / 404 / 422 | delete a template; refused (`template_in_use`) while a code that can still be redeemed names it; spent codes and stamped accounts keep their rows |
| PUT | `/control/accounts/{id}/template` | `{"template"}` | 200 json / 403 / 404 | stamp a template onto an existing account: its tenant allowance, Ask Basel switch and cap, and the runs cap its own tenants will take; tenants it already owns are untouched |
| POST | `/control/tenants` | `{"key", "admin": {"login"} | {"email"}, "deliver"?}` | 201 json / 404 | provision a tenant and mint its first admin's invitation in the same transaction, then email it unless `deliver: "none"` (`delivery` in the answer); the `bsi_` secret is in this response and that email only; an `admin.login` naming no live account is `404 invitation.login` and provisions nothing |
| POST | `/control/elevations` | `{"tenant", "tenant_principal", "reason", "ttl_seconds"}` | 201 json / 404 | borrow a tenant identity, audibly: answers with a TENANT `api` session bound to the elevation row, capped at one hour |
| DELETE | `/control/elevations/{id}` | — | 204 / 404 | hand the borrowed authority back; the tenant session it opened stops resolving on its next request |
| GET | `/control/elevations?live=&limit=&after=` | — | 200 json / 400 | elevations newest first, one page at a time, with reason, identities and whether each is still live; never the session it opened; `live=false` (the default) is EVERY elevation, live or not |
| GET | `/control/attempts?actor=&action_name=&code=&limit=` | — | 200 json | the instance attempt sink: every refusal belonging to no tenant, plus every one naming a tenant key that resolves to nothing |
| GET | `/control/attempts/export?from=&to=&after_id=&limit=` | — | 200 `application/x-ndjson` | the instance attempt sink over a ≤31-day window, oldest first, one object per line — each naming the tenant key it was refused under — and a final `{"export":{rows, complete[, next_from, next_after_id]}}` line; no session, credential, trace, reason or action name; each export is itself a `control:attempt.export` event; operators only |
| GET | `/control/mcp-calls?since=&tenant=&account=&tool=&code=&errors=&bodies=&before=&limit=` | — | 200 json | the MCP call log: every `tools/call` on either hosted MCP endpoint with its caller, arguments, answer, outcome, duration and sizes, newest first as `{calls, next}` (`before` = the previous `next`; `limit` ≤1000); `errors=true` keeps failed calls, `bodies=false` drops arguments and answers; operators only |
| GET | `/tenants/{key}/whoami` | — | 200 json | the authenticated caller as the engine sees them, minus every secret; a run session also gets `run: {run, may_call}`, the actions its task narrows its writes to (`null`: not narrowed) |
| GET | `/tenants/{key}/invitations` | — | 200 json | every invitation into this tenant that can still be redeemed, newest first; never a secret |
| POST | `/tenants/{key}/invitations` | `{"login"|"email": "...", "kind": "human"|"agent", "roles": [...], "deliver"?: "email"|"none"}` | 201 json / 403 / 404 / 409 / 422 | invite an existing account (`login`) or an email that is not yet one (`email`) into the tenant, and email it unless `deliver` is `none`; each of `roles` is a role's name (`member`, `admin`, a declared one) or id (`role_member`); the `bsi_` secret is in this response and nowhere else, ever again, beside its `delivery` |
| GET | `/tenants/{key}/roles` | — | 200 json / 403 | every role an invitation may name, by `name` and `id`, with `builtin` (`member` and `admin` are always among them); needs `member.invite` |
| DELETE | `/tenants/{key}/invitations/{id}` | — | 204 / 404 | withdraw an invitation, so its secret stops redeeming from the next request on |
| POST | `/tenants/{key}/invitations/{id}/resend` | — | 200 json / 403 / 404 / 422 / 429 / 503 | replace an invitation's secret and email the new one; the old secret stops redeeming, and the new one is in this response, once |
| GET | `/tenants/{key}/principals` | — | 200 json | every principal in the tenant this caller may read, oldest first, each carrying exactly the attributes their readable fields admit; carries no secret |
| DELETE | `/tenants/{key}/principals/{id}` | — | 204 / 404 / 422 | remove a membership — deactivated, not deleted, so the tenant's own history stays readable; the account and its memberships of other tenants are untouched; `422 last_admin` rather than leave the tenant with no ACTIVE admin |
| GET | `/tenants/{key}/principals/{id}/roles` | — | 200 json / 403 / 404 | the role ids this principal holds a membership row for. Your own is always readable; anyone else's needs `role.assign` |
| PUT | `/tenants/{key}/principals/{id}/roles/{role}` | — | 204 / 403 / 404 / 422 | assign a role id; needs `role.assign`, plus `role.assign_admin` for `role_admin`; `422 unknown_role` for an id this metadata version does not declare, and `400 validation_error` for `role_authenticated`, the built-in virtual role nobody holds a row for. Idempotent |
| DELETE | `/tenants/{key}/principals/{id}/roles/{role}` | — | 204 / 403 / 404 / 422 | unassign a role id, idempotently; `422 last_admin` rather than leave the tenant with no ACTIVE admin, and `400 validation_error` for `role_authenticated`, which is virtual and cannot be taken away |
| PUT | `/tenants/{key}/principals/{id}/manager` | `{"manager": UUID|null}` | 200 json / 403 / 404 / 422 | assign or clear a visible Principal manager under direct live principal.manage; atomically update reports_descendants, reject cycles and depth above eight, and audit the change |
| POST | `/tenants/{key}/dev/members` | `{"login", "display_name"?, "roles"}` | 201 / 200 json / 400 / 404 / 422 | **development only** — create (or reuse) a credential-less account and its membership holding `roles` (see "Development mode"); `201` on creation, `200` on reuse |
| POST | `/tenants/{key}/principals/{id}/active` | `{"active": true|false}` | 200 json / 403 / 404 | activate or deactivate under direct `principal.manage` authority and target visibility. Deactivation atomically revokes sessions and grants; return read-projected Principal or only id on visibility loss |
| POST | `/tenants/{key}/installations` | `{"agent_login", "roles"}` | 201 json / 403 / 404 / 409 / 422 | host an agent the caller already owns (`status: "installed"`), or invite its owner's consent (`status: "invited"`, with the invitation's `bsi_` secret); each of `roles` is a role's name or id |
| GET | `/tenants/{key}/rollups` | — | 200 json / 403 | `{rollups}`: every declared rollup with `state` `computing` (an unfinished recompute run covers it; `recompute` names it), `failed` or `ready` (`metadata.read`) |
| POST | `/tenants/{key}/rollups/recomputes` | `{"object"?, "field"?, "reason"?}` | 202 json / 200 json / 403 / 404 / 422 | queue an exact re-fold of every record of one rollup, one object's rollups or (`{}`) the tenant's, run in the background (`metadata.push`): `{recompute}`; `200` names the unfinished run already covering the same scope; `not_a_rollup` |
| GET | `/tenants/{key}/rollups/recomputes` | — | 200 json / 403 | `{recomputes}`, newest first (`metadata.read`) |
| GET | `/tenants/{key}/rollups/recomputes/{id}` | — | 200 json / 403 / 404 | one run: `state` (`pending`, `running`, `done`, `failed` with `error`), `cause`, `scope`, `step` of `steps`, `carriers_scanned`, `carriers_changed` (`metadata.read`) |
| POST | `/tenants/{key}/runs` | `{"task", "input", "idempotency_key"?}` | 201 json / 200 json / 400 / 403 / 404 / 409 | start a run of a declared task (`task.run`; never a run session): `{run}` pending at once; the same `idempotency_key` within 24 hours answers `200` with the run it created; `invalid_input` names the field; `tasks_disabled` where `BASEL_TASKS` is off; a run whose runner name is unbound ends `error` / `runner_not_bound` |
| GET | `/tenants/{key}/runs` | `?task&state&actor&mine&cursor&limit` | 200 json / 400 | `{runs, next_cursor}`, newest first: the caller's own runs, every run with `run.manage` (`mine=true` narrows), a service principal's runs bound to it |
| GET | `/tenants/{key}/runs/{id}` | — | 200 json / 404 | one run: state (`pending`, `active`, `complete`, `error`, `stale`, `cancelled`; `awaiting_input` reserved), attempts, lease, deadline, summary or error, `cost` as its runner reported it, and `transitions` (every change of state: `at`, `from`, `to`, `attempt`, `code`, `actor`); also readable with its own run session |
| GET | `/tenants/{key}/runs/{id}/events` | `?limit&offset` | 200 json / 404 / 422 | `{events}`: the writes the run's sessions made, every attempt, newest first, each as history shows it plus `object` and `record_id`, narrowed to what the caller may read; whoever may read the run |
| POST | `/tenants/{key}/runs/{id}/cancel` | — | 200 json / 403 / 404 | end a run that has not ended `cancelled` and revoke its run session; writes made before stand; own runs, or any with `run.manage` |
| POST | `/tenants/{key}/runs/{id}/claim` | — (runner `bsr_` credential) | 200 json / 401 / 403 / 404 / 409 | a runner takes a pending run: `{lease, lease_expires_at, deadline, heartbeat_secs, session, tenant, mcp_path, run, task, started_by_account, runs_cap_micros}`; `session` is a run session as the bound service principal; `runner_not_bound`, `run_not_pending`, `run_not_due` (before the run's `not_before`), `task_changed` (the run ends `error`) |
| POST | `/tenants/{key}/runs/{id}/heartbeat` | `{"lease"}` (run session) | 200 json / 401 / 403 / 409 | extend the lease and the run session, never past the deadline; `lease_lost` for a superseded lease, `session_revoked` once the run has ended |
| POST | `/tenants/{key}/runs/{id}/complete` | `{"lease", "summary"?, "transcript_url"?, "usage"?, "output"?}` (run session) | 200 json / 400 / 401 / 403 / 409 | end the run `complete` and revoke its session; repeating the same call answers the same run. `usage` is what the run cost, `{cost_micros, …}` of non-negative integer counts, kept on the run as the runner's report (`invalid_usage` otherwise). A `typed_output` task requires `output` (at most 64 KB, checked against its declared fields: `output_required`, `invalid_output`, `output_too_large`, the run staying `active`); Basel then invokes `on_result` with it and answers after: applied, the run is `complete`; refused, it ends `error` / `result_refused`. For a `worker_writes` task `output` is kept as summary data only |
| POST | `/tenants/{key}/runs/{id}/fail` | `{"lease", "code", "message"?, "usage"?}` (run session) | 200 json / 400 / 401 / 403 / 409 | end the run `error` with the worker's `snake_case` code and revoke its session; `usage` as for `complete`. A `typed_output` task's `on_failure`, when declared, is invoked with `code` and `message` first; the run's `result` shows what became of it |
| GET | `/runner/runs` | `?state=pending&limit&cursor` (runner `bsr_` credential) | 200 json / 400 / 401 | a page of the runner's pending runs, `{runs: [{tenant, run, task, runner, created_at}], next_cursor?}`, oldest first, across every tenant that bound it; `cursor` continues after the page that answered it as `next_cursor`, so runs left pending never hide those behind them; a run waiting for its `not_before` is not listed |
| GET | `/.well-known/basel-signing-keys` | — | 200 json | the public keys `push` offers are signed with, a JWK set `{keys: [{kty: OKP, crv: Ed25519, kid, x}]}`, the signing key first; no credential. An offer carries `Basel-Signature: t=<unix>,kid=,sig=<base64>`, Ed25519 over `<t>.<body>`: verify the exact bytes, refuse a `t` more than 300 s off |
| GET | `/tenants/{key}/runners` | — | 200 json / 403 | the tenant's runner bindings (`runner.manage`): name, `builtin`, `kind` (`pull`, `push`, `builtin`), runner account, service principal, doorbell URL, `delivery_url`, the runner's `runner_last_seen_at` and its live `runner_credentials` (prefix, label, created, expires, last used; never a secret); issuing and revoking stay the operator's |
| PUT | `/tenants/{key}/runners/{name}` | `{"runner"?, "service", "doorbell_url"?, "kind"?, "delivery_url"?}` | 200 json / 400 / 403 / 404 | bind a runner name to a runner account (its login) acting as one of this tenant's service members (principal id or login); the doorbell is an `https://` URL rung with one empty `POST`. A built-in runner's name (`basel:email`) is bound with `{service}` alone: Basel runs it, so `runner` or `doorbell_url` is `builtin_runner_binding`; a worker's name without `runner` is `runner_required`. `kind: "push"` with a `delivery_url` (same URL rule as the doorbell, `invalid_delivery_url`) has Basel offer each run there in a signed POST `{type: task_run.offered, run, attempt, tenant, task, input, instructions, api, lease_seconds}`; the worker still claims; no claim in 60 s re-offers it (one attempt), a failed POST retries, then `delivery_failed`; only with `BASEL_TASKS_OUTBOUND_DELIVERY` on |
| DELETE | `/tenants/{key}/runners/{name}` | — | 204 / 403 / 404 | remove a runner binding; its pending runs wait until it is bound again |
| GET | `/tenants/{key}/me/definitions` | `?kind&subject` | 200 json / 401 | your own saved definitions (a personal list view is kind `list_view`, its `subject` the object), newest first, `{definitions: [{id, kind, name, subject, revision, state, updated_at}]}`; ids are `udef_` TypeIDs and nobody else can read them, an administrator included |
| POST | `/tenants/{key}/me/definitions` | `{"kind": "list_view", "name", "body"}` | 201 json / 401 / 409 / 413 / 422 | save a definition as yours; the answer is the definition with `body`, `problems`, `notices` and resolved `columns`, and its `ETag` is the revision to send as `If-Match`; `422 invalid_definition` carries `problems: [{code, element, detail}]`, `409 definition_name_taken`, `413 definition_too_large` |
| POST | `/tenants/{key}/me/definitions/preview` | `{"kind": "list_view", "body", "size"?}` | 200 json / 401 / 413 / 422 | validate an unsaved body and answer its first page (at most 25 rows, no cursor) in the UI query door's shape as you; nothing is stored; refusals as for create |
| GET | `/tenants/{key}/me/definitions/{id}` | — | 200 json / 401 / 404 | one of your definitions, re-resolved against the current model: `state` `ok` or `needs_attention` with `problems`, `notices` for dropped columns; `ETag` is its revision; someone else's id is `404` |
| PUT | `/tenants/{key}/me/definitions/{id}` | `{"name", "body"}` with `If-Match: "<revision>"` | 200 json / 401 / 404 / 409 / 412 / 413 / 422 / 428 | replace a definition and write its next revision; `428` without `If-Match`, `412 precondition_failed` when the revision moved; a valid save restores `state: ok` |
| DELETE | `/tenants/{key}/me/definitions/{id}` | `If-Match: "<revision>"` | 204 / 401 / 404 / 412 / 428 | delete one of your definitions and its revisions |
| POST | `/tenants/{key}/me/definitions/{id}/query` | the UI query door's body (`parameters`, `order_by`, `page`, `include`) | 200 json / 401 / 404 / 409 / 422 | run your list view as you, answering in the UI query door's shape plus `notices`; `409 definition_needs_attention` with `problems` when the model no longer fits it; a cursor from before an edit is `invalid_cursor` |
| GET | `/tenants/{key}/me/settings` | — | 200 json / 401 | your own settings in this tenant, `{default_app?, last_app?, default_views?: {"<app>/<object>": "<view id>"}, column_widths?: {"<app>/<list>": {"<column>": <px>}}}`, `{}` when you have none; a `<list>` is `object:<Object>`, `view:<view id>` or `related:<Object>.<traversal>`, a width a whole number from 40 to 2000; `ETag` is their revision (`"0"` before the first write); nobody else can read them, an administrator included |
| PATCH | `/tenants/{key}/me/settings` | a JSON Merge Patch (RFC 7396) with `If-Match: "<revision>"` | 200 json / 401 / 412 / 413 / 422 / 428 | merge into your settings: a member set to `null` is removed, `default_views` merges key by key and `column_widths` list by list and column by column (a list left with no widths is removed); the first write sends `If-Match: "0"`; answers the merged settings and their new `ETag`; `428` without `If-Match`, `412 precondition_failed` when they moved; `422 invalid_settings` with `problems` (`unknown_setting`, `invalid_setting`, `too_many` past 64 lists or 32 columns in one) for any other key or a wrong shape |
| POST | `/tenants/{key}/services` | `{"login", "display_name", "roles"}` | 201 json / 403 / 409 / 422 | create a service account and its membership in one transaction; each of `roles` is a role's name or id, as for an invitation; answers `{account, principal, roles}`, and `principal` is the `{id}` its credential doors take; a service has no self-service credentials |
| POST | `/tenants/{key}/services/{id}/credentials` | `{"audience": "api"|"git", "label", "expires_at"?}` | 201 json / 403 / 404 / 422 | mint a bearer credential for a service (`{id}` is its membership, the `principal` its creation answered), scoped to this tenant only; the plaintext token is returned once |
| DELETE | `/tenants/{key}/services/{id}/credentials/{credential}` | — | 204 / 404 | revoke one of a service's credentials and every live session it authenticated, in one transaction |
| POST | `/tenants/{key}/objects/{object}/{id}/shares` | `{"grantee": UUID, "actions": [...], "reason": text, "expires_at": optional RFC3339}` | 201 json / 403 / 404 / 422 | transfer current direct actions on a sharing-enabled visible record; no re-sharing. Update fields are privately frozen from transferable permits and the recipient readable fields; receipts omit reason and field evidence |
| GET | `/tenants/{key}/shares` | `?after`, `?limit` | 200 json / 403 / 422 | one page of the live shares this tenant holds, oldest first, under `share.manage`; `limit` defaults to 100 and caps at 500, `next` is the cursor to hand back as `after` (`null` on the last page) and `count` is this page's rows; rows carry the creation receipt's own fields and never the reason, the frozen update fields or the provenance |
| DELETE | `/tenants/{key}/shares/{id}` | — | 204 / 403 / 404 | revoke as the grantor or under direct share.manage; idempotent and atomically audited |
| GET | `/tenants/{key}/grants` | — | 200 json | the delegation grants the caller is a party to, as delegator or delegate, newest first |
| POST | `/tenants/{key}/grants` | `{"delegate", "audience": "api"|"git", "expires_at", "reason", "scope"?}` | 201 json / 403 / 422 | delegate to an agent/service until `expires_at`, which may not outlast the caller's own session; `reason` is mandatory |
| DELETE | `/tenants/{key}/grants/{id}` | — | 204 / 404 | revoke a grant and every session it opened; either party may. A grant you are not party to is `404`, never `403` |
| POST | `/tenants/{key}/grants/{id}/sessions` | — | 201 json / 404 / 422 | open the delegated session: a `bss_` token for the delegate, resolving with the delegator as effective principal |
| GET | `/tenants/{key}/attempts?actor=&action_name=&code=&limit=` | — | 200 json | this tenant's attempt log — every refusal, newest first, with no free text |
| GET | `/tenants/{key}/audit/export?from=&to=&after_id=&limit=` | — | 200 `application/x-ndjson` | the public projection of this tenant's audit (see "Exports" under "Policy") over a ≤31-day window, oldest first, one object per line and a final `{"export":{rows, complete[, next_from, next_after_id]}}` line; no session, credential, trace, reason or parameters; each export is itself a `security:audit.export` event; needs `audit.export` |
| GET | `/tenants/{key}/events?after=&limit=` | — | 200 `{events, next, has_more}` | the tenant's event feed by cursor: committed events in transaction-id order, each as history shows it plus its `object`, `record_id` and `cursor`; `after` is a previous `next` or event `cursor` (or `now` to start at the watermark, which may still yield events committed just before; omitted, the start), `invalid_cursor` otherwise; a page once read never changes, and `next` moves past events withheld from you; fields and records you may not read are withheld as in history; each landed metadata apply is one `metadata:applied` event on `basel:Metadata` whose `proposals` list the plan as `{op: schema, element, object?, attribute?, physical, semantic}` (`physical: writes` rewrote existing rows) and whose `applied` names its `commit`, `model_checksum` and `plan_hash`; accounts-and-access changes (`security:…` events, such as a role assignment) are not on the feed, which `next` moves past too: the security audit carries them (`/audit/export`); `limit` default 100, max 1000; needs `audit.read` |
| GET | `/tenants/{key}/attempts/export?from=&to=&after_id=&limit=` | — | 200 `application/x-ndjson` | this tenant's refusals over a ≤31-day window, oldest first, one object per line and a final `{"export":{rows, complete[, next_from, next_after_id]}}` line; no session, credential, trace, reason or action name; each export is itself a `security:attempt.export` event; needs `security_attempt.export` |
| GET | `/tenants/{key}/git/status` | — | 200 json | canonical `main` oid and metadata-version linkage |
| GET | `/tenants/{key}/git/receives` | — | 200 json | structured receive audit, diagnostics, and phase timings |
| GET | `/git/{key}/info/refs?service=git-upload-pack` | — | 200 Git protocol | smart-HTTP clone/fetch discovery; use `git-receive-pack` for push |
| POST | `/git/{key}/git-upload-pack` | Git protocol bytes | 200 Git protocol | clone/fetch from canonical objects |
| POST | `/git/{key}/git-receive-pack` | Git protocol bytes | 200 Git protocol | authenticated guarded push to protected `main` |
| POST | `/git/{key}/plan` | exact commit/object JSON | 200 json | authenticated preflight; quarantines but never advances `main`; the response's `"advisories"` array is always present (empty when there's nothing to say) — `guard_is_state_predicate` (see "Guards") and `backfill_unused` (see "Metadata grammar and type table") are the only codes — and never blocks this plan or a later apply |
| GET | `/tenants/{key}/reflect` | — | 200 json | all reflected metadata for this tenant |
| GET | `/tenants/{key}/reflect/authority` | — | 200 json / 404 | this tenant's declared authority: roles, permits, readable fields, and assertions (see "Policy") |
| GET | `/tenants/{key}/authz/declared_grant_matrix` | — | 200 json / 403 / 409 | metadata.read: declared role × object × action cells and complete permit conditions; not effective permissions |
| POST | `/tenants/{key}/authz/explain` | `{action, record\|object, version?, patch?, fields?, target?, principal?}` | 200 json | why this actor may or may not do this — the decision and its determining permits for any member; conditions, outcomes, readable fields and the row filter under `authz.explain_full`; another principal or a hidden record under `authz.explain_others`; never writes, and `Cache-Control: no-store` |
| GET | `/tenants/{key}/authz/subjects?action=&object=&record=&after=&limit=` | — | 200 json | who holds `action` on `object` (or on `record`): the exact principals the permits and live shares admit, paged, under the caller's `Principal` readable fields, or `unsupported` naming the permit it cannot reverse; needs `authz.lookup_subjects` |
| GET | `/tenants/{key}/reflect/objects` | — | 200 json | every declared object, summarized |
| GET | `/tenants/{key}/reflect/objects/{Object}` | — | 200 json / 404 | one object: attributes, relationships |
| GET | `/tenants/{key}/reflect/objects/{Object}/attributes/{attr}` | — | 200 json / 404 | one attribute, including its queryable operators |
| GET | `/tenants/{key}/reflect/objects/{Object}/guards` | — | 200 json / 404 | this object's declared guards, verbatim (see "Guards") |
| GET | `/tenants/{key}/reflect/packages` | — | 200 json | installed packages: version, dependencies, provenance and what each contributes, by kind (see "Full names") |
| GET | `/tenants/{key}/reflect/relationships` | — | 200 json | every declared relationship, summarized |
| GET | `/tenants/{key}/reflect/relationships/{Name}` | — | 200 json / 404 | one relationship: endpoints, traversal names, properties (see "Relationships") |
| GET | `/tenants/{key}/reflect/relationships/{Name}/guards` | — | 200 json / 404 | this relationship's declared guards, verbatim (see "Guards") |
| GET | `/tenants/{key}/ui` | — | 200 json / 304 / 404 / 501 | evaluated UI identity, counts, locales, theme, and links |
| GET | `/tenants/{key}/ui/app` | — | 200 json / 304 / 404 / 501 | evaluated app shell: `app`, `title`, `route`, the installed `apps`, navigation, home, theme, presentation `selection`, and root tree |
| GET | `/tenants/{key}/ui/objects` | — | 200 json / 304 / 404 / 501 | localized object-surface listing |
| GET | `/tenants/{key}/ui/objects/{Object}?mode=list|view|create|edit&locale=...&record_id=...` | — | 200 json / 304 / 404 / 422 / 501 | one normalized object surface; with `record_id`, an abstract root's `view` or `edit` serves that record's concrete kind's |
| GET | `/tenants/{key}/ui/pages` | — | 200 json / 304 / 404 / 501 | localized custom-page listing, including pages placed on an object (`placed`) |
| GET | `/tenants/{key}/ui/pages/{page}?locale=...` | — | 200 json / 304 / 404 / 501 | one normalized custom page |
| GET | `/tenants/{key}/ui/components` | — | 200 json / 304 / 404 | installed component catalog |
| GET | `/tenants/{key}/ui/components/{component}@{major}` | — | 200 json / 304 / 404 | complete component manifest and examples |
| POST | `/tenants/{key}/ui/queries/{query_id}` | json + If-Match | 200 json / 404 / 412 / 422 / 428 / 501 | execute an apply-compiled named UI query |
| GET | `/tenants/{key}/search` | ?search=&objects=&per_object=&app= | 200 json / 404 / 422 | a few matching records per searchable object (`groups`, each with `rows` and `has_more`; no totals); see Object views › Search |
| GET | `/tenants/{key}/ui/assets/{logical_name}/{sha256}` | — | 200 asset bytes / 304 / 404 | content-addressed tenant asset, exact bytes; strong digest ETag, `public, max-age=31536000, immutable`; a mismatched logical name/sha256 pair is 404 |
| POST | `/tenants/{key}/ui/artifacts` | raw bytes + `Content-Type` `text/javascript` or `text/css` | 201 json / 200 json / 403 / 413 / 415 / 422 | upload one immutable UI implementation artifact (see "Independent UI releases"): `{sha256, kind, media_type, bytes, url, created}`; idempotent on the same bytes (200, `created: false`); 4 MiB cap; the same signature check as `ui/assets/`; needs `ui.release` |
| GET | `/tenants/{key}/ui/artifacts/{sha256}` | — | 200 artifact bytes / 304 / 404 | content-addressed artifact, exact bytes; strong digest ETag, `public, max-age=31536000, immutable`, `nosniff` |
| GET | `/tenants/{key}/ui/activations` | — | 200 json / 404 | the tenant's UI activation state: `activation_revision` (also the ETag, ready for `If-Match`), `selections` per `<id>@<major>` with `effective`, and the append-only `history` |
| POST | `/tenants/{key}/ui/activations` | json + If-Match | 201 json / 403 / 404 / 412 / 422 / 428 | activate `{component, entry: sha256|null, styles: [sha256], reason[, rollback_of]}` at `If-Match: "<activation_revision>"` (compare-and-set: 412 `stale_activation` names the current revision; 428 without the header); 422 `unknown_component`, `unknown_artifact`, `artifact_kind_mismatch`, `invalid_reason`, `unknown_revision`; needs `ui.release`; each activation is one `ui:release` audit event. Presentation releases use `{selections: [{component, entry, styles, declaration}], reason, expected_ui_checksum, presentation_digest, rollback_of?}`; declaration is the component endpoint's `release_contract`; the complete batch shares one revision |
| POST | `/tenants/{key}/packages/plan` | `{"name"[, "version"]}` | 200 json / 404 / 409 / 422 / 502 / 503 | review installing a Basel Catalog package (by its catalog name, full or short): the server builds the commit `basel upgrade` would (manifest entry, `basel.lock`, `vendor/`) and plans it like a push, changing nothing; `{plan_hash, base_oid, summary: {package, adds, installs, components}, operations, checks, drift, advisories, grants}`, where `grants` is the grant table `basel plan` shows (one row per role, object and action, marked `added`/`removed` against the live generation). 404 `package_not_in_catalog`; 422 `tenant_format_1`, `vendored_format_1_release`; 409 `dependency_conflict`; needs `metadata.push` |
| POST | `/tenants/{key}/packages` | `{"name"[, "version"], "plan_hash"}` | 201 json / 400 / 404 / 409 / 422 | install it: applies the reviewed commit through the push path only if `plan_hash` still matches (409 `plan_changed` with the current hash otherwise), then uploads and activates the package's components with everything active before; `{metadata_version, installed, activated, activation_error, app_route}` |
| POST | `/tenants/{key}/mcp` | one JSON-RPC 2.0 object | 200 json / 202 / 400 / 401 / 403 / 404 / 413 | the hosted MCP endpoint: the agent tool catalog over MCP streamable HTTP, stateless — `initialize`, `ping`, `tools/list`, `tools/call`; a notification is `202`, a batch `-32600`, GET/DELETE `405`. The caller is this door's caller (bearer, or the console cookie with `X-Basel-CSRF`); a present `Origin` must be the public app origin. Each tool runs through the same doors as a direct call; `isError` results carry the failure in `structuredContent` |
| POST | `/tenants/{key}/ui/frames/{component}@{major}` | Origin header | 201 json / 400 / 404 / 409 | mint a frame for an `execution: isolated` component — `frame.url` on the isolated origin with a sealed two-minute ticket; 409 `isolation_unavailable` when no isolated origin is established or it is the caller's own |
| GET | `/tenants/{key}/ui/frames/{component}@{major}` | ?ticket= | 200 html / 404 / 412 | the frame endpoint: no session read, the ticket is the authorization; the isolated page's document under its CSP (`sandbox allow-scripts`, `connect-src 'none'`); 412 `stale_ui` for a ticket sealed under a superseded metadata version |
| GET | `/tenants/{key}/ui/frames/{component}@{major}/assets/{logical_name}/{sha256}` | — | 200 asset bytes / 304 / 404 | the frame asset endpoint: no session, `Access-Control-Allow-Origin: *`; only that component's entry and stylesheets and the tenant's image/font assets, by digest |
| GET | `/tenants/{key}/reflect/ui?app=...` | — | 200 json / 404 | one app's UI source ownership and provenance, topology, query contracts, and evaluated links |
| GET | `/tenants/{key}/reflect/ui/objects/{Object}?app=...` | — | 200 json / 404 | one object view's source and provenance, modes, overlays, queries, and evaluated links |
| GET | `/tenants/{key}/reflect/ui/pages/{page}?app=...` | — | 200 json / 404 | one page's source and provenance, route or placement, queries, and evaluated link |
| GET | `/tenants/{key}/reflect/ui/components` | — | 200 json / 304 / 404 | every component the tenant can use, standard, its own and installed; the same as `/ui/components` |
| GET | `/tenants/{key}/reflect/ui/components/{component}@{major}` | — | 200 json / 304 / 404 | one component's manifest: config schema, bindings, slots, accepted modes, frame and examples |
| GET | `/tenants/{key}/reflect/lifecycles` | — | 200 json | every declared lifecycle, flattened and navigable (see "Actions") |
| GET | `/tenants/{key}/reflect/actions` | — | 200 json | every declared plain action, objects AND relationships (see "Actions") |
| GET | `/tenants/{key}/reflect/invariants` | — | 200 json | every declared invariant, flattened and navigable (see "Aggregates, rollups, and invariants") |
| GET | `/tenants/{key}/reflect/rollups` | — | 200 json | stable rollup topology with metadata-version ETag and diagnostics link |
| GET | `/tenants/{key}/reflect/formulas` | — | 200 json | every declared formula, flattened and navigable, metadata-version ETag (see "Formulas") |
| GET | `/tenants/{key}/reflect/validators` | — | 200 json | every declared admission validator, flattened and navigable, metadata-version ETag (see "Functions") |
| GET | `/tenants/{key}/reflect/functions` | — | 200 json | every declared function (with its role), every `wasm/` binary and its referencing bindings, and every attachment of a function to an action or transition, metadata-version ETag (see "Functions") |
| GET | `/tenants/{key}/reflect/types` | — | 200 json | every declared named scalar type (`types/`), flattened and navigable (see "Metadata grammar and type table") |
| GET | `/tenants/{key}/reflect/types/{name}` | — | 200 json / 404 | one named scalar type's own `base`/`check` (see "Metadata grammar and type table") |
| POST | `/tenants/{key}/queries/{name}` | json | 200 json / 404 / 412 / 422 / 501 | execute a declared named query (`queries/`) by its authored name; If-Match is optional here, unlike the UI endpoint above (see "Metadata grammar and type table") |
| GET | `/tenants/{key}/reflect/queries` | — | 200 json | every declared named query (`queries/`), flattened and navigable (see "Metadata grammar and type table") |
| GET | `/tenants/{key}/reflect/queries/{name}` | — | 200 json / 404 | one named query's own contract (see "Metadata grammar and type table") |
| GET | `/tenants/{key}/reflect/tasks` | — | 200 json | every declared task (`tasks/`), and whether this server enables tasks (`BASEL_TASKS`) |
| GET | `/tenants/{key}/reflect/tasks/{name}` | — | 200 json / 404 | one task: runner, input, instructions, result, timeout, retries, digest |
| GET | `/tenants/{key}/reflect/triggers` | — | 200 json | every declared trigger (`triggers/`), and whether this server enables tasks |
| GET | `/tenants/{key}/reflect/triggers/{name}` | — | 200 json / 404 | one trigger: the event or schedule, the task it starts, its input mapping |
| POST | `/tenants/{key}/functions/{name}` | `{"arguments": {...}, "execution": {"seed": "..."}}` | 200 json / 404 / 422 | invoke one pure function; no audit event (see "Functions") |
| GET | `/tenants/{key}/diagnostics/rollups?limit_events=N` | — | 200 json / 400 | bounded audit-window measurements; no-store and no metadata ETag |
| GET | `/tenants/{key}/diagnostics/feed` | — | 200 json / 403 | the event feed as the run dispatcher reads it: `started`, `read_at`, `consumed_at`, `backlog` (committed events not read yet) and `lag_seconds`; needs `diagnostics.read` |
| GET | `/tenants/{key}/diagnostics/invariants/objects/{Object}/{name}/violations?limit=N&cursor=ID` | — | 200 json / 400 / 404 | paginated current FALSE/NULL records on an object invariant; read-only and no-store |
| GET | `/tenants/{key}/diagnostics/invariants/relationships/{Relationship}/{name}/violations?limit=N&cursor=ID` | — | 200 json / 400 / 404 | paginated current FALSE/NULL links on a relationship invariant; read-only and no-store |
| GET | `/tenants/{key}/metadata` | — | 200 verbatim / 404 | current metadata document, verbatim |
| GET | `/tenants/{key}/metadata/versions` | — | 200 json | metadata history |
| GET | `/tenants/{key}/metadata/versions/{n}` | — | 200 verbatim / 404 / 410 | one historical document, verbatim (an older one rebuilt from its commit; 410 when that no longer reproduces it) |
| POST | `/tenants/{key}/query` | `{"bql": "..."}` | 200 json | BQL in, rows out |
| POST | `/tenants/{key}/objects/{Object}` | `{field: value, ...}` | 201 json + ETag | create one row; the body is the committed row as a GET would read it (formulas evaluated, rollups final); ETag is the new opaque evt_ row version. Send only fields you may set (the surface's `create.writable_fields`): never a numbered or stamped field, which the server fills and the response carries; one sent is refused `422 managed_attribute` naming it |
| GET | `/tenants/{key}/objects/{Object}/{id}` | — | 200 json + ETag / 404 | read one row by id and version — TypeID or bare uuid (see "Ids: TypeID on the wire") |
| PATCH | `/tenants/{key}/objects/{Object}/{id}` | `If-Match: "evt_..."` + `{field: value, ...}` | 200 json + ETag / 404 / 412 / 428 | version-guarded partial update; the body is the committed row as a GET would read it |
| DELETE | `/tenants/{key}/objects/{Object}/{id}` | `If-Match: "evt_..."` | 204 / 404 / 412 / 428 | version-guarded delete |
| POST | `/tenants/{key}/objects/{Object}/{id}/convert` | `If-Match: "evt_..."` + `{"$type": "<Kind>", "fields": {...}, "reason"?: "..."}` | 200 json + ETag / 403 / 404 / 412 / 422 / 428 | version-guarded **conversion**: moves the row to another concrete kind of its family, keeping its id, its prefix and its history. `fields` supplies the destination's own members only — a member both kinds share is retained, and editing one is a PATCH; `reason` is the usual audit envelope field, at the body's top level beside `$type`. Checked as a delete of the old kind AND a create of the new one, so both permits are required |
| GET | `/tenants/{key}/objects/{Object}/{id}/history` | — | 200 json / 404 / 422 | audit history, newest first (see "Actions") |
| POST | `/tenants/{key}/objects/{Object}/{id}/actions/{name}` | `If-Match: "evt_..."` + `{<declared param>: value, ..., "reason"?: "..."}` | 200 json + ETag / 404 / 409 / 412 / 422 / 428 | version-guarded lifecycle transition or plain action (see "Actions"); the body is the committed row as a GET would read it; `?measure=true` runs it under measurement ceilings and rolls back, answering `{measured, outcome, failure?, row?, invocations}` — the cost of every function it ran beside its budgets, a refusal included |
| GET | `/tenants/{key}/invocations?element=&record=&limit=` | — | 200 json / 404 / 422 | the invocation log, newest first: what each function invocation consumed (fuel, rows, host calls, wall, operations) beside the budget it ran under, for committed, refused, and measured invocations alike |
| POST | `/tenants/{key}/proposals` | root, operations, reason? | 200 json / 403 / 404 / 412 / 422 / 428 | atomic imports and administration; proposal.submit plus every operation witness; existing root requires If-Match (see "Raw proposals" below) |

### Control mutations

Instance operators hold authority through live control sessions. An operator is an account holding the `operator` instance role.

These control writes recheck that authority inside their own transaction, against the LOCKED account row rather than a context snapshot, and record sanitized instance security evidence atomically:

- creating an account;
- instance-role and activation changes;
- password resets;
- elevation and revocation;
- tenant lifecycle writes.

Rules for particular writes:

- A managed password reset replaces the account's old password, its reset credentials and its held sessions. It requires an active human or agent account, and refuses a `service`, which is keyed only by the tenant that manages it.
- Revoked or expired source credentials invalidate control sessions, and so does losing the `operator` role.
- Provisioning commits the tenant, its engine principal, the first administrator's invitation and the security event together. No admin account is created, because a tenant's first admin is invited exactly as its second one is.
- Deactivating an account deactivates every membership it holds, in one transaction across every tenant, and refuses `last_admin` in any of them.
- The last active operator cannot lose the role (`last_operator`).
- Elevations require a nonempty reason (at most 500 characters) and a positive TTL capped at one hour. Their tenant session expires no later than the elevation and reaches only that one tenant.
- Control logout is idempotent.

### Raw proposals

`POST /tenants/{key}/proposals` takes a closed object with `root: {object, id?}`, `operations` (1–128), and an optional `reason`.

Record operations:

- `{op: create, object, local_id?, values}`
- `{op: save, object, match_on, local_id?, values}` (see "Save by key")
- `{op: update, object, target, values}`
- `{op: delete, object, target}`

Link operations:

- `{op: link, relationship, from, to, properties?, local_id?, source?}`
- `{op: unlink, relationship, link, source}`

A source is `{target, side: from|to}`; when a link omits it, its from endpoint is selected. A link address is `{kind: id, id}` or `{kind: pair, from, to}` (exactly one instance required).

Addressing rules:

- Targets accept the declared object's TypeID or UUID, or an earlier `$local` alias.
- A link's `from`/`to`, and an unlink pair's, may also name the row by key, `{"match": {...}}` (see "Save by key"); a refusal is at `operations[i].to` or `operations[i].link.to`.
- Record aliases and link aliases have separate namespaces.
- Ordinary ref-valued fields take a concrete ID or a ref by key (see "Save by key"), never a `$local` alias.
- Unknown keys and internal operations are refused.

The root is the first record target or declaring relationship source. An existing root requires a strong `If-Match`; a new root omits id and must be the first create and survive. The precondition asserts only the root version. Every operation still needs its own current authority.

Results contain `event_id`, projected `records`, identity-only `links`, and surviving typed `local_records`/`local_links` maps. One failure rolls back the whole batch.

**Refusals name the operation.** Every refusal's `element` is the position you wrote, so a bad operation at index 37 of 100 says so:

- a field value: `operations[37].values.active` (`.properties.` for a link), with the field's own code and detail;
- a name or alias: `operations[37].object`, `.relationship`, `.target`, `.from`, `.to`, `.local_id`, with the bad name in the detail (`` `$o_nope` names no earlier `create` in this proposal``);
- a target or ref that names no row you can read: `404`, `operations[37].target` or `operations[37].values.owner`. A row that does not exist and one you may not read answer the same.

Field values are checked in every operation before the transaction, and each bad one is listed in `errors[]` (see "Every error at once"), so one round trip shows them all.

### Save by key

Any unique rule without `when` is a key: a field declared `"unique": true`, or a `constraints` entry with `unique: [...]` and no `when`. There is no separate "external id" declaration. An importer keeps the source system's id in a plain unique field (say `import_key`) and writes by it.

**Save.** A create body that carries `"$match_on": ["import_key"]` is a save. If a row you can read holds the same values in exactly those fields, it is updated with the other fields you sent: `200`, with its new `ETag`. Otherwise a row is created: `201`. A save that sends nothing besides the key is `200` with the row unchanged (no event, same `ETag`). The same save sent twice therefore leaves one row.

```json
POST /tenants/{key}/objects/Contact
{"$match_on": ["import_key"], "import_key": "H-123", "name": "Ada", "account": {"match": {"import_key": "H-55"}}}
```

`$match_on` names the fields of exactly one rule, in any order; a multi-field rule such as `unique: [account, term]` is named whole. Every key field must have a non-null value in the body. A save is not conditional on a version you observed: it is refused `invalid_match` when sent with `If-Match`.

**Refs by key.** In any create, update, save or proposal, a `ref` field may name its target as `{"match": {<field>: <value>, …}}` instead of an ID. The fields must be exactly one unique rule of the target object without `when`, and a ref field among them may itself be given by key. The row must exist before the write and be readable to you.

The same holds for a `ref` field of a record written inside a relationship field (an inline create, an envelope's `create`, an envelope's `update` values), refused at that record's position (`accounts[0].region`, `accounts.update[0].values.region`), and for a proposal's link endpoints (see "Raw proposals"). A key never chooses among several rows: fields that are not a unique rule are `no_match_rule`, even when one row happens to match.

**Relationships in a save.** A save body is a create body, so it names a relationship the way a create does: `"party": "<TypeID>"`, `{id, properties}`, or an array of those. When the key matches, each record named is read as "should be linked":

- one already linked to the row is no change, so the same save sent twice converges;
- one not yet linked is linked;
- on a to-one field, a record other than the one linked now moves the row to it, unless that end declares `reparent: refuse`: then the save is refused `reparent_refused` at the field (`party`);
- links the body does not name are never removed. To unlink, update with the envelope.

A field written as the update envelope (`{"link": [...], "unlink": [...]}`) is applied as an update's would be. Refused `validation_error` on a matched save, since no reading of them converges: an inline object (it would create a related record on every send), `properties` for a record already linked, and `null` for a to-one field that holds a link. A `ref` field is not a relationship; it is a column and is simply written.

**Concurrency.** The match and the write are separate steps. An update carries the version the match saw, so a row that changes in between is matched again, not overwritten. A create that loses to another saver of the same key is refused by the unique rule and becomes an update of the winner's row. A save makes at most three such attempts.

**Rows you cannot read** are never found. A ref by key to one is `match_not_found`; a save of its key tries to create and is refused `constraint_violated`, exactly as a plain create would be.

**A key on a child row, or an object in a subtype family.** `$match_on` names the object's own fields, and a member of a subtype family has no save by key yet (`match_not_supported`). A contact whose key is its email address, held on an `EmailAddress` row linked to the contact, is both. Capture it in three steps instead:

1. Look the key up on the child: `SELECT party.id FROM EmailAddress WHERE LOWER(address) = 'ada@example.org'` (an `Email` key ignores letter case, as the unique rule does; BQL's `=` does not).
2. Found: update that parent by id, with `If-Match`. Add contact points that are new with the update envelope (`{"emails": {"create": [...]}}`), after checking which are already there.
3. Not found: create the parent with the child nested, in one write: `POST /objects/Contact {"name": "Ada", "emails": [{"address": "ada@example.org"}]}`.

This never makes two contacts for one key: the child's unique rule refuses a create that repeats it, `constraint_violated` at `EmailAddress.constraints.<rule>`, and the whole write rolls back, parent included. Two captures racing on a new key end with one `201` and the others refused. On that refusal, go back to step 1: the winner's row is there now. The child itself is a plain object, so it saves by key (`POST /objects/EmailAddress {"$match_on": ["address"], "address": …, "party": "<id>"}`), and a nested child's `ref` fields take refs by key (`"platform": {"match": {"code": "github"}}`).

A key is matched exactly as stored, except that an `Email` member matches whatever its letter case, as its unique rule compares it: `Ada@Example.org` finds the row stored as `ada@example.org`. Normalize any other key (trim it, settle its case) before you look it up or write it.

**In a proposal**, `{op: save, object, match_on, local_id?, values}` becomes an update of the matched row or a create. A later operation may address it by `$local_id` either way. A first-operation save that matches becomes the existing root, at the version the match saw, with no `If-Match`. The response adds `saved`: one `{operation, object, id, outcome}` per save, `outcome` being `created` or `updated`. A matched save that sends only its key writes the key's own values. Saving the same key twice in one proposal is `duplicate_match`.

Refusals, all `422`:

- `no_match_rule`: no unique rule covers exactly those fields; the detail lists the rules that can.
- `match_rule_conditioned`: the only rule on those fields has a `when`, so it does not prove one row.
- `match_value_missing`: a key field is absent or null.
- `match_not_found`: a ref by key names no row you can read.
- `match_ambiguous`: more than one row carries the key. Only rows whose `Email` member differs in letter case and were written before that member compared case-insensitively can; merge them, and the rule's next apply tightens it.
- `match_not_supported`: the object is built in or a member of a subtype family (for a family member, see the child-row capture under "Save by key").
- `invalid_match`: a malformed `$match_on`, `match_on` or `{"match": …}` value.
- `reparent_refused`: a matched save names a different record for a to-one field whose end declares `reparent: refuse`.

### Status code vocabulary

- `200`/`201`/`204`: success.
- `304`: an evaluated `/ui` metadata request whose `If-None-Match` matches its locale-and-surface ETag (empty body, `ETag` still set).
- `400`: a malformed request body, or a BQL parse or compile error.
- `401`: an authentication refusal, uniformly `unauthenticated`, or the self-naming `audience_mismatch` or `control_session_required` (see "Authentication").
- `403 forbidden`: an authenticated caller was refused an operation.
- `404`: unknown tenant, object, attribute, or row.
- `409`: a concurrent-change conflict (a stale Git base, candidate, or approval, or two pushes racing), or a wrong-from action invocation: the record isn't currently in one of the invoked transition's declared `from` states (see "Actions").
- `415 unsupported_media_type`: a JSON endpoint was handed a body that did not declare `application/json`.
- `422`: a validation failure (for example `validation_error`, or `invalid_bind` for a value that doesn't match its attribute's type), a refused plan, or a refused guard (`guard_failed`, see "Error shape").
- `429 rate_limited`: the authentication flood gates.
- `500`: an internal error, logged server-side and never leaked into the response body.
- `503 superseded` (`/health` only): another instance has claimed the singleton epoch. That instance is now the live one, and this one is shutting down.

## Authentication

Every `/tenants/{key}/...` route authenticates, and so does every `/accounts/...` and `/control/...` route.

### Open endpoints

Nine endpoints do not authenticate, because each one is where authentication comes from:

- `POST /accounts/sessions`
- `POST /accounts/password-resets`
- `POST /accounts/password-resets/complete`
- `POST /accounts/invitations/accept`
- `POST /accounts/signup`
- `POST /accounts/verify`
- `POST /accounts/device/authorizations`
- `POST /accounts/device/token`
- `POST /control/sessions`

The pages `GET /signup`, `GET /verify`, `GET /invite`, `GET /device`, `GET /forgot` and `GET /reset` are open too. A dev-mode server adds two more, for the same reason (see "Development mode"); they are absent from every other instance. `GET /`, `/health`, and `/abi/...` are open because they describe the engine, not a tenant.

The two tenant-*management* endpoints (`GET /tenants`, `DELETE /tenants/{key}`) take a **control** session rather than a tenant one: a tenant's own administrator does not get to create or delete tenants. A live account session (`bss_`) at any control endpoint is refused `401 control_session_required`, which says to open a control session with `POST /control/sessions`.

**Authenticating is not being authorized.** Tenant policies govern actor-facing reads and the implemented write paths described under "Policy" below. Existing-record mutation targets are checked through the caller's read filter; hidden targets answer `404`. An admitted action may compute and act on internal records beyond its caller's read scope, while its result and failure channels obey public projection rules. Authentication alone grants no operation.

### The exchange

`POST /accounts/sessions` trades a credential for a session, and it is the only exchange there is. Identity is an ACCOUNT in the control plane rather than a login inside one tenant, so there is no per-tenant `POST /tenants/{key}/sessions`.

The body is either `{"login": "...", "password": "..."}` or `{"token": "<bst_ or bsg_ credential token>"}`, optionally with `"profile": "ui"`. A person's login is their email address, so `"email"` is accepted in place of `"login"`; case does not matter. `POST /control/sessions` takes the same. Content type must be `application/json` (`415 unsupported_media_type` otherwise, on this and every other JSON endpoint).

Without a profile the answer is `201 {"token": "bss_...", "expires_at": "...", "account": {...}}`, and the token is yours to send as `Authorization: Bearer <token>`. This is the agent and CLI path.

A session token is **not** the credential token. The exchange takes the long-lived credential; the session is what every other endpoint accepts; and `POST /accounts/sessions` is the only place the two meet.

#### One session reaches every tenant the account belongs to

The session belongs to the account. A request to `/tenants/{key}/...` resolves it to that account's MEMBERSHIP in that tenant. The membership is a different principal id in each tenant and is checked under that tenant's own roles. `GET /accounts/me/memberships` names them.

Two things narrow the reach:

- the credential behind the session carries a `tenant_scope` (one tenant key, or `*` for every current membership);
- a session opened under a delegation grant or an elevation is bound to that one tenant for the whole of its life.

A tenant the account is not a member of answers the same `404` a tenant that does not exist answers, byte for byte, so membership is never disclosed to a non-member. Two answers are for members only, since they tell a member nothing it does not know: the account's own session at a tenant where its membership was deactivated (or removed) is refused `403 membership_inactive`, so ask a tenant admin to reactivate it; and a path under your own tenant that matches no route is `404 unknown_route`, naming the path, so check the URL.

#### Browser sessions

With `"profile": "ui"` the answer is `201 {"expires_at", "account"}` with **no** token in the body, and two cookies beside it: `basel_session` (`HttpOnly`, the session token itself) and `basel_csrf` (readable by the page's own script). A browser therefore never stores a bearer token.

Every unsafe method behind a cookie session must echo the CSRF value in an `X-Basel-CSRF` header. Omitting it is refused `403 csrf_required`; a wrong value is the uniform `401`. The server compares the header against a digest on the session row, not against the cookie beside it, so setting both cookies is not enough for a cross-site attacker. `GET` and `HEAD` need no header.

The profile chooses the SHAPE of the answer, never the audience the credential was issued at. It is legal for a password login or an `api` credential only, so a transport-only `git` credential cannot become a twelve-hour cookie session.

#### Lifetimes and limits

A bearer header wins over a cookie when a request somehow carries both.

Session lifetimes are absolute:

- `api`: one hour;
- `ui`: twelve hours, plus a thirty-minute idle window that slides on use;
- `git`: five minutes;
- control session: one hour.

An ACCOUNT may hold at most 20 active sessions across every audience at once; opening the twenty-first evicts the oldest.

### Audiences and token prefixes

Every credential and every session is scoped to one of five audiences: `api`, `git`, `ui`, `control`, `runner` (a runner account's credential, which claims runs; see "Tasks and triggers"). Every bearer secret announces its kind in its own first four characters, so a leaked string is identifiable without being verifiable. The secret half (everything after the `.`) is never stored: the engine keeps a keyed digest and the public prefix only.

| Prefix | What it is | Which endpoints it opens |
|---|---|---|
| `bss_` | an ACCOUNT session (`api` or `ui` audience), minted by the exchange | every `/accounts/...` endpoint and every `/tenants/{key}/...` endpoint its account is a member of, at its own audience only |
| `bst_` | an `api` credential — long-lived, issued once and shown once | the exchange; trade it for a `bss_` session at `api` or, with `profile: "ui"`, at `ui` |
| `bsg_` | a `git` credential | Git smart-HTTP (`/git/{key}/...`), as `Bearer` or as the password half of `Basic`; and the exchange, which yields a `git`-audience session |
| `bcs_` | a control session, minted by `POST /control/sessions` | `/control/...`, plus `GET /tenants` and `DELETE /tenants/{key}` |
| `bse_` | a one-time password-reset secret: valid 24 hours when an operator issues it, 1 hour when a person asks for it themselves, 7 days in an operator's server invitation | `POST /accounts/password-resets/complete`, exactly once |
| `bsr_` | a `runner` credential, issued by an operator for a runner account | listing pending runs (`GET /runner/runs`) and claiming one (`POST /tenants/{key}/runs/{id}/claim`); the claim answers a run session for the work itself |
| `bsi_` | a one-time tenant INVITATION secret — the bearer half of the invitation that creates a membership | `POST /accounts/invitations/accept`, exactly once, and in the request BODY rather than the path |

Beside its audience, every TOKEN credential names the tenants it may be presented to. `tenant_scope` is one tenant key, or `*` for every current membership, chosen at issue and never edited. A scope naming a tenant the account holds no active membership in is refused at issue (`not_member`) rather than handed over as a key that opens nothing. A password carries no scope at all: `tenant_scope` is NULL for a password credential and, by a table constraint, for nothing else.

Audiences do not overlap and do not fall back:

- A `git`-audience session presented at a data-plane endpoint is refused `401 audience_mismatch`. It names itself because its holder already has a valid session and telling them saves an unbounded retry loop. For the same reason an account session at a control endpoint is refused `401 control_session_required`.
- A session whose credential is scoped to tenant A, presented at tenant B, gets the silent `401 unauthenticated`. So does a borrowed session presented outside the one tenant it was borrowed in.
- A tenant the account is not a member of, and a tenant that does not exist, are one `404`.

### Who you are, and logging out

`GET /tenants/{key}/whoami` answers with the caller as the engine sees them:

- `tenant`;
- `account`: the instance identity behind the membership (`id`, `login`, `kind`);
- `effective_principal`, `acting_principal`, `delegation_grant`, `elevation`;
- `session`: id, audience, method, expiry;
- `method`, `audience`, `metadata_version`: the tenant's metadata version the caller's authority was resolved under (every apply moves it);
- the caller's own `security_facts`.

**Breaking change, 2026-10-30.** The version key that `whoami`, a session, explain, the subjects listing and the declared grant matrix answer was `policy_version`; it is now `metadata_version`. Audit, history and attempt rows answer it as `actor_metadata_version`, since a history event's own `metadata_version` is the version the write committed under. A `409`'s `diff` says `session_metadata_version` and `current_metadata_version` where it said `session_policy_version` and `current_policy_version`. No old key is answered any more, and a page cursor issued before the change is refused `invalid_cursor`: start the query again from its first page.

Two memberships of the same account carry the same `account.id` and different principal ids. That is how a client tells one person in two tenants from two people.

`whoami` carries **no** secret of any kind: no token, no verifier, no CSRF value, not even the credential id, which a caller learns from the exchange that issued it rather than from an endpoint any page script can call. It carries no email and no instance role either; those are control-plane facts, answered at the account endpoints. `GET /control/whoami` is its control-plane twin.

Above the tenant, `GET /accounts/me` answers with the account itself: id, login, email, display name, kind, instance roles. `GET /accounts/me/memberships` lists every tenant this one session reaches, with the membership id, display name and role ids it carries in each. That listing is what a console's tenant switcher is built from, and it is the only endpoint that says which `/tenants/{key}/...` paths a token opens.

`DELETE /accounts/sessions/current` revokes the session the request itself authenticated with and, for a cookie session, clears both cookies. **Logging out logs you out of every tenant at once**: the session row lives in the control plane and every tenant reads it there, so there is no per-tenant logout to forget. It is idempotent: `204` even when there is no session row behind the context (development mode). `DELETE /control/sessions/current` is its control-plane twin.

### Invitations: where an account comes from

An account comes from an INVITATION, from an operator, or, with an operator's access code, from signing up (see "Sign-up with an access code" below). A tenant membership is created by accepting an invitation, or by creating a tenant of your own.

#### Inviting

A member holding the tenant action `member.invite` posts `POST /tenants/{key}/invitations` with:

- either a `login` (an account that must already exist) or an `email` (one that need not);
- a `kind` of `human` or `agent`;
- the `roles` to assign on acceptance, each by its name (`admin`, `viewer`, `crm:contact_user`) or its id (`role_admin`). Assigning `admin` needs `role.assign_admin` as well.

An unknown role is `422 unknown_role`, and its `detail` lists every role this tenant's policy declares as `name (id)`. `GET /tenants/{key}/roles` answers the same list as `{"roles": [{"name", "id", "builtin"}]}`, for a caller holding `member.invite`.

The response carries the one-time `bsi_` secret exactly once. Basel also emails the invitation (see "Invitations by email" below), so a script, an agent or a person can still pass the secret on by hand. `GET /tenants/{key}/invitations` lists the ones that can still be redeemed, each with its `delivery`. `DELETE .../{id}` withdraws one, so its secret stops redeeming from the next request on.

#### Accepting

Acceptance is `POST /accounts/invitations/accept`, and **the secret rides in the body**, never in the path. A URL reaches a reverse proxy's access log, a browser's history and a `Referer` header, none of which Basel controls. There are two paths through one endpoint.

With a session, the body is `{"secret"}`. The caller's own account joins, and the invitation must have been issued to exactly them.

Without a session, the body is `{"secret", "password", "display_name"}` (optionally `"profile": "ui"`). The invitation's email becomes a NEW account whose login is that address:

- a `"login"` given beside it must be the same address (`422 login_is_email`);
- `display_name` may not be blank (`422 display_name_required`);
- an agent invitation's new account still names a `"login"` of its own.

The new account is created, joined to the tenant, given its roles and handed its first session, all in one transaction, so a taken login leaves neither a half-made account nor a spent invitation.

A request that presents a credential at all takes the first path even if that credential is dead, and gets the uniform `401`: a session that expired must never quietly become a second account.

A signed-in person can also join without the secret. `GET /accounts/me/invitations` lists the live invitations addressed to them: to their account, to their login, or to their email address once that address is **verified**. `POST /accounts/me/invitations/{id}/accept` joins (`201`, the same answer as above), and `POST /accounts/me/invitations/{id}/decline` withdraws one (`204`, audited `security:invitation.decline`). Any id that is not the caller's, whether unknown, in a deleted tenant or addressed to somebody else, is one `404`. An agent's invitation is not listed; its owner redeems it with the secret.

Acceptance runs under the tenant's own version lock, because the membership it writes is stamped with the metadata version its roles were resolved under. A metadata apply that commits mid-acceptance is `409 model_changed`; retry with the same secret. On success the tenant records `security:member.join` and `security:role.assign`. The answer names the tenant key, the roles, and the MEMBERSHIP id that every tenant endpoint and every policy condition is keyed on.

#### Logins

A person's login is their email address. Sign-up, an email invitation's new account and an operator's `POST /control/accounts` for a `human` all set it to the (trimmed, lower-cased) address, up to 254 characters. There is no separate username.

Agents and services keep short logins of their own: 3–39 lowercase letters, digits and hyphens, never an address. So does the built-in `control-admin`.

A person whose login predates this rule keeps it until an operator renames it with `PUT /control/accounts/{id}/login {"login": "<address>"}` (audited `control:account.login`).

An invitation by `login` that names an address is an invitation by `email`. It finds an account only through a verified address, so an account that merely holds an address as its login cannot collect an invitation meant for the mailbox's owner.

Members of a tenant see each other's logins (so, for people, each other's addresses) and display names.

#### Acceptance refusals

Ten refusals, and none of them discloses whether a login or an email exists to anyone but the inviter.

| Status | `code` | When |
|---|---|---|
| 422 | `invitation_invalid` | the secret is unparsable, names no invitation, or fails its digest — one answer for all three |
| 422 | `invitation_expired` | past its `expires_at` |
| 422 | `invitation_consumed` | already accepted, or withdrawn |
| 422 | `invitation_mismatch` | the caller is not the invitee; it names nobody |
| 422 | `managed_account` | the invitee is an account another tenant manages |
| 409 | `login_taken` | the invited address is already some account's login |
| 422 | `login_is_email` | a `login` given on the new-account path is not the invited address |
| 422 | `display_name_required` | the new account's display name is blank |
| 409 | `already_member` | that account already holds a membership here |
| 409 | `conflict` | a metadata apply committed mid-acceptance; retry |

The last two are `409` rather than `422` on purpose: the request was well formed and the world disagreed with it.

Passwords must be 8–256 characters and are checked against a blocklist; a refusal is `weak_password`.

A live EMAIL invitation withdraws itself after five failed acceptances, so the new-account path cannot be walked as an unbounded probe for which logins are taken.

Whether a login exists is disclosed in exactly three places:

- to an inviter naming one;
- to an account naming an agent at `POST /accounts/me/agents`;
- to the holder of a valid access code signing up with an address that is already a login.

The first two are rate-limited, per account and per source address. For the third, failed code redemptions are limited per source address.

### Agents and services

An agent is an account a person owns. `POST /accounts/me/agents` mints one under the caller's own direct live authority, joined to nothing. `GET /accounts/me/agents` lists the caller's own, and `DELETE /accounts/me/agents/{id}` deletes one with its credentials, sessions and elevations; an agent still a member of a tenant is refused (`422 account_has_memberships`, naming the tenants) until it is removed there, and another owner's agent is `404`.

A tenant hosts an agent with `POST /tenants/{key}/installations`, which needs `member.invite` and the owner's consent. Install your own agent and the membership is created outright (`status: "installed"`). Install somebody else's and the owner gets an invitation to accept on the agent's behalf (`status: "invited"`).

A service is the other shape. `POST /tenants/{key}/services` creates an account this tenant MANAGES, together with its membership, in one transaction. A service is a member of that tenant and of nowhere else. Its `roles`, like an installation's and an invitation's, name each role by its name (`desk`) or its id (`role_desk`); an unknown one is `422 unknown_role`, listing the roles the policy declares.

A service manages none of its own keys. `POST /tenants/{key}/services/{id}/credentials` and its revoke twin, where `{id}` is the service's membership (the `principal` the creation answered), are the only endpoints that issue and cut them, under `member.invite` and direct live authority, always scoped to this tenant.

A service may still open a session and read `GET /accounts/me` and its own credential summaries; every other account-plane lifecycle endpoint answers `403`. Asked for at a tenant that does not manage it, a service is `404`, like anyone else who is not a member.

### The first member of a new tenant

`POST /control/tenants` with `{"key", "admin": {"login"} | {"email"}}` provisions the tenant, seeds ONLY the engine principal, and mints the first administrator's invitation, in the same transaction.

The invitation is then emailed as a tenant invitation is (see "Invitations by email"), unless the body says `"deliver": "none"`; the answer's `delivery` says how that went, and a mail problem never fails the request. That response and the email are the only places its `bsi_` secret appears, and redeeming it is the first thing anyone does with a new tenant.

An operator can also invite a person to the server itself: `POST /control/accounts` with `{"kind": "human", "display_name", "email", "invite": true}` creates the account and emails a set-password link, `{BASEL_PUBLIC_ACCOUNT_URL}/reset#<bse_ secret>`, valid for 7 days. The answer adds `invite: {secret, expires_at, delivery}`. Setting the password through that link (the `/reset` page, or `POST /accounts/password-resets/complete`) after a `sent` email also verifies the address. An agent, or an account that already has a password, cannot be invited (`invite_requires_email`, `invite_not_needed`). The CLI spelling is `basel tenants create <key> --admin-login <login>` or `--admin-email <address>`.

A person who forgot their password asks for a link themselves: `POST /accounts/password-resets {"email"}` (or the `/forgot` page, linked from the console's sign-in) answers `202` with the same body for every address. When a person's active account has that address verified, it emails `{BASEL_PUBLIC_ACCOUNT_URL}/reset#<bse_ secret>`, good once for an hour; asking again withdraws the earlier link. Asking changes nothing else. Setting the new password at `POST /accounts/password-resets/complete` revokes the old password and every session the account holds. Requests are limited per client (`429`), per account and per address (silently, the answer unchanged); a server with no mail provider refuses `503 mail_not_configured`. Audited as `account:password.reset_request` and `account:password.reset_complete`.

### The rest of the identity lifecycle

The rest of the identity lifecycle is split the way the entities are: some endpoints act on the ACCOUNT, others on a MEMBERSHIP.

#### On the account

- `POST /accounts/me/credentials` mints a bearer credential, `{"audience": "api"|"git"|"control", "tenant_scope": "<key>"|"*", "label": "...", "expires_at"?: "<RFC 3339>"}`, returning the plaintext exactly once.
- `DELETE /accounts/me/credentials/{id}` revokes it and every live session it authenticated.
- `POST .../{id}/rotate` replaces it with a successor carrying the same audience, scope and label and inheriting its expiry. It revokes the predecessor and its sessions in the same transaction.
- `POST /accounts/me/password` changes the password and closes every other session of the account.

All four need DIRECT live authority: a delegated or elevated session manages no durable credential, not even its own. A `control` audience is checked against the `operator` role on the LOCKED account row, not against the snapshot in the caller's context.

#### On the membership

- `GET /tenants/{key}/principals` is the roster.
- `POST /tenants/{key}/principals/{id}/active` deactivates and reactivates, under direct `principal.manage`.
- `DELETE /tenants/{key}/principals/{id}` removes a member. The member is deactivated, never deleted, so the tenant's own history stays readable, and the ACCOUNT and its memberships of other tenants are untouched.

Neither endpoint will leave a tenant with no active `role_admin`: that is `422 last_admin`.

#### Instance-wide

- `POST /control/accounts/{id}/active` deactivates an account across EVERY tenant in one transaction. A `last_admin` anywhere undoes the whole thing.
- `POST /control/accounts/{id}/instance-roles` grants or revokes `operator`, refusing `last_operator` for the last one.
- `DELETE /control/accounts/{id}` deletes an account outright, with its credentials, sessions and elevations. It refuses (`422`) the caller, an instance-role holder, a service whose tenant is live, an owner of other accounts and an active member of any tenant, each naming what to do first.

Deactivation retains display names, so history stays attributable.

### Invitations by email

`POST /tenants/{key}/invitations` emails the invitation from the server's configured sender, in fixed platform wording: the tenant, the inviter's display name, when it expires, and a link.

Who gets the email:

- an invitation by `email` goes to that address;
- one by `login` goes to the account's verified address, if it has one;
- an agent invitation is never emailed;
- `"deliver": "none"` in the request skips the email.

The answer carries `delivery`: `{"status", "code"?, "to"?, "at"}`. `status` is one of:

- `sent`;
- `failed`, with the provider's `code`, or `mail_rate_limited`;
- `not_sent`, where `code` says why: `opted_out`, `agent`, `no_verified_email`;
- `not_configured`: the server has no mail provider.

A failed email never fails the invitation. Each row of `GET /tenants/{key}/invitations` carries the same `delivery`, or `null` when nobody tried to email it.

#### The invitation link

The link is `{BASEL_PUBLIC_ACCOUNT_URL}/invite#bsi_...`. The secret is in the fragment, which a browser never sends to a server, so it reaches no log and no `Referer`.

The page at `GET /invite` reads the fragment and asks `POST /accounts/invitations/preview {"secret"}` what it is for. The preview answers `tenant`, `roles`, `kind`, `target_kind`, `new_account`, `invited_by` (the inviter's display name, when one was recorded), `expires_at`, and `open`, the tenant's address.

The page then offers three choices, each of which posts the secret in a request body to `POST /accounts/invitations/accept`:

- join as the signed-in account;
- create an account (login, display name, password), only for an email invitation no account answered;
- sign in and join.

An account created this way from an invitation that was emailed has that address set and **verified**, since receiving the email proves it. It has a tenant allowance of **0**: it can join the tenant but create none of its own until an operator or an access code grants some. No access code is needed.

#### Resending

`POST /tenants/{key}/invitations/{id}/resend` replaces the invitation's secret (the old one stops redeeming at once) and emails the new one. The answer is the invitation again, with its new `secret` (once) and `delivery`, and it is good for another seven days. It needs the same authority as inviting.

It refuses before changing anything:

- `404` for an invitation that is not live;
- `422 invitation_not_deliverable` for one with nowhere to send it;
- `503 mail_not_configured`;
- `429` when the address has had its hourly mail.

### Sign-up with an access code

An operator can let people make their own accounts. `POST /control/access-codes` with `{"label"?, "max_uses"?, "tenant_allowance"?, "template"?, "expires_at"?}` mints an **access code**: six lowercase words joined by hyphens (`maple-river-quiet-falcon-tundra-velvet`), generated by the server.

A code is good for `max_uses` sign-ups (default 1) until `expires_at` (default never). Each account it creates starts with a tenant allowance of `tenant_allowance` (default 1), or, when the code names a **template**, with everything the template grants.

#### Sign-up templates

A template is what a sign-up starts with, named so an operator can reuse it: a tenant allowance, Ask Basel's switch and monthly cap (in dollars, across every tenant), and the monthly cap on task-run spending every tenant the account creates starts with (`null`: the Ask Basel Worker's default).

`POST /control/account-templates` with `{"name", "description"?, "tenant_allowance"?, "ask_basel"?: {"enabled", "monthly_cap_usd"}, "runs"?: {"monthly_cap_usd"}}` creates one; `GET` lists them with how many codes and accounts name each; `PUT` and `DELETE /control/account-templates/{id}` edit and remove one. A template is deleted only while no code that can still be redeemed names it (`422 template_in_use`); spent codes and stamped accounts keep their rows.

A code minted with `"template"` (in place of `"tenant_allowance"`) stamps the template onto every account it makes, and a tenant such an account creates takes the stamped runs cap. Editing a template changes future sign-ups only; `PUT /control/accounts/{id}/template {"template"}` stamps one onto an account that already exists (tenants it already has are untouched).

#### Signing up

`POST /accounts/signup` with `{"code", "email", "password", "display_name"}` creates an **unverified** account whose login is that address, and emails a verification link. `display_name` is required; a `"login"`, if sent at all, must be the same address. Case, spaces and hyphens in the code do not matter.

The page at `GET /signup` is a form for it. After signing up it signs the browser in, so the person can send the link again or send it to a corrected address.

#### Verifying the address

The link opens `GET /verify` on the server's account origin (`BASEL_PUBLIC_ACCOUNT_URL`) with the token in its fragment, `#bsv_...`. That page posts it to `POST /accounts/verify {"token"}`; a script can do the same.

The answer is `{"account_id", "login", "email", "next"}`, where `next` is the tenant side's public origin (`BASEL_PUBLIC_APP_URL`, followed by `/`). The page says "Email verified" and goes there. A failed verification stays on the page with its named refusal.

A sign-up started from the CLI's sign-in page may send `"device"`, the request's user code. The link is then `/verify#bsv_...&device=XXXX-XXXX`. After verifying, the page returns a browser signed in as that account to `/device#XXXX-XXXX` to approve the CLI. Any other browser is told to go back to the window it started in: the link verifies an address; it never signs anyone in.

A token is single use and good for 24 hours. `POST /accounts/me/email-verification` sends a new one and withdraws the old.

The account signs in with the address at once. The address becomes the account's `email` (the one email invitations find it by) only when verified.

Because the address is the login, a second sign-up with it is `409 login_taken`, which only a code holder can ask. An address one account has verified is `409 email_taken` to another account verifying it.

`POST /accounts/me/email {"email"}` changes a person's address. It mails a link to the new address, and only when that link is opened does the address become the account's `email` and its login; until then the old one stands.

#### Creating tenants

An unverified account can sign in and do everything an account can, except create tenants. A verified one creates tenants for itself, up to its allowance:

- `POST /accounts/me/tenants {"key"}` creates one with the caller as its administrator, with no invitation. It answers with the tenant, the caller's membership id, its `api` base and its `git_remote`.
- `GET /accounts/me/tenants` lists them with `tenant_allowance`, `tenants_used` and `email_verified`.
- `DELETE /accounts/me/tenants/{key}` with `{"confirm": "<key>"}` deletes one permanently (the same deletion as `DELETE /tenants/{key}`) and frees its place. A tenant the caller did not create answers `404`.
- An operator changes an allowance with `PUT /control/accounts/{id}/tenant-allowance {"tenant_allowance"}`, or stamps a whole template with `PUT /control/accounts/{id}/template`.
- A reached quota is emailed once a calendar month to the account's verified address: the tenant allowance when `POST /accounts/me/tenants` refuses `tenant_allowance_reached`, the Ask Basel cap when the Worker refuses a chat (it reports the refusal, as the person, to `POST /accounts/me/quota-notices`), and a tenant's runs cap when one of its runs fails `cap_reached` (mailed to the tenant's owner). The refusal itself is unchanged.

The CLI's `basel tenants create|list|delete` use these endpoints when the token is an account's, and the operator's endpoints when it is a control session.

#### Sign-up refusals

| Status | `code` | When |
|---|---|---|
| `422` | `access_code_invalid` | the code is unknown, malformed or revoked — one answer for all three |
| `422` | `access_code_expired` | the code is past its `expires_at` |
| `422` | `access_code_used_up` | the code has been used `max_uses` times |
| `409` | `login_taken` | the address is already some account's login (asked only after the code is good) |
| `422` | `login_is_email` | a `login` was sent and is not the same address |
| `422` | `display_name_required` | the display name is missing or blank |
| `409` | `email_unchanged` | changing to the address already verified |
| `429` | `rate_limited` | too many failed code redemptions from this address |
| `503` | `mail_not_configured` | this server has no mail provider; nothing was created |
| `422` | `verification_invalid` / `verification_expired` | the token is unknown or used / past its 24 hours |
| `409` | `email_taken` | another account has verified this address |
| `403` | `email_not_verified` | creating a tenant before verifying |
| `403` | `tenant_allowance_reached` | the account already has as many tenants as its allowance |

Every step is audited in the instance's security events: `control:access_code.mint`, `control:access_code.revoke`, `control:account.tenant_allowance`, `account:signup`, `account:access_code.use`, `account:email.verify`, `account:tenant.create` and `account:tenant.delete`.

### Signing the CLI in through the browser

`basel auth login` with no `--login` signs the CLI in without anyone typing a password into a terminal or copying a token.

It prints a link and an eight-letter code (`WDJB-MJHT`) and opens the browser. Use `--no-browser` for an agent or a machine without one: show the person the link and the code, and wait. The person, in their own browser, signs in (or signs up with an access code, or joins a tenant from an invitation link) and approves. The CLI then stores its own credential and says where; it never prints it.

**If you are an AI agent:** run `basel auth login --no-browser`, give the person the link and the code, and wait for the command to finish. You never handle a password or a token, and every later `basel` command, `basel deploy` and plain `git` work as that person.

#### The device flow on the wire

For other clients, start with `POST /accounts/device/authorizations {"client_name"?, "client_host"?}` (no credential). It answers `201 {"device_code", "user_code", "verification_uri", "verification_uri_complete", "expires_in": 600, "interval": 5}`. The links are `{BASEL_PUBLIC_ACCOUNT_URL}/device` and `…/device#<user_code>`.

Poll `POST /accounts/device/token {"device_code"}` no faster than `interval` seconds. The answers:

- `202 {"status": "authorization_pending"}` until someone decides;
- `202 {"status": "slow_down", "interval"}` if you poll too fast (the interval grows by five seconds);
- then once, `200 {"status": "approved", "token", "credential_id", "expires_at", "account", "account_url", "app_url"}`;
- `422 device_denied` for a denial, `422 device_expired` for an expired request.

The approved token is a new `api` credential (`bst_`, `tenant_scope` `*`, label `basel CLI on <host>`, 90 days), minted at that poll for the approving account and never again (`422 device_code_invalid` after).

The page at `GET /device` shows the signed-in person which client, on which host and from which address, is asking. It posts `POST /accounts/device/lookup | approve | deny {"user_code"}` with the cookie session and its CSRF header. An unknown, expired or decided code is `422 user_code_invalid`, and a service account or a development session cannot approve (`403`).

Signed out, or with a session that has ended, the page says to sign in first and shows its sign-in form; signed out, it also links to `/signup#device=<code>`.

Starting sign-ins and presenting unknown codes are each limited to twenty per client address per ten minutes (`429`). Approvals, denials and the credential's issue are security events (`account:device.approve`, `account:device.deny`, `account:credential.issue` with `via: "device"`).

#### Where the CLI keeps the credential

The CLI keeps the credential per server: in the macOS keychain, otherwise (or with `BASEL_CREDENTIAL_STORE=file`) in `~/.config/basel/credentials.json`, mode `0600`. It uses it for every command that has no `--token` or `$BASEL_TOKEN`, against the last server signed in to when no `--server` or `$BASEL_SERVER` names one.

One sign-in answers for both of the server's origins. `--server`, `$BASEL_SERVER` and a Git remote may name the account origin it was made on or the app origin (`app_url`) the approval named, so `basel deploy --server https://app.example` uses a sign-in made at `https://account.example`.

`basel auth status` shows what is stored, without secrets. `basel auth logout` revokes the credential on the server and forgets it.

**Git:** `basel auth git-credential` is a Git credential helper. `basel auth login` offers to set `credential.<app origin>.helper` and `useHttpPath` in the global Git config: it asks on a terminal, does it and says so without one, and never does it with `--no-git-helper`. For a `/git/<tenant>` remote the helper answers a `git` credential for that tenant, minted from the stored one and good for an hour, so `git clone`, `git push` and `basel deploy` need no token and no `http.extraHeader`.

`basel deploy` resets inherited global and remote-URL `http.extraHeader` values for its own Git subprocesses before supplying its credential; it does not rewrite your Git config. A Git request that reaches Basel with multiple Authorization headers returns `400 duplicate_authorization_header`, naming `Authorization` and the duplicate-header cause without echoing either credential.

`basel auth login --login <email>` (or `--with-password`) is still the password exchange, for CI; it stores nothing.

### Delegation

An agent acts *for* a human rather than as one. A human's live session mints a **delegation grant** naming:

- a delegate (a `service` or `agent` principal);
- an audience;
- an expiry no later than the delegator's own session expiry;
- a mandatory `reason`: a durable audit string, at most 500 characters.

Opening a session from that grant yields an `AuthContext` whose **effective principal** is the delegating human and whose **acting principal** is the delegate. `whoami` shows both, and every audit event and attempt row records both.

Delegation is **one hop**: a grant-backed session cannot mint a further grant (`delegation_not_allowed`). Deactivating either principal revokes every grant that touches them and every session opened from one.

#### Grant scope

Every grant carries an immutable normalized scope. The optional `scope` accepts `roles` bundles plus `objects`, `fields`, `tenant` and `permits` in policy grammar. Each inline permit names its `object`, `actions`, optional `write`, `when` and `after`.

An omitted scope snapshots the delegator's current role closure; an empty explicit scope grants nothing. Role widening and new wildcard fields never widen an old cap.

#### One tenant only

A grant is written between two MEMBERSHIPS of the same tenant and checked inside that tenant's transaction against that tenant's roles, so it confers nothing anywhere else. The session opened from it is bound to that tenant for the whole of its life, even though the delegate's account may be a member of several.

Presented at any other tenant, a borrowed session is the silent `401`, and no reach is created for it there. The same is true of an elevation.

A borrowing is not an identity, so it does not travel with one. For the same reason a borrowed session opens no endpoint on `/accounts/**` at all: acting as the borrowed account there would be impersonation, so every account endpoint answers the uniform `401`.

#### Grant endpoints

- `POST /tenants/{key}/grants` mints one from the caller's own live session (`{delegate, audience, expires_at, reason, scope?}`).
- `GET /tenants/{key}/grants` lists the ones the caller is a party to.
- `POST /tenants/{key}/grants/{id}/sessions` turns a grant into the delegate's session.
- `DELETE /tenants/{key}/grants/{id}` revokes it, along with every session it opened.

Either party may open or revoke. A grant you are not a party to answers `404`, not `403`: whether somebody else's grant exists is not yours to learn.

### The control plane and elevation

The control plane is not a separate identity space. An **operator is an ordinary account holding the `operator` instance role**: the same `basel_core.account` row that may be a member of tenants, with the same login and password. There is no separate control-principal table.

What is separate is the AUDIENCE. `POST /control/sessions` opens a `bcs_` session, an hour at a time, and the role is re-read on every use, so an account that loses `operator` stops being able to use the control session it already holds.

The control plane is where tenants and accounts are created and deleted, and it keeps its own attempt sink in `basel_core`. A control session opens nothing inside a tenant on its own: presented at a tenant endpoint it is the silent `401`, and a tenant session presented at `/control/...` is the same. The last active operator cannot lose the role (`last_operator`), for the same reason a tenant cannot lose its last admin.

#### Elevation

The bridge between the two planes is an **elevation**, and it is auditable by construction. `POST /control/elevations` takes `{"tenant", "tenant_principal", "reason", "ttl_seconds"}`; the reason may not be blank. It returns a *tenant* `api` session bound to the elevation row it just wrote, capped at one hour.

Every request that session makes, and every refusal it collects, names the elevation. `DELETE /control/elevations/{id}` hands the borrowing back, and the tenant session stops resolving on its next request.

Borrowed authority may not be turned into durable authority: an elevated session cannot mint a credential, not even for the principal it borrowed, and cannot delegate.

#### The first operator

The very first operator comes from the server itself. On a database where no account holds `operator`, `basel-server` mints a `control-admin` account and prints exactly one `BASEL_CONTROL_ENROLLMENT=<bse_ secret>` line on stderr and nothing else.

Redeem that secret at `POST /accounts/password-resets/complete` (on the ACCOUNT plane, like every other password reset) to set its password. It is printed once, on the first start only.

### Development mode

`BASEL_SECURITY_KEY` (base64 of exactly 32 bytes) is required at startup. The server refuses to start without it, because every credential digest in the database is keyed with it. There is no generated default: a key that changes silently invalidates every credential the deployment holds.

#### The development principal

Dev mode needs **all three** of:

- `BASEL_DEV_MODE=1`;
- a loopback peer address;
- `BASEL_DEV_PRINCIPAL` naming an ACCOUNT login.

With all three, every tenant request authenticates as that account's membership in the path tenant, with no token exchange at all, and does so even if it carries a real token. Any one of the three missing falls through to ordinary authentication rather than refusing.

The membership is created on first use, with `role_admin` if and only if the tenant has no active admin yet. A freshly provisioned tenant is therefore usable, without dev mode becoming a way to mint authority in a tenant that already has an administrator.

The server refuses to start with `BASEL_DEV_MODE=1` and a non-loopback bind.

#### Development-only endpoints

Two development-only endpoints exist under the SAME two conditions, `BASEL_DEV_MODE=1` and a loopback caller, and are absent otherwise. Absent literally: without `BASEL_DEV_MODE=1` the router holds no such path, so every request to one, by any method and with any body, is the same `404` an unrouted path earns. A production instance discloses nothing about either.

`POST /tenants/{key}/dev/members` `{"login", "display_name"?, "roles"}` creates a credential-less account (no password, no token) and its membership holding those roles. It answers `201` on creation and `200` on reuse. The `roles` it echoes are the ones this call assigned or confirmed, not necessarily every role the membership holds, because the endpoint never removes one.

`POST /accounts/dev/sessions` `{"login", "audience"?, "profile"?}` then opens an ordinary session for it, with `method: dev` and no credential behind it, in whichever of `POST /accounts/sessions`' two shapes `profile` asks for.

Both write the ordinary `member.join`, `role.assign` and session history, so a tenant's audit trail stays truthful about how the identity came to exist. They exist for local load testing; a production engine never has them.

There is still no development shortcut for the AUTHORITY behind `/control/...`: a dev-mode server is still a server that can delete tenants. `POST /accounts/dev/sessions` will open a `control`-audience session, which lets a local harness provision its own tenant without a password. It does so only for an account that already holds the `operator` instance role, and no dev endpoint hands that out. The shortcut is past the password, never past the role.

#### Credentials minted in development

A development session can mint only `git`-audience credentials, each expiring within an hour. A `dev` session reaches `POST /accounts/me/credentials` like any other. What it mints there is an ordinary row in the credential table, with no mark of where it came from, and a restart without `BASEL_DEV_MODE=1` does not take it away.

So the endpoint is narrowed at both ends: every audience but `git` is refused, and the credential's `expires_at` is capped at one hour from issuance whatever the request asked for (a request naming none gets the hour anyway).

`git` is the audience that survives the narrowing because it exchanges only into a `git` session, which opens `/git/{key}` and no account or control endpoint. It cannot be walked back up into the authority the dev endpoints withhold.

Label such a credential anyway, and revoke it at `DELETE /accounts/me/credentials/{id}` when you are done. The load harness labels its git credential `basel-load-harness` and deletes it in a `finally`, so an interrupted run leaves nothing behind.

Every other endpoint that mints a credential, or a secret that redeems into one or into a new account, is refused from a development session outright (`403`, element `credential`):

- rotating a credential (`POST /accounts/me/credentials/{id}/rotate`), whose successor would inherit the predecessor's audience and expiry;
- keying a tenant's service (`POST /tenants/{key}/services/{id}/credentials`), whose credential belongs to the tenant and outlives the session entirely;
- changing a password (`POST /accounts/me/password`);
- an operator's password reset (`POST /control/accounts/{id}/password-resets`) and account invitation (`POST /control/accounts` with `invite: true`, refused before the account is created), whose secrets redeem into a password;
- issuing or re-sending a tenant invitation (`POST /tenants/{key}/invitations`, `POST /tenants/{key}/invitations/{id}/resend`), whose secret can create an account;
- minting a sign-up access code (`POST /control/access-codes`), which redeems into a new account with a password;
- approving or denying a CLI sign-in (`POST /accounts/device/approve`, `POST /accounts/device/deny`), whose approval mints the waiting CLI a credential;
- deciding an MCP client's request (`POST /accounts/oauth/decide`), whose approval mints an OAuth code that exchanges into tokens;
- provisioning a tenant (`POST /control/tenants`) for an `admin.email`. Provisioning for an `admin.login` stays open, which is what a `control`-audience development session is for: a login names an account that already exists, so its invitation creates no identity.

Revoking a credential is not minting one and stays open.

#### The enrollment secret on stderr

One more thing lands on a developer's terminal: on a database where no account holds `operator` the server prints `BASEL_CONTROL_ENROLLMENT=<bse_ secret>` on **stderr**, once. That is a live credential in a place terminals scroll back through and log collectors follow, so redeem it promptly and rotate the password afterwards rather than leaving the line sitting in a buffer.

### Refusals, and finding out why

Authentication refusals are deliberately uniform. Every one of them renders the identical body, `401 {"code": "unauthenticated", "detail": "authentication required"}`, with `WWW-Authenticate: Bearer` (a bare scheme: a `realm` would name the tenant). That covers:

- no credential;
- a malformed token;
- a revoked or expired session;
- a session that expires or is revoked while its write waits, for example on a row lock, and the same for the credential, grant or elevation it rests on. Nothing was written: sign in again and send the request again;
- an unknown login;
- a wrong password;
- a token presented outside its `tenant_scope`;
- a borrowed session presented outside the tenant it was borrowed in.

Two 401s name themselves, because their holder already holds a valid session and learns nothing new: `audience_mismatch` (a session at a endpoint of another audience) and `control_session_required` (an account session at a `/control/...` endpoint).

The one neighbouring answer that is NOT a 401 is uniform for the same reason. A tenant that does not exist, a tombstoned tenant, and a tenant the authenticated account holds no membership in are one `404 {"code": "not_found", "element": "tenant", "detail": "no such tenant"}`, byte for byte, and so is any unmatched `/tenants/...` path asked by anyone but a member of that tenant.

A member is told two things a stranger is not, because neither is news to them:

- the account's own session at a tenant where its membership is deactivated (or was removed) is `403 {"code": "membership_inactive", "element": "tenant"}`. A token scoped to another tenant, and a delegated or elevated session, still get the `404`;
- an unmatched path under the member's own tenant is `404 {"code": "unknown_route", "detail": "no route for <path>"}`.

Nothing in a refusal discloses to a caller not entitled to it whether a tenant, login, principal, or record exists.

| Status | `code` | When |
|---|---|---|
| 401 | `unauthenticated` | every authentication failure, uniformly — see above |
| 401 | `audience_mismatch` | a session that resolves at another audience; it names itself |
| 401 | `control_session_required` | an account session (`bss_`) at a `/control/...` endpoint, which takes only a control session (`POST /control/sessions`) |
| 403 | `membership_inactive` | the account's own session at a tenant where its membership is deactivated or was removed; ask a tenant admin |
| 403 | `forbidden` | an authenticated caller refused an operation — by tenant policy (see "Policy"), by a missing tenant action, or by one of the identity rules the security plane keeps outside policy: credential and password lifecycle needs DIRECT live authority, so no delegated or elevated session manages a durable credential, not even its own; and a `service` account manages none of its own at all, because the tenant that manages it holds its keys |
| 404 | `unknown_route` | a member's path under its own tenant that matches no route; anyone else gets `no such tenant` |
| 429 | `rate_limited` | the login/token flood gates: 10 attempts per minute per login or token prefix, 60 per minute per source address. Every password attempt counts; a bearer token counts only when it is refused, so a valid token is never throttled, however often it is used. A `429` on a token therefore means that token (or another one sharing its prefix or address) has been failing: fix the credential rather than retrying, and re-authenticate with `basel auth login` |
| 415 | `unsupported_media_type` | a JSON endpoint handed a body with no `Content-Type: application/json` — checked before the body is read |
| 500 | `authorization_evaluation_failed` | authentication could not be *evaluated* (a database fault), which is not a refused credential |

### Trace ids and the attempt log

Every refusal the security plane itself decides carries an `X-Basel-Trace` header: each `401`, the `403` above, and a `429` from the flood gates. The header is a uuid naming the durable row that recorded the refusal. The body still says nothing; the header says *which* nothing, so a caller can quote it and an operator can look it up.

Two exceptions: `415` is refused before authentication runs, and carries none. The Git transport's 401 stays byte-identical to what a `git` client expects, so the row is written but no header is stamped.

That row lives in the **attempt log**, which is separate from the audit log: audit records what happened, attempts record what was refused.

- `GET /tenants/{key}/attempts?actor=&action_name=&code=&limit=` reads a tenant's own.
- `GET /control/attempts` reads the instance sink: every refusal belonging to no tenant, plus every refusal naming a tenant key that resolves to nothing. That is what makes tenant enumeration visible to an operator.

Rows carry the matched route *template* rather than the concrete path, a fixed `code`, and the actor when one was identified, and no free text at all. The actor is the membership id, plus the ACCOUNT id once one is resolved, so an operator can correlate one person's refusals across tenants without joining schemas.

### Secrets never echo

No password, no credential verifier, no session or CSRF secret, and no reset or invitation secret appears in any reflection, query, history, audit event, attempt row, log line, or error body. A plaintext bearer secret is returned exactly once, by the call that mints it, and never again.

## Policy

Policy decides which principal may read or change which records and fields. You declare it in JSON files under `policies/`, and the engine checks every actor-facing read and every write against it. This section covers the files first (roles, permits, readable fields, conditions), then how reads and writes are checked, then the endpoints that explain authority.

### The `policies/` tier

Policy is metadata, pushed through the same Git endpoint as the rest of the repository and compiled in the same metadata version as the model:

| File | What it declares |
|---|---|
| `policies/roles.json` | every role: stable `id`, `includes`, `read_fields` (readable fields), `grants` (unconditional whole-object grants), `tenant` actions |
| `policies/<object>.json` | every conditional (or field-limited) permit on that object (or relationship): each grants one action, with its own condition |
| `policies/assertions.json` | structural expectations the planner enforces |

The resolved policy carries its own checksum, published beside the model's. A policy edit is **not** a schema change and never moves `model_checksum`. So `/tenants/{key}/reflect/authority` reports both checksums, and you need both to say what you read.

**Relationships in policy.** Relationship metadata also declares `operations`; omitted means no generic verbs. Object and relationship policy files grant exposed writes and named actions. Property updates require complete field permits. Relationship actions require invocation permits and keep their admitted internal effects. Endpoint fields stay immutable, and reads still require both endpoints to be visible.

A role's `read_fields` also names relationships, including their properties and `from`/`to`. If a relationship's readable fields are omitted, only the link id is exposed, and both endpoint rows must still be visible. Queries, history, write readback and link aggregate values obey these readable fields.

### Roles and permits

The repository below declares two roles and what they may do. A role's key is its display name and its `id` is the stable identity memberships name. `read_fields` lists, per object, the fields the role may read; it grants no row by itself. Rows come from two places:

- **`grants`** on the role: whole objects, unconditionally ("reps read every customer"). See "Role grants" below.
- **Permits** in the object's own policy file, each granting exactly one `action`, with a condition or a narrower `write` list ("reps update their own deals").

```json basel-repository
# file: basel.json
{"format": 2, "name": "sales"}
# file: objects/customer.json
{"name": "Customer", "fields": {"name": {"type": "text"}}}
# file: objects/contact.json
{"name": "Contact", "fields": {"name": {"type": "text"}, "email": {"type": "Email"}, "phone": {"type": "Phone"}}}
# file: objects/salesperson.json
{"name": "Salesperson", "fields": {"name": {"type": "text"}, "team": {"type": "text"}}}
# file: objects/deal.json
{
  "name": "Deal",
  "operations": ["create", "update"],
  "fields": {
    "name": {"type": "text"},
    "stage": {"type": "enum", "values": ["new", "qualified", "won", "lost"], "default": "new"},
    "owner": {"type": "ref", "to": "Principal"}
  },
  "actions": {
    "qualify": {"effects": [{"op": "set", "values": {"stage": "qualified"}}]}
  }
}
# file: policies/roles.json
{
  "roles": {
    "sales_rep": {
      "id": "role_sales_rep",
      "read_fields": {
        "Customer": ["*"],
        "Contact": ["name", "email"],
        "Deal": ["*"]
      },
      "grants": {"Customer": ["read"], "Contact": ["read"]}
    },
    "sales_manager": {
      "id": "role_sales_manager",
      "includes": ["sales_rep"],
      "tenant": ["metadata.read", "audit.read"],
      "read_fields": {"Salesperson": ["name", "team"]},
      "grants": {"Deal": ["read"]}
    }
  }
}
# file: policies/deal.json
{
  "object": "Deal",
  "permits": {
    "rep_reads_own_deals": {"roles": ["sales_rep"], "action": "read", "where": "row.owner = actor"},
    "rep_updates_own_deals": {
      "roles": ["sales_rep"],
      "action": "update",
      "write": ["name", "stage"],
      "before": "row.owner = actor",
      "after": "row.owner = actor"
    },
    "rep_qualifies_own_deals": {
      "roles": ["sales_rep"],
      "action": "action.qualify.invoke",
      "before": "row.owner = actor"
    }
  }
}
# file: policies/assertions.json
{"assertions": [{"roles": ["sales_rep"], "never_reads": ["Salesperson.team"]}]}
```

`includes` forms a DAG. A cycle is refused `role_cycle`, and depth above eight is refused `role_depth`. Holding a role is holding everything it includes. Reflection publishes both forms: the declared one you edit, and the flattened closure the engine checks with.

**Three roles are built in.**

- `authenticated` is the virtual membership every active principal holds. It may carry `read_fields` and `tenant`, and permits may name it. Out of the box it **grants nothing** — notably not `metadata.read`, so a principal with no other role cannot read `/reflect/**` or the `/ui/**` catalog. One floor stands outside policy altogether: a member's `display_name`, read through a reference (the "Owner names" paragraph under the identity roster below). A principal holding any other role opens the tenant's own app (see "Who may open an app's UI" under "Apps from packages"); `metadata.read` opens the metadata.
- `admin` (`role_admin`) holds every action on every object, every set of readable fields, and every exposed tenant action. It cannot be declared, and no role may include it.
- `member` (`role_member`) is the general-user role every tenant has without declaring one: every action every object and relationship exposes except `share`, every field readable, on the tenant's objects and its installed packages' alike, and exactly three tenant actions, `metadata.read` (so the console, the standard UI and the agent tools work), `proposal.submit` (imports and atomic batches) and `query.aggregate`. It cannot change the app, its roles, its members or its credentials. It cannot be declared; a tenant role may include it (`"includes": ["member"]` plus a `tenant` action is the ordinary way to widen it). It opens the tenant's own apps and every installed app package's app. Nobody holds it until it is assigned. Declare roles of your own only when someone needs less than `member`.

**Membership is data, not metadata.** A role id is assigned with `PUT /tenants/{key}/principals/{id}/roles/{role}` and taken away with `DELETE` on the same path. Both need the tenant action `role.assign`, plus `role.assign_admin` for `role_admin` itself.

The tenant's last ACTIVE admin cannot be unassigned or deactivated (`last_admin`). Borrowed authority — a delegated or elevated session — may not change membership at all. Because membership names the stable `id`, renaming a role in `roles.json` orphans no assignment. An id the current metadata version no longer declares simply grants nothing.

### Role grants

`grants` gives a role whole objects, unconditionally:

```json
"grants": {
  "Deal": ["read", "manage"],
  "Party": {"actions": ["read", "manage"], "scope": "descendants"},
  "Affiliation": ["read", "manage", "relationship.party.link", "relationship.party.unlink"]
}
```

Each entry names actions from the object's vocabulary (below), plus two bundles:

- **`manage`** is the object's exposed `create`, `update` and `delete`, and nothing else.
- **`*`** is everything the object exposes except `share`.

Named actions, `reference`, relationship links and `share` are each granted by their own token. A bundle is expanded per concrete kind, so `scope: descendants` on a family root reaches each member's own vocabulary. A bundle that grants nothing on its object is refused `grants_nothing`.

A grant is a set of ordinary permits: one per action, unconditional, writing every field (`write: ["*"]`). Reflection, explain and the declared grant matrix show them as permits named `<role>.<Object>.<action>`.

**A grant must not silently undo a condition.** A conditional permit is refused `shadowed_permit` when every role it names already holds an unconditional permit covering its action and fields on the same object, through a grant or an included role. Such a condition can never narrow anything. `reference` covers `relationship.<t>.reference`. A permit naming `admin` is judged without it. Delete the dead permit, or narrow the grant.

**Packages ship narrow roles.** Policy is permit-only, so a tenant can add authority but never subtract it, and a package role is a floor. A package should grant the narrowest roles that make its app usable, conditional permits included. A tenant widens a package role by including it in its own role and adding grants. To narrow one, the tenant writes its own role instead of assigning the package's. A package's grants reach only its own objects, and `write: ["*"]` covers only the package's own fields of an object another owner extended.

### Permits

A permit is `{roles, action, write?, where?, before?, after?, scope?}`. Its condition slots are the ones its action evaluates, and nothing else:

| `action` | Condition slots | Judged against |
|---|---|---|
| `read`, `reference`, `relationship.<t>.reference` | `where` | the row |
| `create` | `after` | the completed record after the write |
| `update` | `before`, `after` | the record before the write, and the record after it |
| every other action (`delete`, links, `action.<name>.invoke`, `share`) | `before` | the record before the write |

A slot the action does not evaluate is refused `invalid_policy_condition`. `write` (omitted means none; `["*"]` means all eligible fields) belongs only to `create` and `update`. An update's `after` is never inherited from its `before`: an update permit with `before` and no `after` has no postcondition.

**The action vocabulary is closed** and per object:

- `read`, `create`, `update`, `delete`, `reference`
- `relationship.<traversal>.link`, `relationship.<traversal>.unlink`, `relationship.<traversal>.reference`
- `action.<name>.invoke`, and the reserved `action.<name>.approve`
- `share`

A token is only nameable when the object actually exposes it:

- the generic write verbs come from the object's `operations` (omitted means none);
- a traversal must be declared on a relationship touching the object;
- `action.<name>` must name a declared action (a transition is an action);
- `share` needs `"sharing": true`.

Anything else is refused `unknown_action` at push.

**There is no forbid rule.** Effective authority is the union of the matching permits, inside the readable fields, inside the structural readable fields (tenant, principal active, session audience, delegation scope). Adding a permit never removes authority, and "why may this actor do this" always has a named permit as its answer.

**A permit is atomic**: its roles, action, `write` list and conditions are never recombined with another permit's. A permit that could grant nothing at all is refused `grants_nothing`. Examples: a `read` permit whose roles have no `read_fields` on the object, or a `create`/`update` permit whose `write` list is empty.

### The readable fields

A role's `read_fields` is its **readable fields** per object: `["*"]` for every eligible field, or a named list. An object absent from `read_fields` has no readable fields there at all. An actor's readable fields are the union of the readable fields of the roles they hold. This depends on roles alone — never on a row, never on a permit's condition — so it is stable for the whole request.

A formula is readable only when every field it transitively reads is readable. Naming a formula in a role's readable fields does not license its inputs.

A field outside the readable fields is **omitted from the response, never nulled**. A BQL query that names one is refused `unreadable_attribute` rather than silently narrowed. A name the model does not declare at all is a compile error (`bql_compile_error`, naming `<Object>.<attr>`) when you hold `metadata.read`, as `admin` does; without `metadata.read` it is refused `unreadable_attribute` like a withheld field, so the refusal never tells you which hidden fields exist. The one exception is a generated UI list query, which leaves out the columns and sort terms the caller cannot read (see "Apps from packages").

### Conditions: the actor root and `IN <path>`

A permit's condition is an expression in the shared grammar (see "Guards" and "BQL") under its own legality profile. `row.` is the judged record, and one more root matters most here: **`actor`**, the effective principal of the request. You can use it bare (`row.owner = actor`) and as a path (`actor.team`, `actor.manager.id`) through declared relationships from `Principal`.

`IN <path>` is set membership against a to-many traversal: `actor IN row.team.members`, `row.owner IN actor.reports`. It is legal only where the condition is compiled to SQL, which is exactly where policy conditions are checked. A *guard* that writes `IN <path>` is refused at resolve, because guards are checked in memory.

A condition must compile to bounded, parameterized SQL; one that cannot is refused at push. It may use transaction-stable `NOW()`. It may not use history functions or unbounded aggregates. `NULL`, `FALSE`, or an evaluation failure grants nothing.

#### `before.` in a permit condition

`before.` is accepted only in an `update` permit's `before` and `after`. It names the same operation's record immediately before the write, so an `after` can compare the two (`row.stage != 'lost' OR before.stage = 'lost'`). It reaches only the object's own stored values, not relationship hops or formulas. Read, create and other permits, and BQL, refuse it.

A create's `after` and an update's `after` refuse `row.` reads of own rollups that are not yet recomputed, including Money members. `before.` reads and reads of the record before the write keep stored semantics; traversals see frozen database facts. Final derived constraints belong in guards or invariants.

#### Conditions on a create

A create checks its permit's `after` on the completed record after the write.

Hops in a permit condition read frozen facts from before the write. So a relationship traversal from the record being created reads NULL and never grants. Check the parent on its `relationship.<end>.link` permit or in a create guard instead. A `create` permit that requires such a traversal (not under `OR`, `NOT` or `IS NULL`) is refused at push with `invalid_policy_condition`, naming the path and the parent's `link` permit. Guards, unlike permits, read hops through the record after the whole write, so a create guard sees a parent created or linked in the same proposal.

### Reads and explicit writes are checked

Every actor-facing read uses a compiled per-principal program for objects, rows and fields. Writes are checked as follows:

- **Updates.** Direct object and relationship-property updates enforce complete permits over the locked records before and after the write, over all requested fields (including no-ops), with fresh session and role facts. A successful write's audit record names the determining permits.
- **Creates and deletes.** Direct object and relationship creates check the completed record after the write. Deletes check the locked record before the write. An administrator still needs `delete` declared in the object's `operations`; an admin permit cannot add an undeclared operation. Use a scratch tenant for spike data and delete that tenant when it is no longer needed.
- **Delegation.** Delegated operations intersect both principals' current permissions with the immutable grant cap (described in the paragraph after this list).
- **Actions.** Object and relationship actions check invocation authority before privileged effect and function reads, and again after locking. Admitted consequences need no primitive update permit, and keep the caller's attribution.
- **Nested and raw operations.** A nested write through a declared relationship (a create body with members, an update envelope, or the delete of a record whose end declares `on_delete`) needs no tenant action: each operation it expands into needs its own create, update or delete witness (the permit that authorizes that one operation), and the whole write commits atomically or not at all. A raw client batch at `POST /proposals` needs the same witnesses plus the tenant action `proposal.submit`. Link and Unlink require the relationship's create/delete witnesses, even when they are canceled within the batch. Source link/unlink and independent target reference are checked alongside the relationship's witnesses.
- **Transitions.** Raw transitions must use the action endpoint.
- **Shares and hierarchy.** Record shares and a bounded manager hierarchy are enforced.
- **Metadata installation.** Installing metadata requires direct, current push/admission authority and exact acknowledgment of the flagged plan (see "Operator endpoints and the metadata tier" below).

Permission explanations and the permitted-action and writable-field projections are implemented; see "Endpoints", "User interface", and "Explaining a decision" and "`permitted`" below. A request for the reserved evaluated-UI actor/context override still returns 501. That is not an absence of data-plane authorization.

**Delegation intersects three authority sources:** the acting agent, the effective human and the immutable grant cap. Each principal's conditions bind `actor` to that principal; cap conditions bind it to the human. Reads, readable fields, writes, actions and tenant actions must pass every source. Current role narrowing reduces old grants. Elevation continues to use the borrowed tenant principal's permissions.

### Existing row targets require visibility

Every direct row write endpoint — `PATCH`, row `DELETE`, and action invocation, measured or not — probes its target. The probe splices the caller's own hiding filter into the version check that reads the row.

The probe is **unconditional**. It runs whether or not an `If-Match` came with the request (only the version *comparison* needs one), and whether the action touches one record or many. A row outside that filter is not found by the probe, so the write answers `404` in a body identical to a nonexistent id. That is the same concealment reads get, on the same rows, for the same reason.

**And regardless of the object verdict.** The probe hides rather than refuses. So an object you hold no `read` permit on at all answers `404` on a write and `403` on a read — the one place the two rules deliberately diverge.

Source-addressed relationship operations use the declaring source plus target reference instead. A hidden but referenceable far endpoint can participate, without making its link ordinarily readable.

**Shares.** A share grants only its transferred row actions and never widens read fields. Shared updates use a frozen field cap intersected with the recipient's current readable fields. A transferable update permit has no `after`; a conditional postcondition cannot be transferred. The grantor losing access does not revoke a share; explicit revocation, expiry and record deletion do.

### Relationship writes

A relationship mutation needs three things:

- the relationship's create/delete authority;
- link/unlink on its declaring source traversal;
- reference on the target endpoint's reverse traversal.

Target-wide `reference` also licenses that target. It is required for explicitly supplied non-null ordinary ref fields, including no-op assignments. Clearing a ref uses the source field's update witness.

An intent pays it too when the caller chose the target. If an action's `set` writes a `ref` or `reference_choice` field and one of the action's params flows into the value (the param itself, or inside `COALESCE(...)`, arithmetic or a `CASE` result), the caller needs `reference` on the target, just as through `PATCH`; refusals are the same as below. A target the action computes itself (a constant, the record's own field, a `with` binding that follows a reference) needs only the `action.<name>.invoke` permit. Function bodies are bounded by their declared write grant.

Direct link CRUD uses the canonical from end; nested writes keep their declaring direction.

Refusals:

- source-object denial is `403`;
- hidden or missing sources are `404`;
- a missing target and a reference-forbidden one are the same `404 not_found`, located at the field the write named it in: `element` is `<Object>.<field>` for a `ref` or choice field (the field an action's param writes, for a param), `<Object>.<traversal>` for a link through a traversal, `<Relationship>.<from|to>` at the direct edge door, and at the raw `/proposals` door the position you wrote it at (`operations[i].values.<field>`, `.properties.<field>`, `.from` or `.to`), and `detail` is "`<element>` names no record you may reference: no record has that id, or you may not reference it". The two stay indistinguishable; choose another record for that field. A caller holding live `authz.explain_others` gets instead, for a reference-forbidden target, `403 forbidden` naming `<Object>.reference` or `<Object>.relationship.<end>.reference`, without target values or ids;
- unknown or ambiguous client link probes also return `404`.

**Which refusal comes first.** An operation no permit of yours names at all (a create, update, delete, link or unlink your roles never grant) is reported before any reference: you get the `403` "none of your roles grants", not a `404` for a target you can read. That answer depends on your roles alone, so it is the same whether the target exists or not. A reference is reported next, then any other denial. A denial whose cause is a permit's condition or its fields comes after the references, because a condition can read the referenced row.

Reference access never grants ordinary reads of the target row or its fields. Post-write projection can return an identity-only receipt.

### What write refusals disclose

A refusal from inside a write keeps its code but not internal detail:

- **Invocation consequences.** Validation of an invocation's consequences keeps platform codes but uses fixed detail and `invocation` as its element.
- **Generic CRUD and nested/raw transactions.** Failures use the same safe boundary, with `write` as the element and fixed consequence detail.
- **Before the transaction.** Model and input errors keep their field guidance. That includes a Date that does not exist, text over its length limit and a Money amount with more places than its field keeps. On update, a value only the stored row can excuse (an amount or an `Email` the row already holds, sent back unchanged) is judged in the transaction, and its refusal still names the field.
- **During the transaction.** Conversion and integrity errors keep their codes, without internal object names or runtime values.
- **Conflict diffs** omit runtime state.
- **Messages.** Static declared function, guard and invariant messages stay available. Currency mismatch diagnostics do not disclose runtime currency values.

`reference_ineligible` and `constraint_violated` are not exempt from that boundary. The wire response keeps the real code, but on every non-engine endpoint its `element` is rewritten to `write` (or `invocation`) and its detail to the fixed consequence text. The `{Object}.{attr}` / `{Object}.constraints.{name}` position survives only for the tenant's own `engine` actor.

### What the read filter does to a caller

The same program filters every actor-facing read:

- `GET /tenants/{key}/objects/{Object}/{id}` and `POST /tenants/{key}/query`;
- per-record history and row versions;
- the evaluated UI's named queries and their counts;
- the record-narrowed invocation log;
- `GET /tenants/{key}/principals`.

**The identity roster.** `GET /tenants/{key}/principals` is a read of the built-in `Principal` object and is checked as one. So the canonical `"where": "row.id = actor"` read permit on `Principal` answers a listing of exactly one principal: the reader.

A membership names an account. `login` and `account_kind` are projected onto `Principal` from it as ORDINARY attributes: readable, filterable, orderable and traversable like any other, and bounded by the role's readable fields in exactly the same way. A role whose readable fields omit `login` reads members without logins, and a query selecting `login` under that role is `422 unreadable_attribute`. That is how a tenant hides logins from a role; there is no separate switch for it.

**Owner names.** A member's `display_name` is readable *through a reference to them* by every active member, whatever the reader's `Principal` permits and readable fields say. `owner.display_name` in a query, a list column, a search term or a formula resolves for anyone who can read the row that holds `owner`. It is a floor of the platform, not a permit: it is in no role, it shadows no conditional permit, and no metadata can withdraw it. So a role that named `Principal` in its readable fields only to show owner names needs nothing on `Principal` at all.

The floor covers that one attribute, reached through a reference, and nothing else. `login`, `kind`, `active`, `manager` and `account_kind` stay behind your readable fields and your row filter: a query reading both `owner.display_name` and `owner.login` resolves the first for every row and the second only for the rows your filter admits. The roster (`FROM Principal`, `GET /tenants/{key}/principals`) stays behind a `read` permit, and choosing a principal stays behind `reference`.

**Identity lifecycle endpoints.** Every identity lifecycle endpoint that names a principal id gates its tenant action first, then checks that target's visibility, and answers `404` for one it hides, in the body a nonexistent id earns. A caller without the action gets the same `403` naming it whether the target is hidden, visible or names nobody, so it learns nothing about who exists. These are: activation and re-pointing a manager (`principal.manage`), membership removal (`member.remove`), service credential issuance and revocation (`member.invite`), and the three role endpoints (`role.assign`). Grant creation needs no tenant action: it refuses what is wrong with the caller first, then checks the delegate's visibility.

You are always visible to yourself. Your own credentials live on the account plane, so managing them needs no `Principal` read permit at all. Principal activation requires target visibility and direct `principal.manage` authority; it has no self-service exception.

**The 404/403 rule.** A row your filter hides answers `404`, in a body identical to one that never existed — for every method, so probing tells you nothing. An object you hold no `read` permit on at all answers `403 forbidden`, naming the object and nothing else. Its existence is already public through reflection, but no refusal ever names the permit, condition, or row that decided. `/reflect/authority` is where authority is explained; a refusal is not.

**What a write's `403` says.** A write that policy refuses on a row you can see answers `403 forbidden` in one of three forms. "You may not write `discount` on this `Invoice`" means a permit allows the action on this row but not for the fields named, and its element is the first of them: drop them, or read the record's `permitted.writable_fields`. "No permit allows `update` on this `Invoice`" means you hold a permit for the action, but its condition does not match this row or the row your write would leave. "None of your roles grants `delete` on `Invoice`" means no permit of yours names the action at all. A create that sends a numbered field is none of these: it is refused `422 managed_attribute` naming the field, because the server fills it (see "Metadata grammar and type table", "Who may supply a number"); omit it.

Under a delegated session whose roles allow the write but whose grant does not, the `403` says "the delegation this session acts under does not allow `<action>` on `<Object>`": a session outside the delegation, or a wider grant, could.

**Audit reads.** The built-in `Event` pseudo-object as a **query source** needs the tenant action `audit.read`. **Per-record history** (`GET .../{id}/history`) needs no such action; it is filtered by the record's own visibility instead, as is a record-scoped activity feed. A feed or history page whose events were redacted away comes back **shorter** than the page size without changing `has_next`. So page until `has_next` is `false`, never until a page looks short.

**Cursors.** A UI query cursor is signed and version-bound. **Any apply invalidates every outstanding cursor**: the next page request answers `stale_cursor`, and the client restarts from page one. Rotating `BASEL_SECURITY_KEY` invalidates them too, as `invalid_cursor`. Neither is an error to retry; both mean start over.

### Operator endpoints and the metadata tier

Operator endpoints and the tenant actions they need:

| Endpoint | Tenant action |
|---|---|
| `/tenants/{key}/diagnostics/**` | `diagnostics.read` |
| `/tenants/{key}/attempts` | `security_attempt.read` |
| `Event` as a query source | `audit.read` |
| A grouped query (`GROUP BY`, `SUM`, …) through `/tenants/{key}/query`; a plain `COUNT(*)` with no `GROUP BY` needs none | `query.aggregate` |
| `/tenants/{key}/events` (the event feed read by cursor) | `audit.read` |
| Starting a run (`POST /tenants/{key}/runs`) | `task.run` |
| Listing and cancelling every run, not only the caller's own | `run.manage` |
| Runner bindings (`/tenants/{key}/runners/**`) | `runner.manage` |
| Asking for a rollup recompute (`POST /tenants/{key}/rollups/recomputes`) | `metadata.push` |
| Rollup states and recompute runs (`GET /tenants/{key}/rollups`, `GET /tenants/{key}/rollups/recomputes/**`) | `metadata.read` |
| `/tenants/{key}/invocations` | `audit.read`, unless you narrow it to one `record`, which makes it an ordinary read under that record's own visibility |

Per-record history keeps its own rule: it needs no tenant action and is filtered by the record's own visibility (see "What the read filter does to a caller" above).

The authority surfaces add six tenant actions to that vocabulary:

- `authz.explain_full` — the full explain view;
- `authz.explain_others` — explaining another principal, or a record the caller cannot see;
- `authz.lookup_subjects` — `/authz/subjects`;
- `security_attempt.read` — above;
- `audit.export` and `security_attempt.export` — the two tenant exports. The instance twin is for operators only, gated directly, with no lookup.

**Everything that serves the metadata tier needs `metadata.read`**, in whatever form it serves it:

- `/tenants/{key}/reflect/**`;
- the `/tenants/{key}/ui/**` catalog (except the tenant's own apps, open to any member holding a role other than `authenticated`, and an installed app's own surfaces, open to that app's role holders and to the built-in `member` — see "Who may open an app's UI" under "Apps from packages");
- `/tenants/{key}/metadata` and its version endpoints;
- `/tenants/{key}/git/status` and `/tenants/{key}/git/receives`;
- the Git **read** transport itself: `info/refs` for **both** services, `git-upload-pack`, and the `plan` preflight.

The Git read transport refuses with a plain `403` and no `WWW-Authenticate`, so a `git` client does not retry a credential that is already good. A git-audience credential authenticates a clone; it does not authorize one, because the repository is `policies/`. Discovery is checked whichever service asked for it: the advertisement names refs and the commit ids they point at either way, and a principal who may push `policies/` must be able to read it anyway.

Push requires direct live `metadata.push`. Flagged authority expansions additionally require current `policy.admit_expansion` or `function.admit_scope`, and the exact `basel-plan` acknowledgment. Proposed permissions cannot authorize their own installation.

None of these is granted by `authenticated`, so an ordinary principal reads none of them.

### What a push grants

Every plan response carries `"grants"`: the declared grant table the push leaves behind, one row per role, object and action (the materialized built-ins `admin` and `member` are left out: they hold every cell by construction). Each row says how it is granted (`how`): `grant` (a role's `grants`), `permit` (an unconditional permit), or `conditional` (a permit with a condition). Against the live generation, a row is marked `"change": "added"` or `"removed"`. `basel plan` prints only the changes.

The plan's `advisories` also carry `authority_overlap` when a conditional permit's condition never applies to the holders of some role, because that role's effective roles already hold the same action and fields unconditionally. A common case is a tenant role that includes a package role and also grants the object outright. It is a notice, never a refusal; a permit whose condition applies to none of its roles is refused at push (`shadowed_permit`).

### Assertions

`policies/assertions.json`:

```json basel-fragment
{
  "assertions": [
    {"roles": ["sales_rep"], "cannot": "action.reopen.invoke", "on": "Deal"},
    {"roles": ["authenticated"], "never_reads": ["Salesperson.salary"]}
  ]
}
```

An assertion is a structural expectation about the policy set. The **planner evaluates it against the policy the push proposes**, before anything is written. Both shapes are checked after flattening:

- `cannot`/`on` fails when some permit grants that action on that object to any role the named roles hold;
- `cannot: action.<transition>.invoke` also fails when a named role holds the `invoke` permit of an action whose function can propose that transition (see "`/tenants/{key}/reflect/authority`" below), since that action moves the record without a direct permit. The refusal names each such action and the permit through which the role holds it. Reach is the function's write scope, so a function whose scope names a lifecycle reaches every transition in it;
- `never_reads` fails when the flattened readable fields of a named role admit that field.

A violation refuses the push with `assertion_failed`, addressed at `policies.assertions[N]` and naming the roles and the action or attribute involved. An assertion that names a role, object, action or attribute that does not exist is refused earlier, as `unknown_role`, `unknown_action`, or `unknown_attribute`.

### `/tenants/{key}/reflect/authority`

The tenant's complete declared authority, under `metadata.read`. The body contains:

- every role: `id`, `builtin`, `includes`, the flattened closure, `objects`, `fields`, `tenant`;
- the closed `tenant_actions` vocabulary;
- every object with its `operations`, `sharing`, and the permits naming it — each permit's `roles`, `actions`, `write`, and its condition as **source text** in the internal spelling: `when` for `where` and `before`, `after` as is, without `row.` roots;
- every assertion, with the element the planner would refuse it at;
- `function_reachable_transitions`: the lifecycle transitions each action's function can propose on the strength of the action's own `invoke` permit alone;
- both `model_checksum` and `policy_checksum`.

It is structural and complete: it describes what was declared, never who holds it and never any record. For who *you* are and which roles you hold, read `GET /tenants/{key}/whoami`.

**Transitions reachable through a function.** An action's function may propose a transition the caller could not invoke directly: the action's `invoke` permit and the function's write scope authorize it, and transition guards still apply. `/reflect/authority` lists these transitions under `function_reachable_transitions`, and the grant matrix repeats them on each `action.<name>.invoke` cell. Read both when reviewing who can move a record between states. A `cannot:` assertion on such a transition counts this route: to keep one, withhold the actions whose functions reach it, or narrow the function's write scope.

**The declared grant matrix.** `GET /tenants/{key}/authz/declared_grant_matrix` requires `metadata.read`. It groups complete permits by role, object and action, with inclusion and readable fields. Its `effective_permissions: false` is deliberate: conditions are not evaluated, and principal memberships, records, shares and delegation are absent. Use its `metadata_version` and both checksums to identify the metadata. Do not use a matrix cell as authorization to execute an action.

### Explaining a decision

`POST /tenants/{key}/authz/explain` answers what the subject's own read program or write check would decide. It handles seven shapes: `read`, `delete`, `action.<name>.invoke`, `update`, `create`, `relationship.<name>.link`, `relationship.<name>.unlink`.

It runs that endpoint's OWN program. A read is checked by the endpoint's read program; a write by the same write check every write path reaches, over the endpoint's own completed records before and after the write. There is no second evaluator. If explain and the endpoint ever disagree, the endpoint changed underneath it.

**Record shapes.** The record shapes model the record endpoints (`/objects/{Object}[/{id}]`), which need no tenant action. A relationship record is a record: `read`, `create` (`fields: {from, to}`), `update` and `delete` on `{"object": "<relationship>"}` are checked as `/objects/<relationship>` checks them. That always treats the `from` end as the edge's source.

**Traversal shapes.** The two traversal shapes model ONE operation of `POST /tenants/{key}/proposals`, declared from the record's side (`source: {side, target: <record>}`):

- `record` is the end the token names, and the edge's source, whichever end that is;
- `target` is the far record for a `link`, and the link record (`{"object": "<relationship>", "id": …}`) for an `unlink`.

Like that endpoint, they check the source record's visibility first, then the junction's `create`/`delete`, the traversal's `link`/`unlink` on the record, and `reference` on the far end. They require no tenant action, as the update envelope (`PATCH` with `{<end>: {"link": [...]}}`) requires none; the raw `/proposals` door adds `proposal.submit`.

#### The bounded view

Every caller gets the bounded view:

- `decision`: `permitted`, `denied`, or `not_found`;
- the `action` asked about, the subject, `metadata_version`, and both metadata checksums;
- the record, with `version_mismatch` for an `update` whose caller-supplied version is well-formed but not the row's current one. This is never a refusal; the check always runs on the current record regardless;
- `determining`: the permit ids and `share:`-prefixed share ids that decided it;
- on a denial only, `code`: the refusal code the endpoint itself would return, and `element` and `detail`: the endpoint's own refusal text, built by the same function, so the fields you may not write (or "no permit allows") read here as they do in the refusal.

A write whose reference names no record you may reference refuses here exactly as the endpoint does: the same `404` located at the field.

A refusal raised before any permit is consulted at all (the subject is not live, say) cannot name one, so `determining.permits` is empty there. That is the check-level case, not a missing answer. When the cause is that the subject is not live, the answer adds `subject_live: false` — but only when the caller IS that subject or holds `role_admin`. Anyone else gets the same denial with nothing added.

#### The full view

Holding `authz.explain_full` on top adds:

- every candidate permit that names the action, held or not, each with its `when`/`after` outcome: `"true"`, `"false"`, or `"unknown"` for a permit the widened check pass never reached;
- the write-field cap (`declared`/`requested`/`uncovered`, by the check's own coverage rule, so a numbered field is `uncovered` under `"*"`; `managed` names the requested fields the server numbers, which only a permit naming them covers);
- the SUBJECT's own readable fields and the rendered `row_filter`, both drawn from the subject's own program — the answer being asked for — never the caller's;
- the record's live shares.

#### Explaining another principal

**`principal`.** Naming another membership's principal explains THEIR authority, not the caller's, and needs `authz.explain_others`. That is checked before the named principal is even looked up, so explain cannot be used as an existence oracle for memberships: without it, a nonexistent uuid and a real one refuse identically.

The record is still fetched under the **caller's** own read program. That non-disclosure gate protects the caller, who must not learn that a record they cannot see exists. The check then runs under the **named subject's** program — which is the whole point: every interesting question is about a record the subject cannot reach.

**The byte-identical 404.** A record the CALLER'S own filter hides answers the record endpoint's own `not_found` body, unchanged down to the wording, because it is the same function. Without `authz.explain_others` a hidden record refuses outright with that body. With it, the identical body rides inside an ordinary `200` as `decision: "not_found"`, since the action already answered the one visibility question the caller is allowed to ask about someone else.

#### Explain never writes

Explain opens a transaction so the predicate evaluator can lower every `when`/`after` into one statement. It rolls that transaction back unconditionally on every path — success, denial, or a database error alike. So no audit event, attempt row, or session touch is ever left behind by a call to it.

**Both widening actions go through the delegation cap**, exactly as every other tenant action does. Under a grant-scoped session what counts is the intersection of the effective principal's tenant actions, the acting principal's, and the frozen grant scope. So a delegated caller whose scope omits `authz.explain_full` gets the bounded view, and one whose scope omits `authz.explain_others` cannot name another principal — whatever the delegator holds.

### Who can do this

`GET /tenants/{key}/authz/subjects?action=&object=&record=&after=&limit=` needs `authz.lookup_subjects`. It inverts a permit's own condition into a query over memberships, rather than approximating it.

Reversible shapes:

- `<record path> = actor`
- `<record path>.id = actor`
- `actor.<attr> = <literal or record path>`
- `<record path> IN actor.<traversal>`, and its mirror `actor IN <record path>`
- conjunctions and disjunctions of those.

A comparison naming no actor at all is an ordinary record predicate and reverses trivially, whatever its operator.

Refused as a whole:

- an actor compared any way but `=`;
- a NEGATED actor reference: `NOT (owner = actor)` asks for every principal the row does *not* name, which no join over memberships produces;
- a quantifier over a traversal;
- an actor inside a computed value or an aggregate.

A permit the planner cannot reverse answers `422 {"error": "unsupported", "code": "unsupported", "element": "<permit id>", "detail": "the permit's condition cannot be reversed into a subject query"}` for the WHOLE request. The endpoint never returns a partial list beside a permit it cannot reverse.

**The answer.** When every applicable permit reverses, the answer is the union over those permits, plus every live share on the record whose actions include the one asked about. There is one row per membership:

- `principal`, `kind`;
- `display_name`/`login`, under the caller's own `Principal` readable fields;
- `via`, naming the permit id or `{"share": "<id>"}` that admitted it.

**Paging.** Pages default to 100 and cap at 500, ordered and cursored by principal id. `complete` is `false` whenever a cursor was returned, the cap was hit, or a subject was dropped because the caller's own `Principal` program hides them. `next` is always present in the body (`null` once the page is complete), so a client never has to special-case a missing key.

**Who is never a subject.** A deactivated membership, one whose account is suspended, and the tenant's own engine principal are never subjects.

**Without a record.** Naming no `record` lists every principal an UNCONDITIONAL permit admits on every row. Every conditional permit's own id is reported under `conditional_permits` instead of being expanded. Because `role_admin` holds every action unconditionally, its holders are subjects of every record — often including the caller who asked.

**Through a family route.** A permit names one concrete kind exactly, so the permits judged are the kind's the row actually is. With a `record`, a lookup whose `object` is a family's root or another base judges the record's own kind's permits and shares, and answers as the concrete route would. Without one, it covers every concrete kind a row read through that route may hold: a holder of an unconditional permit on any of them can read some of its rows.

**Hierarchy is not expanded.** No check reads the principal hierarchy closure, so subject lookup mirrors exactly what a check would decide today, no more.

### Exports

Three endpoints answer the same shape:

- `GET /tenants/{key}/audit/export` (`audit.export`);
- `GET /tenants/{key}/attempts/export` (`security_attempt.export`);
- the instance twin `GET /control/attempts/export` (operators).

The request and response:

- a required RFC 3339 `from`/`to` window at most 31 days wide. Absent, inverted, empty, or over-wide is one refusal, `422 invalid_window`;
- a `limit` (default 10 000, max 100 000), CLAMPED rather than refused;
- the response is `200 application/x-ndjson`, one JSON object per line, oldest first;
- a final summary line `{"export": {"rows": N, "complete": bool[, "next_from": "...", "next_after_id": "..."]}}`.

**Resuming.** The query asks for `limit + 1` rows. When the extra one comes back, the page answers `complete: false` and names the LAST KEPT row's `(occurred_at, id)` pair as `next_from` and `next_after_id`. Resume by handing BOTH back, as `from` and `after_id`; the page then starts strictly after the row you already read.

Both halves are required. `occurred_at` alone is not unique, because one transaction stamps every row it writes with the same `transaction_timestamp()`. A resume on the timestamp alone would re-serve the same page forever once a single instant held more than `limit` rows. The summary line carries the fields too, so a caller that never looks past it still cannot mistake a page for the whole window.

Export bodies are materialized in full up to the cap rather than streamed to the wire; streaming is not yet supported.

#### Never more than the public projection

Every field that could carry a secret, a handle to one, or free text a person typed is not merely filtered out of an export row; it is never selected. Those fields are: session ids, credential ids, tokens, verifiers, trace ids, `reason`, request bodies, `parameters`, `proposals`, `action_name`, `grant_id`, `elevation_id`, `method`, `detail`.

An audit row carries `id`, `occurred_at`, `operation`, `object`, `record`, `actor` (`principal`, `account`), `actor_metadata_version` (the metadata version the actor was resolved under), and `affected` (every record the event wrote).

An attempt row carries `id`, `occurred_at`, `action`, `object`, `result`, `code`, `actor`, `audience`, `actor_metadata_version`, and `determining_permits`. Its `object` is the object the refusal was about: the object a denied read named, `Event` for a query the `audit.read` gate turned away, or the route's own `{object}` segment. It is `null` when the refusal reached no object at all, which is every authentication refusal and every refusal that is not about an object.

The instance twin's row additionally carries `tenant`, present only there. Every id on the wire is a plain uuid, never a `TypeID`.

#### Exports are themselves audited acts

Each call writes exactly one event — `security:audit.export`, `security:attempt.export`, or the control plane's `control:attempt.export`. The event names the window, the row count, and whether the cap cut it, and never the rows read. The `SELECT` runs before that event is inserted, in the same transaction. So an export never contains its own receipt, and always appears in the NEXT export over an overlapping window.

### `permitted`

A record response can carry a `permitted` block, `{"actions": [...], "writable_fields": [...]}`. For the row already returned, it answers what this actor may do to it NEXT and which of its attributes they may change. It is checked by the same write check every write path reaches, over the endpoint's own completed records, and rolled back unconditionally like explain (no audit event, no attempt row).

`actions` lists, each only when the check allows it:

- `read` first — a fact, since the row already passed the caller's read program;
- then `update`, then `delete`;
- then each declared `action.<name>.invoke`, in name order.

`create`, `share`, `reference`, traversals, and `action.<name>.approve` are never checked here.

`writable_fields` is the check's own field witnesses minus whatever any layer left uncovered — a role permit, a delegation cap, or a share's own field cap. It is not a union computed beside the check. So a row reached only through a share reports exactly the fields that share transfers, and a delegated write reports exactly what the grant still covers, never what the underlying role alone would.

**Where it appears.** Every `GET /tenants/{key}/objects/{Object}/{id}` carries it unconditionally. A UI query row carries it only on request: `include: ["permitted"]` in the query body, refused `unknown_include` for any other name this metadata version does not serve. The exception is a query bound to one record's own context, which gets it appended whether asked for or not, the same as the single-record endpoint.

**How a form should read it.**

- A generated `view`/`edit`/`create` surface — gated commands and forms over writable attributes — always `consumes_permitted`.
- A `list` surface does not, because a list gates nothing per record; it asks for the block per query instead when it wants one.
- A hand-built page `consumes_permitted` exactly when some bound component in its tree WRITES a field (as the UI compiler determines it). So a read-only dashboard or report never claims authority it never asks anyone to exercise.

A form that renders a control before `permitted` answers is guessing. One that offers an action absent from `actions`, or a field absent from `writable_fields`, is offering something the endpoint will refuse.

### `create` on a surface document

A new record has no `permitted` block, so a surface document answers create instead. Every object surface carries `create: {"allowed": ..., "writable_fields": [...]}` for its own object, and every `object` binding in the tree carries the same block on its value, for this viewer. It is read off the compiled policy, with no record:

- `allowed` means "may create SOME records". A permit whose `after` reads the values entered counts, so `true` does not promise that every record will be accepted.
- `writable_fields` is what may be set on EVERY record they may create: the fields of the unconditional create permits, plus the fields every matching create permit covers. A delegated session intersects the same three layers the write check uses.
- An abstract root is `allowed` when some concrete member below it is, and names no fields.

`GET /tenants/{key}/ui/objects` carries the same block on each listed object. The console leaves "New" off a list and its search palette when `allowed` is false, marks a create-form field outside `writable_fields` (a necessary input says the new record needs it), and disables Create, saying why, when such a field is a necessary input; a component reads it with `useCreatePermitted(props)`. Such a document is this viewer's own (`Cache-Control: private`, an `ETag` naming the viewer). The create endpoint is still authoritative: `allowed: true` can over-offer, for example when a condition reads only the actor.

## Ids: TypeID on the wire

Every externally emitted engine-owned `id` and every `ref` value is `TypeID`-formatted: `<snake_object>_<26-char base32 suffix>`. For example, `widget_01h455vb4pex5vsknk084sn02q` for a `Widget` row.

This is a wire-only relabeling of the stored `uuid`, which itself defaults to `uuidv7()`, not random `v4`. The prefix is the same `snake_case` name reflection already uses for the object's table.

A declared `uuid` attribute is ordinary user data, not an engine-owned id. It stays bare, in both directions.

Every id-accepting input accepts **either** form, the `TypeID` a prior response returned or a bare uuid. That covers a `ref` value in a create/update body, `{id}` in a `GET`/`PATCH`/`DELETE` path, and a `UUID '...'` literal compared against `id`/`path.id` in BQL. In BQL a plain string holding the `TypeID` (`'issue_01h…'`) is accepted too.

A `TypeID` whose prefix disagrees with what the context expects is refused `422 id_prefix_mismatch` before any database access, never silently coerced to the "right" object. The expected object is a ref's declared target object, the route's `{Object}`, or an `id` path's target object. In BQL the refusal is a `bql_compile_error` with that same code.

In BQL specifically, `id` and `<path>.id` are pseudo-attributes, resolvable in projection and `WHERE` everywhere a declared attribute would be. See "BQL" below for their full operator set and the `ORDER BY` exclusion.

## Error shape

Every error response is one shape, carrying the metadata element at fault:

```json
{"error": "refused",
 "code":  "removal_not_supported",
 "element": "Widget.legacy_code",
 "detail": "declared previously, absent in submitted document; removing elements is not supported in M1"}
```

A refused metadata plan also carries a top-level `"refusals"` array: one entry per refused element, each with its own `code`/`element`/`detail`. A caller can act on every refusal in one response rather than fixing one and re-submitting to discover the next.

### Every error at once

A refusal lists every error the validator found, not only the first. When there is more than one, or the one carries `later_checks_skipped`, a top-level `"errors"` array carries them, `[{code, element, detail, follows_from?, later_checks_skipped?}, …]`, and the four top-level fields mirror `errors[0]`. Fix them all before pushing again.

The same holds for a write. A create or `PATCH` body with three bad fields is refused naming all three (`Widget.active`, `Widget.opened`, `Widget.tier`). A raw proposal lists each bad field of every operation at its position, `operations[i].values.<field>` (see "Raw proposals").

- **Where it stops.** A file that cannot be read (malformed JSON or YAML) is checked no further, since there is nothing in it to check. An error inside a file that was read does not stop the other files' references from being checked.
- **Every stage, over what resolved.** Once the data model (objects, relationships, types) is sound, the app's views and pages, its other apps and its policies are all checked in the same push, each over whatever of the rest resolved, so a page problem and a policy problem are refused together. Inside the views, a refused `record_pages:`-style entry does not stop the pages' own checks (components, bindings, queries); most other view errors do, and say so. A refused data model still stops them: they all need it, so fix the model's errors first and the rest follow in the next refusal. The database plan's checks run only once all of this is sound.
- **Checks that were skipped.** A check that needs something an earlier error refused is skipped rather than reported as a second error (a binding to a query that did not resolve, say, or the binding checks of a page whose tree could not be built). The earlier error then carries `later_checks_skipped: true` (on a push, `(checks that depend on this were skipped; more may follow once it is fixed)`), so expect more errors from that part after fixing it.
- **Root causes first.** One mistake can cause others. An error that follows from another carries `follows_from`, the `element` of the error it follows from, and comes after every root cause. Fix the root and its knock-ons go away. Basel marks one case: a file that cannot be read, and every reference elsewhere to what it declares (an object or relationship named in backticks in the detail).
- **The cap.** `errors` lists at most 20. When there are more, `errors_omitted` counts the rest.
- **On `git push`.** Each error is its own `remote: Basel:` line, root causes first, and a knock-on is folded into its root's line as `(and K errors that follow from this one)`. At most 20 lines and 2,048 characters, never cutting an error in two, then a last line `and N more`. The rejected line names the first error and how many more lines are above. `basel validate` prints the same lines.

### A model that changed under the request (`409 model_changed`)

A tenant's model can change between building a request and sending it: a push applies, a field is archived, a table moves. Any such request is refused `409 model_changed` rather than served through a model that no longer exists. `diff.metadata_version` is the tenant's current version; reload the model (reflection, the UI app) and send the request again.

- **Send the version you built on.** A client may send `Basel-Model-Version: <n>` on any `/tenants/{key}/…` request. When `n` is not the current version, the request is refused before it runs. The console sends it on every request.
- **Without the header**, a write that began under the old model is refused the same way when the tenant's version moves under it. A read or query that meets a column or table the apply renamed, moved or dropped is too, instead of failing as a server error.
- The console answers `model_changed`, and a named query's `412 stale_ui`, by offering the application update. Applying it keeps any open draft.

### Guard and invariant failures

A write refused by a guard's `assert` is `422` with:

- `code: "guard_failed"`;
- `element: "<Object|Relationship>.<guard name>"`;
- `detail`: the guard's own `message` when it declared one, else a derived detail.

A refusal caused by the guard's expression evaluating `NULL` says so, for example `"guard evaluated to NULL (unknown)"`, distinct from an ordinary `FALSE` refusal. When the guard *does* declare a `message`, a NULL-caused refusal appends that same note to it, for example `"Amount must be positive (guard evaluated to NULL (unknown))"`, rather than the message alone reading identically to an ordinary `FALSE` refusal.

Like a refused plan's `"refusals"`, an additive top-level `"errors"` array, `[{code, element, detail}, …]`, carries **every** failing guard: `commit()` evaluates all binding guards in declaration order and collects every failure. The four top-level fields always mirror `errors[0]`, so a client reading only them keeps working unchanged.

An **invariant** failure (`code: "invariant_failed"`, element `"<Object>.<invariant name>"`, see "Aggregates, rollups, and invariants") rides this same array, one entry per failing object.

A single guard or invariant failure carries `errors` too. Any other single error carries no `errors` array; several errors of any kind carry it (see "Every error at once").

A guard failure and an invariant failure never appear in one response. Guards are a hard gate, so a refused guard means no write, no recompute, and therefore no object post-state to assert against.

### A write that collided with a concurrent one

When the database rolls a write back to break a deadlock or a serialization conflict with another write, the answer is `503` with `error: "unavailable"`, `code: "write_contention"` and a `Retry-After: 1` header, on every door that writes. Nothing was written, so send the same request again.

### A tenant waiting for a metadata migration

When a tenant's stored metadata no longer loads on this engine (it predates a grammar change), the engine still starts. Every request to that tenant answers `503` with `error: "unavailable"`, `code: "metadata_upgrade_required"`, the first refusal's element, and a `detail` naming the refusal.

Only these stay open for that tenant:

- its metadata Git endpoints (`/git/<tenant>/…`: fetch, push and plan, open to its `admin` members);
- `GET /tenants/<tenant>/git/status`;
- `/git/receives`.

Push corrected metadata there with the usual plan approval. Once the push applies, the tenant is served again without a restart.

The operator's `GET /tenants` lists the reason under `needs_migration` (`null` for a tenant that loads). A push to such a tenant is planned against its stored metadata read through the upgrade view (plan advisory `previous_metadata_upgraded`), or refused with `previous_metadata_unreadable` when even that cannot read it.

### Name clashes

A push whose tenant tree and vendored packages would give one short name to two objects, relationships, named types or queries is refused `422` with:

- `code: "ambiguous_name"`;
- the short name as `element`;
- an additive top-level `"candidates"` array: one `{name, namespace, package?, version?, path?}` per element the name could mean. `name` is the full `namespace:short`; a tenant-authored candidate is `namespace: "core"`.

A client therefore need not parse `detail`. No other error carries `candidates`.

Related package refusals:

- a package that declares no namespace but exports a model element is refused `package_namespace_missing`;
- one whose namespace is malformed or reserved (`core`, `basel`) is refused `invalid_namespace`;
- two packages declaring one namespace are refused `namespace_conflict`.

### Rule owner

A refusal caused by a guard or invariant the tenant added to a package's object carries an additive `"owner": "tenant"`, at the top level and on its `errors[]` entry, naming who owns the rule. It appears only when the rule's owner differs from the object's. No other error carries `owner`.

## Metadata files at a glance

A tenant's metadata is a Git repository of small JSON (or YAML) files: one path per construct. This section is the quick reference: every path, every top-level key, and the shape each key takes. It ends with one small repository that `basel validate` accepts, showing each common file kind once. The sections after this one explain each construct in depth. "Format 2" (under "Start here") gives the rules every file follows.

### File rules

- **Only known paths.** Every file must sit at one of the paths in the table below. Anything else is refused `unknown_path`, including a script, stylesheet or `README.md` under `ui/components/` and a nested folder. `README.md` and `.gitignore` are ignored only at the repository root.
- **JSON or YAML, by extension.** Every metadata file is one strict JSON object in a `.json` file, or the same object in strict YAML in a `.yaml` (or `.yml`) file (see "Format 2"). The paths below are written `.json`; each may be `.yaml` instead, but not both. A format-1 repository is converted with `basel convert` (see "Converting from format 1").
- **The file name follows the declaration.** A file's identity key (`name`, or `object`/`page` for UI and policy files) must snake-case to its file name: `"name": "ProjectTasks"` lives in `relationships/project_tasks.json`. A mismatch is `filename_mismatch`; the same declaration twice is `duplicate_construct`.
- **Package objects.** The tenant's view and policy file for a package's object name it with the package namespace, `"object": "crm:Contact"`, and sit in a folder named after the namespace (`ui/objects/crm/contact.json`, `policies/crm/contact.json`). Its additions sit in that kind of folder too (`additions/crm/contact.json`) but name the object by its short name, `"object": "Contact"`, because the folder supplies the namespace; `"crm:Contact"` there is `unknown_object`. A folder that disagrees with the namespace is `filename_mismatch`.
- **Expressions are JSON strings.** Expressions use single quotes for text, so they sit inside JSON's double quotes without escaping: `"assert": "row.status = 'open'"`. A double quote inside an expression (a quoted identifier) is escaped as JSON requires: `"assert": "row.\"order\".status = 'open'"`. In YAML an expression needs no quotes (`assert: row.status = 'open'`) unless it starts with a quote, a bracket or another YAML indicator, or holds `: ` or ` #`.
- **Sizes.** At most 4 MiB per file (`file_too_large`) and 16 MiB per repository (`repository_too_large`).

### Paths

| Path | Declares | Identity |
|---|---|---|
| `basel.json` | the app: format, name, title, currency, time zone, packages | (required) |
| `objects/<snake>.json` | one object: fields, lifecycles, actions, rules | `name` |
| `relationships/<snake>.json` | one relationship | `name` |
| `types/<snake>.json` | one named type, structured type, tagged reference or interface | `name` |
| `queries/<snake>.json` | one query plan, public or internal | `name` |
| `tasks/<snake>.json` | one task: runner, input, instructions, result (needs `BASEL_TASKS=1`) | file stem |
| `triggers/<snake>.json` | one trigger: the event that starts a task, and its input | file stem |
| `functions/<snake>.json` | one function: an export of a module, with its `kind` | `name` |
| `wasm/<snake>.wasm` | one WebAssembly module | its path |
| `policies/roles.json` | every role | (one file) |
| `policies/<snake>.json` | every permit on one object or relationship | `object` |
| `policies/assertions.json` | structural expectations about the policy | (one file) |
| `additions/<namespace>/<snake>.json` | the tenant's fields and rules on a package's object | `object` |
| `archives.json` | archives to restore or destroy | (one file) |
| `ui/app.json` | the app's UI definition | (one file) |
| `ui/apps/<name>/app.json`, `ui/apps/<name>/pages/<snake>.json`, `ui/apps/<name>/objects/<snake>.json` | a further app of the tenant's: its UI definition, pages, and views of package objects | `<name>` (folder), `page`, `object` |
| `ui/objects/<snake>.json` | one object's view | `object` |
| `ui/pages/<snake>.json` | one page or page template | `page` |
| `ui/components/<snake>.json` | one tenant component manifest | `id` (`<namespace>.<name>`) |
| `ui/presentations/<snake>.json` | one tenant presentation (the app's look) | `id` |
| `ui/assets.json`, `ui/assets/<file>` | the tenant's images, fonts, scripts and stylesheets | logical asset name |
| `basel.lock`, `vendor/...` | installed packages, written by `basel upgrade` and `basel sync` | — |

### Keys and their shapes

"Object" means a JSON object keyed by name, whose member order carries no meaning; "array" means an ordered JSON array. The most common mistake is mixing the two up: `guards`, `locks`, lifecycle `states`, `effects` and `bindings` are arrays, while `fields`, `actions`, `lifecycles`, `invariants`, `validators`, `constraints` and `permits` are objects.

#### `basel.json`

- `format`: the number `2`, required. `name`: string, the app, required.
- `title`: string, the app's display name. `default_currency`: string, a currency code such as `USD`.
- `time_zone`: string, an IANA zone name such as `America/New_York`. `TODAY()`, `DATE()` and `DATE_TRUNC()` without a zone argument read local dates in it; UTC when absent. An unknown name is `invalid_time_zone`. Declaring or changing it plans with a `time_zone_changed` advisory and one `time_zone_dependent` advisory per formula, guard, rollup, action or other element that reads the clock or converts dates; values already stored are not recomputed.
- `dependencies`: object of package id to `{source, version?, ref?, path?, use?}`. `source` is a Git source: `git+https://…`, `git+file:///absolute/path`, or a local path; `path` is the package root inside that repository.
- **How a source is read.** Every spelling of `source` is read as a Git repository, through its refs and never its working tree: a version range chooses among its release tags (`v1.2.0`, or `<name>/v1.2.0` where `<name>` is the last segment of the package id), and `ref` names one branch, tag or commit instead. So a local package needs its built release committed, and a tag or a `ref`, before a tenant can use it.
- **Fetching a source.** A `git+https://` source is fetched by your own Git, with its credential helpers and `url.<base>.insteadOf` rewrites (map the URL to a local clone with `git config --global url.<local path>.insteadOf <url>`); a package the Basel Catalog lists is fetched from its release store by `basel upgrade` and needs no credential.
- `approve`: object of elevated-read approvals (see "Apps from packages").
- `apps`: object, optional, the apps people open by default: `{"default": "<app>", "by_role": [{"role": "<role>", "app": "<app>"}]}`, both members optional. An app is the primary app's `name`, a further app's name (`ui/apps/<name>/`) or an installed app package's namespace; a role is named as `policies/roles.json` names it, or by its id. An unknown app is `unknown_app`, an unknown role `unknown_role`, and a role default naming an app whose `audience` leaves that role out (counting the roles it includes) is `role_outside_audience`. `GET /ui/app` serves them as `default_apps` (see "Several apps (`ui/apps/<name>/`)").
- `package`: makes the repository a package source instead of a tenant (see "Apps from packages"). `default_currency`, `time_zone`, `approve` and `apps` belong to a tenant and are refused beside it (`package_tenant_setting`).

#### `objects/<snake>.json`

- `name`: string. `description`: string, optional (on every named declaration and rule).
- `fields`: object of field name to a field (next heading).
- `operations`: array of `create`, `update`, `delete`, the generic write verbs the object exposes. Omitted means none.
- `lifecycles` and `actions`: objects (see "Lifecycles and actions" below).
- `guards`: **array** of `{name, on, assert, message?}`, where `on` is an array of `create`/`update`/`delete`.
- `locks`: **array** of `{fields, unless, message?}`.
- `invariants`: **object** of name to `{assert, message?}`.
- `validators`: object of name to `{on, run, scope?}`; `run` names a function of kind `validator`. `constraints`: object of name to `{unique | exclude, when?}`.
- `sharing`: true or false. `extends`: string, the parent object. `abstract`: true or false. `backfill_kind`: string, the kind existing rows take when a populated object becomes a family root. `implements`: object (see "Subtypes and interfaces"). `extensible`: true or false (packages only). `renamed_from`, `restore` and `id_prefix` (the `TypeID` prefix a renamed object keeps for its record ids): see "Renaming a field, object or relationship".

#### Fields

Every business field is one entry of `fields`, and it has exactly one source of its value:

- **Stored:** `{type, nullable?, default?, backfill?, stamp?, numbering?}` plus the type's keys: `values` (an `enum` or a multi-select), `of` (a `set`), `to` (a `ref`), `currency` and `precision` (Money), `max_length` (a text field), `select` (a `ref`'s reference selector), `unique`, `on_delete`, `retype`, `renamed_from`, `restore`, and `display` (how the value reads; see "Display").
- **Formula:** `{type, formula, queryable?, usable_in_invariants?, display?}`. `formula` is an expression computed when the record is read.
- **Rollup:** `{type, rollup, nullable?, currency?, display?}`. `rollup` is an aggregate expression the engine maintains on every write that changes it.
- **Primary:** `{primary: {of, project?}, description?}`. This names one member of the to-many end `of` as the record's primary, such as the primary email of a contact. It declares no `type`. See "The primary member" below.

A field is required unless it says `"nullable": true`. A `default` or `backfill` is a typed literal, or for a default `{"expr": ...}`; a `stamp` is `{"on": "create" | "every_write", "value": {"expr": ...}}`. A lifecycle's state is a field too, but the lifecycle declares it: do not also list it in `fields`.

```json basel-fragment
{
  "fields": {
    "title": {"type": "text"},
    "count": {"type": "int", "default": "3"},
    "posted_on": {"type": "Date", "nullable": true},
    "opened_on": {"type": "Date", "default": {"expr": "TODAY()"}},
    "created_by": {"type": "ref", "to": "Principal",
                   "stamp": {"on": "create", "value": {"expr": "acting"}}},
    "total": {"type": "Money", "rollup": "SUM(row.lines -> amount)"},
    "tax": {"type": "Money", "formula": "row.total * 0.2"}
  }
}
```

#### The primary member

`"primary_email": {"primary": {"of": "emails", "project": "address"}}` stands for four ordinary declarations with fixed names, which reflection shows. Write it instead of building them by hand:

- `primary_email_ref`: a nullable `ref` to the member object. Without `project`, the field itself is this pointer.
- `primary_email`: a formula, `row.primary_email_ref.address`, typed like the member's field.
- The guard `primary_email_is_own` on create and update: the pointer is null or names one of this record's own `emails`.
- The action `set_primary_email`, whose one parameter `member` names the new primary. It switches the primary in one write, and the guard refuses another record's member.

The far end of `of` must be named and declare `"cardinality": {"max": 1}`. Declare `primary` on the object's own file, not in an addition. If the object already declares one of the four names, the declaration is refused `name_collision`. Roles grant `set_primary_email` like any other action.

Reflection lists each expansion under the object's `primaries`. The guard's `origin` is `{"kind": "primary", ...}`, naming every generated member.

On the record page, the related list for `of` (generated, or a `basel.inline_collection@1` section) marks the primary and lists it first. Each other row's menu offers **Make primary**, which invokes `set_primary_email`. The primary itself cannot be deleted while the pointer names it: a direct delete is refused `422 delete_blocked_by_reference` at `<Object>.primary_email_ref`, and a nested delete through `emails` by the guard `primary_email_is_own`. Make another member primary first. Deleting the record itself deletes its members with it, primary included, when its end of the relationship declares `"on_delete": "delete_members"`.

#### Lifecycles and actions

- A lifecycle is `{initial, states}`. `initial` is a string. `states` is an **array** of `{name, outcome?, description?}`, where `outcome` is `success`, `failure` or `canceled`.
- Every invocable lives in the object's one `actions` object. An action that moves a lifecycle says so with `transition: {lifecycle, from, to}`: `from` is an array of states, `to` is one state. A lifecycle has no transitions or effects of its own.
- Two transitions of one lifecycle may share a `from` state and a `to` state; they are told apart by name. A qualified Lead that converts to a new Deal or joins an existing one is two transitions, `convert` (a `create` effect) and `join_deal` (a `link` effect), both `qualified` → `converted`. Each has its own params, guards, effects and permits, the record page offers both, and reflection lists both. The one thing that needs a single answer is an `{"op": "transition", "lifecycle", "to"}` effect, which names no transition: metadata apply refuses it `invalid_effect` when two transitions enter its `to` from a common `from` (see "Sibling transitions").
- An action takes `params` (object of name to `{type, optional?, nullable?, default?}` plus the type's keys), `guards` (**array** of `{name, assert, message?}`, with no `on`), `bindings` (**array** of `{name, path}`), `effects` (**array** of operations, each `{"op": "set" | "create" | "update" | "link" | "unlink" | "transition", ...}`), `result` (object), and `run` (the name of a function of kind `action`, beside or instead of `effects`) with its `scope`, `errors` and `elevated`.

#### `relationships/<snake>.json`

- `name`: string. `from` and `to`: objects, one per end. `properties`: object, in the stored-field vocabulary. `unique`: true or false. `operations`: array of `create`, `update`, `delete`.
- `guards`: array, like an object's. `invariants` and `actions`: objects, like an object's. A relationship takes no `validators`.
- An end is `{object, name, cardinality?, nested?, on_delete?, reparent?, document_lock?, revision?}`:
  - `object` and `name` (the traversal name) are strings;
  - `cardinality` is an object, `{"max": 1, "min": 0 | 1}`;
  - `nested` is `{"create": [...], "update": [...]}`: the nested operations a generic create or update may perform through this traversal. `create` admits `link`, `create`, `unlink`; `update` also admits `update` and `delete`;
  - `on_delete` is `restrict`, `delete_members` or `detach`; `reparent` is `allow` or `refuse`;
  - `document_lock` is `{editable_when, editable_fields?, message?}`, never a bare condition; `editable_fields` is an array of the parent's stored field names that stay editable after the lock closes;
  - `revision` is true or false.

#### Other files

- **`types/<snake>.json`:** `name`, plus exactly one of: `base` and `check` (and `values` when `base` is `enum`); `fields` (object); `reference_choice` (object); `interface` (object). A scalar named type needs `check`, which reads only `value`.
- **`queries/<snake>.json`:** `name`, `exposure` (`public` or `internal`, required), `from`, `select` (array), `where` (expression, `row.` and `args.`), `params` (object of name to `{type, to?, values?, optional?}`), `optional_filters`, `order_by` (array of `{field, direction}`), `orderable`, `page` (`{default_size, max_size, total?}`), `group_by` (array of `select` names; makes the query grouped, and `select` may then hold `{name, value}` aggregate or key entries), and for a reference selector `"purpose": "reference"` with `target`.
- **`tasks/<snake>.json`:** `runner` (required, snake_case), `input` (object of name to a parameter, as an action's `params`), `instructions` (required text), `result` (required, `{"mode": "worker_writes", "may_call": ["<Object>.<action>", …]}`), `timeout` (`{lease?, heartbeat?, max?}`, durations such as `"15m"`), `retries` (`{max}`, 0 to 10), `idempotent`. See "Tasks and triggers".
- **`triggers/<snake>.json`:** `on` (`{"event": "created", "object": "<Object>"}`, or `{"event": "entered", "object": "<Object>", "lifecycle": "<lifecycle>", "state": "<state>"}`), `task`, `input` (object of task input to `"record.id"` or `"record.<field>"`).
- **`functions/<snake>.json`:** `name`, `kind` (`pure`, `validator` or `action`) and `code: {"module": "wasm/<file>.wasm", "export": "<export name>"}`.
- **`policies/roles.json`:** `roles`, an object of role name to `{id, includes?, read_fields?, grants?, tenant?}`. `grants` gives whole objects unconditionally (`{"Customer": ["read"]}`, with the `manage` and `*` bundles); every conditional or field-limited row grant is a permit (see "Role grants" under "Policy").
- **`policies/<snake>.json`:** `object` and `permits`, an object of permit name to `{roles, action, write?, where?, before?, after?, scope?}`. Each permit grants exactly one `action`. A relationship takes no `read` action: its readability comes from `read_fields` in a role (see "Policy").
- **`policies/assertions.json`:** `assertions`, an array of `{roles, cannot, on}` or `{roles, never_reads}`.
- **`ui/app.json`:** `presentation` (string, `<id>@<major>`), `home` (`{"object": …}` or `{"page": …}`), `navigation`, `shell`, `theme` (only when no `presentation` is selected), `queries`, `fonts`, `default_locale`, `supported_locales`, `audience`, `workspace_context`, `record_pages`, `list_pages`, `edit_pages`, `create_pages`, `defaults`. `title` is accepted and ignored: the app's title comes from `basel.json`. See "User interface".
- **`ui/objects/<snake>.json`:** `object`, plus `label`, `plural_label`, `description`, `record_label` (one of the object's own fields, never a dotted path such as `product.name`), `icon`, `compact` (array), `route`, `fields` (each field's widget), `record` (the record page's sections, ending with `{"fields": "remaining"}`), `editor` (equal to `record` when present), `create`, `list` (columns and sort, or a named query), `related_lists` (array), `relationships`, `queries` (object), `initializers`. See "Object views".
- **`ui/pages/<snake>.json`:** `page`, `label`, `route`, `template`, `queries` (object), `root` (a node, `{id, component, config?, bindings?, slots?}`).
- **`ui/presentations/<snake>.json`:** `id`, `contract_major`, `requires`, `tokens`, `variants`, and optionally `contract_minor` (0 when absent), `title`, `renderers`, `fallback`, `stylesheets`, `icons`, `layout` (the shell's layout and the page width), `theme`. Within one `<id>@<contract_major>`, adding a renderer family needs a higher `contract_minor` (`presentation_minor_required` otherwise); removing or changing a renderer, an existing family's fallback, `requires`, `variants` or a token needs a new `contract_major` or a new `id`.

#### A tenant's own look

A tenant does not need a theme package to have its own look. It can write a presentation under `ui/presentations/`, declare its stylesheet in `ui/assets.json`, list it in the presentation's `stylesheets` as `tenant:<asset>` (at most 16; any other spelling is `invalid_presentation_stylesheet`), and select the presentation in `ui/app.json` with `"presentation": "<id>@<contract_major>"`. The console loads those stylesheets into the `presentation` cascade layer while the presentation is selected. The presentation owns every token value: each token's `default` is the value drawn, and its `theme` carries the platform theme values. Its `layout` may choose a top-bar shell and the page width. "The styling contract" under "User interface" lists the hooks, tokens and attributes the stylesheet styles through. The repository below does exactly this.

### One repository with every common file kind

Each file starts with a `# file: <path>` line naming its path; the line is not part of the file. `basel validate` accepts this repository as written. It declares no function (a function needs a compiled `wasm/` module) and no addition (an addition needs an installed package).

```json basel-repository
# file: basel.json
{
  "format": 2,
  "name": "tracker",
  "title": "Tracker",
  "default_currency": "USD",
  "time_zone": "America/New_York"
}
# file: types/hours.json
{"name": "Hours", "base": "decimal", "check": "value >= 0"}
# file: objects/project.json
{
  "name": "Project",
  "operations": ["create", "update"],
  "fields": {
    "name": {"type": "text"},
    "code": {"type": "text"},
    "budget": {"type": "Money", "nullable": true},
    "priority": {"type": "enum", "values": ["low", "normal", "high"], "default": "normal"},
    "opened_on": {"type": "Date", "default": {"expr": "TODAY()"}},
    "created_by": {
      "type": "ref",
      "to": "Principal",
      "stamp": {"on": "create", "value": {"expr": "acting"}}
    },
    "closed_note": {"type": "text", "nullable": true},
    "task_count": {"type": "int", "rollup": "COUNT(row.tasks)"},
    "planned_hours": {
      "type": "decimal",
      "rollup": "SUM(row.tasks -> estimate WHERE row.done = false)"
    },
    "busy": {
      "type": "bool",
      "formula": "CASE WHEN row.task_count > 20 THEN true ELSE false END"
    }
  },
  "lifecycles": {
    "status": {
      "initial": "open",
      "states": [{"name": "open"}, {"name": "closed", "outcome": "success"}]
    }
  },
  "actions": {
    "close": {
      "params": {"note": {"type": "text", "optional": true, "nullable": true}},
      "transition": {"lifecycle": "status", "from": ["open"], "to": "closed"},
      "guards": [
        {
          "name": "has_name",
          "assert": "row.name != ''",
          "message": "Name the project before closing it."
        }
      ],
      "effects": [
        {"op": "set", "values": {"closed_note": {"expr": "COALESCE(args.note, 'closed')"}}}
      ]
    },
    "rename": {
      "params": {"new_name": {"type": "text"}},
      "effects": [{"op": "set", "values": {"name": {"expr": "args.new_name"}}}]
    }
  },
  "guards": [
    {
      "name": "name_present",
      "on": ["create", "update"],
      "assert": "row.name != ''",
      "message": "A project needs a name."
    }
  ],
  "locks": [
    {
      "fields": ["code"],
      "unless": "before.status = 'open'",
      "message": "The code is fixed once the project is closed."
    }
  ],
  "invariants": {
    "not_too_many_tasks": {
      "assert": "row.task_count <= 500",
      "message": "A project holds at most 500 tasks."
    }
  },
  "constraints": {"unique_code": {"unique": ["code"]}}
}
# file: objects/task.json
{
  "name": "Task",
  "operations": ["create", "update", "delete"],
  "fields": {
    "title": {"type": "text"},
    "estimate": {"type": "Hours"},
    "done": {"type": "bool", "default": false}
  },
  "guards": [
    {
      "name": "project_open",
      "on": ["create", "update", "delete"],
      "assert": "row.project.status = 'open'",
      "message": "Tasks change only while the project is open."
    }
  ]
}
# file: relationships/project_tasks.json
{
  "name": "ProjectTasks",
  "operations": ["create", "delete"],
  "from": {
    "object": "Project",
    "name": "tasks",
    "nested": {"create": ["create"], "update": ["create", "update", "delete"]},
    "on_delete": "delete_members"
  },
  "to": {"object": "Task", "name": "project", "cardinality": {"max": 1, "min": 1}}
}
# file: queries/open_projects.json
{
  "name": "open_projects",
  "exposure": "public",
  "from": "Project",
  "select": ["id", "name", "status"],
  "where": "row.status = 'open'",
  "order_by": [{"field": "name", "direction": "asc"}],
  "page": {"default_size": 50, "max_size": 200}
}
# file: policies/roles.json
{
  "roles": {
    "teammate": {
      "id": "role_teammate",
      "read_fields": {"Project": ["*"], "Task": ["*"], "ProjectTasks": ["*"]}
    }
  }
}
# file: policies/assertions.json
{"assertions": [{"roles": ["teammate"], "cannot": "delete", "on": "Task"}]}
# file: policies/project.json
{
  "object": "Project",
  "permits": {"teammate_reads_projects": {"roles": ["teammate"], "action": "read"}}
}
# file: policies/task.json
{
  "object": "Task",
  "permits": {
    "teammate_reads_tasks": {"roles": ["teammate"], "action": "read"},
    "teammate_updates_tasks": {
      "roles": ["teammate"],
      "action": "update",
      "write": ["title", "estimate", "done"]
    }
  }
}
# file: ui/app.json
{"presentation": "tracker.look@1", "home": {"page": "overview"}}
# file: ui/objects/project.json
{
  "object": "Project",
  "label": "Project",
  "record_label": "name",
  "icon": "target",
  "compact": ["code", "status", "task_count"],
  "record": {
    "sections": [
      {"id": "overview", "label": "Overview", "fields": ["name", "code", "priority"]},
      {"id": "more", "fields": "remaining"}
    ]
  }
}
# file: ui/pages/overview.json
{
  "page": "overview",
  "label": "Overview",
  "route": "/overview",
  "root": {"id": "overview", "component": "tracker.overview@1"}
}
# file: ui/components/overview.json
{
  "id": "tracker.overview",
  "version": "1.0.0",
  "contract_major": 1,
  "title": "Overview",
  "implementation": "react",
  "entry": {"asset": "tenant:tracker.app"},
  "accepts": [{"attachment": "ui.root", "modes": ["page"]}],
  "bindings": {},
  "config_schema": {"type": "object", "additionalProperties": false, "properties": {}},
  "slots": {},
  "draft": {"reads": [], "writes": []},
  "commands": [],
  "capabilities": [],
  "tokens": [],
  "responsive": {"min_width": 320, "preferred_width": 1120},
  "examples": []
}
# file: ui/presentations/tracker.json
{
  "id": "tracker.look",
  "contract_major": 1,
  "contract_minor": 0,
  "requires": {"presentation": 1},
  "tokens": {"color.accent": {"kind": "color", "default": "#2f6f4e"}},
  "variants": {
    "label_layout": "stacked",
    "button_decoration": "plain",
    "lookup_annotations": false,
    "narrow_below": 760,
    "minimum_target": 40
  },
  "stylesheets": ["tenant:tracker.styles"],
  "layout": {"content_width": "80rem"}
}
# file: ui/assets.json
{
  "assets": {
    "tracker.app": {"source": "assets/tracker.js", "kind": "script", "media_type": "text/javascript"},
    "tracker.styles": {"source": "assets/tracker.css", "kind": "stylesheet", "media_type": "text/css"}
  }
}
# file: ui/assets/tracker.js
/* basel-sdk-contract:2.0 */
export const components = {};
# file: ui/assets/tracker.css
:root { --tracker-accent: #2f6f4e; }
```
## Metadata grammar and type table

Canonical metadata is a decomposed Git tree of format-2 JSON files. Each file owns one construct:

- `basel.json` declares `format` (`2`) and `name` (the tenant's root app).
- `objects/<snake>.json`, `relationships/<snake>.json`, `functions/<snake>.json`, `queries/<snake>.json` and `types/<snake>.json` each own one named construct.
- `additions/<namespace>/<snake>.json` adds to one package object, a subtype family's root or one of its kinds included (see "Apps from packages").
- `wasm/<snake>.wasm` owns one WebAssembly module.
- `ui/` owns the app's UI definition, object, page, and indexed asset metadata.

`README.md` and `.gitignore` are ignored; every other path is refused. A construct's authored `name` (or UI object/page identity) must snake-case to its filename. Basel compiles these files deterministically into the read-only document returned by the metadata history endpoints; that compiled document is an internal format, not something to author.

Objects and fields retain authored casing in BQL and in JSON. Physical names are derived by snake-casing: `Widget` → table `widget`; `closeDate` → column `close_date`; a `ref` field `account` → column `account_id`. Two declarations that snake-case to the same physical name are a validation error at resolution, never a collision at apply time.

| Basel type | Postgres | Notes |
|---|---|---|
| `text` | `text` | |
| `bool` | `boolean` | |
| `int` | `bigint` | |
| `decimal` | `numeric(18,4)` | |
| `uuid` | `uuid` | user data, always bare on the wire — not an engine-owned id |
| `Money` | amount `numeric(18,4)`; open currency also has a currency column | Fixed or open currency; see "Money" below. Amounts cross JSON as strings. |
| `Date` | `date` | |
| `Timestamp` | `timestamptz` | written as RFC 3339 with an offset; always returned as RFC 3339 in UTC (`2026-09-18T00:30:53.214000Z`, always six fractional digits, so it sorts as text), which writes back unchanged |
| `Duration` | `interval` | fixed elapsed time; read and written as ISO-8601 (`PT3H12M`, `P1DT2H`) — always returned in canonical form |
| `DateRange` | `daterange` | |
| `Email`, `Url`, `Phone` | `text` | checked whenever a value is assigned; an `Email` is one address whatever its letter case in a unique rule and a key match; see "Email, Url and Phone" below |
| `PersonName` | `text` | never validated: any text is a name |
| `Region` | `text` | **deprecated**: plain text with no check; `basel validate` warns and `basel plan` carries a `region_deprecated` advisory. Declare `text` or a named type instead |
| `enum` | `text` + `CHECK (col IN (...))` | Not a PG enum type — see below |
| `set` | `text[]` | `"of": "text"` holds any strings; `"of": "enum"` with `values` is a multi-select, held by a `CHECK` — see below |
| `ref` | `uuid` + `FOREIGN KEY` | `ON DELETE RESTRICT`; `TypeID` on the wire |

**Display of `Timestamp` and `Date`.** A `Timestamp` is stored and sent as an instant (RFC 3339, UTC); the console shows it in the viewer's browser locale and time zone as a medium date with a short time (`Sep 23, 2026, 9:37 AM` in en-US). A `Date` has no zone and shows as the same calendar day everywhere (`Sep 23, 2026`). A packaged component is expected to do the same with the locale the host hands it.

Every object gets `id uuid PRIMARY KEY DEFAULT uuidv7()` — that column type is storage only; `id` renders as a `TypeID` everywhere it's emitted (see "Ids: TypeID on the wire" above).

### Values on the wire

`decimal` and `Money` values cross the JSON boundary as **strings**, never JSON numbers — a JSON number is an `f64` and would silently lose precision, so a JSON number there is refused, not converted. An `int` may be sent either way. Each type has one form in metadata files (see "Format 2"), the forms the record API takes (a create or update's `fields`, an action's or transition's `params`), and the one form it answers with:

| Type | Metadata literal | API takes | API answers |
|---|---|---|---|
| `int` (and a named type over it) | `"12"` | `12` or `"12"` | `12` |
| `decimal` | `"0.25"` | `"0.25"` only | a decimal string |
| Money, fixed currency | `"12.50"` | `"12.50"` only | a decimal string |
| Money, open currency | `{"amount": "12.50", "currency": "USD"}` | the same object, amount a string | the same object |
| `bool` | `true` | `true` only | `true` |
| `set` | `["a", "b"]` | an array of strings | an array of strings |
| `Date` | `"2026-11-01"` | the same | the same |
| `Timestamp` | `"2026-11-01T09:30:00Z"` | RFC 3339 with an offset | RFC 3339 in UTC |
| `Duration` | `"PT3H12M"` | ISO 8601 | ISO 8601, canonical |
| `ref` | — | a TypeID or a bare uuid | a TypeID |
| `text`, `uuid`, `enum`, `Email`, `Url`, `Phone`, `PersonName`, `DateRange` | a string | a string | a string |

An `int` string is the integer's digits with an optional leading `-` (`"5"`, `"-12"`, `"007"`), within the 64-bit range; `"5.0"`, `"+5"`, `" 5"` and `"1e3"` are refused `validation_error` (`'5.5' is not a valid int`), and so is a JSON number with a fraction (`5.5`, `5.0`, `invalid_bind`). A named type's `check` judges the integer either form carries. Any other form refuses `invalid_bind` saying what the field takes.

### Email, Url and Phone

These are stored as text, and Basel checks every value **assigned** to one, whatever assigns it: a create or update, a `default`, an action's `set` and other effects, a function body's writes. A value that fails refuses the write with `422 validation_error` on the field, saying what is wrong (a refusal from an action's effects or a function body is reported against the invocation). Surrounding whitespace is trimmed before the check and the trimmed value is stored; nothing else is changed.

- `Email`: an address as a browser's `<input type=email>` accepts one: `name@domain`, where the domain is dot-separated labels of letters, digits and hyphens (`ada@example.com`; `a@b` too). At most 254 characters. Case is kept: the address is stored as entered, but a unique rule and a key match ignore it (below).
- `Url`: an absolute URL with the scheme `http` or `https` (`https://example.com/docs`), at most 2,048 characters. `example.com`, `ftp://…`, `mailto:…` and `javascript:…` are refused. The value is stored as typed, not re-written.
- `Phone`: digits, spaces and `+ ( ) - . /`, with `+` only as the first character, and 3 to 20 digits. An extension may end it, written `x123`, `ext 123` or `ext. 123`; no other letters. Stored as typed (`(512) 757-6000`, `+1 415 555 0100 x12`); Basel does not reformat numbers.

**An `Email` ignores letter case where it is an identity.** In a unique rule and in a key match (`$match_on`, `{"match": …}`) it compares without regard to letter case, over the whole address, so `Jane.Rivera@Example.com` and `jane.rivera@example.com` are one address there: the second is refused `constraint_violated`, and a save by key in either case finds the row.

A unique rule built before this held case-variant addresses as different. The tenant's next `basel plan` or push tightens it, with no plan approval needed. If rows differ only in an address's case, that plan and push are refused instead, `constraint_apply_failed` on the rule with a count and a sample of the rows, and the rule stays as it was until they are merged; meanwhile a key match that finds more than one of them is refused `match_ambiguous`. Any other comparison (`=` in BQL, a filter) is exact; write `LOWER(address) = 'jane.rivera@example.com'` to compare without case.

A value stored before a field was checked (or before it became `Email`, `Url` or `Phone`) is left as it is: an update that does not assign that field succeeds, and so does one that sends the stored value back unchanged (the same text, ignoring surrounding spaces), so a client that sends the whole record can still edit the rest of it. A different value is checked. `basel plan` lists, per field, how many stored rows hold a value the check would now refuse (plan advisory `text_type_invalid_rows`, never a refusal).

### Text length

Every `text`, `PersonName`, `Email`, `Url` and `Phone` field has a length limit, counted in **characters** (not bytes: `"é"` and `"😀"` are one character each). A value over it refuses the write with `422 validation_error` on the field, naming the limit, and nothing is written. The limit holds for every value assigned, as the checks above do, and a value exactly at the limit is accepted.

- **Default:** 1,048,576 characters.
- **Sort and unique keys:** 500 characters, for a field Basel keeps in an index: the field a list, lookup or record label sorts by first, or a field in a `unique` rule. One index entry must hold the value, and 500 characters fit even when each takes four bytes.
- **Override:** `"max_length": <n>` on the field sets its own limit, from 1 to 268,435,456: `"title": {"type": "text", "max_length": 120}`, or `"body": {"type": "text", "max_length": 5000000}`. A sort or unique key may declare at most 600; more is refused `invalid_max_length` when the metadata resolves, since its index could not hold it. `max_length` on a field that is not text is refused the same way. `Email` and `Url` keep their own maximums too.
- **Reading it back:** reflection of a text field (`/reflect/objects/<Object>`, a relationship's properties, MCP `basel_discover`) carries its effective limit as `max_length`, the default included, so a client can check a value before it writes.

A value stored before a limit existed or was lowered is left as it is, under the same rule as the checks above: an update that does not assign the field, or sends the stored value back unchanged, succeeds. `basel plan` lists, per field, how many stored rows are over a limit lower than the default (advisory `text_too_long_rows`). While such rows remain in a sort key, Basel does not build that field's sort index, and sorting it stays unindexed until they are shortened and the next push or server start builds it.

### Multi-select (`set` of `enum`)

`"tags": {"type": "set", "of": "enum", "values": ["urgent", "billing", "legal"]}` is a field that holds any number of its declared values. `values` takes the same shape as an `enum`'s: a non-empty array of distinct strings. `values` on a `set` of `text` is refused.

- Every write is checked: each element must be a declared value (a refusal names the element, such as `Ticket.tags[1]`, and lists the allowed values) and may not be null. This holds for every value assigned, including one an action's effects assign.
- Duplicates are dropped and the values are stored in declared order, so `["legal", "urgent", "legal"]` is stored and returned as `["urgent", "legal"]`.
- An empty selection, `[]`, is stored as null: there is one empty state, and `tags IS NULL` finds it. A required multi-select needs at least one value.
- Query one in BQL with `SET_CONTAINS(tags, 'urgent') = true` or `SET_OVERLAPS(tags, 'urgent', 'legal') = true` (has any of); a quoted value must be a declared one. The same functions work in guards, formulas and rollup predicates, with the field rooted (`SET_CONTAINS(row.tags, 'urgent') = true`), and on a `set` of `text`. They are null for an empty (null) multi-select, so write `COALESCE(SET_CONTAINS(row.tags, 'urgent'), false) = false` to match records without `urgent`, empty ones included.
- Adding a value is an ordinary change. Removing one is flagged (the push needs the plan's approval), and applying it fails while any record still holds the removed value: change those records first. Turning a `set` of `text` into a multi-select is flagged the same way and fails while a record holds an undeclared value; turning a multi-select back into a `set` of `text` is refused.
- Multi-selects are not grouped or reported on.

### Money

- `{"type": "Money"}` is in the currency `basel.json` names as `default_currency`. `"currency": "EUR"` on the field fixes another currency. `"currency": "open"` lets each row carry its own currency, stored in an extra column. A `Money` parameter of an action, a transition, an interface or a task (which takes no `currency`) is in the `default_currency` too, so it can be assigned to a `Money` field that names none; assigning it to a field in another currency is refused, and the refusal names both currencies (`… is Money in EUR; the assigned value is Money in USD`).
- **Packages and currency.** A package's Money field should leave `currency` off, so it takes the currency of the tenant that installs it (`default_currency`); a package field that names one currency cannot be used as shipped by a tenant in another, and `basel build` warns about it. A tenant that has Money but no `default_currency` gets a plan advisory: its Money keeps four places and is not checked against a minor unit. Declaring `default_currency` later changes no stored data.
- **Moving a field to open.** A field in a named currency (its own `currency` or the `default_currency`) may be changed to `"currency": "open"`. The plan adds the currency column and gives every stored amount the field's old currency; the amounts do not change. It is flagged (a push needs the plan's approval) and carries a `money_currency_opened` advisory, because the field is then read and written as `{amount, currency}` instead of a bare amount, so clients, functions and UI that use it must change too. It cannot be undone. Changing one named currency to another, changing open back to fixed, and changing a field with no named currency to open are refused `retype_not_supported`: declare `default_currency` first, apply it, then make the field open.
- An amount crosses JSON as a string at its field's **precision**: the currency's minor unit (`"12.50"` in USD, `"5000"` in JPY, `"1.250"` in BHD), or four places for Money with no named currency. An open-currency value is written and read as `{amount, currency}`, its amount at that value's own currency's precision.
- `"precision": 0` to `4` on a Money field keeps that many places instead of the currency's minor unit, e.g. a unit price to four places: `"unit_price": {"type": "Money", "precision": 4}`. Storage keeps four places either way.
- A value you write may not have more places than the field keeps (`1.005` in a USD field refuses `422 validation_error`); trailing zeros are fine, so `"12.5000"` is accepted and every amount Basel returns can be sent back unchanged.
- Money is **rounded half away from zero to its field's precision** at fixed points: a Money formula's result, each term of a Money `SUM`/`MIN`/`MAX` before the terms are combined, and every Money value Basel computes and stores itself (an action's `set` and other effects, a function body's writes, a rollup). Arithmetic inside one expression keeps four places until then. So three invoice lines of `19.79 * 0.25` are `4.95` each and total `14.85`, and a guard, a query and a read all see that same `14.85`.
- `ROUND(x)` / `ROUND(x, places)` rounds the same way. For Money without `places` it rounds to the field's precision (when `x` names a Money field) or its currency's minor unit; for a `decimal` without `places` it rounds to a whole number. `places` is a whole-number literal from 0 to 4.
- A stored amount with more places than its field keeps (written before rounding existed, or before `precision` was lowered) is left as it is and returned with those places. Sending it back unchanged in an update is accepted and leaves it as it is, so the rest of the record can still be edited; a different amount with too many places is refused. It is rounded the next time that field is written with a new value, and a rollup the next time it is recomputed. `basel plan` lists, per Money field, how many rows hold such amounts.
- In expressions, a money literal names its currency (`12.50 USD`). Basel never converts between currencies; see "BQL" for aggregating open-currency amounts.

### Display

The API always returns canonical values: an `int` as a JSON number, a `decimal` or Money amount as a string. How a value reads to people is the field's optional `display` block, and every reader Basel owns (the console's pages, lists, metric tiles and chart labels) applies it. It is a fact about what the number means, so it lives on the field, not on each screen:

- `"grouping": false` (int, decimal, Money) turns thousands separators off. A year, a code or an outside id is an identifier, not a quantity: `"year": {"type": "int", "display": {"grouping": false}}` shows 1965, not 1,965. An `int` with `numbering` or `"unique": true` is ungrouped without saying so; `"grouping": true` puts the separators back.
- `"style": "percent"` (int, decimal) reads a ratio as a percent: a stored `"0.25"` shows as 25%. The default is `"number"`.
- `"decimals": 0` to `4` (decimal, Money) shows that many places, rounded for display only; the stored value and the API keep every place. More places than a Money field keeps (its `precision`, else its currency's minor unit) is refused.
- `"currency": "symbol" | "code" | "none"` (Money): `$12.50`, `USD 12.50` or `12.50`. The default is the symbol.
- `"lines": "single" | "multi"` (text): `multi` keeps the value's line breaks and gives it a full-width, multi-line box; the object view's `"config": {"presentation": "multiline"}` says the same.

A formula and a rollup take `display` too. A key on a type it does not suit, an unknown key, or a value outside these is refused `invalid_display` when the metadata resolves. Reflection (`/reflect/objects/<Object>`) and the UI field descriptors carry each field's `display`, with an identifier's `"grouping": false` filled in, so an outside client can format a value the same way. Changing a field's `display` is a model change, applied by a push like any other.

One screen may make a value more compact, but not change what it means: an object view's `fields.<f>.config.display`, or a metric's or chart's own `config.display`, takes only `decimals` (fewer than the field shows, never more), `currency`, and `"units": "auto"` for compact figures ($1.2M). `grouping` and `style` there are refused `invalid_display`.

### Creation defaults (`default`)

A stored field may declare a literal creation default. The literal is a typed literal:

- `enum`/`text`-family values and `Date`/`Timestamp` as strings;
- `int` as a **decimal string** (`"3"`);
- `decimal` as a **decimal string** (`"0.25"`, the same precision rule above);
- `bool` as `true`/`false`;
- `Money` as a decimal-string amount (`"12.50"`, a fixed-currency field) or `{"amount": "12.50", "currency": "USD"}` (an open one).

A literal that does not fit the field's type is `invalid_literal` when the file is read; it is then validated against the field's own resolved type at metadata resolution — the identical gate a guard or rollup literal passes through.

`default` is refused (`invalid_default`) on:

- a `ref` or `set` field (neither has a creation-time literal form);
- a rollup or formula (its value is computed, never created);
- a relationship property (`default` applies only to an object's own fields).

A default is applied **exactly once**, on create, to a declared field the request omits **entirely**. An explicit `null` is not "absent": it is validated exactly as it would be with no default declared (required and missing, if the field is not nullable). A default is never re-applied on update, and never overwrites a value the request actually supplies.

Defaults behave identically through the generic endpoints, the nested write path, and creates made by action effects or functions, since all three seed a create's starting row from the same declared defaults. Reflection publishes a default as `"default": <literal>` on the field, in its wire shape — present only when declared, never `null`.

### Expression defaults (`{"expr": ...}`)

A default may instead be one of a small, fixed set of expressions, written `"default": {"expr": "<expression>"}`:

- `NOW()` — the write's own instant, for a `Timestamp` field;
- `TODAY()` — that instant's date in the tenant's `time_zone` (UTC when none is declared), or `TODAY('<IANA zone>')` in a named zone, for a `Date` field;
- `acting` — the principal making the write, for a `{"type": "ref", "to": "Principal"}` field. A service account is its own caller; under a delegation grant, `acting` is the delegate that acted, while a permit condition's `actor` is the principal the write is on behalf of, so the two differ only under delegation. `actor` is refused here.

```json basel-fragment
{
  "fields": {
    "opened_at": {"type": "Timestamp", "default": {"expr": "NOW()"}},
    "opened_on": {"type": "Date", "default": {"expr": "TODAY()"}},
    "owner": {"type": "ref", "to": "Principal", "default": {"expr": "acting"}}
  }
}
```

One more form looks up the caller's own record of an app object: `"default": {"expr": "LOOKUP(Member WHERE row.principal = acting)"}` fills a `{"type": "ref", "to": "Member"}` field with the `Member` whose `principal` is the acting principal, or `null` when there is none (so declare the field nullable unless every caller has one). Inside `LOOKUP`, the object is named bare and `row.` is the candidate `Member`. `principal` must be a `ref` to `Principal`, and `Member` must declare it unique with no condition (`"unique": true`, or a unique constraint on exactly that field with no `when`), which proves at most one row matches; otherwise it is refused `invalid_default`. The engine reads that one row itself, so the person creating the record need not be able to read `Member`. A subtype family member cannot be looked up.

Nothing else is admitted: no field references, no related-record hops, no aggregates, no arithmetic. Anything else — or an expression whose result does not fit the field's type — is refused `invalid_default` at metadata resolution, and the detail names what is allowed. A literal is written directly as `"default": <literal>`, never inside `expr`; a plain string is always a literal, so `"default": "NOW()"` is the text `NOW()`.

An expression default is a suggestion, exactly like a literal one: it fills a field the create omits entirely, an explicit `null` stays `null`, and a supplied value always wins. It is evaluated on the server, at create, through every door — the generic and nested endpoints, raw proposals, action effects, functions and conversion. `NOW()` and `TODAY()` read the write's one transaction instant, the same instant its audit event records as `occurred_at`, so every record one write creates agrees on it.

Reflection publishes it as `"default_expression": "<source>"` (internal spelling: `actor` for `acting`) — never under `default`, which is a value a client may prefill — beside `"set_when_saved": true`. The generated create form leaves the field empty and says "Set when saved"; the author may still type a value.

### Stamps (`stamp`)

A **stamp** is a value the engine owns: `"stamp": {"on": ..., "value": {"expr": ...}}`. The value is `NOW()` (a `Timestamp`), `acting` (a `ref` to `Principal`) or `LOOKUP(Member WHERE row.principal = acting)` (a `ref` to `Member`, under the rules above). `"on": "create"` sets it when the record is created; `"on": "every_write"` sets it then and again on every later write to the record — an update, a transition, an action or a conversion.

```json basel-fragment
{
  "fields": {
    "created_by": {"type": "ref", "to": "Principal", "stamp": {"on": "create", "value": {"expr": "acting"}}},
    "changed_at": {"type": "Timestamp", "stamp": {"on": "every_write", "value": {"expr": "NOW()"}}},
    "changed_by": {"type": "ref", "to": "Principal", "stamp": {"on": "every_write", "value": {"expr": "acting"}}}
  }
}
```

A value supplied for a stamped field is refused `managed_attribute`, naming the field, through every door — create, update, nested, proposal and conversion alike. An effect naming a stamped field is refused `invalid_effect` at metadata resolution, and a permit listing one in `write` is refused `invalid_permit`: no permit can make a stamp writable, and permitted-field listings leave it out. A stamp may not also declare `default` (`invalid_stamp`); like a default, it is not available on a relationship property. `created_at` and `modified_at` are the engine's own audit fields already, so a stamp needs another name.

Reflection publishes a stamp in its internal spelling, `"stamp": {"value": "actor", "on": "create"}` (`now` for `NOW()`, `actor` for `acting`), with `"read_only": true` and `"set_when_saved": true`. Forms show it read-only, and a create form shows "Set when saved" in its place.

### Filling existing rows (`backfill`)

`backfill` is a *second*, independent literal. A migration uses it to fill a required field's existing rows the moment the field is first added to a table that already has data. Django's one-off default prompt is the precedent.

It takes the same typed-literal shapes, passes the same validation gate, and uses the same refusal code shape as `default` (`invalid_backfill` in place of `invalid_default`). It is refused the same way on a `ref`/`set` field, a rollup or formula, and a relationship property; it is never an expression.

`default` and `backfill` are independent keys with **independent lifetimes**. Declaring both on the same field is legal, and each can carry its own literal.

- `default` is read by the engine, every time a create omits the field, for as long as it stays declared.
- `backfill` is read **once**, by the planner, at the moment a required field is added to a table that already has rows — never again afterward, and never at create.

Adding a required field to a table that already has rows is refused (`required_column_on_nonempty_table`) unless the field declares `backfill`. Basel has no other value to fill existing rows with. The refusal's own detail names the remedy: declare a `backfill` literal to fill existing rows, or declare the field `"nullable": true`. A `default` does not help here: it applies only to records created later.

A rollup is the exception: it is never filled by a literal, so a required rollup on a populated table is refused with a different remedy. Declare it `"nullable": true`. The apply then adds it at once and computes it for every existing row in the background (see "Recomputing rollups" under "Aggregates, rollups, and invariants").

With `backfill` declared, the plan emits one `backfill_required_column` operation instead of refusing. It runs these steps, all in the one apply transaction:

1. `ADD COLUMN ... NULL`;
2. a row-fill step writing the literal into `<column>` wherever it is still NULL;
3. `ALTER COLUMN ... SET NOT NULL` (plus the column's `CHECK`, for an `enum` field).

This always succeeds. `backfill`'s literal is validated against the field's resolved type at metadata resolution — the identical gate `default` and a guard/rollup literal pass through — so it is never a *flagged* operation the way a constraint added over unverified existing data can be.

A plan's `checks` list the data-dependent questions it raised, each with a `result`. `empty`, `has_rows` and `passed` are answered when planning. `runs_at_apply` marks a check on a table that holds rows, which only the apply can answer: either the operation's own statement enforces it over the existing rows (making a field required, adding a constraint), or the apply runs its query after the statements. A check that does not hold refuses the whole apply and nothing changes; a field made required that existing records leave empty is refused `constraint_apply_failed`, naming up to ten of those records. A landed apply returns `checks` too: every check of the plan, with each `runs_at_apply` reported `passed`.

A declared `backfill` that is never actually read this way is reported, not silently dropped. The plan response's `"advisories"` array (see the rule-selection advisories under "Guards") carries a `backfill_unused` entry when:

- the table turns out to be empty (an ordinary `ADD COLUMN NOT NULL` needs nothing to fill); or
- the field already exists (it isn't newly added by this plan at all, so `backfill` was never going to be read either way).

### Record numbering (`numbering`)

A `numbering` block on a `text` or `int` field makes the server number it, in sequence, when a record is created: invoice numbers, ticket keys, order numbers.

```json basel-repository
# file: basel.json
{"format": 2, "name": "billing"}
# file: objects/invoice.json
{
  "name": "Invoice",
  "operations": ["create", "update"],
  "fields": {
    "title": {"type": "text"},
    "number": {
      "type": "text",
      "numbering": {"format": "INV-{YYYY}-{0000}", "restart": "yearly", "start": 1}
    }
  }
}
```

- `format` is literal text plus tokens: `{YYYY}`, `{YY}` and `{MM}` print the creation date in the tenant's `time_zone` (UTC when none), and exactly one run of zeros such as `{0000}` is the counter, zero-padded to that width and growing past it (`INV-2026-12345`). A `text` field requires `format`; an `int` field refuses it and stores the bare number.
- `restart` is `never` (the default), `yearly` or `monthly`, and a period is a year or month of that same date: with `"time_zone": "America/Los_Angeles"`, a record created at 02:00 UTC on 1 January still numbers into the old year. A restarting counter must print its period, or two periods would produce the same value: `yearly` needs `{YYYY}` or `{YY}`, `monthly` needs a year and `{MM}`. A date token finer than the restart is simply printed. An `int` number never restarts.
- `start` (default 1, a JSON number) is the first number of every period.

Malformed blocks refuse `invalid_numbering` at `{Object}.attributes.{attr}.numbering` (the internal element for `fields.<f>.numbering`), as does `numbering` on a relationship property, on any other type, or beside a `default` or `stamp` (the server supplies the value).

#### What the server guarantees

- **The number comes back in the create response.** It is allocated in the write's own transaction, after every guard, invariant and permission check. A refused or failed write takes no number, so failures leave no gaps. Deleting a record does not give its number back.
- **Several records in one request are numbered in request order**, including nested creates, raw proposals and records an action creates.
- **Concurrent creates wait for each other**, briefly, on the counter. In the rare case the database breaks a lock cycle, the write answers `503` with code `write_contention` and a `Retry-After`; nothing was written, so send it again.
- **Unique automatically.** A numbered field carries the same one-field unique rule `"unique": true` declares (`{attr}_unique`); saying `"unique": true` as well is allowed.
- **Fixed once set.** An update naming the field refuses `managed_attribute`, and a lock (listed in the object's reflected `locks`) keeps every other door from changing it once it has a value. An action effect may not set it (`invalid_effect`).
- **One counter per subtype family.** A numbered field on an abstract root is shared by every kind below it: an `Issue`, an `Epic` and a `Note` extending `Item` draw `KEY-001`, `KEY-002`, `KEY-003` from one sequence. Converting a record into a kind that declares its own numbered field numbers it then.

#### Who may supply a number

A numbered field is not writable by callers. `"write": ["*"]` never covers it, and generated forms leave it out (lists and the record page show it as usual). A create that sends it anyway is refused `422 managed_attribute` at the field (`issues[1].key` for a nested create), saying to omit it and read the number from the response; it is not a role problem, and `POST /tenants/{key}/authz/explain` answers the same code, listing the field under the permit's `write_fields.uncovered` and `write_fields.managed`. Never send one: a surface's `create.writable_fields` (see "Policy") already leaves it out.

The exception is an **import**: a create whose permit names the field explicitly in `write` may carry an existing number over. The value must still be unique (a duplicate refuses `constraint_violated`). When it reads back under the format for the current period, the counter is raised to at least that number, so the next record follows it.

#### Existing rows

- **A new numbered column on a table with rows** numbers every existing row in creation order (per period, for a restarting counter), then continues from there. A required numbered field needs no `backfill`.
- **Adding `numbering` to a column that already holds values** keeps every value and starts the counter after the highest one that matches the format. The plan says so in two advisories: `numbering_seeded` names the next value, and `numbering_unmatched_values` counts the values the format does not read (they are kept, and ignored by the counter). Existing duplicates refuse the plan, as for any new uniqueness rule.
- Either change adds a uniqueness rule to an existing table, so its plan needs approval like any other.
- A padded counter narrower than five digits draws a `numbering_sort_width` advisory: the values sort as text, so `KEY-1000` sorts before `KEY-999` once the counter outgrows its width.

The counter is data, not metadata: changing `format` affects new numbers only, and rolling metadata back never resets a counter. Reflection publishes the block as `"numbering": {format, restart, start}` on the field; the counter's current value is not published.

### Named scalar types (`types/`)

A `types/<snake_name>.json` file declares `{name, base, check}`, for example `{"name": "Hours", "base": "decimal", "check": "value >= 0"}`:

- `base` is any scalar type in the table above, or `enum` (with its own `values`) — never `Money`, `ref`, `set`, or another named type.
- `check` is a predicate over the single name `value` (the one root a check offers), bound as `base`. It is restricted to comparisons/arithmetic/`AND`/`OR`/`NOT`/`IN` over `value` and literals. No function call is admitted at all, so a transaction-time one like `TODAY()`/`NOW()` refuses the same way any other disallowed construct does: `invalid_type_check`.

Named types are structural, not nominal, with Postgres `DOMAIN` semantics. A field or param declared `{"type": "<Name>"}` resolves to `<Name>`'s own `base` unchanged — a consumer that never looks past the base type sees an ordinary scalar.

A named type compiles to a per-column `CHECK` named `{table}_{column}_{Name}_check`. Changes plan like this:

- Tightening or otherwise changing a still-declared check plans as a same-name `DROP`+`ADD`, validated against existing rows through the ordinary constraint-addition path. Loosening is allowed the same way.
- Dropping the named type outright (reverting to a bare base type) drops that `CHECK` and is refused like any other constraint removal.

A `default`/`backfill` literal on a named-type field is validated against the check too, not only the base type (`invalid_default`/`invalid_backfill` on a violation). A write that violates the check at the database refuses `check_violation`, naming the field and the type.

Reflection publishes `"named_type": "<Name>"` beside a field's/param's ordinary `"type"`. `/reflect/types`/`/reflect/types/{name}` (see "Endpoints" above) list every declared named type's own `base`/`check`.

### Queries (`queries/`)

Every query plan is one `queries/<snake_name>.json` file: `{name, exposure, from, select, where, params, order_by, page}` (plus `optional_filters`, `orderable`, and `purpose`/`target` for a reference selector). `where` reads the record through `row.` and the parameters through `args.`. A bad `select` path refuses `invalid_ui_query` at `queries.{name}...`. `search` is not a name a parameter may take (`search_parameter_reserved`): every list accepts it as the text a search matches, interpreted by the engine (see Object views › Search).

```json basel-fragment
{
  "name": "company_contacts",
  "exposure": "internal",
  "from": "Contact",
  "select": ["id", "name", "email"],
  "where": "row.company = args.company_id",
  "params": {"company_id": {"type": "ref", "to": "Company"}},
  "order_by": [{"field": "name", "direction": "asc"}]
}
```

`exposure` is required and says who may run the plan:

- `"public"`: served by name at `POST /tenants/{key}/queries/{name}`, listed at `/reflect/queries`/`/reflect/queries/{name}` (see "Endpoints" above), callable from functions, and usable as a reference selector.
- `"internal"`: reachable only through the UI views, pages and apps that use it, never at `/queries/{name}`. Its plan id is the consumer's (`object.{Object}.{local}`, `page.{page}.{local}`), never `query.{name}`. An internal query nothing uses is refused.

**Running a public query.** `POST /tenants/{key}/queries/{name}` takes a JSON object whose every member is optional; `{}` runs the plan as authored. `POST /tenants/{key}/ui/queries/{id}` takes the same body.

```json
{
  "parameters": {"company_id": "company_01h455vb4pex5vsknk084sn02q", "search": "acme"},
  "order_by": [{"field": "name", "direction": "asc"}],
  "page": {"after": "<end_cursor>", "size": 50, "include_total": false},
  "include": ["permitted"],
  "context": {"record_id": "<TypeID>"}
}
```

- `parameters` carries a value for each of the plan's `params` by name, typed as a field of that type is written (a `ref` as a `TypeID` string, `decimal` and Money amounts as strings), plus the `search` text every list accepts. One the plan does not declare, or a required one left out, is refused `422 invalid_bind` at `parameters.<name>`.
- `page.size` must be 1 to the plan's own `page.max_size` (`limit_exceeded` at `page.size`); `include_total` adds a count to the answer's page.
- `include` names per-row blocks; `permitted` is the only one served (`unknown_include` for any other). `context.actor` and `context.policy` are not implemented (`501`).
- The door takes no `?app` (every app's public queries share one namespace). `If-Match` is optional on it; present, it is checked as `/ui/queries/{id}` checks it.

The answer is `{"rows": [{"id", "version", "values": {...}, "permitted"?: {...}}], "page": {"end_cursor", "has_next", "total"}, "ui_checksum"}`. Send `page.after` as the last answer's `end_cursor` for the next page.

A query resolves against the complete model (every object, formula, lifecycle and relationship). A UI object view's, page's or app's own `queries` object binds one by name: `"queries": {"contacts": {"use": "company_contacts", "arguments": {"company_id": {"context": "record.id"}}}}`. An argument is `{"context": "record.id"}` (the record being shown: in an object view, or in a page an app places with `record_pages`, `edit_pages` or `create_pages`) or `{"request": "<param>"}` (from the request, the default for a parameter the consumer does not bind). A fixed literal argument is not supported yet. The bound query compiles to a clone of the plan under the consumer's own id, keeping the query's `owner`/`name`, so it runs and pages identically whichever endpoint calls it.

A `queries/<name>.json` plan's id is `query.<name>` and its `owner` is `query` (reflection and `/reflect/ui` publish both), as an app shell's own query is `app.<name>` with `owner: app`.

Naming rules:

- A consumer's local name may not collide with a public query's name unless it binds exactly that query: `query_shadowed`.
- A `use` naming no declared query is `unknown_query`, positioned at the binding's own `use` key.
- A plan declares its parameters as `params` (types only); a consumer supplies their values under `arguments`. `parameters` is refused.

### Grouped queries

A query with `group_by`, or with a named aggregate in `select`, is grouped: its rows are groups with totals, the BQL `GROUP BY` of "Groups and totals" as a named plan. A `select` entry is a path (a group key) or `{"name": ..., "value": ...}`, where `value` is a group aggregate (`"COUNT(*)"`, `"COUNT(id)"`, `"COUNT(<path>)"`, `"SUM(<path>)"`, `"MIN(<path>)"`, `"MAX(<path>)"`) or a key expression such as a date bucket (`"DATE_TRUNC('month', close_date)"`, or the calendar month `"MONTH(close_date)"`). `group_by` names the keys by their `select` name: a path, or a key expression's `name`.

```json basel-fragment
{
  "name": "pipeline_by_stage",
  "exposure": "public",
  "from": "Deal",
  "where": "row.won = false",
  "select": ["stage", {"name": "deals", "value": "COUNT(*)"}, {"name": "amount", "value": "SUM(amount)"}],
  "group_by": ["stage"],
  "order_by": [{"field": "amount", "direction": "desc"}]
}
```

- Every selected item is a `group_by` key or a named aggregate; a grouped plan with no `group_by` is one total over every readable row. `order_by` and `orderable` name output columns (a key or an aggregate's `name`). `AVG` and aggregates of expressions are refused (declare a formula and total it). An open-Money total needs its currency pinned in `where` or grouped (`mixed_currency_aggregate` at push). `page.total: exact` and `purpose: reference` are refused.
- A row is `{"values": {...}, "filter": {...}}` and carries no `id`, `version` or `permitted`. `include: ["permitted"]` does not apply to a grouped query: it is ignored rather than refused, since a group has no record to judge.
- `filter` reproduces the group on the fields its keys read, for drilling into the records behind it: a key that is a path filters that path by the group's value (`{"stage": "won"}`), a `DATE_TRUNC` key filters its source field by the bucket's half-open range (`{"close_date": {"gte": "2026-03-01", "lt": "2026-04-01"}}`), and a null group is an explicit `null`. A key that extracts a part of a date (`MONTH(close_date)`: March of every year) or computes any other value has no entry: it is not drillable.
- Groups page like rows: 50 by default, at most 500 (`page`). The cursor resumes after the last group's `order_by` values and keys, so `has_next` and `end_cursor` work as for a list.
- A grouped query runs under the limits in "Limits on grouped queries" (BQL): over 1,000,000 estimated rows it is refused `aggregate_too_broad` naming the query, a fifth at once in one tenant `429 too_many_grouped_queries`, and `basel plan` warns `slow_query` for one that reads a whole table of about a million rows.
- Read permits apply to rows before totals, and a key or aggregate argument outside the caller's read ceiling is refused `unreadable_attribute`, as in BQL. A named grouped query needs no `query.aggregate`: that action gates only ad-hoc grouping through `POST /tenants/{key}/query`.
- Reflection (`/reflect/queries/{name}`, and a UI surface's query contract) carries `"grouped": true`, `group_by` and `columns` (each `{name, role: key|aggregate, ty, value?, aggregate?, argument?, drill?}`; a drillable key's `drill` is `{field, range?, zone?}`, `range` being a `DATE_TRUNC` unit). A function's `grant.queries` may not name a grouped query, and it is not searchable.
- A grouped query binds only to a component whose query binding `accepts: grouped` or `any` (`basel.metric@1` and `basel.chart@1` do); bound to one that draws records (a table, a list, a picker) it is refused `grouped_query_not_accepted` at the binding. That component's field bindings then name the query's output columns (see "Grouped queries and `accepts`").

### Reference selectors

A reference selector is a public query that decides which rows a `ref` field may point at. Declare it in `queries/<name>.json` with `"exposure": "public", "purpose": "reference", "target": "<Object>"`. Then:

- `where` must be present and admissible (see below) over `target`;
- `from` must equal `target`;
- `select` is clamped to `["id"]` or `["id", <one orderable, non-ref field>]`: identity and a label, nothing else;
- **`order_by` is clamped to that same `{id, label}` set**. A caller who may reference but not read a row must not be able to binary-search a hidden column by reordering the picker.

A `ref` field names one as its own selector with `"select": "<query name>"` in its `fields` entry.

#### Declaration refusals

- A `select` naming no declared query refuses `unknown_query` at `{Object}.{attr}.select`.
- A `select` naming a query which is not `"purpose": "reference"`, or whose `target` does not equal the field's own `to`, refuses `invalid_ui_query` at that same element. So does a `select` on a non-`ref` field.
- `select`/`"unique": true` are object-only field keys. On a relationship property they refuse `not_implemented` at `relationships.{Relationship}.properties.{name}.select` and `invalid_constraint` at `.unique`.
- A purposed query declares no `params` at all, because every caller must reach the same verdict for the same row. Otherwise it refuses `reference_query_inadmissible` at `queries.{name}.parameters`.
- Its `where` must be present and read only stored columns of `target`/`from`: a single-segment field, a rollup's own field, or a lifecycle's managed state. It may never read a formula (which owns no column), a relationship traversal, an aggregate, a quantifier, or a transaction-time function. This is the same admissibility gate an invariant's `assert` passes through. A breach refuses under the same code, `reference_query_inadmissible`, positioned at `queries.{name}.where`.

#### The check at write time

Choosing (or replacing) a selector-governed field at commit time is a third, independent check, run beside every other write-authority check:

1. Visibility decides which rows a *query* returns.
2. The `reference` permission (see "Policy") decides whether this actor may point at this row at all (refuses `not_found`).
3. This selector's `where` decides whether the model still calls it a legal choice *now*. It is evaluated against the chosen row's complete, unfiltered record inside the write transaction — never the caller's own visibility — so every caller reaches the identical verdict for the identical row.

A row that already held a selector-governed field before this write is never re-checked: deactivating a referenced record does not retroactively invalidate what already points at it. A field is checked exactly when this operation's own values name it with a non-null id. A failing choice refuses `reference_ineligible` at `{Object}.{attr}`.

#### Invoking a selector

**Invoking a `"purpose": "reference"` plan** needs no ordinary `read` on the target. A `reference`/`referenceAny` permit alone admits it, and discloses the plan's own id and label and nothing else.

- Holding `read` as well does not narrow that. The two grants compose (the readable fields are their union, the row filter the `OR` of their filters), so adding a permit never takes selector authority away.
- Holding `read` on every field does not widen it either, because the `{id, label}` clamp is structural.
- A delegated/capped session is refused outright rather than admitted through the delegator's own uncapped `reference` permit. This is a current limitation, not a permanent shape.

A page whose admission drew on a `reference` grant carries **no `permitted` block at all**, even when `include: ["permitted"]` asks for one. That block is checked under the caller's own read policy, where a row reached by reference alone would be stamped `actions: ["read"]` — a claim a reference selector is defined never to make.

#### Reflection

`/reflect/queries`/`/reflect/queries/{name}` carry `"purpose": "list"|"reference"` and, for a reference selector, `"target": "<Object>"`. A field's own reflection always carries `"select": "<query name>"|null`, present whether or not the field declares one.

### Tasks and triggers

A task is work the app hands to a named runner (an agent or program outside Basel); a trigger starts one when a record is created, when it enters a lifecycle state, or on a recurring schedule. Both are off unless the server runs with `BASEL_TASKS=1`: a push that declares either is refused `tasks_disabled` otherwise. `basel validate` checks them offline either way.

```yaml basel-repository
# file: basel.yaml
format: 2
name: tracker
# file: objects/issue.yaml
name: Issue
operations: [create, update]
fields:
  title: {type: text}
  effort: {type: int, nullable: true}
actions:
  set_effort:
    params: {points: {type: int}}
    effects:
      - {op: set, values: {effort: {expr: args.points}}}
# file: tasks/size_issue.yaml
description: Estimates a new issue.
runner: triage_agent
input:
  issue: {type: ref, to: Issue}
instructions: |
  Read the issue and set its effort in points.
result:
  mode: worker_writes
  may_call: [Issue.set_effort]
timeout: {lease: 15m, heartbeat: 2m, max: 1h}
retries: {max: 2}
idempotent: true
# file: triggers/size_new_issue.yaml
on: {event: created, object: Issue}
task: size_issue
input:
  issue: record.id
```

A declaration is named by its file (`tasks/size_issue.yaml` is `size_issue`); an explicit `name` must equal the file stem (`filename_mismatch`). Unknown keys are `unknown_property` at every level. A package may not declare either yet: `package_tasks_unsupported`.

A task:

- `runner` (required): a snake_case name, bound to a worker outside metadata, or a built-in runner, `basel:email` (below). Malformed: `invalid_runner`; another `basel:` name: `unknown_builtin_runner`.
- `input`: parameters declared exactly like an action's `params` (`type` and its keys, `optional` with `nullable`, `default`). A `ref` names a declared object.
- `instructions` (required): non-empty text for the runner (`invalid_instructions`). Optional for a built-in runner, which reads none.
- `result` (required): `mode` is `worker_writes` or `typed_output`; any other mode is `invalid_result_mode`.
  - `{mode: worker_writes, may_call}`: the worker records the outcome itself, invoking only the actions `may_call` lists, each `Object.action` naming an action (or lifecycle transition) of a declared object (`unknown_object`, `unknown_action`, `invalid_may_call`). It takes no `output`, `on_result` or `on_failure` (`invalid_result`).
  - `{mode: typed_output, output, on_result, on_failure?}`: the worker returns data and Basel writes it. `output` (required) declares the fields `complete` carries, each exactly like an action parameter. It lists no `may_call` (`invalid_result`): the worker writes nothing.
  - `on_result` (required) and `on_failure` are `{action: Object.action, record: input.<name>}`: an action or lifecycle transition of a declared object (`invalid_result_action`, `unknown_object`, `unknown_action`), applied to the record a required `ref` input of the task names, a `ref` to that object or one that descends from it (`invalid_result_record`).
  - `on_result` receives the output fields as its parameters by name: every field is one of its parameters with the same type, a field that may be omitted is an optional parameter, and every required parameter is a field. `on_failure` receives `code` (text) and `message` (text, optional), and requires nothing else (`invalid_result_params`).

```yaml basel-repository
# file: basel.yaml
format: 2
name: estimates
# file: objects/issue.yaml
name: Issue
operations: [create, update]
fields:
  title: {type: text}
  effort: {type: int, nullable: true}
  failure: {type: text, nullable: true}
actions:
  record_size:
    params:
      points: {type: int}
      note: {type: text, optional: true, nullable: true}
    effects:
      - {op: set, values: {effort: {expr: args.points}}}
  flag_failure:
    params:
      code: {type: text}
      message: {type: text, optional: true, nullable: true}
    effects:
      - {op: set, values: {failure: {expr: args.code}}}
# file: tasks/estimate_issue.yaml
runner: estimator
input:
  issue: {type: ref, to: Issue}
instructions: Estimate the issue and return the points.
result:
  mode: typed_output
  output:
    points: {type: int}
    note: {type: text, optional: true, nullable: true}
  on_result: {action: Issue.record_size, record: input.issue}
  on_failure: {action: Issue.flag_failure, record: input.issue}
```
- `may_call` at run time: a task that lists actions narrows its run session to them. Any other write, from any door, is refused `403 not_in_may_call` and rolls back; reads are not narrowed. The run keeps its refusals: `GET /tenants/{key}/runs/{id}` shows `refusals`, oldest first, each `{code, message, at}`, at most 50. A task that lists none is bounded by its service principal's roles alone. A `typed_output` task's run session may write nothing at all (`not_in_may_call`); it may read.
- `typed_output` at run time: `complete` carries `output`, an object of at most 64 KB checked against the declared fields. Missing, malformed or too large output is refused (`output_required`, `invalid_output`, `output_too_large`) and the run stays `active`, so the worker may report again within its lease. The contract is the one the task declared when the run was claimed.
- Valid output is handed to `on_result`, which Basel invokes in its own transaction as the runner's service principal, on the record the run's input names; history names the run on that write. `complete` answers after the action is applied (the run ends `complete`) or refused (a guard, an invariant, a version conflict, a missing record: the run ends `error` with code `result_refused`, and is not offered again).
- The run shows `output` and `result`: `{action, record, outcome: "applied", event}` or `{action, record, outcome: "refused", code, message}`. On `fail`, a declared `on_failure` is invoked the same way with `code` and `message`; the run ends `error` with the worker's code, and `result` shows what became of `on_failure`.
- `runner: basel:email` is Basel itself, sending one email to a tenant member. The task takes `to`, a required `{type: ref, to: Principal}`, and `subject` and `body`, required `text` (`invalid_builtin_input`); it may take `html`, an optional `text` input; it may take other inputs, such as the record `on_result` writes to. Its result is `typed_output` (`invalid_builtin_result`), and `output` declares any of `message_id: {type: text}` and `sent_at: {type: Timestamp}`, which Basel fills in (`invalid_builtin_output`).
- The tenant binds `basel:email` to a service member alone: `PUT /tenants/{key}/runners/basel:email {"service": "<login>"}`; unbound, a run ends `error` / `runner_not_bound`. Basel starts the run itself, in-process: `pending`, `active`, then `complete` with `on_result` applied as that service member, or `error` with `on_failure` applied.
- The recipient must be an active human member with a verified email address (`recipient_not_member`, `recipient_unverified`); arbitrary addresses are not accepted. The subject (1 to 200 characters, one line) and `body` (plain text, at most 100,000 bytes) are sent as given, from the server's mail address, with a line naming the tenant. `body` is the text part; the HTML part is the run's `html` when given (at most 256 KB), sanitized, else `body` escaped.
- Sanitizing keeps headings, paragraphs, lists, tables, `b`/`strong`/`i`/`em`, `code`/`pre`, `blockquote`, `hr`, `br` and links. A link keeps only an `http`, `https` or `mailto` `href` and gets `rel="noopener noreferrer"`. Every other attribute (`style`, `onclick`, …) is dropped, and scripts, styles, forms, frames and all images are removed, so nothing remote loads. An oversized field is `invalid_email`.
- Other failure codes: `mail_not_configured` (`BASEL_MAIL_PROVIDER` is `none`), `mail_rate_limited` (the address's hourly allowance), `mail_tenant_rate_limited` (`BASEL_MAIL_TASK_PER_TENANT_PER_HOUR`, default 100), `mail_rejected`, `mail_failed`. A run sends at most once: a re-attempt finds the first send and completes with its `message_id`, or fails `mail_outcome_unknown` when the first attempt's outcome was never recorded. Declare `idempotent: true` so a run interrupted by a restart is re-attempted.

```yaml basel-repository
# file: basel.yaml
format: 2
name: notices
# file: objects/notice.yaml
name: Notice
operations: [create, update]
fields:
  title: {type: text}
  message_id: {type: text, nullable: true}
  sent_at: {type: Timestamp, nullable: true}
  failure: {type: text, nullable: true}
actions:
  mark_sent:
    params:
      message_id: {type: text}
      sent_at: {type: Timestamp}
    effects:
      - {op: set, values: {message_id: {expr: args.message_id}, sent_at: {expr: args.sent_at}}}
  mark_failed:
    params:
      code: {type: text}
      message: {type: text, optional: true, nullable: true}
    effects:
      - {op: set, values: {failure: {expr: args.code}}}
# file: tasks/notify.yaml
runner: basel:email
input:
  to: {type: ref, to: Principal}
  subject: {type: text}
  body: {type: text}
  notice: {type: ref, to: Notice}
result:
  mode: typed_output
  output:
    message_id: {type: text}
    sent_at: {type: Timestamp}
  on_result: {action: Notice.mark_sent, record: input.notice}
  on_failure: {action: Notice.mark_failed, record: input.notice}
idempotent: true
```
- `timeout`: `{lease, heartbeat, max}`, each `<n>s`, `<n>m` or `<n>h` (`invalid_duration`); defaults `15m`, `2m`, `1h`. The heartbeat is shorter than the lease, the lease at most `max`, and `max` at most `24h` (`invalid_timeout`).
- `retries`: `{max}`, a whole number from 0 to 10 (default 2; `invalid_retries`). `idempotent`: true or false (default false).

A trigger:

- `on` (required): `{event, object}`, plus `lifecycle` and `state` for `entered`. `event` is `created` or `entered` (any other is `unsupported_trigger_event`); `object` is a declared object (`unknown_object`), and a record of a subtype of it fires it too.
  - `created` fires once for each record created, by a plain create, a nested create or an action's `create:` effect. It takes no `lifecycle` or `state` (`invalid_trigger_on`).
  - `entered` fires each time a record enters `state` of its lifecycle `lifecycle`: by a transition (its own, or another record's `transition:` effect), or by being created into it, so a trigger on a lifecycle's initial state fires for every new record, as `entered_at` counts the entry. A plain update never enters a state. `lifecycle` must be one of the object's lifecycles and `state` one of its states (`invalid_lifecycle`). Example: `on: {event: entered, object: Issue, lifecycle: status, state: review}`.
  - Writes a run makes never start a worker's task, so a worker moving its own record into a state starts nothing. One exception: a worker run's writes, and the `on_result` Basel applies for it, may fire a trigger whose task runs on `basel:email`. A worker can write a record (a daily review with `subject`, `body`, `html` and a `Principal` field) whose `created` trigger mails it. The email run's own `on_result` and `on_failure` writes start nothing at all, so the chain stops there.
  - `{schedule, time_zone}` instead runs the task on a recurring schedule, with no event or object: `on: {schedule: "0 2 * * *", time_zone: Europe/Paris}`. `schedule` is a five-field cron expression, `minute hour day-of-month month day-of-week` (`*`, numbers, `a-b`, `/n` steps and comma lists; day-of-week 0-7, Sunday 0 or 7; no names), or `@hourly`, `@daily`, `@weekly`, `@monthly`, `@yearly`. When both day fields are restricted, a day matching either fires. Ticks at least 5 minutes apart, and a schedule that never fires, are refused `invalid_schedule`. `time_zone` is an IANA zone (`invalid_time_zone`); without one the tenant's `time_zone` applies, else UTC. A wall time a daylight-saving change skips fires when the clocks jump; one that happens twice fires once, at the first.
  - A schedule keeps one waiting run, for its next tick: `pending`, with `not_before` set to the tick, and invisible to runners until then. One tick makes at most one run. After downtime a missed tick runs once, late, and further missed ticks are skipped. Cancelling the waiting run skips that tick. An apply that changes the schedule, its task or its input replaces the waiting run.
- `task` (required): a declared task (`unknown_task`).
- `input`: each task input to `record.id` or `record.<field>` (a stored field of the object; `unknown_attribute`), or, for a schedule, to `schedule.at`, the tick's instant, which fits a `Timestamp` input. Every required input is mapped and no other name is (`invalid_trigger_input`). `record.id` fits a `ref` to the object or one it descends from; a field fits an input of its own type, and a field that may be empty only an `optional` input (`invalid_trigger_input`).

An action or transition starts a run itself with a `run_task` effect: `{op: run_task, task: size_issue, input: {issue: {expr: row.id}}}`. Each input value is an expression over the action's scope (`row.<field>`, `row.id`, `args.<param>`, a binding), never a bare literal; a record created earlier in the list cannot be passed (`invalid_effect`). The task must be declared (`unknown_task`), every required input mapped and no other (`invalid_effect`, `unknown_attribute`), each value of its input's type. It counts one operation of the effect budget.

- The run is requested in the action's own commit and created from the committed event a moment later, exactly once; a refused or rolled-back action starts nothing. Find it in `GET /tenants/{key}/runs`: `trigger.kind` is `action`, `trigger.source` the action (`action:Issue.submit`), `caused_by` the caller.
- Whoever may invoke the action may start its run; `task.run` is not needed. A `ref` input must name a record the caller can read, or the action is refused `422 invalid_input`.
- The action is refused `409 tasks_disabled` while `BASEL_TASKS` is off, and `403 not_for_run_session` when a run's worker calls it: a run never starts another run this way. That includes an action applied as a run's `on_result`.
- History shows the request's `run` and `task`, not its input; read the run for that.

Reflection: `/reflect/tasks` and `/reflect/triggers` (with `enabled`, the server's `BASEL_TASKS`), `/reflect/tasks/{name}` (runner, input, instructions, result, `timeout` in seconds and as text, retries, idempotent, and `digest`, a hash of the whole declaration), and `/reflect/triggers/{name}`. The root `/reflect` counts both.

### Conditional uniqueness and interval exclusion (`constraints`)

An object may declare `constraints`, an object of named integrity rules the *database* owns rather than a read-then-write check the engine runs. Two examples:

```json basel-fragment
{
  "constraints": {
    "one_active_enrollment": {
      "unique": ["student", "program", "academic_year", "term"],
      "when": "row.status != 'cancelled'"
    },
    "no_double_booking": {
      "exclude": {"resource": "room", "interval": ["starts_at", "ends_at"]},
      "when": "row.status = 'confirmed'"
    }
  }
}
```

The first compiles to a partial unique index (`ux_<table>_<name>`), the second to a `gist` exclusion constraint (`ex_<table>_<name>`).

Two writers who each see no conflicting row still cannot both commit: the index, not a read, is the arbiter.

#### Rules

- An entry declares exactly one of `unique`/`exclude`.
- A `unique` tuple names declared fields with one physical column each. A `ref` qualifies (one FK column); a `set` and an open `Money` do not.
- An `exclude`'s `resource` is compared with `=`, and its `interval` names exactly two fields of one shared `Date`/`Timestamp`/`int`/`decimal` type.
- **Intervals are half-open, `[start, end)`, and that is not configurable**: a booking that starts exactly when another ends does not overlap it.
- `when` is optional; omitted, every row participates. It passes the same own-row admissibility gate an invariant's `assert` does: stored columns of this row only, no formula, no traversal, no aggregate, and **no transaction-time function**. A predicate that moved with the clock would silently change which rows the index covers with no write happening at all.
- `"unique": true` on a field is sugar for a one-field entry named `{attr}_unique` with no `when`. Declaring both refuses (`invalid_constraint` at `{Object}.attributes.{attr}.unique`) — a rule is declared once.
- Malformed declarations refuse `invalid_constraint`. That includes a `when` naming a construct a partial-index predicate cannot render: a function call, a `CASE`, or a money literal (Basel's money is an amount/currency column pair, which no single-column comparison names).

#### Changes, existing data, and conflicts

Removing a `constraints` entry, or re-declaring it under the other kind, **drops** the physical object Basel owns for it in the same plan. A `ux_`/`ex_`-named object that appears in no declaration, this version's or the last, stays drift and is never touched.

Declaring a rule over rows that already break it refuses at plan *and* at apply: `constraint_apply_failed` at `{Object}.constraints.{name}`, with a violation count and a bounded `TypeID` sample. A write that conflicts refuses `constraint_violated` at that same element, naming the object and the rule and never the conflicting values.

#### Deployment requirement

An `exclude` entry's DDL runs `CREATE EXTENSION IF NOT EXISTS btree_gist` first. A scalar `resource WITH =` operand needs it, and the extension is database-scoped, so it cannot live in a per-tenant schema.

The statement is idempotent and runs inside the apply transaction. A deployment role without `CREATE EXTENSION` privilege refuses at apply with the raw Postgres error. Install `btree_gist` once, as a superuser, before applying any metadata that declares `exclude`.

#### Reflection

An object carries `"constraints"` beside `"invariants"`, each entry `{kind, unique | {resource, interval}, when, compiled}`. `compiled` is the emitted `ux_…`/`ex_…` identifier, so a reader can find the physical object.

#### Cross-object exclusion

A partial exclusion constraint is an index on *one* table. Two different objects competing for the same resource therefore cannot share an `exclude` directly.

Instead, model a shared reservation object that holds the interval fields and the single `exclude`, and have both competing objects hold a `ref` to it instead of duplicating the fields onto each. For example, a `RoomReservation` object carries `room`/`starts_at`/`ends_at`/`status` and `no_double_booking`; `Booking` and `Assessment` each hold only a `ref` to a reservation. A conflict's refusal names the reservation object's constraint, never either referencing object.

### Structured types and `list` params

A `types/<snake_name>.json` file may declare `fields` instead of `base`/`check`. That makes it a structured type, e.g. `types/invoice_line_input.json`:

```json basel-fragment
{
  "name": "InvoiceLineInput",
  "fields": {
    "description": {"type": "text"},
    "product": {"type": "ref", "to": "Product"},
    "quantity": {"type": "PositiveQuantity"},
    "unit_price": {"type": "Money"},
    "note": {"type": "text", "optional": true}
  }
}
```

- A field's own type is a builtin, `ref`, `Money`, or a scalar named type — never another structured type (`invalid_type`) and never `list`. A structured type's field may be `optional`.
- A structured type is legal only as a param's own bare type, or as a `list`'s `of` — never an object field's own type.

`{"type": "list", "of": "<Name or builtin>", "min_items": ..., "max_items": ...}` declares a bounded list param, e.g. `"params": {"lines": {"type": "list", "of": "InvoiceLineInput", "min_items": 1, "max_items": 10}}`. An invocation's list value shorter/longer than the declared bounds refuses `list_bounds` at `params.{p}`.

A structured param's/list item's value crosses the wire as a JSON object/array exactly matching the declared fields. Each field/item is validated recursively, including a named-typed field's own `check`. Errors are positioned `params.{p}.{field}` (a bare structured param) or `params.{p}[i].{field}` (a list item).

A function receives a structured/list param's value as its already-validated JSON, serialized to a string in the existing `field-value::text` wire slot; the function interface is not widened for it.

Reflection: a param's own `"type"` is `{type: "list", of, min_items, max_items}` for a list, or the structured type's own name for a bare structured param. `/reflect/types/{Name}` on a structured type shows `"kind": "struct"` and its `fields` (each shaped like a param).

### Tagged references (`reference_choice`)

A `types/<snake_name>.json` file may declare `reference_choice` instead of `base`/`check` or `fields`. It is a closed, tagged reference to exactly one of N objects, e.g. `types/note_subject.json`:

```json basel-fragment
{
  "name": "NoteSubject",
  "reference_choice": {
    "customer": {"to": "Customer"},
    "vendor": {"to": "Vendor"},
    "campaign": {"to": "Campaign", "select": "live_campaigns"}
  }
}
```

#### Declaring arms

- An arm is `"<arm_name>": {"to": "<Object>", "select"?: "<reference query>"}`.
- Arm names are `snake_case`. `kind` and `id` are **reserved**, because they are the wire value's own members (`name_collision`).
- Two arms of one type may not name the same target (`duplicate_arm_target`).
- The type is legal as a stored field's own type and nowhere else — not a param's, a `list`'s `of`, a struct field's, a relationship property's, a formula's or a rollup's (`invalid_type`).

Use it as `"subject": {"type": "NoteSubject"}`. `"nullable": true` admits no arm at all; otherwise the field is required, meaning exactly one arm, enforced by a database `CHECK` over the arm columns.

`on_delete` may name arms, but `restrict` is the only legal value in v1, and it is also the default. Anything else, or the key on a non-choice field, refuses `invalid_choice_lifecycle`.

#### Wire value

The value is one JSON object, `{"kind": "customer", "id": "customer_01j9…"}`. Both members are always present, since there is no partial form: a half-chosen value is not representable. Writing one arm replaces whatever arm was there in the same statement.

Reading adds `label` when the populated arm declares `select`, from that query's own label projection. The key's presence is a function of the arm, never of the reader. But its **value** is a checked read of the arm's target:

- `null` unless the reader may read or reference that row;
- `null` on a write echo always, since a `POST`/`PATCH` response is produced inside the write transaction where there is no reader to check. Read the label back with a `GET` or a query.

#### Paths

- `{attr}.kind` is the derived tag. It is computed from which arm is populated, never stored, and **read-only**: writing `{attr}.kind` refuses `choice_tag_not_writable`. Any *other* dotted key on a write refuses `unknown_attribute`, since no such name exists to write.
- `{attr}.<arm>` is an ordinary `ref` path that traverses. `subject.customer.owner.region` resolves; one segment deeper does not, because an arm costs two segments of depth.
- An arm name no declared arm matches refuses `unknown_choice_arm`, whether written as a value's `kind` or as a tag literal.

#### Where the whole value is legal

**The whole value** is legal in exactly three positions, and nowhere else:

1. `IS [NOT] NULL`;
2. `=`/`!=` against another path of the *same* nominal type;
3. a `set` effect copying it whole.

There is no object literal in BQL or the expression grammar, so `subject = 'customer_01j9…'` refuses `choice_not_arm_qualified` and tells you to compare an arm instead (`subject.customer = UUID '…'`).

Ordering refuses at two different gates. A bare choice in an ordering position is not one of the three positions above, so it refuses `choice_not_arm_qualified` before any operator is weighed. The tag refuses `choice_tag_not_a_value` — an arm set has no order — in `ORDER BY` and in a `<`/`>` comparison alike.

#### Reverse reads

"Everything attached to this customer" is a filter on one arm column, `WHERE subject.customer = '<id>'`, and each arm gives its own such read. A choice is not a relationship, so a target has no writable inbound related list: attaching is a write to the **referring** row, and the target's own surface is a read-only query binding.

A row that breaks the count `CHECK` refuses `reference_choice_violated` at `{Object}.{attr}`, naming neither the row nor any value.

#### Reflection

`/reflect/types/{Name}` shows `"kind": "reference_choice"` with its arms. The field carries `pg_type: null` and a `reference_choice` block beside its `type`: the arms, their labels, selectors and `on_delete`, and the tag's own value set. Arm columns, FK names and the count-constraint name appear nowhere under `/reflect`; they are in the `/plan` DDL, like every other managed name.

### Declared action results (`result`)

An action or transition may declare `result` — an object of field name to `{type, optional?, disclosure}`, for example `"result": {"ticket": {"type": "ref", "to": "Ticket", "disclosure": "created_identity"}}`.

- `"disclosure": "created_identity"` names the record the invocation itself created, via a declared `create` effect reaching that object or a function the action `run`s. Resolution refuses `invalid_result` if the action has neither. That field's own `type` must be `ref` naming the created object.
- `"disclosure": "<Object>.<field>"` projects that field off the SAME created record. `<Object>` must match some other field's own `created_identity` ref target in the same `result` (`invalid_result` otherwise).

A declared result is projected inside the write transaction, after every other integrity check and before settlement. A projection failure rolls the whole write back.

The projection uses the caller's own readable fields (the same read program the request already pinned). One of three outcomes follows per field:

- The caller can read the created record and the disclosed field both, and gets the full value.
- The caller can read the record but not that field, and the field is omitted.
- The caller cannot read the created record at all. A `created_identity` field is still returned as `{id}` (an identity receipt), with every other field omitted.

If no such record was actually created at invocation time (a function that proposed no matching create despite the resolve-time check), the field is omitted outright.

The invocation response carries the projected result as a `"$result"` object beside the existing receipt/projection row's own fields. It is present only when the invoked action declares a `result` at all. The key is `$`-prefixed, never bare `"result"`: a field may legally be named `result` (`valid_ident` allows it) but never `$result` (`$` is never a legal identifier character). So the key can never collide with a row's own field, structurally, with no resolution-time name check needed.

Reflection's own per-action/transition `"result"` key keeps its bare spelling. It is a sibling of `"params"`/`"function"` on the action's/transition's own descriptor, never mixed into a row, and never keyed by field name, so it carries no collision risk. It is `null` when none is declared, else `{fields: [{name, type, optional, disclosure}, ...]}`.

## Subtypes and interfaces

An object may declare `"extends": "<Object>"`, making it a member of that object's **subtype family**: one immediate parent, one shared table, one `concrete_kind` column the database enforces. `"abstract": true` on the root means the root itself holds no rows of its own kind — only its concrete descendants do.

Every member's `id` — root and subtype alike — carries the **family root's** `TypeID` prefix, never its own table name. A row created as a concrete subtype reads back with the root's own prefix, and every reference to it, from any member's route, resolves the same identity.

**A subtype's own field is a nullable column in the shared table.** When it is required, a kind-conditional `CHECK` requires it of that kind's rows (and its descendants') only. Adding such a field to a populated family needs `backfill` when that kind already has rows; the backfill fills that kind's rows only, and other kinds' rows keep no value. A tenant's `additions/` on a family member follow the same rules (see "Apps from packages").

### `$type`: the concrete kind

`$type` names the concrete kind, on the way in and on the way out. Every response for a family member's row carries `$type`, the row's own concrete object name. Reading a root-typed row through an ancestor's route still returns its true kind.

- Creating through a concrete route fixes that route's own kind.
- Creating through an ancestor's route requires `$type` to say which concrete member the new row is. An ancestor route with no `$type` on a **concrete** root creates that root's own kind, exactly as any ordinary object create does.
- `$type` is never itself writable: a `PATCH` naming it is `kind_not_writable`. Changing a row's kind is a distinct, explicit operation (a separate `convert` endpoint), never a field edit.

**An abstract root refuses a generic create.** `POST` through an abstract root's own route with no `$type` (or with a `$type` naming something outside the family) is `abstract_object`. The refusal names every admitted concrete kind, so the caller knows what to ask for instead; the same route accepts a create the moment `$type` names one of them. Reflection states this up front rather than making a caller learn it by refusal: an abstract root's `entity.instantiable` is `false` and it reflects no `create_contract` at all.

**A permit on a family root reaches its descendants — exactly, by default.** `"scope": "descendants"` on a permit widens it from the named object alone to every member of its family. Without `scope`, a permit is **exact**: it authorizes only the object it names, never a subtype and never an ancestor. Widening is always explicit, in the direction the author writes it.

### Querying a family

BQL reads a family root's rows across every member with `FROM <root>`, projecting only what every admitted member shares. A column only a subtype declares is `unknown_attribute` from the root, exactly as it would be for any object that never declared it; query from the subtype itself to reach it.

`TYPEOF()` is a nullary metadata function. It is legal only where a query, a rollup predicate, or a formula predicate range over a subtype-family source. It reads the row's own concrete kind as a string, comparable with `=`/`!=` against a kind name (no `IN`, no `IS [NOT] NULL`). It refuses `typeof_not_allowed_here` anywhere else — a guard, an invariant, a lock, or a source outside any family.

### Interfaces

An interface is a declared common surface, and nothing is an implementor by accident. A `types/<snake>.json` file may declare `interface` with:

- read-only `members` — each a type (`type` and the type's keys), `optional`, and a free-text `meaning` that reflection carries verbatim;
- `actions` — each a `params` contract and a `result` type;
- an optional `extends` array of other interfaces, flattened once per origin.

An object opts in explicitly, with `"implements": {"<Interface>": {"members": {...}, "actions": {...}}}`. It maps every interface member to **one one-segment path** on its own effective set (a stored field, a rollup, a formula or a `ref`), and every interface action to one of its actions. Matching field names map nothing: two objects that happen to spell a field `amount` are not implementors of each other's contract.

Conformance is checked when the metadata resolves:

- every member is mapped;
- types are equal (a `ref` may narrow to a descendant of the member's target);
- a required member is mapped to a non-nullable source (a formula is nullable by construction and so may satisfy only an optional member);
- a mapped action adds no required param.

A family member inherits its ancestors' implementations as **obligations**: a subtype may add implementations, never drop one.

#### Using an interface

An interface has no entity set; its persistent references are the reflected closed choice. There is no `FROM <Interface>`, no `/objects/<Interface>`, no cross-implementor list or cursor, and no generic invocation endpoint.

To act on an interface, read `/reflect/types/<Interface>`, then invoke the concrete object's own typed action route. That reflection carries:

- the flattened `members`, with their `meaning` and origin;
- the `actions`;
- the `implementations` map (each object's member and action mappings, with `origin` where an implementation is inherited);
- an explicit `unsupported` list, so a client never has to guess.

#### Fields typed by an interface

A field **typed by** an interface is where an interface becomes storage. It reflects `kind: "reference_choice"` with one **exact-kind** arm per concrete implementor, generated in name order, and links back to its contract under `interface: {name, _href}`.

That arm set is the ordinary `reference_choice` construct, unchanged (see "Metadata grammar and type table"): one `{kind, id}` value or `null`, one atomic write across every arm column, per-arm authority and eligibility, `restrict` deletion, and one `basel.reference_choice_picker` for the whole field. Every choice rule documented there applies verbatim.

A family member's arm is its own exact kind: an ancestor's arm never admits a descendant's row, and `{"type": "ref", "to": "<Root>"}` is the way to say "any member of the family". Publishing a new implementor adds its arm in the same metadata version; removing one refuses `removal_not_supported`, like every other structural removal.

## User interface

Tenant UI source lives under repository root `ui/`: `app.json`, `objects/<snake>.json`, `pages/<snake>.json`, `components/<snake>.json`, `presentations/<snake>.json`, `assets.json`, and indexed files under `assets/`. The queries UI binds live in `queries/`, beside the model. It is compiled with the semantic model into immutable, framework-neutral IR. UI-only applies execute zero operations (zero DDL) while still advancing the metadata version. The removed `/views` and `/reflect/layouts` HTTP contracts are not aliases for this API.

### The UI definition (`ui/app.json`)

An app has one UI definition, `ui/app.json`, required when any `ui/` source exists (`missing_ui_definition`). Its keys are:

- `presentation` — the app's look, `<id>@<major>`. The presentation owns every token value the app draws, including the platform theme values in its `theme` (see "A tenant's own look");
- `theme` — the platform theme values, only in an app that selects no presentation; beside `presentation` it is refused `theme_with_presentation`;
- `audience`, `home`, `navigation`, `shell`, `queries`, `fonts`, locales, `workspace_context`, `record_pages`, `list_pages`, `edit_pages`, `create_pages`;
- `defaults` — see below.

Any other key is refused `unknown_property`. The app's title is `basel.json`'s `title` (the tenant's key when absent), not a `ui/app.json` key. The legacy `ui/experiences/` folder is not read; `basel convert` writes it as `ui/app.json`.

`/<tenant>/apps/<app>` and `/<tenant>/` open the app; routes under `/apps` refuse `route_collision`. An object or a page may author its own `route` — a leading-slash, no-trailing-slash path, unique across every object and page (`route_collision` otherwise). An object's default is `/objects/<snake>`, a page's `/pages/<snake>`.

#### Default components and record template (`defaults`)

`defaults` has six keys. `object_list` and `related_list` each name the component every generated object list, or generated related list on a record page, draws with instead of Basel's own `basel.data_table@1`/`basel.related_list@1`. It may be a tenant component, a vendored one this app selected under `use`, or a `basel.*` one. The other four each name one of the app's page templates (see Page templates): `record_page` (`"template": "record"`) draws every record page that no `record_pages` entry places, `list_page` (`"template": "list"`) every list that no `list_pages` entry places, `create_form` (`"template": "create"`) every create form, and `edit_form` (`"template": "record"` or `"edit"`) every edit form. An unrecognized key refuses `unknown_default`.

A component that cannot fill the generated node refuses `default_component_incompatible`, naming what is missing. To fill it, the component must:

- accept the attachment that node takes in its mode (`list.records`: `ui.content` in `list`; a related list: `stack` `children` in `view`);
- declare each binding Basel passes, with the same kind, and require no other. An object list gets `object`, `fields`, `query`. A related list gets `relationship`, `query`, and `fields` when columns are configured, which it must not require;
- require no config key without a default — Basel generates `{}`.

An object list's filter bar and pagination go in its `toolbar` and `footer` slots, and only when it declares them; one that does not draws its own.

### Several apps (`ui/apps/<name>/`)

A tenant may have more apps than its primary one. `ui/app.json` stays the primary app, named by `basel.json`'s `name`; each further app is a folder, such as `ui/apps/dispatch/app.json`:

```json basel-fragment
{"title": "Dispatch", "audience": ["dispatcher"], "home": {"object": "WorkOrder", "mode": "list"}}
```

- `ui/apps/<name>/app.json` is its UI definition, with the keys above plus `title` (its display name, defaulting to `<name>`). It is required (`missing_ui_definition`).
- `ui/apps/<name>/pages/` holds its own pages and templates; `ui/apps/<name>/objects/` its own views of package objects, which replace the owner's keys inside that app only (see "App-scoped views"). A view there of the tenant's own object refuses `app_view_of_tenant_object`. Any other file in the folder is an unknown path.
- `<name>` is lowercase letters, digits, `_` and `-`, starting with a letter (`invalid_app_name`), and may equal neither the primary app's name nor any package's namespace (`app_name_taken`).

Shared by every app: the model, policies, queries and functions; `ui/components/`, `ui/presentations/` and `ui/assets/`; and `ui/objects/` views of the tenant's own objects. Per app: everything in its UI definition (presentation, shell, navigation, home, `defaults`, `record_pages`, `list_pages`, `edit_pages`, `create_pages`, workspace keys, app queries, locales, fonts) and its pages and templates. An app with no pages, templates or presentation draws Basel's generated pages with the shared views. A shared view's initializer reading a workspace key the app does not declare is left out in that app. The `ui/objects/` views of package objects stay the primary app's own.

Each app opens at `/<tenant>/apps/<name>`. Every `/ui/*` door, `POST /tenants/{key}/ui/queries/{id}`, `/reflect/ui` and `?ui=standard` take `?app=<name>`, with that app's own `ui_checksum`; an unknown name is `404 not_found` at `app.<name>`. Who may open its doors is the same rule as for the primary app (see "Who may open an app's UI" under "Apps from packages"): `metadata.read`, or any role other than the virtual `authenticated`.

`GET /ui/app`'s `apps` lists the primary app first, then the further apps and installed app packages by name, each with `namespace`, `title`, `route` and `audience`. The console's launcher and Tenant home offer an app whose `audience` is empty or names a role the person holds, by role id or by the tenant role's name. A declared `audience` admits only holders of one of its roles, on top of that rule; a caller holding `metadata.read` opens every app. `basel validate` prints `tenant app <name>: ui_checksum <checksum>` for each.

`basel.json`'s `apps` declares which app people open by default: a tenant `default` and, under `by_role`, a default per role, in order (see "`basel.json`" under the metadata reference). `GET /ui/app` carries the declaration beside `apps`, the same for every `?app=`, as `default_apps`: `{"default": "<app>" | null, "by_role": [{"role": "<role id>", "role_name": "<name>", "app": "<app>"}]}`, with roles given by id in declaration order, and `{"default": null, "by_role": []}` when `apps` is not declared. A tenant that declares no `apps` keeps its `ui_checksum`. `/<tenant>/` still opens the primary app; the declaration is data a client resolves.

### Objects and pages

An object view names the object's labels (localizable, as `{"default": ..., "<locale>": ...}`), its record label, icon, key fields and route, and binds the queries its pages use. Here the view binds an internal query; its `stage` parameter, which the view does not bind, comes from the request:

```json basel-repository
# file: basel.json
{"format": 2, "name": "pipeline"}
# file: objects/work_item.json
{
  "name": "WorkItem",
  "fields": {
    "name": {"type": "text"},
    "amount": {"type": "Money", "nullable": true},
    "expected_close_date": {"type": "Date", "nullable": true},
    "owner": {"type": "ref", "to": "Principal", "nullable": true}
  },
  "lifecycles": {
    "stage": {"initial": "open", "states": [{"name": "open"}, {"name": "won"}]}
  }
}
# file: queries/open_pipeline.json
{
  "name": "open_pipeline",
  "exposure": "internal",
  "from": "WorkItem",
  "select": ["id", "name", "amount"],
  "where": "row.stage = args.stage",
  "params": {"stage": {"type": "enum", "values": ["open", "won"]}},
  "order_by": [{"field": "name", "direction": "asc"}],
  "page": {"default_size": 50, "max_size": 500, "total": "exact"}
}
# file: ui/app.json
{"default_locale": "en-US", "supported_locales": ["en-US", "fr-FR"]}
# file: ui/objects/work_item.json
{
  "object": "WorkItem",
  "label": {"default": "Work item", "fr-FR": "Élément"},
  "record_label": "name",
  "icon": "target",
  "compact": ["amount", "expected_close_date", "stage", "owner"],
  "route": "/work-items",
  "queries": {"open_pipeline": {"use": "open_pipeline"}}
}
```

`icon` names what the object is, as one of the console's icon names: `search`, `updown`, `chevron`, `plus`, `pencil`, `trash`, `external`, `arrow`, `check`, `close`, `building`, `person`, `target`, `receipt`, `package`, `box`, `link`, `layout`, `lead`, `flag`, `task`, `tag`, `schema`, `reflection`, `states`, `lock`. Any other name refuses `invalid_ui` at `ui.objects.<O>.icon`.

The icon is served with the object (`/ui/objects`, the object's surfaces, reflection). The console shows it beside the record title, the object list's heading and the object home heading, and on the object's rail entry. How it looks is the presentation's: a presentation's `icons: {target: {color: "#fcb95b"}}` colours that icon name's tile (`#rrggbb`).

`compact` lists the object's key fields, in order: up to 6 distinct own fields, formulas or lifecycles, never a traversal (`unknown_ui_field` or `invalid_ui` at `ui.objects.<O>.compact[i]`). They are used in four places:

- the record header shows them as highlights under the title (less the `record_label` field);
- board cards show those their query selects (a board's own card `fields` may also name a to-one link by itself, such as `customer`, to show the related record by its label, or a field through one, such as `customer.region`, labelled "Region (Customer)"; the board's query selects `customer.id` or `customer.region`: `fields: [amount, customer, customer.region]`);
- a reference picker's options show the first two as a second line (the generated reference read selects them);
- a related list with no configured `related_lists` columns takes the related object's `compact` fields as its default columns.

Without `compact`, or with `"compact": []`, each of these keeps its default behavior.

How the record page, its edit and create forms and the object's list are arranged (`record`, `create`, `list`), how subtypes inherit a view and how an app ships its own view of another package's object are in "Object views" below.

### Row versions and optimistic concurrency

Every persisted row's managed audit-event back-link is exposed only as a strong `ETag: "evt_..."` on create, GET-by-id, update, and action responses. Named-query rows carry the same token as `version`.

`PATCH`, row `DELETE`, and action invocation require that token in `If-Match`:

- missing is `428 precondition_required`;
- malformed is `422 invalid_precondition`;
- stale is `412 stale_record` with `diff.current` and `diff.link`.

Refresh and retry deliberately: there is no force or auto-merge token. Formula evaluation alone does not change a version; a materialized rollup write does.

Successful create, update, and action results contain only fields the caller may read in the resulting state, including transitive formula readable fields. If the write makes its target unreadable, success returns only `{id}` plus the new ETag; it is a receipt, not a readable row. Replace result fields rather than merging them with a previously read record, and refresh through ordinary reads. Measured invocation rows use the same projection without committing the write.

### Assets

References are explicit `standard:`, `component:`, or `tenant:` values, and one namespace never shadows another. Tenant assets are declared in `ui/assets.json` (`{"assets": {"<logical name>": {"source", "kind", "media_type", "default_alt"?}}}`) and stored byte-exactly in canonical Git.

An asset is evaluated as a descriptor containing: metadata version, logical name, Git blob OID, SHA-256, kind/media/size, optional dimensions/default alt, and a digest-qualified URL. `GET /tenants/{key}/ui/assets/{logical_name}/{sha256}` returns exact bytes with a strong digest ETag and `public, max-age=31536000, immutable`; a mismatched pair is 404.

Tenant asset kinds are:

- PNG/JPEG/WebP/AVIF/SVG `image`;
- WOFF2 `font`;
- ES-module `script` (`.js`/`.mjs`, `text/javascript`, UTF-8, never beginning with `<`);
- `stylesheet` (`.css`, `text/css`).

### Tenant components

An app ships its own React components as tenant metadata. Each component has a manifest under `ui/components/<name>.json`. The manifest uses the platform manifest's vocabulary (attachments, binding kinds, commands, capabilities, theme tokens stay platform-owned) and declares:

- an `id` in a non-`basel` namespace (`<namespace>.<name>`);
- `"entry": {"asset": "tenant:<script asset>"}`, naming the ES module that exports `components` keyed `<id>@<major>`;
- optional `styles`, naming stylesheet assets.

Trees reference them exactly like platform components (`slate.issue_page@1`). Evaluated surface and app documents carry a `components` map describing only the tenant components that tree uses (`source: tenant`, `origin`, contract, `entry`/`styles` digest URLs). `origin` is `app` for the app's own component and `package` for one another package ships.

The console loads every stylesheet into one of six cascade layers, `@layer basel.reset, basel.host, components, presentation, app, admin;`, and a later layer wins whatever the specificity. Basel's own styles and layout (content width, page gutter) are `basel.host`; its Tenant home and admin pages are `admin`, last, so no tenant style restyles them. An `origin: package` component's styles are `components`. The selected presentation's stylesheets and renderers are `presentation`. The app's own components' styles are `app`. So a theme restyles Basel and any component library without `!important`, and the app's own CSS wins over the theme. `/ui/components` lists both sources, and `/ui/components/{id}@{major}` serves either.

#### What a stylesheet may carry

Each stylesheet is scoped to the app's area (`@scope`), so it may carry style rules, `@media`, `@supports`, `@layer` (a block or the `@layer a, b;` statement), `@container`, `@scope`, `@charset` and `@keyframes` (each renamed for this stylesheet, with the `animation`s here that use it).

Anything else is refused: an `@import` (bundle the styles instead), an `@font-face` (declare the face in `ui/app.json`'s `fonts` over one of the app's own font assets; the host generates it), any other at-rule (`@property`, `@page`, `@font-feature-values`, `@starting-style`, …), a `@keyframes` name that is not an identifier, and a `url()` that resolves to a scheme other than http, https or data.

`basel validate`, `basel plan` and push refuse each one as `unsupported_stylesheet_rule` at `<file>:<line>`, and so do a component-stylesheet upload and `basel build`. A stylesheet already deployed with one still loads: the console skips that rule, applies the rest and says which rule it skipped in the page's notice and the browser console.

Refusals: `reserved_component_namespace`, `invalid_component_id`, `duplicate_component`, `invalid_component_entry`, `invalid_component_styles`, plus the registry's own contract codes.

Tenant components run in the host realm (trusted inline). Admission is the metadata-write authority, not a sandbox.

#### Field types and field maps

A `field` binding may list the field `types` it accepts, by the type names objects use (`text`, `int`, `decimal`, `bool`, `Money`, `Date`, `Timestamp`, `enum`, `ref`, `set`, `reference_choice` and the rest). A page or object view that binds a field of another type is refused `binding_field_type` at the binding. A formula counts by its result type, a lifecycle as `enum`, an audit timestamp as `Timestamp`. Without `types`, any field binds.

#### Grouped queries and `accepts`

A `query` binding may declare which queries it `accepts`: `records` (rows with an `id`, the default when absent), `grouped` (the group rows of a grouped query, which have no `id`) or `any`. A page or object view that binds a grouped query to a binding that accepts only records is refused `grouped_query_not_accepted` at `<surface>.<node>.bindings.<binding>` (for example `page.pipeline.table.bindings.query`); an ungrouped query bound to one that accepts only `grouped` is refused `record_query_not_accepted` there. Grids, lists, pickers and related lists draw records. `basel.metric@1` and `basel.chart@1` accept `any`. A tenant component draws groups by declaring `accepts: grouped` or `any` on its query binding.

On a node whose `query` binding names a grouped query, each `field` binding names one of the query's output columns, a key or an aggregate's `name`, rather than a field of its object. A name that is no output column is refused `invalid_binding`, listing the columns. A field binding's `column_types` lists the column types it takes, and push refuses any other with `binding_field_type`. `basel.chart@1`'s `value` takes `int`, `decimal` or `Money`. `column_types` says nothing about a record query's fields, which `types` governs, and narrowing it is a breaking change too.

- **`basel.metric@1`** on a grouped query shows the server's total. A query with no `group_by` is one group over every readable row, so the figure is exact however many records it covers, and the tile never marks itself partial. `value` names the column (the first aggregate when absent); `config.aggregate` does not apply. A query grouped by a key, such as `price.currency`, combines its groups as the column's aggregate does, one figure per currency for open Money. It is partial only when there are more groups than it loaded. A tile cannot show a mean from the server: `AVG` is not admitted in a grouped query, and a mean of group means is not the mean. `aggregate: average` still averages a record query's loaded page.
- **A query `from` a relationship** reads link records, which have no object, so a field binding on a record query over one is refused `invalid_binding`, and a metric on such a query can only count. To total a link's own property, declare a whole-set query over the relationship, such as `select: [{name: total, value: 'SUM(share)'}]`, and bind `value: total`.
- **`basel.chart@1`** on a grouped query draws one mark per group: `category` names a key, and `value` names a numeric aggregate. A reference key shows the referenced record's label, or its short id where the record is not the viewer's to read.
- **A chart's drill target.** `config.drill` makes each mark open the records behind its group: `{"page": <page>, "query": <one of that page's ungrouped queries>, "parameters": {<key>: <parameter>}}`. Every group key maps onto the target query's parameter that reproduces it. A plain key maps onto one parameter (`"stage": "stage"`). A `DATE_TRUNC` key maps onto its bucket's range (`"month": {"gte": "closes_from", "lt": "closes_before"}`). A key whose group may be null can add `null_param`, an optional `text` parameter whose guard selects the records with no value (`"owner": {"param": "owner", "null_param": "unowned"}`, guard `row.owner IS NULL`). Without one, the null group has no link.
- **Where a drill lands.** The page must fill each parameter from its URL: a node there binding the query declares `"parameters": {"stage": {"source": "params.stage"}}`. The list then opens under the viewer's own read policy. Push refuses `invalid_drill` for an unmapped key, a key with no drill (`MONTH(close_date)`), a parameter the query does not declare, one a URL cannot fill (`bool`, `int`, `decimal`, `Money`), one whose type the key's values do not fit (an enum key takes an enum parameter listing its values), or one the page does not fill from its URL.

```json basel-repository
# file: basel.json
{"format": 2, "name": "sales", "default_currency": "USD"}
# file: objects/deal.json
{
  "name": "Deal",
  "fields": {
    "stage": {"type": "enum", "values": ["open", "won", "lost"]},
    "amount": {"type": "Money"}
  }
}
# file: queries/deals_by_stage.json
{
  "name": "deals_by_stage",
  "exposure": "internal",
  "from": "Deal",
  "select": ["stage", {"name": "deals", "value": "COUNT(*)"}, {"name": "amount", "value": "SUM(amount)"}],
  "group_by": ["stage"]
}
# file: queries/deal_list.json
{
  "name": "deal_list",
  "exposure": "internal",
  "from": "Deal",
  "select": ["id", "stage", "amount"],
  "params": {"stage": {"type": "enum", "values": ["open", "won", "lost"], "optional": true}},
  "optional_filters": {"stage": "row.stage = args.stage"}
}
# file: queries/deal_totals.json
{
  "name": "deal_totals",
  "exposure": "internal",
  "from": "Deal",
  "select": [{"name": "deals", "value": "COUNT(*)"}, {"name": "amount", "value": "SUM(amount)"}]
}
# file: ui/app.json
{"default_locale": "en-US"}
# file: ui/pages/pipeline.json
{
  "page": "pipeline",
  "queries": {"by_stage": {"use": "deals_by_stage"}, "totals": {"use": "deal_totals"}, "deals": {"use": "deal_list"}},
  "root": {
    "id": "pipeline",
    "component": "basel.page@1",
    "slots": {
      "main": [
        {"id": "deals", "component": "basel.metric@1", "config": {"label": "Deals"}, "bindings": {"query": "totals", "value": "deals"}},
        {"id": "pipeline_value", "component": "basel.metric@1", "config": {"label": "Pipeline"}, "bindings": {"query": "totals", "value": "amount"}},
        {"id": "by_stage", "component": "basel.chart@1", "config": {"drill": {"page": "pipeline", "query": "deals", "parameters": {"stage": "stage"}}}, "bindings": {"query": "by_stage", "category": "stage", "value": "amount"}},
        {"id": "deal_table", "component": "basel.data_table@1", "bindings": {"object": "Deal", "query": "deals", "fields": ["stage", "amount"]}, "parameters": {"stage": {"source": "params.stage"}}}
      ]
    }
  }
}
```

Clicking a bar opens `pipeline?stage=won`, and the table below lists the won deals. Binding the chart's `value` to `stage` here is refused `binding_field_type`, because `stage` is an `enum` column. Binding `category` to a field of `Deal` that the query does not select is refused `invalid_binding`, naming the columns it may bind.

A top-level config property may be `{"type": "field_map", "binding": "<binding>", "value": <schema>}`: an object keyed by the fields of that binding's object, each value of the `value` shape. The binding is an `object` binding, a `query` binding (its `from`) or a `record` binding. Keys may be the object's own, inherited or tenant-added fields (by their `core:` name), formulas, lifecycles or audit timestamps; any other key is refused `field_map_unknown_field` at `<node>.config.<property>.<key>`.

```json basel-repository
# file: basel.json
{"format": 2, "name": "planner"}
# file: objects/meeting.json
{
  "name": "Meeting",
  "fields": {
    "title": {"type": "text"},
    "starts_at": {"type": "Timestamp"},
    "room": {"type": "text", "nullable": true}
  }
}
# file: ui/app.json
{"default_locale": "en-US"}
# file: ui/components/calendar.json
{
  "id": "planner.calendar",
  "version": "1.0.0",
  "contract_major": 1,
  "title": "Calendar",
  "implementation": "react",
  "accepts": [{"attachment": "ui.root", "modes": ["page"]}],
  "bindings": {
    "object": {"kind": "object", "required": true, "writable": false},
    "start": {
      "kind": "field",
      "required": true,
      "writable": false,
      "types": ["Timestamp", "Date"]
    }
  },
  "config_schema": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "editable": {
        "type": "field_map",
        "binding": "object",
        "default": {},
        "value": {
          "type": "object",
          "additionalProperties": false,
          "properties": {"optional": {"type": "boolean"}}
        }
      }
    }
  },
  "slots": {},
  "draft": {"reads": [], "writes": []},
  "commands": [],
  "capabilities": [],
  "tokens": [],
  "responsive": {"min_width": 320, "preferred_width": 1120},
  "examples": []
}
# file: ui/pages/schedule.json
{
  "page": "schedule",
  "root": {
    "id": "schedule",
    "component": "planner.calendar@1",
    "config": {"editable": {"title": {}, "room": {"optional": true}}},
    "bindings": {"object": "Meeting", "start": "starts_at"}
  }
}
```

Binding `"start": "title"` here is refused, and so is an `editable` key `venue`. A field map is legal only at the top level of `config_schema`. Narrowing a published binding's `types` is a breaking change to the component's contract.

#### The SDK contract stamp

A trusted entry's first line is the SDK contract stamp `/* basel-sdk-contract:<major>.<minor> */` that `@basel/ui-sdk/vite` writes. The host accepts the same major with a minor up to its own `sdk_contract` (on `/health` and `/reflect/ui`). Metadata admission, activation and the console refuse any other stamp, the retired `/* basel-sdk:… */` one, or none, with `sdk_contract_incompatible`, naming both versions. The contract version changes only when the SDK's surface does, not with every release.

#### The app shell: navigation and brand

An app that declares no `navigation` gets a generated rail: the tenant's own objects under "Objects", then each package's objects under the package's title (its namespace when it has none). Two kinds of object stay off it, since an entry for them is noise: an abstract root (`abstract: true`) and an owned member, an object whose own end of some relationship declares `cardinality: {min: 1, max: 1}`, so each row holds exactly one link to its parent for its whole life (the owned member of "Deleting an endpoint row" below), such as a contact's email addresses or an order's lines; both stay reachable from the parent's record page, and an authored `navigation` may list them. A declared `navigation` replaces the generated groups entirely: what it leaves out is hidden.

An app's `"shell": {"navigation": <node>}` hands the app shell's navigation slot to an authored `ui.navigation` node in place of the generated one. The brand row, tenant plate, account, sign-out and administration stay host-owned; `/ui/app` still lists the navigation groups.

`"shell": {"brand": {"name": "<text>", "mark": {"asset": "tenant:<image asset>"}, "caption": "<text>"}}` puts the app's own brand in that row in place of the console's Basel mark:

- `name` is localizable, and the app's title when absent;
- `mark` is an optional tenant image asset;
- `caption` is optional plain text.

`/ui/app` serves it as `shell.brand` (`name`, `caption`, `mark` as the asset descriptor with its URL), and `shell.brand` is null when undeclared.

#### Commands

- A tree holding a component that declares the `record.create` command gets a `record.create` descriptor of kind `row_create` naming the node's `object` binding (or `null`), invoked as `record.create` with `{object, values}`.
- An object `view` surface declares `record.update` (kind `row_update`, naming the object) beside `record.delete` and its actions. A custom view root PATCHes the current record with `command('record.update', {id, version, patch})`.
- `edit`/`create` keep their draft commands (`record.save`/`record.cancel`) and no `record.update`. `edit` also declares `record.reload` and `record.discard` (kind `reload`): after a `412 stale_record` they re-read the record and move the draft onto its new version, keeping the reader's edits (an edited field the server also changed is flagged `changed_elsewhere`) or dropping them.
- The generated view's `record.actions` bar (`basel.action_bar@1`, where `record.delete` lives) exists on every object view, with `actions: []` when the object declares no lifecycle transition or action. So `{"generated": "record.actions"}` always resolves.

#### Query bindings

Every binding whose manifest kind is `query` — `comments`, `all`, not only one named `query` — is compiled to the same contract (`{id, name, compiled: true, from, select, parameters, order_by, page}`). A component executes any of them at `/ui/queries/{id}`. One naming a query its surface does not declare refuses `invalid_binding` at `<surface>.<node>.bindings.<name>`.

An app's `queries` binds the app shell's own surface queries, exactly like an object's or a page's (`{"use": "<query>", "arguments"?: {...}}`), with arguments from the request only (the shell has no record context). They plan as `app.<name>` with `owner: app`. `/ui/app` serves their contracts under `queries`, `/ui/queries/app.<name>` executes them, and the authored `shell.navigation` node binds them by local name through its query-kind bindings.

The effective principal's id is not on `/ui/app` (a document cached by UI checksum for every reader). `GET /tenants/{key}/whoami` serves `effective_principal.id` and `acting_principal.id` per caller.

#### Node parameters from the page URL

A node in a page or list tree may declare `"parameters": {"<query param>": {"source": "params.<url key>"}}` beside its `bindings`. It names a parameter of a query the node binds, and the page request parameter (`ShellState.params`) the host fills it from. The evaluated node serves it as written.

It refuses at `<surface>.<node>.parameters.<name>` with:

- `invalid_binding` — on a record surface, for a name no bound query declares, or for a `source` that is not `params.<key>`;
- `unknown_key` — for any key beside `source`.

### Presentation release batches

Use `{selections: [{component, entry, styles, declaration}], reason, expected_ui_checksum, presentation_digest, rollback_of?}` at the same activation endpoint and tenant CAS (see "Independent UI releases" below). Each declaration carries API 1.0, a semantic fingerprint and the admitted baseline from the component endpoint's `release_contract`. Missing/breaking presentation declarations refuse.

All selections commit together with one audit event; a rollback reselects the exact retained batch. Expected UI/presentation mismatch is `412 stale_presentation_activation`. Legacy single-component bodies remain supported for legacy components. Isolated artifact activation refuses; use metadata assets. Mounted editors retain their snapshot; ordinary navigation or explicit update prepares scoped CSS/fonts and swaps only when ready.

### Independent UI releases

A compatible implementation of a tenant component is released without a metadata apply.

#### Artifacts

`POST /tenants/{key}/ui/artifacts` stores raw `text/javascript` (`script`) or `text/css` (`stylesheet`) bytes as an immutable, content-addressed artifact. It has SHA-256 identity, is idempotent on the same bytes, has a 4 MiB cap, and gets the same signature check as `ui/assets/`; it is never in tenant Git. It is served from `GET /tenants/{key}/ui/artifacts/{sha256}` with the asset endpoint's immutable headers.

#### Activations

`POST /tenants/{key}/ui/activations` appends to a per-tenant append-only activation log. The body is `{component: "<id>@<major>", entry: <sha256> (or null to clear), styles: [<sha256>], reason, rollback_of?}`, sent with `If-Match: "<activation_revision>"` — compare-and-set. Refusals:

- `412 stale_activation`, naming the current revision;
- `428` without the header;
- `422` for an unknown component/artifact, a kind that does not fit its slot, an empty reason, or a `rollback_of` that is not a prior revision of that component.

Rollback is a new activation naming a retained artifact; an artifact any activation references is never deleted. `GET /tenants/{key}/ui/activations` serves the state (`metadata.read`). The write paths need the tenant action `ui.release`, a separate grant from `metadata.push` that `role_admin` holds.

#### What a surface loads

`activation_revision` (0 before any activation) rides beside `ui_checksum` in `/ui`, `/ui/app`, every surface, the catalog and each manifest, and in every metadata ETag. `ui_checksum` itself never changes on a release, so named-query `If-Match` preconditions are unaffected.

A surface's `components[key].entry`/`styles` point at:

- the activated artifacts, when a selection is live for a key the current metadata version declares (`activation: {source: activation, revision}`);
- else the manifest's metadata assets (`source: metadata`);
- else nowhere (`source: none`; a manifest may omit `entry` entirely and be supplied by activation).

An apply that changes a contract major retires the old key's selection (`effective: false`, reported, not resolved), and the new key starts on its metadata asset; restoring the old contract restores its selection. The engine reconstructs every selection from the log at startup. A dev session's browser-local preview override still beats an activation.

### Isolated pages

A tenant component manifest may say `execution: isolated` (default `trusted`). The component then renders as a whole page in a `sandbox="allow-scripts"` iframe on a separate origin. It is admitted only for `ui.root` in `page`/`list` modes with no `slots`, no `draft` and none of `draft.read`, `draft.write`, `overlay`, `asset.read` (refusal `invalid_component_execution`). Surface documents carry `components[key].execution`.

#### Minting and serving the frame

The console mints the frame with `POST /tenants/{key}/ui/frames/{id}@{major}` (`metadata.read`, an `Origin` header required). It gets `frame.url` on the isolated origin (`BASEL_ISOLATED_ORIGIN`; in dev mode the engine's own) with a sealed two-minute ticket. The response is `409 isolation_unavailable` when no isolated origin is established or it equals the caller's, and the page then refuses rather than running trusted.

`GET` of that URL reads no session — the ticket is the authorization (`404` without one, `412 stale_ui` after a redeploy). It serves the frame document under this policy:

```
default-src 'none'; script-src <entry>; style-src <stylesheets>; style-src-attr 'unsafe-inline'; img-src/font-src <the frame asset endpoint>; connect-src 'none'; frame-ancestors <the console>; base-uri 'none'; form-action 'none'; sandbox allow-scripts
```

Its assets come from `GET /tenants/{key}/ui/frames/{id}@{major}/assets/{logical_name}/{sha256}` (no session, `Access-Control-Allow-Origin: *`; only that component's entry and stylesheets and the tenant's image/font assets).

#### The bridge

Inside the frame the page talks to the console over the `isolated/1` `postMessage` bridge (`@basel/ui-sdk/isolated`). It grants its node's named queries, its manifest's commands, object/page navigation, notifications and the theme/context snapshots — never the draft, an overlay, a fetch or a credential.

### Surfaces

A surface is a typed node tree. Each node has a stable `id`, a `<component>@<contract-major>`, one attachment, closed-schema config, typed bindings, optional compiled conditions, and manifest-declared named slots. Generated list/view/create/edit trees are total.

A page writes its tree explicitly: `{id, component, presentation?, config?, bindings?, parameters?, visible_when?, enabled_when?, slots?}`, where each slot is an ordered array of nodes, `{"part": ...}` or `{"generated": ..., "except"?: [...]}`. There are no selector patches, loops, macros or interpolation, and an object view has no overlays (see "Custom screens are app pages"). Duplicate ids and limit breaches refuse apply. Conditions (`visible_when`, `enabled_when`) are UX-only, rooted at `row.`, and may read own stored fields/lifecycle state plus deterministic scalar functions; they never grant write authority.

### Rendering, caching, and preconditions

`GET /tenants/{key}/ui` is the rendering root; `/reflect/ui` is the authoring/topology root. Evaluated metadata returns normalized IR, never the authored files, and uses strong locale-and-surface ETags with `If-None-Match`/`304`. The tags also move with the engine build, the metadata version and the model checksum, so neither an engine upgrade nor a metadata change that leaves `ui_checksum` as it was (a model-only push) answers `304` with an older body.

Named-query POSTs require `If-Match: "<ui_checksum>"`: missing is `428 precondition_required`, stale is `412 stale_ui`. Query/data responses are `no-store`. An explicit evaluated-UI actor/context override is reserved for a later release and returns `501 {"status":"not_implemented","milestone":"M6"}`.

### The standard UI (`?ui=standard`)

Every `/ui/*` GET door, and `POST /tenants/{key}/ui/queries/{id}`, take an optional `?ui=standard`. It answers with the standard UI: Basel's generated UI for the model alone, ignoring the app's UI definition — its object views, pages, record and list page choices, components, shell and theme. Every object the model declares gets its generated list, view, create and edit surfaces, and the navigation lists them all; permissions and data are unchanged. It has its own `ui_checksum` and its own generated query ids, so a query posted with `?ui=standard` must name one of its plans and carry its checksum. It needs `metadata.read` itself: a caller admitted only through an installed app's package role is refused `403`. Any other `ui` value is `422 invalid_query_parameter`. The console offers it to tenant admins as the Basel menu's **Standard UI** switch.

### Limits and installed components

**Published limits.**

- Component-tree depth: 24
- Nodes per surface: 500
- Slots per component manifest: 32
- Overlay operations per mode: 200
- Named queries per object/page: 32
- Selected paths per query: 64
- Query parameters: 32
- Default/max cursor page: 50 / 500
- UI condition nodes: 128
- Localized variants per text: 20

**Installed standard components.**

Each line names a component's config keys, bindings and slots, `*` marking a required one, the modes it is placed in, and whether it draws its own frame. Its full manifest (the config schema, binding kinds, slot rules and examples) is `basel reflect <tenant> ui/components/<id>@<major>`, the MCP tool `basel_components`, or `GET /tenants/{key}/reflect/ui/components/{id}@{major}`; without the last segment it lists every component the tenant can use, its own and installed ones included.

- `basel.action_bar@1` — Action Bar. Bindings: `actions`, `object`*, `record`. Slots: `actions`. Modes: view, create, edit.
- `basel.activity@1` — Activity. Config: `title`. Bindings: `query`*, `record`*. Modes: view. Draws its own frame.
- `basel.app_shell@1` — App Shell. Slots: `footer`, `header`, `main`*, `navigation`*. Modes: list, view, create, edit, page.
- `basel.card@1` — Card. Slots: `body`*, `footer`, `header`. Modes: list, view, create, edit, page. Draws its own frame.
- `basel.chart@1` — Chart. Config: `display`, `drill`, `kind`. Bindings: `category`*, `query`*, `value`*. Modes: list, view, create, edit, page. Draws its own frame.
- `basel.command_palette@1` — Command Palette. Bindings: `action`, `route`. Modes: list, view, create, edit, page.
- `basel.conflict_state@1` — Conflict State. Modes: list, view, create, edit, page.
- `basel.data_table@1` — Data Table. Config: `density`. Bindings: `fields`*, `object`*, `query`*. Slots: `footer`, `toolbar`. Modes: list, view, edit, page. Draws its own frame.
- `basel.empty_state@1` — Empty State. Config: `detail`, `title`. Slots: `actions`. Modes: list, view, create, edit, page.
- `basel.error_state@1` — Error State. Modes: list, view, create, edit, page.
- `basel.field@1` — Field. Config: `display`, `presentation`. Bindings: `query`, `value`*. Modes: view, create, edit.
- `basel.filter_bar@1` — Filter Bar. Config: `parameters`. Bindings: `fields`*, `query`*. Modes: list, page.
- `basel.grid@1` — Grid. Config: `columns`. Slots: `children`. Modes: list, view, create, edit, page.
- `basel.heading@1` — Heading. Config: `level`, `text`. Modes: list, view, create, edit, page.
- `basel.image@1` — Image. Config: `alt`, `fit`. Bindings: `asset`*. Modes: list, view, create, edit, page.
- `basel.inline_collection@1` — Inline Collection. Config: `label`, `primary_action`, `primary_param`, `primary_pointer`, `title`, `value`. Bindings: `query`*, `record`*, `relationship`*. Slots: `actions`. Modes: view. Draws its own frame.
- `basel.kanban@1` — Kanban. Config: `columns`. Bindings: `fields`, `group`*, `lifecycle`, `object`*, `query`*, `title`*. Modes: list, page.
- `basel.kind_chooser@1` — Kind Chooser. Config: `kinds`. Modes: create.
- `basel.lifecycle@1` — Lifecycle. Config: `orientation`, `show_outcomes`. Bindings: `lifecycle`*, `value`*. Modes: view, edit. Draws its own frame.
- `basel.loading_state@1` — Loading State. Modes: list, view, create, edit, page.
- `basel.markdown@1` — Markdown. Config: `text`. Modes: list, view, create, edit, page.
- `basel.markdown_field@1` — Markdown Field. Config: `height`, `preview`. Bindings: `value`*. Modes: view, create, edit.
- `basel.metric@1` — Metric. Config: `aggregate`, `display`, `label`. Bindings: `query`*, `value`. Modes: list, view, create, edit, page.
- `basel.metric_strip@1` — Metric Strip. Slots: `metrics`*. Modes: list, view, create, edit, page.
- `basel.navigation@1` — Navigation. Bindings: `routes`. Slots: `items`. Modes: list, view, create, edit, page.
- `basel.navigation_group@1` — Navigation Group. Config: `collapsed`, `label`. Bindings: `route`. Slots: `items`. Modes: list, view, create, edit, page.
- `basel.page@1` — Page. Slots: `footer`, `header`, `main`*, `sidebar`. Modes: list, view, create, edit, page.
- `basel.pagination@1` — Pagination. Bindings: `query`*. Modes: list, page.
- `basel.record_fields@1` — Record Fields. Bindings: `fields`*, `object`*, `record`*. Slots: `fields`*. Modes: view.
- `basel.record_form@1` — Record Form. Bindings: `object`*, `record`. Slots: `actions`*, `fields`, `sections`. Modes: create, edit.
- `basel.record_header@1` — Record Header. Bindings: `object`*, `record`*. Slots: `actions`. Modes: view, edit.
- `basel.reference_choice_picker@1` — Reference Choice Picker. Bindings: `value`*. Modes: create, edit.
- `basel.reference_picker@1` — Reference Picker. Bindings: `query`*, `value`*. Modes: create, edit.
- `basel.related_list@1` — Related List. Bindings: `fields`, `query`*, `relationship`*. Slots: `actions`. Modes: view, create, edit. Draws its own frame.
- `basel.relationship_editor@1` — Relationship Editor. Bindings: `query`, `relationship`*. Modes: create, edit.
- `basel.relationship_field@1` — Relationship Field. Bindings: `query`*, `relationship`*. Modes: view, create, edit.
- `basel.section@1` — Section. Config: `columns`, `frame`, `label`. Slots: `actions`, `body`*, `header`. Modes: list, view, create, edit, page.
- `basel.split@1` — Split. Config: `ratio`. Slots: `primary`*, `secondary`*. Modes: list, view, create, edit, page.
- `basel.stack@1` — Stack. Config: `gap`. Slots: `children`. Modes: list, view, create, edit, page.
- `basel.tab@1` — Tab. Config: `label`. Slots: `body`*. Modes: list, view, create, edit, page.
- `basel.tabs@1` — Tabs. Config: `activation`. Slots: `tabs`*. Modes: list, view, create, edit, page.
- `basel.unavailable_state@1` — Unavailable State. Modes: list, view, create, edit, page.
- `basel.validation_summary@1` — Validation Summary. Modes: create, edit.

### Link-only traversal

Start at `/`, choose a tenant, follow its `/reflect` root's `ui._href`, then an object/page `_href`. Follow an `evaluated_href` to obtain the normalized tree and `ui_checksum`. Follow a query contract's `_href` and POST its typed context/parameters/page object with that checksum in `If-Match`.

Commands in the evaluated surface identify the existing typed object/action endpoints; no undocumented UI URL or raw BQL construction is required. Runtime errors add `stale_ui`, `invalid_cursor`, `invalid_query_parameter`, and `ui_registry_mismatch` to the ordinary Basel error envelope.

### Related-list edit mode

In `create`/`edit` mode, `basel.related_list` binds its relationship writably to the shared draft. It renders existing members and pending rows as one editable table:

- adding a line stages a `create` entry;
- editing a cell on an existing member stages an `update` entry (`{"id": ..., "values": {...}}`);
- removing a row stages a `delete` entry (dropping any staged `update` for the same id).

There is no independent save: the record's own `submit()` remains the only serializer.

### Related records on generated surfaces

A traversal whose declaring end allows at most one record (`"cardinality": {"max": 1}` on this object's own end) is a field, not a related list.

- The generated record page shows it as `field.<traversal>`, a `basel.relationship_field` among the fields (the linked record by its label, linking to it), and places no related list for it.
- The generated `create`/`edit` forms carry the same node as a picker (search, choose, clear) when the mode may write it (`nested.create` lists `link`; `nested.update` lists `link` or `unlink`).
- Saving the form creates, replaces or removes the link in the record's own write: `{"<traversal>": [<id>]}` on create, `{"<traversal>": {"link": [...], "unlink": [...]}}` on update.
- A to-one relationship that declares its own properties keeps a related list.

Generated forms carry no other relationship editor. Linked records are added, edited and removed on the record page's related lists, whose rows offer Edit (the related record, in its own editor) and Remove (the link only, never the record).


### The styling contract

A presentation's stylesheet styles Basel's pages through the hooks, tokens and attributes below, and through nothing else. The `.ngui-*` classes and `--ngui-*` variables in the console's own CSS are private: a release may rename them without notice. Renaming or removing a hook or a token listed here needs a new presentation contract major. The same contract is served as `presentation_contracts.styling` in `GET /tenants/{key}/reflect/ui` (and `basel reflect <tenant> ui`), from the same source as this section.

**Hooks.** Everything a presentation draws sits under its root, `[data-ui-presentation]`. A page part is `[data-ui-part="<part>"]`, one of the names below (served as `presentation_contracts.parts.css`). A shell part uses a different attribute, `[data-basel-part="<part>"]`, and the shell's root says its layout in `data-basel-shell` (`rail` or `bar`).

| Page parts | Mark |
|---|---|
| `page`, `page-header`, `page-title` | a page, its header, its level-1 heading |
| `crumbs`, `crumb`, `crumb-meta` | the breadcrumb bar, one segment, its right-hand record and view text |
| `list-header` | an object list's heading row: title and New |
| `list-view-picker`, `list-view-editor`, `list-view-state` | a list's view picker, the list-view editor, and its problem or warning banner |
| `record-header`, `record-eyebrow`, `record-title`, `record-actions`, `record-fields` | a record's header, the subtype label above its title, its title, its action buttons, its field grid |
| `highlights`, `highlight` | a record's key fields under its title, and one of them (`data-field="<name>"`) |
| `object-icon` | an object's icon tile (`data-icon="<name>"`) |
| `section`, `section-header`, `section-body` | a section, its header, its body |
| `card`, `card-header`, `card-body`, `card-field` | a card, its header, its body; a board card's key field line |
| `table-frame`, `table`, `table-header`, `column-resizer`, `table-row`, `table-cell` | a list's table: frame, table, column heading, a heading's resize handle, body row, body cell |
| `pagination`, `result-count` | the pager and the total line |
| `related-list`, `related-list-header`, `related-list-count` | a record's related list, its header, its shown and total count |
| `path`, `path-header`, `path-step`, `path-step-index`, `path-step-label`, `path-step-note` | the lifecycle path, its header, one state, and that state's number, name and note |
| `path-actions`, `path-actions-label` | the available transitions and their label |
| `metric-strip`, `metric`, `metric-label`, `metric-value` | a row of metrics, one metric, its label, its figure |
| `tabs`, `tab`, `tab-panel` | a tab set, one tab, one panel |
| `kanban`, `kanban-column`, `kanban-column-header`, `kanban-card` | a board, a column, its heading, a card |
| `chart` | a chart |
| `dialog`, `dialog-header`, `dialog-title`, `dialog-meta`, `dialog-close`, `dialog-body`, `dialog-footer`, `dialog-status`, `dialog-actions` | Basel's own dialogs and their pieces (the record editor is the presentation's `editor` renderer instead) |
| `activity`, `activity-header`, `activity-count`, `activity-item`, `activity-marker`, `activity-title`, `activity-time` | a record's activity feed and one entry in it |
| `form-section`, `form-section-title` | a form's field group and its heading |
| `help` | a note under a board |
| `empty-state` | the empty-list message |
| `value`, `value-unit` | a displayed value (`data-type`: `text`, `money`, `date`, `reference`, `state`, …) and the muted unit after a number |
| `button` | a host action button (see `data-variant`) |
| `menu`, `menu-item`, `lookup-results`, `lookup-option`, `lookup-option-detail`, `content` | menus, reference-picker results, rich content |
| `ornament` | Basel's decorative corner marks |

The shell parts are `brand`, `tenant`, `tools`, `nav`, `nav-items`, `nav-group`, `nav-group-label`, `nav-item`, `session`, `session-principal`, `session-identity`, `session-account`, `session-signout`, `session-add-user`, `session-tenants`, `header`, `main`, `footer`. A shell may hide or restyle any of them except the session controls, `session-identity`, `session-account`, `session-signout`, which stay visible and clickable whatever a stylesheet says.

**Tokens.** Each token a presentation declares is a CSS variable on its root: `color.accent` is `--presentation-color-accent`, each `.` of the name a `-`. A stylesheet reads any of them with `var()`. The host itself reads the tokens below, so each of these names must have the kind shown (`invalid_presentation_token` otherwise); a token named otherwise is the presentation's own, for its stylesheets and renderers.

| Token | Kind | Variable | The host draws with it |
|---|---|---|---|
| `color.accent` | color | `--presentation-color-accent` | links, primary buttons, the current navigation item and selection |
| `color.text` | color | `--presentation-color-text` | body text |
| `color.canvas` | color | `--presentation-color-canvas` | the page background behind cards and sections |
| `color.surface` | color | `--presentation-color-surface` | the presentation's surface: controls, menus and lookup results |
| `color.border` | color | `--presentation-color-border` | control, menu and card borders and rules |
| `color.focus` | color | `--presentation-color-focus` | the focus outline |
| `color.error` | color | `--presentation-color-error` | a field's error text |
| `color.hover` | color | `--presentation-color-hover` | a hovered button or menu item and the active lookup option |
| `color.section-marker` | color | `--presentation-color-section-marker` | the marker before a record section's or card's heading (every section; without it the host alternates three tints) |
| `color.related-list-marker` | color | `--presentation-color-related-list-marker` | the marker before a related list's heading |
| `color.activity-marker` | color | `--presentation-color-activity-marker` | the marker before the activity list's heading |
| `font.body` | font | `--presentation-font-body` | body text |
| `font.heading` | font | `--presentation-font-heading` | small uppercase headings: board columns, chart captions, empty states, action parameters, Markdown headings |
| `font.display` | font | `--presentation-font-display` | the headings of record sections, cards, related lists and activity |
| `font.numeric` | font | `--presentation-font-numeric` | numbers: metrics, money and table figures |
| `space.control` | length | `--presentation-space-control` | the gap between a field's label and its control |
| `radius.control` | length | `--presentation-radius-control` | the corner radius of buttons, inputs and menus |
| `elevation.blur` | length | `--presentation-elevation-blur` | the blur of a menu's and lookup's shadow |
| `motion.duration` | duration | `--presentation-motion-duration` | the hover transition of buttons (0ms under reduced motion) |
| `opacity.disabled` | number | `--presentation-opacity-disabled` | a disabled button's opacity |
| `text.size` | length | `--presentation-text-size` | reserved: the kind is fixed, the host does not read it yet |

Two more variables come from the manifest itself: `--presentation-target` (from `variants.minimum_target`: the minimum height of inputs and buttons, in px); `--presentation-icon-<icon>` (from `icons.<icon>.color`: the tile colour behind an object icon).

**State attributes.** The root and the parts carry their state as attributes, so a stylesheet selects a state rather than a class:

| Attribute | Values | On | Means |
|---|---|---|---|
| `data-ui-presentation` | `<id>@<major>` | the presentation root | the selected presentation |
| `data-ui-theme` | the theme's name | the presentation root | the theme drawn |
| `data-ui-narrow` | true \| false | the presentation root | the viewport is narrower than variants.narrow_below |
| `data-ui-coarse` | true \| false | the presentation root | a coarse pointer (touch) |
| `data-ui-hover` | true \| false | the presentation root | a pointer that hovers |
| `data-label-layout` | inline \| stacked | the presentation root | variants.label_layout |
| `data-button-decoration` | plain \| outline | the presentation root | variants.button_decoration |
| `aria-current` | page | nav-item, and the last crumb's text | the current page |
| `aria-selected` | true \| false | tab | the open tab |
| `aria-current` | step | path-step | the record's current lifecycle state |
| `data-state` | complete \| current \| upcoming | path-step | the step against the current state |
| `data-outcome` | success \| failure, empty when the state has none | path-step | a terminal state's outcome |
| `data-variant` | primary \| secondary \| danger | button | the button's role |

**Renderer regions.** A presentation that brings its own renderer component for a family receives these pieces as props, to place as it likes:

| Renderer | Regions |
|---|---|
| `editor` | `heading`, `body`, `messages`, `actions` |
| `field` | `label`, `control`, `help`, `errors` |
| `lookup.option` | `label` |
| `record_header` | `icon`, `eyebrow`, `title`, `actions`, `highlights` |
| `shell` | `brand`, `tenant`, `navigation`, `session`, `tools`, `header`, `main`, `footer` |

**Layout.** A presentation chooses the built-in shell's layout and the page width in its manifest, without a shell renderer:

```json basel-fragment
{"layout": {"shell": "bar", "content_width": "90rem"}}
```

`shell` is `rail` (the left rail, the default) or `bar` (the same parts in a band across the top, the page below). `content_width` is the widest a page's content reads: `<n>rem` from 20 to 200, `<n>px` from 320 to 3200, or `none` for the full width of the main column; the default is `72rem`. Anything else is refused `invalid_presentation_layout`, naming `layout.shell` or `layout.content_width`. A presentation with its own `shell` renderer lays out its own root instead and sets `data-basel-shell` there.

**Cascade.** A presentation's stylesheets load into the `presentation` layer, above the host's own layout, so a plain selector on a hook wins without `!important` or extra specificity (see "Tenant components" for the layer order).

## Object views

An object view, `ui/objects/<snake>.json`, says how one object appears: its name and icon, its key fields, each field's widget, how its record page and edit form are arranged, what its create form asks for and what its list shows. Basel draws the generated pages from it, so a field added later still appears without editing a page.

A view holds names, lists, references and a few fixed choices. It holds no logic: no computed values, loops, conditional defaults or effects. The only expressions are a section's `visible_when` condition and the `where` of a query it uses. A rule such as "the amount is locked once won" is a model rule (`locks`, guards); it reaches the page as a read-only field. When a view can't say something, use a query, a function or a component.

### A worked example

A sales app with Deal and Customer. The Deal view uses most of what this chapter describes; the subsections below explain each part. It validates as written:

```json basel-repository
# file: basel.json
{"format": 2, "name": "sales", "default_currency": "USD"}
# file: objects/customer.json
{
  "name": "Customer",
  "fields": {"name": {"type": "text"}, "industry": {"type": "text", "nullable": true}}
}
# file: objects/deal.json
{
  "name": "Deal",
  "fields": {
    "name": {"type": "text"},
    "amount": {"type": "Money", "nullable": true},
    "probability": {"type": "int", "nullable": true},
    "expected_close_date": {"type": "Date"},
    "description": {"type": "text", "nullable": true},
    "next_step": {"type": "text", "nullable": true},
    "loss_reason": {"type": "text", "nullable": true},
    "import_key": {"type": "text", "nullable": true},
    "weighted_amount": {"type": "Money", "formula": "row.amount * row.probability / 100"}
  },
  "lifecycles": {
    "stage": {
      "initial": "open",
      "states": [
        {"name": "open"},
        {"name": "won", "outcome": "success"},
        {"name": "lost", "outcome": "failure"}
      ]
    }
  },
  "actions": {
    "win": {"transition": {"lifecycle": "stage", "from": ["open"], "to": "won"}},
    "lose": {"transition": {"lifecycle": "stage", "from": ["open"], "to": "lost"}}
  }
}
# file: relationships/deal_customer.json
{
  "name": "DealCustomer",
  "from": {
    "object": "Deal",
    "name": "customer",
    "cardinality": {"max": 1},
    "nested": {"create": ["link"], "update": ["link", "unlink"]}
  },
  "to": {"object": "Customer", "name": "deals"}
}
# file: queries/open_deals.json
{
  "name": "open_deals",
  "exposure": "internal",
  "from": "Deal",
  "select": ["id", "name", "customer.name", "stage", "amount", "expected_close_date"],
  "where": "row.stage = 'open'",
  "params": {"closes_by": {"type": "Date", "optional": true}},
  "optional_filters": {"closes_by": "row.expected_close_date <= args.closes_by"},
  "order_by": [{"field": "expected_close_date", "direction": "asc"}]
}
# file: ui/app.json
{"default_locale": "en-US"}
# file: ui/objects/deal.json
{
  "object": "Deal",
  "icon": "target",
  "compact": ["amount", "expected_close_date", "stage"],
  "fields": {"description": {"config": {"presentation": "multiline"}}},
  "queries": {"open_deals": {"use": "open_deals"}},
  "record": {
    "sections": [
      {"id": "details", "label": "Details", "fields": ["name", "customer", "amount", "expected_close_date", "stage"]},
      {"id": "forecast", "label": "Forecast", "fields": ["probability", "weighted_amount", "customer.industry"]},
      {"id": "plan", "label": "Plan", "columns": 1, "fields": ["description", "next_step"]},
      {
        "id": "lost",
        "label": "Why it was lost",
        "fields": ["loss_reason"],
        "visible_when": "row.stage = 'lost'"
      },
      {
        "id": "history",
        "label": "History",
        "component": "basel.activity@1",
        "bindings": {"query": "generated.activity"}
      },
      {"id": "more", "fields": "remaining"}
    ],
    "hidden": ["import_key"]
  },
  "create": {"fields": ["name", "customer", "amount"]},
  "list": {
    "query": "open_deals",
    "columns": ["name", "customer.name", "amount", "expected_close_date"],
    "filters": ["closes_by"]
  }
}
```

What it draws:

- **Record page and edit form:** Details, Forecast, Plan (each field on its own full-width row), "Why it was lost" only while the stage is `lost`, the activity feed, and a trailing "More" section for anything not placed (here nothing). `import_key` never appears.
- **Create form:** name, customer and amount, then a trailing "More" section with `expected_close_date`, because a create can't succeed without it.
- **List:** open deals only, four columns, soonest close first, with a "closes by" filter.

`basel validate` reports one notice for it, `component_section_not_in_edit`: the activity feed draws only on the record page, so the edit form leaves that section out.

### Record layout: sections, `hidden` and `remaining`

`record` arranges the record page. The edit form follows the same sections in the same order. `editor` may be written too, but it must equal `record`; a different edit form for one object is an app page under `edit_pages` (see "Which declaration wins").

- A field section is `{id?, label?, fields, columns?, visible_when?}`. `fields` names, in order, the object's own stored fields, formulas, rollups and lifecycles, its to-one links (`customer`, shown as a picker in forms) and fields through a to-one link (`customer.industry`).
- `id` names a section, and its node on the page is `section.<id>` (the Forecast section above is `section.forecast`) wherever the section stands, in `record`, the edit form and `create`. It is unique within the layout or create form (`duplicate_section`) and uses lowercase letters, digits and underscores. A section without an `id` is numbered by position: the first is `section.details`, the others `section.2`, `section.3`, …; the `remaining` section is always `section.more` (or `section.details` when it is the only one), whatever its `id`. So `more`, a number, and `details` anywhere but the first section are refused (`invalid_ui_id`). Adding or changing an `id` renames that section's node, so anything that names the old node id, such as `{"generated": "section.2"}` on an app page, must change with it.
- `hidden` names fields that never appear on the record page or the edit form.
- **`{"fields": "remaining"}` is required, and comes last** (`missing_remaining`, `remaining_not_last`). It is drawn as a section labelled "More" and holds every field no section places and `hidden` does not name, in the generated order. So a field added later, by you or by a tenant addition, still shows up. Hiding is always explicit. It takes only an `id`: no label, columns or condition. A lifecycle is the exception on the record page: its stage path already shows it, so it appears among the fields only where a section names it.
- In the edit form, formulas, derived fields and fields the viewer can't write are read-only. A field through a link (`customer.industry`) is always read-only, since editing it would change another record; to change which customer, edit `customer`.
- A field the viewer can't read is skipped, and a section left empty isn't shown.
- Refusals, at `ui.objects.<O>.layout.sections[i].fields[j]` or `…layout.hidden[k]` (the compiler's internal names for `record.sections` and `record.hidden`): `object_view_unknown_field` for a field the object doesn't have, `object_view_field_twice` for a field named twice or both in a section and in `hidden`.

Without `record`, the page draws every readable field as before, except the lifecycles its stage path shows.

### Field widgets

`fields.<f>` holds a field's presentation once, used on the record page, in create and in edit: `label`, `help`, `placeholder`, one `widget` (a registered component, `<id>@<major>`) and its `config`. A mode may override only the widget: `"view": {"widget": ...}` on the record page, `"edit": {"widget": ...}` in create and edit, which share one widget. `config` is never per mode.

```json basel-fragment
{
  "object": "WorkItem",
  "fields": {
    "problem": {"widget": "basel.markdown_field@1", "config": {"height": 220}},
    "summary": {"label": "Summary", "view": {"widget": "acme.summary@1"}}
  }
}
```

### Wide fields and `columns: 1`

Fields sit two label/value pairs to a row. A field takes the whole row, on the record page and in the edit form, when:

- it is multi-line text (`"display": {"lines": "multi"}` on the field in the model, or `"config": {"presentation": "multiline"}` on its `fields` entry, as `description` above) or Markdown;
- it is the only field in its section the viewer can read;
- its section declares `"columns": 1` (the Plan section above). The default is `2`; any other value refuses `object_view_section_columns`.

A wide field's label stays in the page's shared label column.

### Conditional sections: `visible_when`

A field or component section may declare `visible_when`, a predicate over the record's own stored fields and lifecycle states, rooted at `row.`, as in `"row.stage = 'lost'"` above. It is judged against the record on the record page, and against the draft in the edit and create forms, so a section appears and disappears as the person types. Hiding a section never clears its values.

- No formulas, aggregates, quantifiers or time functions; at most 128 nodes. A malformed condition refuses `ui_condition_error` (or `limit_exceeded`) at `…sections[i].visible_when`.
- If the condition reads a field the viewer can't read, the section stays hidden. A readable empty field is null (`IS NULL` is true).
- The `remaining` section is never conditional.
- A difference that is only visual is a condition, not a new subtype.

### Component sections

A section may draw one component instead of fields: `{id?, label?, component: <id>@<major>, config?, bindings?, slots?, visible_when?}`. The History section above draws `basel.activity@1`. Use one for an activity feed, a chart, or a picker in a form.

- The component may be a `basel.*` one, your own, or a vendored one. It is checked against its manifest like any page node: `unknown_component`, `invalid_binding` (at `…sections[i].bindings.<name>`), and its config against its schema.
- If the manifest declares a `record` binding, Basel fills it: the current record on the record page and in edit, the draft in create.
- It appears in each of the record page, the edit form and the create form whose mode its manifest accepts. Where it can't be drawn, it is left out with a notice (`component_section_not_in_view`, `…_in_edit`, `…_in_create`) from `basel validate` and on the push plan's `advisories`, never an error. One that can be drawn on neither the record page nor the edit form refuses `invalid_attachment`.
- **`frame: own`.** A component whose manifest says `frame: own` draws its own card: `basel.activity@1`, `basel.related_list@1`, `basel.data_table@1`, `basel.chart@1`, `basel.lifecycle@1`, `basel.card@1`. It gets no section card around it; the section's `label` becomes its title when its config takes one, and a plain heading above it otherwise. Any other component sits in a section card under its label. Your own component declares `frame: own` in its manifest when it draws its own card.
- A layout that places `basel.activity@1` gets no second activity feed at the foot of the page.

**Slots of plain nodes.** A component section may also fill its component's slots, so a `basel.metric_strip@1` keeps its metrics. Each node in `slots` is plain: `id`, `component`, `config`, `bindings`, and `slots` of plain nodes. The nodes may bind the view's own `queries`, and those queries may name objects and hard-code values. Here a Customer's record page totals its open deals; the view passes the record it shows to the query's `record` parameter:

```json basel-repository
# file: basel.json
{"format": 2, "name": "sales"}
# file: objects/customer.json
{"name": "Customer", "fields": {"name": {"type": "text"}}}
# file: objects/deal.json
{
  "name": "Deal",
  "fields": {
    "name": {"type": "text"},
    "amount": {"type": "int", "nullable": true},
    "stage": {"type": "enum", "values": ["open", "won", "lost"]}
  }
}
# file: relationships/customer_deals.json
{
  "name": "CustomerDeals",
  "from": {"object": "Customer", "name": "deals"},
  "to": {"object": "Deal", "name": "customer", "cardinality": {"max": 1}, "nested": {"create": ["link"]}}
}
# file: queries/customer_open_deals.json
{
  "name": "customer_open_deals",
  "exposure": "internal",
  "from": "Deal",
  "select": ["id", "amount"],
  "where": "row.customer.id = args.record AND row.stage = 'open'",
  "params": {"record": {"type": "ref", "to": "Customer"}}
}
# file: ui/app.json
{"default_locale": "en-US"}
# file: ui/objects/customer.json
{
  "object": "Customer",
  "queries": {
    "open_deals": {"use": "customer_open_deals", "arguments": {"record": {"context": "record.id"}}}
  },
  "record": {
    "sections": [
      {
        "label": "Pipeline",
        "component": "basel.metric_strip@1",
        "slots": {
          "metrics": [
            {
              "id": "open_pipeline",
              "component": "basel.metric@1",
              "bindings": {"query": "open_deals", "value": "amount"},
              "config": {"label": "Open pipeline", "aggregate": "sum"}
            },
            {
              "id": "open_count",
              "component": "basel.metric@1",
              "bindings": {"query": "open_deals"},
              "config": {"label": "Open deals", "aggregate": "count"}
            }
          ]
        }
      },
      {"label": "Details", "fields": ["name"]},
      {"fields": "remaining"}
    ]
  }
}
```

- No fields (`basel.field@1` or a picker; use a field section), no `{"part": …}`, no `{"generated": …}` and no `visible_when` on a node: each refuses `section_slot_not_plain`. Put a condition on the section.
- Node ids must differ across the layout's sections and from the page around them (`duplicate_node`).
- Each node is checked against its manifest like a page node, at `…sections[i].slots.<slot>[j]`.
- The section is drawn on the record page and in edit, never in create, where there is no record to read (`component_section_not_in_create`).
- In an app-scoped view (below) the `queries` and the section apply inside that app only.
- A subtype that inherits the layout does not inherit `queries`. It must declare its own `queries` of the same names (bound to a query whose parameter is a `ref` to its own object), or it is refused `invalid_binding`.

### The create form

`create` chooses the create form's fields: `"fields": [...]` for one section, or `"sections": [...]` in the same shape as `record.sections` (labels, `columns`, `visible_when`, component sections), without a `remaining` section. Without `create`, the form follows `record`, keeping only fields a create can set (no formulas, numbered, stamped or derived fields, no fields through a link). Without either, the generated form is used.

**Necessary inputs.** A necessary input is a required stored field with no default, stamp or numbering, that no rollup fills: the engine refuses a create without it. Layout choices never remove one from the create form.

- One the form leaves out is added to a trailing "More" section, as `expected_close_date` is above.
- One under `record.hidden`, or in a record section with `visible_when`, refuses `create_hides_necessary_input` when the view declares no `create`. Declare `create` or move the field to an unconditional section; hiding it on the record page and in edit is then fine. A `create` section with `visible_when` may not hold one either.
- A field through a link refuses `create_traversed_field`; name the link (`customer`) instead.
- A person who may not write a necessary input still sees the form, with the field marked as not writable. The server's refusal stays authoritative.

### The list

`list` says what the object's list shows. Without one, the generated list shows the record label (or the first own field), then the object's to-one links as link columns drawn by the related record's label, then its other own fields, five columns at most; its filter bar filters on the own fields. `list` takes one of two forms.

**A simple list:** Basel writes the query from the columns and sort.

```json basel-fragment
{
  "list": {
    "columns": ["name", "customer.name", "stage", "amount", "expected_close_date"],
    "sort": [{"field": "expected_close_date", "direction": "asc"}]
  }
}
```

The generated query selects the columns (plus `id`, the record label, any sort field and an abstract root's `$type`) and orders by `sort`, else by the generated order. The filter controls are the generated list's.

**A list over a query,** as in the worked example: `query` names a query this view (or `ui/app.json`) binds in its `queries`, `columns` chooses which of its selected fields show, and `filters` chooses which of its parameters show as filter controls, in order (all of them when absent). The query stays authoritative: its `where`, `params`, `optional_filters` and `order_by` are unchanged, and the records, filter bar and total all run it.

**A fixed predicate belongs in a query.** `list` has no `where`, operators or computed values. To show only open deals, write the condition in the query's `where`, as `open_deals` does, and point the list at it.

- `columns` are own fields (stored fields, formulas, lifecycles, audit timestamps), to-one paths such as `customer.name`, or a to-one link by itself such as `customer`. A path column is read-only and labelled like a layout's through-link field: `customer.name` reads "Name (Customer)". A link column shows the related record by its label (the target's `record_label`), as a `ref` field does, and is headed by the link's label ("Customer"); write it when you mean "show the customer", rather than guessing which of the customer's fields holds its name. It selects `customer.id`, so a list over a query needs `customer.id` in that query's `select`.
- `sort` takes the same fields and paths. A link by itself sorts by the related record's label: `{"field": "customer"}` orders as `customer.name` when `name` is the customer's `record_label` (refused when the target has none). To sort by another of its fields, name the path, `{"field": "customer.region"}`. In a query's `order_by`, write the path itself (`customer.name`).
- Refusals at `ui.objects.<O>.list…`: `object_view_unknown_field`, `list_column_not_in_query` (a column the query doesn't select), `list_sort_with_query` (`sort` beside `query`: the query's `order_by` is the one order), `list_filter_not_a_parameter`, `list_unknown_query`, `list_query_wrong_object`.
- Table versus board is not a `list` choice; it is the app's `list_pages` page or its `defaults.object_list` component.

**A board** is a page whose tree holds `basel.kanban@1`. Its `query` binding is required and names a query the page binds in its own `queries`, so the page declares both: `queries` maps a local name to the query (`{"use": "<query>"}`), and the board's `query` binding names that local name. Without it the page is refused `required query binding query is missing`. `group` names the field the columns are drawn by (a lifecycle or an enum), `title` the card's heading, `fields` the card's other lines, and `config.columns` the column order. The query selects every field the board names:

```json basel-repository
# file: basel.json
{"format": 2, "name": "sales", "default_currency": "USD"}
# file: objects/deal.json
{
  "name": "Deal",
  "fields": {
    "name": {"type": "text"},
    "amount": {"type": "Money", "nullable": true},
    "expected_close": {"type": "Date", "nullable": true}
  },
  "lifecycles": {
    "stage": {"initial": "lead", "states": [{"name": "lead"}, {"name": "proposal"}, {"name": "won"}, {"name": "lost"}]}
  }
}
# file: queries/pipeline_deals.json
{
  "name": "pipeline_deals",
  "exposure": "internal",
  "from": "Deal",
  "select": ["id", "name", "stage", "amount", "expected_close"],
  "order_by": [{"field": "expected_close", "direction": "asc"}],
  "page": {"default_size": 100, "max_size": 200}
}
# file: ui/app.json
{"default_locale": "en-US", "home": {"page": "pipeline"}}
# file: ui/pages/pipeline.json
{
  "page": "pipeline",
  "route": "/pipeline",
  "queries": {"deals": {"use": "pipeline_deals"}},
  "root": {
    "id": "pipeline",
    "component": "basel.page@1",
    "slots": {
      "main": [
        {
          "id": "board",
          "component": "basel.kanban@1",
          "bindings": {"object": "Deal", "query": "deals", "group": "stage", "title": "name", "fields": ["amount", "expected_close"]},
          "config": {"columns": ["lead", "proposal", "won", "lost"]}
        }
      ]
    }
  }
}
```

### Search

Any list over an object, and any picker choosing one, takes free text: the console's search box, a picker's search field, or an agent sending `{"parameters": {"search": "acme john"}}` to `POST /tenants/{key}/ui/queries/{id}` (or to a public query at `/queries/{name}`). `search` is a reserved parameter name that every list accepts without declaring it; a query of your own may not declare one.

The text is never a predicate. The engine splits it into terms (whitespace-separated; `"a quoted span"` is one term), and a record matches when **every** term matches **at least one** of the object's searchable fields, ignoring case. `field:value`, a leading `-`, `OR` and wildcards mean nothing yet and are matched literally; they are reserved for a later grammar. Over 8 terms or 200 characters is refused (`search_too_long`).

The guard is ANDed onto the query's own `where` and optional filters, applies on every page, and is bound into the page cursor. Results keep the list's order.

Across objects, `GET /tenants/{key}/search?search=acme` answers a few matching records per searchable object (`groups`, each with `rows` and `has_more`; `per_object` 1–20, default 5; `objects=a,b` to choose and order the objects, else the app's navigation objects whose view says `global: true`, less an abstract family root when a subtype of it is among them — the root's plan reads the whole family, so its rows would appear twice; a root is kept when it is the only family member shown, and its rows then carry `$type`). It runs each object's `generated.search` plan (the id, the label and the view's `results` columns) under the same guard and policy as any list, and carries no totals. The console's ⌘K palette reads it.

Which fields match is the object view's `search` key:

```json
"search": {
  "fields": ["name", {"field": "email", "match": "prefix"}, {"field": "code", "match": "exact"}, "customer.name"],
  "results": ["name", "customer.name", "stage"],
  "global": true
}
```

- `fields` (1–8): own text-like fields (text, email, phone, url, person name, region; stored or formula) or one to-one hop to one (`customer.name`). Each entry's `match` is `contains` (the default: the term occurs anywhere), `prefix` (the field starts with the term) or `exact` (the whole field equals the term). Order is priority, reserved for ranking later. The BQL behind the modes is `CONTAINS`, `STARTS_WITH` and `LOWER(...) =`.
- `results` (at most 8; default the record label then `compact`): the columns a search result shows — a picker option's second line, and a results page.
- `global` (default `true`): whether the object takes part in a tenant-wide results page.
- Omit the key and the object searches its `record_label` plus the text-like fields of its `compact`, all `contains`, so every object with a text label is searchable with no metadata. `"search": false` turns it off: its lists show no search box and a request carrying `search` is refused (`search_not_enabled`). An object with nothing text-like to match is unsearchable the same way.
- A field this caller may not read never matches, so a match reveals nothing the page would not; a `purpose: reference` query matches only the fields it selects.
- Refusals at `ui.objects.<O>.search…`: `search_field_not_text`, `search_field_unknown`, `search_path_too_deep`, `search_too_many_fields`, `search_no_fields`, `search_match_unknown`.
### Actions

The record page's action bar draws **only the actions the view lists**, in that order; it draws none by default, so declaring an action on the object does not put a button on the page. `"actions": ["escalate", "archive"]` names the object's own actions. Lifecycle transitions are not listed here: the stage path draws them, and naming one refuses `unknown_ui_action` with that pointer, as does any name that is not an action of the object. The bar itself is always there (it carries delete), and every action stays invocable through the record's `commands` for a custom component, whether or not it has a button.

### Related lists

`related_lists` is an array, drawn on the record page in its order: `[{"relationship": "<traversal>", "columns": [...]}]`. Each entry names one of the object's traversals once (`duplicate_related_list`) and the columns its list shows, such as `{"path": "target.body"}`. `"keep_generated": true` matters only beside a section that binds the traversal (next paragraph).

A layout component section that binds a traversal as its `relationship` draws that traversal itself, such as `basel.inline_collection@1` showing a contact's emails with the primary marked. The record page then leaves out the traversal's generated related list, so it is not drawn twice. The section's rows show the traversal's related-list columns: the default set, or `related_lists.<traversal>.columns`, so that entry configures the section and the list stays out. To draw the list beside the section as well, add `"keep_generated": true` to the entry. Its Add is the same dialog a related list has, so a member is created through its object's own form, every required field included; the inline collection's `config.value` and `config.label` are accepted and change nothing drawn.

**Records that point here through a `ref`.** `related_lists` follows relationships only. To list the records whose `ref` field names this one, such as the issues whose `milestone` is this milestone, bind a query in the view's `queries` that takes the record (`{"context": "record.id"}`) and draw it in a layout section with `basel.data_table@1`. The query's `where` chooses the rows (only the open ones here), its `order_by` their order, and its `page.default_size` how many show; the table shows the total and opens each row. It reads with the viewer's permissions, like any list. There is no data to move and no relationship to add:

```json basel-repository
# file: basel.json
{"format": 2, "name": "planning"}
# file: objects/milestone.json
{"name": "Milestone", "fields": {"title": {"type": "text"}}}
# file: objects/issue.json
{
  "name": "Issue",
  "fields": {
    "title": {"type": "text"},
    "status": {"type": "enum", "values": ["todo", "active", "done"]},
    "milestone": {"type": "ref", "to": "Milestone", "nullable": true}
  }
}
# file: queries/milestone_open_issues.json
{
  "name": "milestone_open_issues",
  "exposure": "internal",
  "from": "Issue",
  "select": ["id", "title", "status"],
  "where": "row.milestone = args.record AND row.status != 'done'",
  "params": {"record": {"type": "ref", "to": "Milestone"}},
  "order_by": [{"field": "title", "direction": "asc"}],
  "page": {"default_size": 50, "max_size": 200, "total": "exact"}
}
# file: ui/app.json
{"default_locale": "en-US"}
# file: ui/objects/milestone.json
{
  "object": "Milestone",
  "queries": {
    "open_issues": {"use": "milestone_open_issues", "arguments": {"record": {"context": "record.id"}}}
  },
  "record": {
    "sections": [
      {"label": "Details", "fields": ["title"]},
      {
        "label": "Open issues",
        "component": "basel.data_table@1",
        "bindings": {"object": "Issue", "fields": ["title", "status"], "query": "open_issues"}
      },
      {"fields": "remaining"}
    ]
  }
}
```

The table draws on the record page and in the edit form, never in create, where there is no record yet. It has no New button: an issue joins the milestone from its own form, by setting `milestone`. When the list needs one (link, unlink or create from the record), model the link as a relationship and use `related_lists`.

### Subtypes inherit key by key

A subtype's view (an object that `extends` another) takes each of `icon`, `compact`, `fields`, `related_lists`, `record`, `create`, `list`, `search` and `actions` it doesn't declare from the nearest ancestor's view that does, else the generated default. A key it declares replaces the ancestor's whole key; nothing merges inside a key.

```json basel-repository
# file: basel.json
{"format": 2, "name": "tracker"}
# file: objects/item.json
{
  "name": "Item",
  "abstract": true,
  "fields": {
    "title": {"type": "text"},
    "body": {"type": "text", "nullable": true},
    "status": {"type": "enum", "values": ["open", "done"], "default": "open"}
  }
}
# file: objects/issue.json
{
  "name": "Issue",
  "extends": "Item",
  "fields": {"severity": {"type": "enum", "values": ["low", "high"], "nullable": true}}
}
# file: objects/note.json
{"name": "Note", "extends": "Item"}
# file: ui/app.json
{"default_locale": "en-US"}
# file: ui/objects/item.json
{
  "object": "Item",
  "icon": "box",
  "compact": ["status"],
  "record": {
    "sections": [
      {"label": "Details", "fields": ["title", "status"]},
      {"fields": ["body"]},
      {"fields": "remaining"}
    ]
  }
}
# file: ui/objects/issue.json
{"object": "Issue", "icon": "target"}
# file: ui/objects/note.json
{
  "object": "Note",
  "compact": [],
  "record": {
    "sections": [{"fields": ["title", "body"]}, {"fields": "remaining"}],
    "hidden": ["status"]
  }
}
```

- Issue declares only `icon`, so it draws Item's `compact` and `record`. Its own `severity` lands in the `remaining` section; to place it, Issue declares its own whole `record`.
- **Omitted versus empty.** An omitted key inherits. A key declared empty is a declaration that means "none": Note's `"compact": []` shows no key fields, though Item has one. `"record": {"sections": [{"fields": "remaining"}]}` puts every field in "More".
- To add one section to an inherited layout, restate the whole `record`.
- `label`, `plural_label`, `description`, `record_label` and `create.chooser` are never inherited. `chooser` is legal only on an abstract root.
- An inherited `list` over a query needs a query of that name on the subtype's view, since the ancestor's query reads the ancestor.
- An app's `record_pages`, `list_pages`, `edit_pages` or `create_pages` entry for an object also serves its subtypes that have none of their own; the nearest ancestor's entry wins.

### App-scoped views

An app may ship its own view of an object it doesn't own. It applies only inside that app, and every other app keeps the owner's view. Each key it declares replaces the owner's whole key; the rest come from the owner. Here the `@acme/sales` app calls crm's Contact "Lead" and gives it its own layout (the two packages are shown already vendored, as `basel upgrade` writes them):

```json basel-repository
# file: basel.json
{
  "format": 2,
  "name": "shop",
  "dependencies": {
    "@acme/crm": {"source": "git+https://example.invalid/crm", "version": "^1"},
    "@acme/sales": {"source": "git+https://example.invalid/sales", "version": "^1"}
  }
}
# file: ui/app.json
{"default_locale": "en-US"}
# file: ui/objects/crm/contact.json
{"object": "crm:Contact", "compact": ["full_name", "phone"]}
# file: vendor/@acme/crm/basel.release.json
{"format": 2, "schema": "basel.release/1", "package": "@acme/crm", "version": "1.0.0", "namespace": "crm"}
# file: vendor/@acme/crm/objects/contact.json
{
  "name": "Contact",
  "fields": {
    "full_name": {"type": "text"},
    "email": {"type": "text", "nullable": true},
    "phone": {"type": "text", "nullable": true},
    "title": {"type": "text", "nullable": true}
  }
}
# file: vendor/@acme/crm/objects/sales_contact.json
{"name": "SalesContact", "extends": "Contact", "fields": {"quota": {"type": "int", "nullable": true}}}
# file: vendor/@acme/crm/ui/objects/contact.json
{
  "object": "Contact",
  "label": "Person",
  "icon": "person",
  "record": {
    "sections": [{"label": "Who", "fields": ["full_name", "email"]}, {"fields": "remaining"}]
  }
}
# file: vendor/@acme/crm/ui/objects/sales_contact.json
{"object": "SalesContact", "icon": "target"}
# file: vendor/@acme/sales/basel.release.json
{
  "format": 2,
  "schema": "basel.release/1",
  "package": "@acme/sales",
  "version": "1.0.0",
  "namespace": "sales",
  "title": "Sales",
  "dependencies": {"@acme/crm": {"version": "^1"}}
}
# file: vendor/@acme/sales/ui/app.json
{"default_locale": "en-US"}
# file: vendor/@acme/sales/ui/objects/crm/contact.json
{
  "object": "crm:Contact",
  "label": "Lead",
  "plural_label": "Leads",
  "record": {
    "sections": [
      {"label": "Pipeline", "fields": ["full_name", "title", "phone"]},
      {"label": "History", "component": "basel.activity@1", "bindings": {"query": "generated.activity"}},
      {"fields": "remaining"}
    ],
    "hidden": ["email"]
  }
}
```

- Inside Sales, Contact is "Lead", draws the Pipeline and History sections, and keeps crm's `icon`. Every other app shows crm's "Person" view.
- An app-scoped view may also set `label`, `plural_label`, `description`, `record_label`, `route`, `relationships`, `queries` and `initializers`. These stay with the object: an app's view of a parent doesn't pass them to subtypes.
- Only an app (a package with `ui/app.json`) may ship one, and only for an object it shows: its own, or one of a package it lists directly (`object_view_not_shown` otherwise). A package that is not an app refuses `object_view_not_owned`.
- **Exporting it.** An app exports the view by its path in the `package` block of its `basel.json`: `{"path": "ui/objects/crm/contact.json"}`; its name is the object's full name, as its `object` writes it. `basel upgrade` vendors it at `vendor/<package>/ui/objects/crm/contact.json`. A view of the package's own object keeps the plain name (`Contact`). `basel build` refuses a full name in a package that exports no `ui/app.json`.
- **The tenant rule.** The tenant's views of its own objects apply in every app. The tenant's file for a package's object, `ui/objects/crm/contact.json` above, is an app-scoped view for the tenant's own app: it applies there only, whether or not the package ships a view, and never changes what an installed app shows.

### Which declaration wins

For a record of kind K opened in app A:

1. **The page:** A's `record_pages` entry for K, else for K's nearest ancestor with one, else A's `defaults.record_page` template, else Basel's generated page (see Page templates).
2. **Each view key,** resolved on its own, first declaration wins: A's view of K → K's owner's view of K → A's view of K's parent → the parent's owner's view → … up to the root → generated.
3. **Edit** uses the resolved `record` layout, drawn in the record page's template when an app template drew it, or A's `edit_pages` entry when there is one. **Create** uses the resolved `create`, else the layout's settable fields, plus necessary inputs.
4. **Lists** follow the same chain through `list_pages` and resolve `list` the same way.

So in the example above, a SalesContact opened in Sales gets SalesContact's own `icon` (crm's view of SalesContact) and Sales' `record` for Contact, since neither Sales nor crm declares a layout for SalesContact itself. There is never a choice between peer layouts.

### Why does this page look like this?

`GET /tenants/{key}/reflect/ui/objects/{object}?app={namespace}` explains it. `view_keys` names, for each inheritable key, the declaration that supplied it, under the compiler's internal key names (`layout` for `record`). For Issue in the tracker example:

```json
"view_keys": {
  "icon":   {"source": "declared", "object": "Issue", "declared_by": "owner",
             "file": "ui/objects/issue.yaml", "package": null, "inherited_from": null},
  "layout": {"source": "declared", "object": "Item", "declared_by": "owner",
             "file": "ui/objects/item.yaml", "package": null, "inherited_from": "Item"},
  "list":   {"source": "generated"}
}
```

- `object` and `inherited_from` say which object's view supplied the key; `inherited_from` is set when that is an ancestor.
- `declared_by` is `app` when the app's own view supplied it, `owner` otherwise; `file` and `package` say where to edit it. `file` is the `.json` file to edit.
- `app_view` is the app's own view of the object (`file`, `package`, `provenance`), or `null`.
- `kind` gives `abstract`, `extends`, `ancestors` and `concrete`; `pages` gives the `record`, `list` and `edit` page and where each came from.
- `layout` lists the drawn `sections` (with node ids `section.details`, `section.2`, … and `section.more`) and `hidden`; `create` gives its `source`, `follows` (`layout` or `fields` when undeclared) and `necessary_inputs`; `list` gives its `source`.

To debug: find the key that looks wrong in `view_keys`, open the file it names, and edit that declaration or declare the key on a view earlier in the chain.

### Custom screens are app pages

An object view has no `surfaces`: a view is shared by every app in the tenant, so it holds no app's screens. `surfaces` is refused `surfaces_removed`. What each former use becomes:

| Former `surfaces` use | Use instead |
|---|---|
| a custom screen | a page in the app, placed with `record_pages`, `list_pages`, `edit_pages` or `create_pages`, or a template (see "Page templates") |
| a configured list (columns, query) | `list` |
| hiding a field on each surface | `record.hidden`, once, for view, create and edit |
| reordering | section order |
| a different arrangement of the record page | `record` sections, or a page template |
| different header contents | `compact` key fields; the theme draws the header; a template places it |
| replacing a field with a widget | `fields.<f>.widget` (or `view`/`edit`) |
| adding a component (activity feed, chart, picker in a form) | a component section |

`basel convert` rewrites the uses that have an exact replacement (a widget swap, a hidden field, a configured list) and refuses the rest, naming the file, with what to use instead.
## Page templates

A page template is a page written once for whichever object is open. It says *where* things go: a header on top, the sections on the left, the activity feed on the right. Each object's view still says *what* goes there: its sections, key fields, stage path and related lists. One template can draw every record page in an app, and an object or field added later appears in it without editing a page.

A template is an ordinary page file, `ui/pages/<id>.json`, with one more key, `template`, and `{"part": "<name>"}` children where the object's content goes. `template` says what it draws: `record` (the record page), `list`, `create` or `edit`. The app chooses templates in `ui/app.json`: `defaults.record_page`, `defaults.list_page`, `defaults.create_form` and `defaults.edit_form` for every object, or a `record_pages`, `list_pages`, `edit_pages` or `create_pages` entry for one object and its subtypes.

### A worked example

Deal and Customer share one frame. It validates as written:

```json basel-repository
# file: basel.json
{"format": 2, "name": "sales", "title": "Sales"}
# file: objects/customer.json
{
  "name": "Customer",
  "fields": {"name": {"type": "text"}, "city": {"type": "text", "nullable": true}}
}
# file: objects/deal.json
{
  "name": "Deal",
  "fields": {"name": {"type": "text"}, "amount": {"type": "int", "nullable": true}},
  "lifecycles": {
    "stage": {
      "initial": "open",
      "states": [
        {"name": "open"},
        {"name": "won", "outcome": "success"},
        {"name": "lost", "outcome": "failure"}
      ]
    }
  },
  "actions": {
    "win": {"transition": {"lifecycle": "stage", "from": ["open"], "to": "won"}},
    "lose": {"transition": {"lifecycle": "stage", "from": ["open"], "to": "lost"}}
  }
}
# file: relationships/customer_deals.json
{
  "name": "CustomerDeals",
  "from": {"object": "Customer", "name": "deals"},
  "to": {
    "object": "Deal",
    "name": "customer",
    "cardinality": {"max": 1},
    "nested": {"create": ["link"], "update": ["link", "unlink"]}
  }
}
# file: ui/app.json
{"default_locale": "en-US", "defaults": {"record_page": "record"}}
# file: ui/pages/record.json
{
  "page": "record",
  "template": "record",
  "root": {
    "id": "sales_record",
    "component": "basel.page@1",
    "slots": {
      "header": [{"part": "header"}],
      "main": [
        {
          "id": "sales_main",
          "component": "basel.stack@1",
          "slots": {
            "children": [
              {"part": "actions"},
              {"part": "lifecycle"},
              {
                "id": "sales_columns",
                "component": "basel.split@1",
                "slots": {
                  "primary": [
                    {
                      "id": "sales_left",
                      "component": "basel.stack@1",
                      "config": {"gap": "small"},
                      "slots": {
                        "children": [{"part": "sections"}, {"part": "related_lists"}]
                      }
                    }
                  ],
                  "secondary": [{"part": "activity"}]
                }
              }
            ]
          }
        }
      ]
    }
  }
}
# file: ui/objects/deal.json
{
  "object": "Deal",
  "record": {
    "sections": [
      {"label": "Deal", "fields": ["name", "customer", "amount"]},
      {"fields": "remaining"}
    ]
  }
}
```

A Deal opens with its header, the Win and Lose actions, its stage path, its Deal section on the left and its activity on the right. A Customer opens in the same frame with its own fields and its Deals list on the left. Customer has no lifecycle, so its page has no stage path.

### Lists and forms

A list template places `title` and `records`. This one puts a line of text under each list's title, and a create template puts a note beside every create form. Both Deal and Customer use them:

```json basel-repository
# file: basel.json
{"format": 2, "name": "sales", "title": "Sales"}
# file: objects/customer.json
{
  "name": "Customer",
  "fields": {"name": {"type": "text"}, "city": {"type": "text", "nullable": true}}
}
# file: objects/deal.json
{
  "name": "Deal",
  "fields": {"name": {"type": "text"}, "amount": {"type": "int", "nullable": true}}
}
# file: ui/app.json
{"default_locale": "en-US", "defaults": {"list_page": "list", "create_form": "create"}}
# file: ui/pages/list.json
{
  "page": "list",
  "template": "list",
  "root": {
    "id": "sales_list",
    "component": "basel.page@1",
    "slots": {
      "main": [
        {
          "id": "sales_band",
          "component": "basel.stack@1",
          "slots": {
            "children": [
              {"part": "title"},
              {
                "id": "sales_tagline",
                "component": "basel.markdown@1",
                "config": {"text": "Shared with the whole sales team."}
              }
            ]
          }
        },
        {"part": "records"}
      ]
    }
  }
}
# file: ui/pages/create.json
{
  "page": "create",
  "template": "create",
  "root": {
    "id": "sales_create",
    "component": "basel.page@1",
    "slots": {
      "main": [
        {
          "id": "sales_create_columns",
          "component": "basel.split@1",
          "slots": {
            "primary": [
              {
                "id": "sales_create_form",
                "component": "basel.stack@1",
                "slots": {"children": [{"part": "sections"}]}
              }
            ],
            "secondary": [
              {
                "id": "sales_create_note",
                "component": "basel.markdown@1",
                "config": {"text": "Fields marked required must be filled in to save."}
              }
            ]
          }
        }
      ]
    }
  }
}
# file: ui/objects/deal.json
{"object": "Deal", "list": {"columns": ["name", "amount"]}}
```

The Deals list shows "Deals", the line of text, and its `name` and `amount` columns with the filter bar and paging. The Customers list has the same frame with Customer's columns. In a form, `sections` draws two nodes (the validation summary and the form), so a split side, which holds one, wraps it in a stack.

### Parts

| Part | Draws | On |
|---|---|---|
| `header` | the record's title, symbol and key fields (`compact`) | record page, edit form |
| `actions` | the action bar: the actions the object view lists (none by default) and delete | record page |
| `lifecycle` | one stage path per lifecycle | record page |
| `sections` | the view's `record` sections, ending with "More"; in a form, the same sections editable, with save and cancel | record page, edit form |
| `related_lists` | one related list per to-many relationship, drawn with `defaults.related_list` | record page |
| `activity` | the record's activity feed | record page |
| `title` | the object's plural name, as a heading | list |
| `records` | the records, drawn with `defaults.object_list` and the view's `list` columns, with the filter bar and paging | list |

A record, edit or create template places the first six; a list template places only `title` and `records`. In a create form, `sections` is the view's `create` form with every required field. A part takes no other keys and may appear once per template. A part with nothing to draw draws nothing: an object without a lifecycle has no stage path, and related lists aren't drawn in an edit form. A page that draws the stage path doesn't repeat the lifecycle among the fields its layout leaves to `remaining`; name it in a section to show it there too.

### Where parts go

A part goes in a region: a slot of one of the structural components, which draws whatever the part expands to. These containers and slots hold parts:

| Container | Slots that hold parts |
|---|---|
| `basel.page@1` | `header`, `main`, `sidebar` (`header` and `sidebar` hold one node each: `header` is for the `header` or `title` part, and a part that draws several nodes goes in a `basel.stack@1` in `sidebar`) |
| `basel.split@1` | `primary`, `secondary` (one node each; wrap several in a `basel.stack@1`) |
| `basel.stack@1` | `children` |
| `basel.tab@1` | `body`, so each tab of a `basel.tabs@1` is a region |

Containers nest: a stack in a split side, a split in a tab. Details in one tab and related lists in another is a `basel.tabs@1` holding two `basel.tab@1`, with `{"part": "sections"}` in the first tab's `body` and `{"part": "related_lists"}` in the second's. A part anywhere else, such as a `basel.section@1` or `basel.card@1` body, another component's slot, or straight in `basel.tabs@1`'s `tabs` without a `basel.tab@1` around it, is refused `part_outside_region`, naming the container and slot. This holds for a hand-built page that places parts as well as for a template. A deployed app that already has such a part keeps running as it is; the refusal comes at its next `basel plan` or deploy.

### Empty containers are dropped

After the parts are drawn, a container left with nothing in it is dropped: a `basel.stack@1` with no children, a `basel.tab@1` whose body is empty, a `basel.tabs@1` with no tabs. A `basel.split@1` with one empty side is replaced by its other side, which then takes the full width. So an object with no relationships gets no empty "Related" tab, and one template serves both the record page and the edit form.

If an object's `record` layout places the activity feed itself, as a `basel.activity@1` component section, the `activity` part draws nothing for that object. In the example, a Deal layout with a History section holding `basel.activity@1` would drop the right-hand column, and Deal's sections would take the whole width.

### Which template draws a record

For a record of kind K, the first of:

1. the app's `record_pages` entry for K, else for K's nearest ancestor with one. It may name a template or a hand-built page;
2. `defaults.record_page`;
3. Basel's own record page.

Several `record_pages` entries may name the same template. Lists follow the same order with `list_pages` and `defaults.list_page`, and several `list_pages` entries may name the same list template.

The edit form is the app's `edit_pages` entry for K (or K's nearest ancestor with one), a hand-built page or a `record` or `edit` template; else `defaults.edit_form`, a `record` or `edit` template. Without either, the edit form follows the chosen record template, drawn in edit mode: the header stays, the sections become a form, and what an edit form doesn't draw is dropped. A record page from a hand-built page then keeps Basel's own edit form. The create form is the app's `create_pages` entry for K, a hand-built page or a `create` template; else `defaults.create_form`, a `create` template; else Basel's own. An abstract object's kind chooser stays its create form.

When the edit form follows the record template, a slot that held only parts an edit form doesn't draw (`actions`, `lifecycle`, `related_lists`, `activity`) is left empty. If it isn't one of the containers dropped when empty, such as the page's `main`, each object's edit form is refused `invalid_slot` ("slot holds 0 children"), and the message names the fix: give the edit form its own template with `defaults.edit_form`, or put those parts in a stack, a tab or a split side.

Basel's own record, edit, create and list pages are themselves templates of these parts, so a template that places the parts in Basel's order draws the same page.

### What a template can't do

A template is written for no object in particular, so it can't name one. It is refused when it declares:

- `queries`, or `parameters` on a node (`template_query`);
- a binding to an object, field, relationship, lifecycle, action or query (`template_names_object`); bind `"record": "current"` or place a part instead;
- a `{"generated": …}` splice (`template_generated_splice`);
- `visible_when` or `enabled_when` on a node (`template_condition`);
- no `{"part": "sections"}` in a record, edit or create template (`template_missing_sections`), so a template can never hide every field;
- a part twice (`template_part_twice`) or an unknown part (`unknown_part`);
- a part outside a region (`part_outside_region`; "Where parts go" above).

`template` is `record`, `edit`, `create` or `list`. `defaults.record_page` and `record_pages` take a `record` template, `defaults.list_page` and `list_pages` a `list` template, `defaults.create_form` and `create_pages` a `create` template, and `defaults.edit_form` and `edit_pages` a `record` or `edit` template (`template_kind_mismatch` otherwise, and for a hand-built page under a `defaults` key). A refusal that only one object triggers, such as two stage paths in a split side that holds one, is reported at the template's element with "for `Deal` (view):" in front.

For content that only one object has, such as a chart or a metric strip, use a component section in that object's view. For a page that is different past what a template can say, map a hand-built page through `record_pages`; it may still place `{"part": "sections"}` so it keeps up with new fields. A form that is different for one object is a hand-built page under `edit_pages` or `create_pages`, drawn in that mode: it may bind `"record": "current"`, place `{"part": "sections"}` (the form, with save and cancel) or `{"generated": "record.validation"}`, and use field and picker components.

### Seeing which template drew a page

`GET /tenants/{key}/reflect/ui/objects/{object}` reports it under `pages`:

```json
"pages": {
  "record": {"source": "template", "page": "record", "file": "ui/pages/record.yaml",
             "chosen_by": "defaults.record_page", "object": "Deal", "inherited_from": null,
             "explain": "page: Sales' record template"},
  "list":   {"source": "generated"},
  "edit":   {"source": "template", "page": "record", "file": "ui/pages/record.yaml",
             "chosen_by": "defaults.record_page", "object": "Deal", "inherited_from": null,
             "explain": "page: Sales' record template"},
  "create": {"source": "generated"}
}
```

`pages` also has `create`. `chosen_by` is the key that chose the template: `record_pages`, `list_pages`, `edit_pages`, `create_pages`, `defaults.record_page`, `defaults.list_page`, `defaults.create_form` or `defaults.edit_form`. An edit form that follows the record template reports the record template's key. A hand-built page is `"source": "page"`, and Basel's own is `"source": "generated"`.
## Relationships

A `relationships/<snake>.json` file declares one named, typed, multi-instance link between two objects. A link may carry its own properties. `unique` defaults to `false`; `true` adds a database-enforced unique `(from, to)`:

```json basel-fragment
{
  "name": "Employment",
  "from": {"object": "Person", "name": "employments"},
  "to": {"object": "Company", "name": "staff"},
  "unique": false,
  "properties": {
    "role": {"type": "text"},
    "start": {"type": "Date"},
    "end": {"type": "Date", "nullable": true}
  }
}
```

### Declaring a relationship

**`from`/`to`** name the endpoint objects and each side's traversal name. A traversal name is the identifier that side's own namespace reserves for reaching the other endpoint (`person->employments`, `company->staff` — notation only). A traversal name that collides with a field, or with another relationship's traversal on the same endpoint object, is a resolution error, just like any other name collision.

**`properties`** reuses the stored-field vocabulary of an object's `fields` (`type`, `nullable` and the type's keys); a property has no `formula` or `rollup`.

The only declared shape is many-to-many, multi-instance: the same pair of endpoint rows may be joined by any number of links. The exception is when **`unique`** is declared `true`. That compiles to a database-enforced `unique(from_id, to_id)`, the only race-proof form of "at most one link between this pair". Any violation surfaces as `422 unique_violation`. `unique` defaults to `false`.

`ref` remains the sugar construct for the anonymous, property-less many-to-one. You only need to declare a relationship when a link needs its own identity, properties, multiplicity, or `unique` enforcement.

### Links as rows

**Endpoints are immutable.** A `PATCH` on a link may change its own properties only. A body naming `from` or `to` is refused. Re-pointing a link at a different endpoint makes it a different link, so the only path is delete-and-recreate. This keeps the link's identity and history honest.

**Deleting an endpoint row while links reference it is refused by default, not cascaded (`RESTRICT`)**, unless that end declares `on_delete` otherwise (see "`on_delete` and `reparent`" below). With no `on_delete` declared, an object never silently loses a link as a side effect of deleting the row it points at. Delete the links first.

**One exception: an owned member takes its own link with it.** When a row's own end declares `"cardinality": {"min": 1, "max": 1}`, the row holds exactly one link there for its whole life, so deleting the row (directly, by raw proposal or by action) also unlinks that one link, in the same write. Its other references still refuse. A `primary` pointer naming the row refuses `422 delete_blocked_by_reference` at `<Parent>.<field>_ref`, nested or direct; move the star first, or in the same write. A caller needs `delete` on the row, `delete` on the relationship and `relationship.<from end>.unlink` on the `from` object, as for an explicit unlink and delete, and no tenant action. In a role's `grants`, `manage` on the row and the relationship plus the `relationship.<end>.unlink` token cover it. An end with `max: 1` alone, or `min: 1` alone, keeps `RESTRICT`.

**Links are rows, addressable through the exact same surfaces an object's own rows are.** `POST`/`GET`/`PATCH`/`DELETE /tenants/{key}/objects/{Name}[/{id}]` and `FROM {Name}` in BQL both work identically for a relationship name. `from`/`to` behave as required, immutable `ref`-typed fields.

Links carry `TypeID`s under the exact same discipline as any object row (see "Ids: TypeID on the wire" above). The prefix is the relationship's own snake-cased table name (`employment_01k…`).

### Reflection

`GET /tenants/{key}/reflect/relationships` and `.../relationships/{Name}` are implemented reflect scopes (see "Using /reflect" below), never a `501` stub. They reflect every declared relationship's endpoints, traversal names, `unique` flag, and properties, in the same full vocabulary `/reflect/objects/{Object}` uses. Relationships are reflected explicitly, never left to be inferred by scanning for a `ref`.

### `cardinality`

Either end may declare `"cardinality": {"max": 1, "min": 1}`.

- **`max: 1`**: each row on that end participates in **at most** one link. This makes the traversal to-one. Aggregates and nested create/update's `422 cardinality_exceeded` both consume this fact.
- **`min: 1`**: each row on that end participates in **at least** one link. This is required participation, with no authority attached. It implies nothing about `on_delete`/`reparent`/`document_lock`. Its one lifecycle effect: with `max: 1` on the same end, deleting the row also removes its one link (see "Links as rows").

`max: 1` also makes the traversal a **readable dotted path hop** from the declaring end's own object. This works in queries, guards, invariants, locks and formulas alike, rendered as a join through the junction. A to-many end, or a second traversal hop in one path, refuses `bql_compile_error`.

`max` is optional and, when declared, only `1` is legal in v1. `min` defaults to `0` (no requirement), and only `0`/`1` are legal.

**`min` and `max` are independent, in both directions.** `min: 1` is legal on a member end alongside `max: 1`, e.g. `InvoiceLine.invoice` for "every line belongs to an invoice". It is equally legal alone on a to-many parent end, e.g. `BudgetaryPosition.accounts` for "every position holds at least one account". The same two refusals (`participation_required`, `participation_apply_failed`) apply at whichever end declares it.

#### How `min: 1` is checked

`min: 1` is checked in commit phase 2, right after invariants, against the record after the write. It covers every row of the `min: 1` end's object that a proposal created, or whose link in that relationship the proposal unlinked or re-pointed.

- A parent, its child, and the link between them may be created in one proposal.
- A `create` of a child with no link refuses.
- An orphaning `unlink` refuses.

The refusal is `422 participation_required`. It names the end (`<relationship>.<end>`) and the offending row's `TypeID`.

A row this same proposal **deleted** is exempt, because a deleted row has no final state to check. So a nested `delete` (unlink then delete the member in one proposal) never orphan-refuses.

Declaring `min: 1` over **existing** rows that already have no link refuses at plan and apply too, with `422 participation_apply_failed`. It names a violation count and a bounded `TypeID` sample. This is the identical admission rule an invariant follows, reused rather than reinvented.

`max: 1` has no scan of its own. It compiles to a database `UNIQUE(<end column>)`, so a violation surfaces as a constraint failure at apply, never through this scan.

Reflection (`/reflect/relationships/{Name}`) always renders both `min` and `max` together when `cardinality` is declared at all, never one without the other.

### `on_delete` and `reparent`

`on_delete` and `reparent` are lifecycle rules, orthogonal to `cardinality`/`nested`. Declaring one implies nothing about another, and resolution refuses a placement that would make the key meaningless.

#### `on_delete`

`on_delete` is declared on a parent end: the one whose *opposite* end declares `"cardinality": {"max": 1}`. It says what happens to the parent's members when a parent row is deleted:

- `restrict`: the default, the `RESTRICT` behavior described above. It needs no declaration.
- `delete_members`: expand the delete into an `unlink` then a `delete` per current member link, ahead of the parent's own delete, all in one proposal and one audit event. A member delete runs that member's own guards, validators, and permits, exactly as an authored delete would.
- `detach`: unlink every member link and keep the members. This is refused at resolution when the opposite end also declares `min: 1`, since detaching would then structurally orphan it.

`delete_members`'s expansion is capped by the same 128-operation proposal budget every other proposal has. A delete whose expansion would exceed it refuses `422 delete_members_over_cap`, naming the member count and the cap, and nothing is written.

A member may also hold a *required* (`min: 1`) link in some OTHER relationship the expansion does not touch. Then the delete refuses `422 delete_blocked_by_participation`, rather than orphaning that requirement or cascading further. A member still referenced through any other plain relationship hits that relationship's own `RESTRICT`, exactly as any other delete would.

#### `reparent`

`reparent` is declared on a member end: one whose *own* cardinality declares `{"max": 1}`. It says whether a row on that end may move from one parent to another:

- `allow`: the default. Nothing has ever refused this.
- `refuse`: a proposal whose record after the write moves an existing member refuses `422 reparent_refused`, naming the member and both parents.

A move is an `unlink` of the member's current link together with a `link` to a different parent, in the same proposal, through any endpoint: a nested `unlink` + `link`, a raw `unlink` + `link` op in a raw client proposal, or an action body. Creating a member with its first parent, and deleting a member outright, are not reparenting and never refuse here.

Reflection (`/reflect/relationships/{Name}`) always renders both `on_delete` and `reparent` on every end, with their defaults, whether declared or not. This is the same "reflection is total" discipline `cardinality`'s always-rendered `min` follows.

### `document_lock`

`document_lock` is an object, `{editable_when, editable_fields?, message?}`, declared on the parent end. It is a business restriction, independent of actor permission. It follows the same placement rule `on_delete`'s non-`restrict` values use: the opposite end must declare `"cardinality": {"max": 1}`.

- `editable_when` is a predicate over the parent. `row.` is the parent record (`row.status = 'draft'`, never `row.invoice.status`), and `before.` its state before the write. The member check reads the parent record *after* the whole write applies; the check on the parent's own fields reads it before (below).
- `editable_fields` lists parent fields that stay editable after the lock closes (below). Leave it out to freeze them all.
- `message` is the refusal message.

```json basel-repository
# file: basel.json
{"format": 2, "name": "invoicing"}
# file: objects/invoice.json
{
  "name": "Invoice",
  "operations": ["create", "update"],
  "fields": {"number": {"type": "text"}, "posted_on": {"type": "Date", "nullable": true}},
  "lifecycles": {
    "status": {"initial": "draft", "states": [{"name": "draft"}, {"name": "posted"}]}
  },
  "actions": {
    "post": {
      "transition": {"lifecycle": "status", "from": ["draft"], "to": "posted"},
      "effects": [{"op": "set", "values": {"posted_on": {"expr": "TODAY()"}}}]
    }
  }
}
# file: objects/invoice_line.json
{
  "name": "InvoiceLine",
  "operations": ["create", "update", "delete"],
  "fields": {"description": {"type": "text"}}
}
# file: relationships/invoice_lines.json
{
  "name": "InvoiceLines",
  "from": {
    "object": "Invoice",
    "name": "lines",
    "nested": {"create": ["create"], "update": ["create", "update", "delete"]},
    "document_lock": {
      "editable_when": "row.status = 'draft'",
      "message": "Lines may not change once the invoice is posted."
    }
  },
  "to": {"object": "InvoiceLine", "name": "invoice", "cardinality": {"max": 1}}
}
```

#### What a document lock freezes: the members and the parent

While `editable_when` is false on the parent record after the write, none of these commit:

- a member `create`/`update`/`delete`;
- a `link`/`unlink` of this relationship;
- a change to **the parent's own fields**.

The last point surprises people. A document lock freezes the parent too, not only its members. A write that changes any of the parent's own stored fields commits only if `editable_when` held on the parent *before* the write. So the transition that leaves the editable state may still set fields (posting a draft invoice can stamp `posted_on`), but after that:

- a lifecycle transition whose effects set a parent field (an `archive` that stamps `archived_on`, a `reopen` that clears a field) is refused `422 guard_failed`;
- an ordinary `PATCH` of the parent's fields is refused the same way;
- deleting the parent is refused.

A transition that only moves the lifecycle state, and sets no field, still passes. A no-op parent update (nothing actually changes) and re-saving an unchanged document also pass. This is the same null-safe no-op exemption `locks` relies on (see "Guards" below). Editing a member and posting the parent in the *same* proposal refuses too, because the member check reads the record after the write (the posted one).

So a document lock fits a parent that is finished once it leaves the editable state, such as a posted invoice. When the parent must keep changing after its members freeze, use a guard on the member instead (next heading).

#### Keeping a few parent fields editable: `editable_fields`

When the parent is finished except for one or two annotation fields, list them in `editable_fields`. Those fields may still change after the lock closes; the members, the links, every other parent field and deleting the parent stay frozen. A field added to the parent later is frozen unless you list it.

```json
"document_lock": {
  "editable_when": "row.status = 'draft'",
  "editable_fields": ["notes"],
  "message": "Lines may not change once the order is activated."
}
```

- Each entry names a stored field of the parent object: its own or one it inherits. A rollup, a formula, a lifecycle or a field only a subtype declares is refused `invalid_relationship` at `…/document_lock/editable_fields/<i>`. Lifecycle state is never frozen by the lock anyway, and a subtype's own fields are never compared.
- A write that changes a listed field *and* an unlisted one is refused as a whole.
- **Several locks on one parent.** Each `document_lock` on the same parent adds its own `edits_<relationship>` guard, and every guard must pass. So a field stays editable only if every lock lists it.
- Reflection shows the list as `edits.editable_fields` on `/reflect/relationships/{Name}` (`[]` when none), and the update guard's condition leaves the listed fields out of its comparison.

#### Two refusals

There are two refusals, not one.

- **Members and links.** This half is a phase-2 check, right after `reparent`'s own. A member `create`/`update`/`delete`, or a `link`/`unlink` of this relationship, refuses `422 edit_locked` at the offending operation's own authored position. The detail is the end's `message`, or a default naming the relationship and the parent.
- **The parent's own `update`/`delete`.** This is governed by an ordinary synthesized guard instead, named `edits_<relationship>` (`origin: {kind: "edits", relationship, end}` in `/reflect/objects/{Object}`'s `guards`). It refuses the usual `422 guard_failed` at `<Parent>.edits_<relationship>`, with the same message.

#### Member edits only while the parent is open: a guard on the member

To let members change only while the parent is in some state, **without** freezing the parent's own fields, put a guard on the member that reads the parent. A `max: 1` end is a readable path hop, so the member reaches its parent through the relationship; no `ref` field is needed. Here `TimeEntry` is a member of `Matter` through a `max: 1` end named `matter` (the whole repository is under "Worked metadata examples"):

```json basel-fragment
{
  "name": "TimeEntry",
  "fields": {"minutes": {"type": "int"}},
  "guards": [
    {
      "name": "matter_open",
      "on": ["create", "update", "delete"],
      "assert": "row.matter.status = 'open'",
      "message": "Time entries change only while the matter is open."
    }
  ]
}
```

The parent (`Matter` here) keeps its whole lifecycle and every field editable. The guard reads the **record after the write**: the parent this proposal links or re-links the member to, not the one the junction still holds. This is exactly how a `ref` hop reads the applied column rather than the stored one.

A member guard sees the member's own `create`/`update`/`delete`, whether sent directly or nested in the parent's write. It does not see a `link`/`unlink` of an existing member. If that matters, add a guard on the relationship itself, which binds `row.` to the link: `"assert": "row.from.status = 'open'"`, `"on": ["create", "delete"]`.

Choose between the two like this:

| You want | Declare |
|---|---|
| Members and links frozen, and the parent's fields frozen too, once the parent leaves a state | `document_lock` on the parent end |
| The same, but one or two parent fields (notes) stay editable | `document_lock` with `editable_fields` listing them |
| Members frozen while the parent keeps changing | a guard on the member reading the parent (`row.matter.status = 'open'`), plus a relationship guard if links must freeze too |

### `revision`

`"revision": true` makes the parent's `ETag` the document version. It follows the same placement rule as `document_lock` and `on_delete`'s non-`restrict` values: the opposite end must declare `"cardinality": {"max": 1}`. There is no new column and no new header.

Every committed change to this end's members' fields, or to the relationship's own membership, also stamps this end's own row's existing `__basel_event_id` with the transaction's event id. A membership change is a member `create`/`delete`, or a `link`/`unlink` of this relationship. The stamp happens once per parent per proposal, after the write and any rollup recompute. So a change that also moves a rollup (e.g. `total`) never double-stamps: both write the identical event id.

A description-only line edit that touches no rollup still advances the invoice's own version. So does a total-neutral line deletion, which a derived "max over document rows" version would miss.

`If-Match` on the parent already covers this: a `PATCH`, an action invocation, or `submit_proposal` naming the parent as root. An approver holding a stale parent version is refused `412 stale_record` by a child edit, exactly as by a change to the parent's own fields. There is no refusal code and no wire surface of its own.

`revision` is `false` when undeclared. No relationship stamps a parent's row version by default, and a relationship that does not declare `revision` behaves exactly as it always did.

### `shape`

`shape` is reflected, never authored. It is `document`, `association`, or `plain`, derived purely from the ends above:

- `document`: a `max: 1` member end whose parent declares `delete_members`, `document_lock`, or `revision`.
- `association`: neither end requires participation and neither declares any lifecycle key.
- `plain`: everything else.

## Nested create and update

A declared relationship's traversal name (see "Relationships" above) is a legal field in the generic `POST`/`PATCH /tenants/{key}/objects/{Object}[/{id}]` body. There are no new endpoints: these are the same two endpoints already documented under "Endpoints".

What a field may do through that traversal is declared **per end**, in the end's `nested` object, and defaults to nothing. Here a registration may link its event while being created; the event end declares nothing, so an event's own writes cannot reach registrations:

```json basel-fragment
{
  "name": "RegistrationEvent",
  "from": {"object": "Registration", "name": "event", "nested": {"create": ["link"]}},
  "to": {"object": "TicketEvent", "name": "registrations"}
}
```

### Vocabulary

- `link` (attach an existing record), `create` (create a related record inline), and `unlink` (detach on update) are legal in `nested.create` and `nested.update`, on either end independently.
- `update` (edit an existing member through the parent) and `delete` (remove an existing member through the parent) are legal **only in `nested.update`**. A create has no existing members, so either in `nested.create` is refused `invalid_relationship`.

Nothing is permitted unless listed: an undeclared relationship permits no nested writes.

A nested verb is also an operation on the link, and a caller needs the relationship's witness for it beside the parent's `relationship.<traversal>.link`/`.unlink` token: `link` and `create` are the link's `create`, `unlink` and `delete` its `delete` (see "Policy"). A role can be granted that witness only when the relationship's `operations` exposes the verb (`manage` and `*` expand to the exposed verbs). So a relationship that lists `unlink` in `nested.update` but leaves `delete` out of `operations` can be unlinked through only by the engine — an action's effects or a function; a role's nested `unlink` refuses `403 forbidden` naming the unexposed operation, and the push plan advises `nested_verb_not_exposed` at the declaration. To let roles unlink, add `delete` to the relationship's `operations`.

The member is written under its own object's permit too: a nested `create`, `update` or `delete` of a member whose object leaves that verb out of its `operations` refuses `403 forbidden` the same way, and the plan advises `nested_member_verb_not_exposed`.

Permissions come from the **declaring (near) end**, never the far end's declaration. The declaring end is the end whose own object is the one being written and whose traversal name is the field. So the registration end's own `nested.create` governs `Registration`'s create body, not `TicketEvent`'s.

### On create: plain values

On create there is nothing to diff against, so the field takes plain values:

- a **`TypeID` string** links an existing record (needs `link`);
- an **inline object** creates a related record (needs `create`), recursively, subject to the same rules and a depth cap;
- an **array** of either, for a to-many end;
- a link with declared properties uses `{"id": ..., "properties": {...}}` in place of the bare `TypeID`.

Omission and `null` mean "no links" and are never errors by themselves. Invariants check the final state. The update envelope (`{"link": [...]}` and its other verbs) is refused `validation_error` in a create body: to link an existing record on create, send its `TypeID`.

```json
POST /objects/BudgetaryPosition
{"name": "Salaries", "accounts": ["account_01h2...", "account_01h3..."]}
```

### On update: an explicit envelope

On update the field takes an explicit envelope. There is no implicit array-diff:

```json
PATCH /objects/BudgetaryPosition/{id}
{ "accounts": {
    "link":   ["account_01h4..."],
    "create": [{ "name": "New account", ... }],
    "update": [{ "id": "account_01h5...", "values": { "name": "Renamed" } }],
    "unlink": ["<link TypeID>", "<link TypeID>"],
    "delete": ["account_01h6..."]
} }
```

- `link` requires `link` in `nested.update`.
- `create` requires `create` in `nested.update`.
- `unlink` requires `unlink` and addresses **link `TypeID`s** (see "Ids: TypeID on the wire" above; link ids are visible in reads and reflection). It never takes the far record's id, since more than one link may join the same pair.

The older verb names `connect` and `disconnect` are refused `unknown_key`, naming their replacement.

Omitting an envelope key leaves that membership untouched. A body that isn't this object (a bare array, a bare `TypeID`, `null`) is refused `validation_error` naming the envelope, rather than guessed at.

There is no "replace all" verb: replacement is an explicit `unlink` + `link`.

#### `update` and `delete`

`update` and `delete` edit or remove a record that is already a member of the relationship. They are legal only in `nested.update`; a create has no existing members.

`update` requires `update` and addresses the member by its own **record `TypeID`**. Alongside it goes a `values` object, validated exactly as a direct `PATCH` on that record would be: the member's own guards, validators, and permits, nothing inherited from the parent. Errors in it are reported at `<field>.update[i].values.<name>`.

`delete` requires `delete` and addresses the member by a bare record `TypeID`. It expands to `unlink` (the link) then `delete` (the record) in the same proposal. The member's own `delete` guards run. If the member still participates in another relationship under `restrict`, or a `ref` field still names it (a `primary` pointer on the parent, say), the whole proposal refuses, exactly as a direct `DELETE` on it would: `422 delete_blocked_by_reference` naming the holder, `<Parent>.<field>_ref` for a pointer, judged on the write's final state and before any guard, so a guard that reads through the pointer never reports the refusal as its own. Moving the pointer to another member in the same write is legal.

Either verb naming a record that is not currently linked through *this* relationship refuses `422 not_a_member` at the record's own position (`<field>.update[i].id` / `<field>.delete[i]`). The same record named under two verbs in one envelope, in either order, refuses `422 conflicting_operations` at the second mention.

Emission order is fixed regardless of the envelope's own key order: `link`/`create` first, then `update`, then `unlink`, then `delete`. So a `delete` never races an `update` targeting the same member.

### Refusals

All refusals are reported at the authoring position: an error `element` like `accounts[1]` or `accounts.link[0]`, per "Error shape" above, never a bare top-level code.

| Refusal | When |
|---|---|
| `422 relationship_not_permitted` | A field names a relationship without the permission it needs. The detail names which of `link`/`create`/`unlink`/`update`/`delete` is missing and on which block, as the metadata spells it: `nested.create` or `nested.update`. |
| `422 validation_error` | A create body spells a relationship field as the update envelope (`{"link": [...]}` or another verb). On create the field takes plain values; the envelope is the update form. |
| `422 duplicate_link` | The same far record is named twice in one field's `link`/`create`. Cites the position it first appeared. |
| `422 conflicting_operations` | The same record is named under `update` and/or `delete` more than once. Cites the position it first appeared. |
| `422 not_a_member` | `update`/`delete` names a record that is not a member of this relationship. |
| `422 cardinality_exceeded` | A to-one declaring end (`"cardinality": {"max": 1}`) is given a second element, or a new link while the record already holds its one. Reported at the field. To replace the link, `unlink` the current link and `link` the new record in the same envelope. |

Basel expands the whole body into one proposal and validates the final state in the same transaction. See "Aggregates, rollups, and invariants" for how a required-membership invariant checks what nested create just built.

### Limits

These are v1 contract numbers:

| Limit | Value |
|---|---|
| Operations per proposal (after expansion) | 128 |
| Nested-create depth | 4 levels |
| Effect operations per action invocation (before cascade) | 32 — see "Actions" below |

Exceeding a cap refuses `422 limit_exceeded` naming the cap. This is the same budget vocabulary the BQL/expression/aggregate limits above already use.

### Reflection

Each object's own `/tenants/{key}/reflect/objects/{Object}` scope carries `create_contract`/`update_contract`. These say which of that object's relationship fields generic create/update accepts, keyed by traversal name, plus `_href` into the owning relationship's own reflection scope. A field appears only when its end's `nested` lists at least one operation for that verb, and each operation is reflected as a true/false flag.

- `create_contract` entries name three flags, `link`/`create`/`unlink`, since `update`/`delete` are structurally never legal in `nested.create`.
- `update_contract` entries name all **five**: `link`/`create`/`unlink`/`update`/`delete`.

A client discovers the nested shape the way it discovers everything else. This document explains the general mechanism; reflection documents each tenant's specifics.

### The honest boundary

Nested create/update is a bounded, explicitly permitted graph write: per-end permissions plus the depth and count limits above, nothing more.

It does not scope a write to "your own" rows; that is an authority question (see "Policy" above). It does not define an aggregate/ownership boundary. When a setup flow needs reach the permissions don't grant, the answer is a named action (see "Actions" below), not wider permissions.

## Guards

A `guards` key, declared on an object *or* a relationship, is an **array** of named, enforced write conditions (an array, because guards are evaluated in order, unlike `invariants`, which is an object keyed by name):

```json basel-fragment
{
  "name": "Widget",
  "fields": {"amount": {"type": "Money"}},
  "guards": [
    {
      "name": "positive_amount",
      "on": ["create", "update"],
      "assert": "row.amount > 0",
      "message": "Amount must be positive"
    }
  ]
}
```

### Guard fields

- **`name`** is unique per object or relationship. It is what the wire and reflection cite.
- **`on`** is a non-empty subset of `create`/`update`/`delete`. An empty array, or a token that isn't one of those three, is refused `invalid_guard`.
- **`assert`** is an expression in the grammar BQL's `WHERE` uses (see "BQL" below), with every name rooted: `row.amount > 0 AND row.stage != 'closed'` is a legal `assert`. It must hold for the write to proceed.
- **`message`**, when present, becomes the failure `detail` a refused write reports. When omitted, the engine derives one.

`assert` is compiled and bound at metadata *resolution*, never at write time. An unknown field, an illegal operator, or a binding-rule violation is a metadata refusal an agent sees while authoring, not a runtime surprise.

A relationship's guard binds `row.` to its link view (`from`, `to` and its properties), exactly like an object's own fields (see "Relationships" above). For example, `"assert": "row.role != ''"` on an `Employment` relationship's `role` property, or `"assert": "row.to.tier = 'gold'"` traversing its `to` endpoint. Both resolve the same way a `ref`-typed field does on an object.

### The clock in a guard

`NOW()` in an `assert` is the write's own transaction instant: the same value its effects, functions and audit event see. `TODAY()` is that instant's date in the tenant's declared `time_zone` (UTC when none), and `TODAY('<zone>')` its date in the named IANA zone, exactly as in BQL. So `"assert": "NOW() < row.deadline"` and `"assert": "row.due_on >= TODAY('Europe/Paris')"` both judge the clock. Declare `time_zone` in `basel.json`, or name the zone, when "today" means a business's local day. Invariants still refuse clock reads (see "Formulas").

### Binding by verb

A guard checks the material of the write it's evaluated against. The proposed row is always the complete record after the write (the stored record with the patch applied), never the partial patch. A `row.` path and a `before.` path each bind differently depending on which verb the guard is being checked for:

| Verb | `row.<field>` binds to | `before.<field>` |
|---|---|---|
| `create` | the proposed row | refused — no stored row exists yet |
| `update` | the proposed row (the record after the write) | the stored value (the record before the write) — own fields only, no further `.` traversal |
| `delete` | the stored row | refused — redundant; `row.` already is the stored row |

An action's or transition's guards follow the `update` row: they see the record after the action's own effects, so `row.<field>` is the value the action writes and `before.<field>` the value it found (see "What an action's guards see" under "Actions").

A guard bound to more than one verb (`"on": ["create", "update"]`) must compile under **every** verb it names. So `before.` in a guard whose `on` includes `create` is refused at resolution, naming `create` specifically, even though the same `assert` would bind legally under `update` alone.

Traversal from a `row.` or `before.` path is to-one-hop only, following `ref` values on the row the guard checks, depth-capped exactly like BQL. `before.` never traverses past the row's own stored fields.

### What a create guard sees

Guards see the record **before** the server numbers it. On create, `row.id`, every default and every stamp are already filled in, but a numbered field (`numbering:`) is assigned after every guard and the record's own invariants have passed, immediately before the record is written. A create guard would read it as `NULL` and refuse every create, so a guard whose `on` includes `create` and whose `assert` reads a numbered field of its own row (`row.key`) is refused at plan and apply (`invalid_guard`, naming the guard and the field). Compare `row.id` instead: `"assert": "row.parent IS NULL OR row.parent != row.id"` keeps a record from being its own parent. Or bind the guard to `update` alone, where `row.key` is the stored number. A hop to another record (`row.parent.key`) reads a stored record, which is already numbered, so it is legal. The number itself comes back in the create's response.

The compiler's internal spelling of `before.` is `old.`, so `old` joins `id` as a reserved name. A field or relationship traversal name that snake-cases to `old` is refused at resolution.

### Enforcement

Enforcement runs in `commit()`. Every write goes through `commit()`'s single endpoint, and `commit()` runs, in order:

1. field/type validation (see "Metadata grammar and type table" above);
2. for `update`/`delete` only, a `SELECT … FOR UPDATE` re-read of the target row (`create` has no stored row to lock);
3. **every** guard bound to the write's verb (`on`), evaluated in declaration order and **collected**, not stopped at the first refusal.

A guard permits the write on `TRUE` only. `FALSE` **and** `NULL` both refuse; this is the deliberate inverse of SQL `CHECK`'s NULL-passes rule. A `NULL`-caused refusal is called out explicitly in the failure detail (`guard evaluated to NULL (unknown)`), so it is never silently indistinguishable from an ordinary `FALSE`. That text is appended after an author `message` when one is declared, and stands alone when it isn't.

A `row.` or `before.` path's traversal is to-one-hop only, following `ref` values on the row the guard checks, depth-capped exactly like BQL. Hop reads are point-in-time reads in the transaction snapshot, **not** locked. Only the guarded row itself is locked.

A refused write reports `422` `guard_failed` (see "Error shape" above), naming every guard that refused, not just the first.

A metadata change that only adds, edits, or removes guards is a valid apply whose plan carries **zero DDL operations**. It still advances the version chain and `model_checksum`. Guards are pure metadata, exactly like object views; enforcement in `commit()` simply starts reading whatever's currently reflected.

### Reflecting guards

`GET /tenants/{key}/reflect/objects/{Object}/guards` and `.../relationships/{Name}/guards` are implemented reflect scopes (see "Using /reflect" below), never a `501` stub.

Every object's `guards` array reflects `{name, on, when, message, origin, _href}` per entry, exactly what `commit()` enforces:

- `on` is a sorted array.
- `when` is the guard's condition (its authored `assert`) as source text, never re-rendered from the parsed expression. It is shown in the compiler's internal spelling: names without the `row.` root, and `old.` for `before.`.
- `origin` is `{kind: "authored"}` for a hand-written entry.
- `origin` is `{kind: "lock", index}` for one a `locks` entry synthesized (below). `index` names its position in the object's own `locks` array, not its position in `guards`.
- `origin` is `{kind: "edits", relationship, end}` for one a `document_lock` synthesized (see "Relationships" above).

A relationship declaring a `document_lock` on one end appends **two** such guards to that end's own parent object, both named `edits_<relationship>`:

- one `on: ["update"]`, whose condition includes the null-safe no-op exemption over every parent field except those in `editable_fields`;
- one `on: ["delete"]`, with no exemption: a delete's own current and prior states are the same row, so one would trivially always hold.

The same array appears inline under each object's own `/reflect/objects/{Object}` and `/reflect/relationships/{Name}` scope. An object's `/reflect/objects/{Object}` scope and its `/guards` scope both also carry a `locks` array: `{fields, unless, message}` per entry.

### `locks`

**`locks` declares anonymous, null-safe field freezes.** It is an object key, sibling of `guards`: an array of field lists, each frozen except under an escape condition. It saves hand-writing a chain of `row.x = before.x` comparisons.

It also avoids that chain's own trap. `NULL = NULL` is `Unknown`, not `TRUE`, so a hand-written freeze guard refuses **every** post-condition update on a record whose nullable `ref` (or any nullable field) is null, even a no-op one on an unrelated field. `locks` compiles the null-safe version instead. Its `fields` name stored fields only, never a rollup or a lifecycle:

```json basel-fragment
{
  "name": "Budget",
  "fields": {
    "name": {"type": "text"},
    "project": {"type": "ref", "to": "Project", "nullable": true}
  },
  "locks": [
    {
      "fields": ["name", "project"],
      "unless": "before.state = 'draft'",
      "message": "Budget planning fields cannot change after draft"
    }
  ]
}
```

#### What a lock compiles to

A lock resolves to an ordinary `update` guard named `lock_<index>`, where `<index>` is this lock's own position in `locks`. It is appended to the object's `guards` *after* every authored guard.

Its condition is `(<unless>) OR (eq(f1) AND ... AND eq(fn))`, where `eq(f)` is `(row.f = before.f) OR (row.f IS NULL AND before.f IS NULL)`. The resolver builds this directly as expression nodes, never by re-assembling and re-parsing text. There is no null-safe operator in the grammar, and `locks` adds none.

#### Lock rules

- `fields` must each name a stored field of the object. It may not name a rollup (computed on every write, so freezing it is meaningless), nor a lifecycle name (a managed state, not a stored field). Any violation refuses `invalid_lock` at `{Object}.locks[{index}].fields`, naming the field.
- `unless` is an ordinary guard expression, bound under `update` exactly like a hand-written guard's `assert` (`before.` legal). It binds under one verb only: freezing a field makes no sense on `create`, which has no prior state to compare against, or on `delete`, which has no post-write row. A syntax or binding error there is `invalid_lock` at `{Object}.locks[{index}].unless`.
- `message` becomes the synthesized guard's own `message`.
- A synthesized `lock_<index>` name colliding with an authored guard's own name is also `invalid_lock`, naming both.

Once resolved, a lock's guard enforces exactly like any other. The engine treats every entry in `guards` uniformly, regardless of `origin`; `origin` exists for reflection, not enforcement.

### Which rule construct

- **Invariant.** A predicate over the record's own final values, with no `before.`, no traversal, no aggregate, no time function, and no delete verb: write an **invariant**.
- **Lifecycle state.** A predicate over the record's own lifecycle state (`row.state = 'draft'`) is not an invariant candidate, even though it passes that same test. As an invariant it would forbid ever leaving that state, freezing the lifecycle. Keep it a guard.
- **Field freezes.** Freezing a fixed set of fields except under an escape condition: declare **`locks`** rather than hand-writing the `row.x = before.x` chain. It compiles to the null-safe guard above automatically.
- **Guard.** A predicate that needs `before.`, a specific verb, or runs on delete: write a **guard**.
- **Validator.** A check that needs code: a **validator**.
- **Permit.** A question about who is acting: a **permit**. Business rules do not go there, because permit refusals are opaque by design.
- **Parent state gating members.** A predicate over a parent's state that decides whether its members may change at all ("lines may change only while the invoice is draft"). Two constructs fit, and they differ in what else they freeze (see "Relationships" above):
  - **`document_lock`** on the relationship's parent end freezes the members, their links **and the parent's own fields** once `editable_when` is false. Use it when the parent is finished at that point, like a posted invoice. List any parent fields that must stay editable (notes) in its `editable_fields`.
  - **A guard on the member** that reads the parent through the `max: 1` end (`"assert": "row.matter.status = 'open'"`) freezes only the member's own writes. Use it when the parent must keep changing: its own fields and lifecycle stay editable. Add a guard on the relationship (`row.from.status = 'open'`) if linking and unlinking existing members must freeze too.

Adding an invariant over rows that already violate it is refused at plan and apply, so preferring invariants never traps existing data.

### Rule-selection advisories

Every plan response carries `"advisories"` (see "Endpoints" above). These are non-blocking findings, never a reason to refuse a plan or an apply. The rule-selection codes are:

- `guard_is_state_predicate`: a guard bound to both `create` and `update`, referencing no `before.` path, whose `assert` would itself pass the invariant-admissibility gate above. Its detail names the guard and the `invariants` entry it could become.
- `guard_reads_own_effect`: an action's or transition's guard reads `row.<field>` where the same action's effects set `<field>`, so it reads the value the action writes rather than the one it found. Its detail names the field and `before.<field>`. `basel validate` prints it as a warning. See "What an action's guards see" under "Actions".
- `backfill_unused`: a declared `backfill` the plan never actually reads, because the table turned out empty or the field already exists. See "Metadata grammar and type table" above.
- `nested_verb_not_exposed`: a relationship end lists a nested verb (`link`/`create`, or `unlink`/`delete`) whose link operation (`create`, or `delete`) the relationship's `operations` does not expose, so no role can be granted it; only an action or a function can write through that end. See "Nested create and update" below.
- `nested_member_verb_not_exposed`: a relationship end lists a nested `create`, `update` or `delete`, which also writes the member, but the member's own object does not expose that verb in its `operations`, so no role can be granted the member's write; only an action or a function can do it through that end. Add the verb to the member object's `operations`.
## Aggregates, rollups, and invariants

Three constructs compose on top of a declared relationship (see "Relationships" above): aggregates, rollups, and invariants.

```json basel-fragment
{
  "name": "Widget",
  "fields": {
    "total": {"type": "Money", "rollup": "SUM(row.parts -> amount WHERE row.stage = 'open')"}
  },
  "invariants": {
    "within_limit": {"assert": "row.total <= 100000", "message": "Total exceeds the declared limit"}
  }
}
```

- **Aggregates** are `SUM`/`COUNT`/`MIN`/`MAX` over a traversal whose far end declares `"cardinality": {"max": 1}`. They are expression-context only: legal inside a field's `rollup` or a guard's `assert`. They are refused inside an invariant's `assert` (declare a rollup and reference its own field instead), and never nested.
- Inside an aggregate, `row.<traversal>` starts from the declaring record, the projection after `->` names the related record's fields bare, and `row.` inside the `WHERE` is the related record being aggregated.
- **Rollups** are fields whose value is an aggregate: `{"type": ..., "rollup": "<aggregate>", "currency"?, "nullable"?}` in the object's `fields`.
- A `Money` aggregate rounds each term to the currency's minor unit before combining them (see "Money"), so `SUM(row.lines -> quantity * unit_price)` equals the sum of the line amounts as each is shown.
- **Invariants** are `invariants` entries, declared on an object or a relationship in the same places as `guards`, but in a different shape: `invariants` is an **object** keyed by name, `{"<name>": {"assert": ..., "message"?: ...}}`, where `guards` is an **array** of entries that each carry a `name`. An invariant is a fail-closed check bound to every verb on its own object.

### Rollups

A rollup owns the field it declares: the field is not also stored or written, and a field has exactly one of a stored value, a `formula` or a `rollup`.

Multi-level aggregation composes rollups rather than nesting aggregates, which is permanently prohibited. A second object's own rollup can `SUM`/`COUNT` a rollup's *own* field across one more traversal. A contributor write recomputes every level transitively, in one transaction.

`ANY(t, e)`/`ALL(t, e)` quantifiers desugar to the same aggregate machinery at metadata resolution, SQL-conservative on `UNKNOWN`. Reflection always serves the author's verbatim source, never the desugared form.

**Over an empty contributor set an aggregate returns the operation's identity element where one exists, and NULL where none does.** `COUNT` and `SUM` are `0`; `MIN`/`MAX` are `NULL`. That is why a `MIN`/`MAX` rollup declares `"nullable": true` on itself. `SUM` is deliberately *not* SQL's `NULL`-on-empty: a childless object's rolled-up total reads `0`, in metadata expressions and in BQL alike.

### Recomputing rollups

A rollup's value is stored. A write that changes what it folds recomputes it in the same transaction; nothing else does, except a **recompute run**: an exact re-fold of every record in a scope, done by the engine in the background, a few hundred records per transaction.

**A rollup you add to an object that already has records, or whose aggregate you change, gets a run of its own.** The push queues it and returns at once. Until the run reaches a record, that record reads what it stores: `null` for a new rollup, the previous value for a changed one. A write to a record meanwhile computes its new value immediately. Declare a new rollup on a populated object `"nullable": true`; a required one is refused `required_column_on_nonempty_table`, because its existing records have no value until they are computed.

`GET /tenants/{key}/rollups` lists every rollup with its `state`: `computing` while an unfinished run covers it (and that run's id in `recompute`), `failed` when the newest run covering it failed, `ready` otherwise. While a rollup is `computing`, a `null` means "not computed yet", never zero, so do not report over it until it is `ready`. It needs `metadata.read`.

**Ask for a run** with `POST /tenants/{key}/rollups/recomputes`, which needs `metadata.push`. The body names the scope: `{"object": "Customer", "field": "won_value"}` for one rollup, `{"object": "Customer"}` for every rollup on an object, or `{}` for every rollup in the tenant. Add `"reason"` to record why. A rollup that reads a field the run re-folds joins it, so a run over `Order` also re-folds the customer totals built on it.

```json
{"recompute": {"id": "019a…", "state": "pending", "cause": "request", "scope": ["Customer.won_value"], "whole_tenant": false, "step": 0, "steps": null, "carriers_scanned": 0, "carriers_changed": 0, "…": "…"}, "_links": {"self": "/tenants/acme/rollups/recomputes/019a…"}}
```

A new run answers `202`. If an unfinished run already covers exactly the same scope, the door answers `200` with that run instead of queueing another, so repeating the request is safe. An unknown object is `404`; a field that is not a rollup, a field without its object, or an object with no rollups is `422 not_a_rollup`.

**Follow a run** with `GET /tenants/{key}/rollups/recomputes/{id}` (or the list at `GET /tenants/{key}/rollups/recomputes`, newest first; both need `metadata.read`). `state` moves `pending` → `running` → `done` or `failed` (with `error`); `step` of `steps`, `carriers_scanned` and `carriers_changed` report progress. `cause` is `request`, `apply` (a push queued it) or `migration` (an engine upgrade queued it). Poll; there is no callback.

**What a run records.** Each transaction that changes at least one record writes one event, operation `rollup:recompute`, naming every record it changed and the values it wrote, with the run's id in its `parameters`. It shows in each record's history like any other write, as the engine's. The run itself names who asked. A changed record's version moves, so a client holding the old version is refused as stale once and must read again. A run never judges invariants: it restores the declared value.

A run survives a restart and resumes where it stopped. A push that lands during a run is picked up by it: the run continues under the new metadata, and a rollup the push removed is dropped from it.

### Invariants

An invariant is evaluated both on a direct write to its own object and for every object a write *affected* through a rollup, whether or not that object's own derived value actually moved.

Applying a metadata revision that adds or tightens an invariant validates **existing rows too**, not only future writes. A push can refuse `invariant_failed` because of data already in the tenant.

### Link aggregates

The `->` aggregate form above counts and sums **related records**. That is why the far end must declare `"cardinality": {"max": 1}`. Without it, "three related records" and "one record reached by three links" are indistinguishable, and a genuine many-to-many like `BudgetaryPosition.accounts` cannot be aggregated at all.

A second marker, `=>`, aggregates the **relationship instances** themselves instead:

- `COUNT(row.<traversal>=>)` counts links.
- `SUM`/`MIN`/`MAX(row.<traversal>=><link property>)` fold one of the relationship's own **declared properties**.

The `=>` form never folds a far record's field. That stays exactly as illegal through this form as through the record form, for the identical double-counting reason.

Because a link is its own row with its own identity, `=>` aggregation is legal **regardless of far-end cardinality**. Three links count and sum as three either way, so the ambiguity the `max: 1` rule guards against never arises here.

Empty-set identity, three-valued NULL handling, and mixed-currency `Money` refusing at apply time all follow the record form unchanged (`COUNT`/`SUM` → `0`, `MIN`/`MAX` → `NULL`, no `AVG`):

```json basel-repository
# file: basel.json
{"format": 2, "name": "budgeting"}
# file: objects/budgetary_position.json
{
  "name": "BudgetaryPosition",
  "operations": ["create", "update"],
  "fields": {
    "name": {"type": "text"},
    "account_count": {"type": "int", "rollup": "COUNT(row.accounts=>)"}
  },
  "invariants": {
    "has_accounts": {
      "assert": "row.account_count > 0",
      "message": "a position requires at least one account"
    }
  }
}
# file: objects/ledger.json
{"name": "Ledger", "operations": ["create"], "fields": {"name": {"type": "text"}}}
# file: relationships/position_ledgers.json
{
  "name": "PositionLedgers",
  "from": {
    "object": "BudgetaryPosition",
    "name": "accounts",
    "nested": {"create": ["link", "create"], "update": ["link", "create", "unlink"]}
  },
  "to": {"object": "Ledger", "name": "positions"}
}
```

As with the record form, a link rollup is a field with a `rollup`. An invariant references the rollup's own field, as with any aggregate (aggregates stay refused directly inside `assert`).

Membership changes (`link`/`unlink`, whichever endpoint authors them) and a write to a relationship's own declared properties are both contributor changes to a link rollup. They are recomputed by the same phase-2 final-state pass everything else in this section uses. That is what lets nested create in "Nested create and update" above satisfy `has_accounts` in the same transaction it creates the accounts.

### Read the live shape, don't assume it

`GET /tenants/{key}/reflect/invariants` serves every invariant's `assert` as source text, `message`, object, and `_href`. So does each object's own `/reflect/objects/{Object}`/`/reflect/relationships/{Name}` scope, under a name-keyed `invariants` key. This is the same source-text discipline `guards`' `when` follows, and in the same internal spelling (no `row.` roots).

Every rollup and every invariant also carries `consistency_scope`: the declared transactional coupling a rollup creates between contributor and object. It has one entry **per level of its cascade**; a two-level chain reflects as two entries, never merged.

`/reflect/objects/{Object}/guards` and `/reflect/relationships/{Name}/guards` additionally compose an `effective_conditions` array. It holds hand-written guards and invariant-derived checks in one list, each entry naming its `origin` (`"guard"` or `"invariant"`). This gives "the effective condition, as a whole" without a second, parallel surface to keep in sync.

`GET /tenants/{key}/reflect/rollups` enumerates the stable topology with a metadata-version ETag. Follow its `diagnostics_href` for bounded no-store measurements. Invariant entries likewise link to paginated, read-only current violation diagnostics. Diagnostics never repair or recompute data and never carry a metadata ETag; a recompute run does (see "Recomputing rollups"), and the listing's `state_href` links to the rollups' current state.

### Refused, flagged, or instrumented

The engine sorts consequential shapes into three distinct tiers, never collapsed.

- **Refused** at metadata-apply time, by name, with the threshold in the detail: cascade depth or rollup count on one object beyond an engine budget. Both budgets are visible at `GET /tenants/{key}/reflect` under its `budgets` key, not a number you have to guess or hard-code.
- **Flagged**: legal, but consequential. These are surfaced through the same flagged-operation machinery an `ADD CONSTRAINT` against existing data already uses, and require the plan-approval push option before they land. Two cases: adding a rollup to a relationship whose contributor already holds data, and adding a level to an already-existing cascade chain.
- **Reflected and instrumented, never refused or flagged**: data skew, which cannot be known at apply time.

For the instrumented tier, every write records typed tenant totals and per-rollup observations on the `basel_event` row it writes, under `rollup_metrics`:

- `rollup.fan_in_links`
- `rollup.matched_contributors`
- `rollup.affected_objects`
- `rollup.cascade_depth`
- `rollup.recompute_ms`
- `rollup.lock_wait_ms`

`rollup_metrics` is present with zero totals, rather than omitted, on every create/update/delete/action-invoke. It is queryable via `GET .../history`, exactly like redacted `proposals` are: a durable, queryable record, not an ephemeral one.

## Formulas

A **formula** is an object-level field computed **when read**, never stored. `elapsed_days`/`theoretical_amount` move as time passes with no write anywhere.

A formula is a field with a result `type` (the full type table) and a `formula` expression in the one shared grammar:

```json basel-fragment
{
  "name": "Widget",
  "fields": {
    "planned_amount": {"type": "Money"},
    "date_from": {"type": "Date"},
    "date_to": {"type": "Date"},
    "elapsed_days": {"type": "int", "formula": "DATE_DIFF(TODAY(), row.date_from)"},
    "theoretical_amount": {
      "type": "Money",
      "formula": "row.planned_amount * (row.elapsed_days / DATE_DIFF(row.date_to, row.date_from))"
    }
  }
}
```

These all resolve inside a `formula`, each through `row.`:

- the record's stored fields;
- lifecycle states;
- rollups;
- other formulas on the same object;
- declared to-one traversal paths;
- the full function registry, time-dependent functions included;
- history calls.

Formulas sit beside the stored fields. A `rollup` (an aggregate over a relationship, maintained on write, see "Aggregates, rollups, and invariants" above) and a `formula` (any scalar computation, evaluated fresh on every read) are siblings, not the same construct under two names.

### Nullability and writes

A Money formula's result is rounded half away from zero to its currency's minor unit (see "Money"); arithmetic inside the `formula` keeps four places until then.

**No storage target exists or may be declared, and a formula takes no `nullable`: every formula is always nullable**, regardless of its declared type. NULL operands propagate, division by zero yields NULL, empty `MIN`/`MAX` yield NULL, and open-`Money` unification failure yields NULL. So the contract states nullability uniformly rather than proving non-nullness per formula.

**Formulas are not writable.** A formula name in any write body (create, update, or the update envelope), or among an action effect's own written values, refuses `422 not_writable` naming the formula. This is the same rule a rollup's own field already enforces.

### Read parity

**The same name means the same thing everywhere.**

- `GET .../objects/{Object}/{id}` and a list read carry **every** declared formula alongside the record's stored fields. There is nothing to name and nothing to opt into. So does the row a write answers with: a `POST`, a `PATCH`, an action invocation and a nested create or update all return the committed row as the `GET` would read it, every formula evaluated against the state the write left and every rollup the write moved at its final value, so there is no need to read a record back after writing it.
- BQL computes only what a query actually **names**. A formula behaves exactly like a stored field in `SELECT`/`WHERE`/`ORDER BY`: project it, compare it, sort by it. `IS NULL`/`IS NOT NULL` are supported (a formula is always nullable, so this is the one null-test every formula answers). `IN` refuses a formula operand in v1; compare with `=`/`!=` instead, or project it and filter client-side.
- A formula on a related record reads through any to-one traversal a stored field reads through: a `ref` attribute (`SELECT owner.display_name FROM Ticket`) or a relationship end declaring `cardinality: {max: 1}` (`SELECT requester.full_name FROM Ticket` when `requester` is such an end), in the same three positions. The formula has to be `reachable_through_traversal` (below); one that is not is refused by name at compile, and at push for a declared query or a UI query plan.
- `"queryable": false` on a formula's own declaration withholds filter and sort (both together), while projection stays legal regardless. `/tenants/{key}/reflect` serves the derived `queryable: {projectable, filterable, sortable}` block per formula, so a client never has to re-derive it. `projectable` is always `true`; `filterable`/`sortable` follow the result type's own operator set, folded through the opt-out.

### Formulas in invariants

An invariant's `assert` may reference a same-object formula only when it passes **both** of two gates. Both are static, and both refuse by name:

- `422 invariant_requires_determinism` when the formula's closure calls a transaction-time function (`TODAY()`/`NOW()` and their zoned variants). An invariant checks state at arbitrary later commits, so a time-dependent read would drift with the clock rather than with any write.
- `422 invariant_requires_closed_dependencies` when the formula's closure reads anything beyond its own row and its rollups. A to-one path, or an aggregate of any kind (correlated included), reads a far row that nothing re-checks this invariant against when it changes.

Both facts are published per formula at `/tenants/{key}/reflect` (`deterministic: true|false`) rather than left for a client to infer from a refusal.

History calls (`entered_at`/`ended_at`, below) pass both gates. They are pure over the record's own event log, involve no clock, and change only on a write to the record itself.

#### The `capabilities` block and `usable_in_invariants`

`/tenants/{key}/reflect` serves a `capabilities` block on every formula, right after `queryable`. It lets a client learn the facts above (and one more) without re-deriving them from the raw closure facts:

- `usable_in_invariants`: `deterministic && write_local`, the two invariant gates above, composed.
- `reachable_through_traversal`: whether the formula may be read through a to-one traversal (`SELECT owner.f FROM Ticket` through a `ref` attribute or a `cardinality: {max: 1}` relationship end, a related list's `to.f` column). It holds when the closure reads only the record's own fields and rollups, or reaches at most one `ref` hop away (`row.primary_email_ref.address`, the projection a `primary` declaration generates). A longer path, a history call or an aggregate keeps it `false`.

Each is `{"ok": true}` or `{"ok": false, "reason": "..."}`, with `reason` omitted exactly when `ok` is `true`.

An author may also declare `"usable_in_invariants": true` directly on the formula itself. This asserts the gate holds, rather than waiting to discover it at a distant invariant reference. Resolution refuses an assertion that does not hold, at the formula's own `<Object>.formulas.<name>.usable_in_invariants`:

- `422 invariant_requires_determinism`, naming the offending function; or
- `422 invariant_requires_closed_dependencies`.

These are the identical codes an invariant reference itself refuses with. `"usable_in_invariants": false`, or omitting the key (the default), makes no claim and is never checked.

### Correlated aggregates

A `formula`, and a BQL expression (one grammar), may aggregate over an **object**. Membership is decided by a `WHERE` predicate rather than a declared relationship traversal. The object is named bare, because it names a declaration, not a value:

```
COUNT ( object-name WHERE predicate )
(SUM|MIN|MAX) ( object-name WHERE predicate -> value-expr )
```

Inside `predicate`:

- a **`row.`** path binds to the **contributor** (the aggregated object);
- an **`outer.`** path binds to the **enclosing record**: the formula's own row, including its declared to-one traversals (`outer.position.account`).

For example, `SUM(Line WHERE row.widget = outer.id AND row.account = outer.position.account -> amount)`. The compiler's internal spelling of `outer.` is `this.`, so `this` is a reserved name, exactly like `id`/`old`.

`value-expr` is required for `SUM`/`MIN`/`MAX` and illegal for `COUNT`. It names the contributor's own fields bare; `outer.` is illegal there in v1.

**Correlation is a compiled fact, not a syntax rule.** The mandatory `WHERE` alone does not make an aggregate correlated. A predicate with no `outer.` reference is an object-wide scan, refused `422 uncorrelated_aggregate` naming the aggregate. A report belongs in BQL, not a formula.

In BQL, which is a runtime language without roots, the same aggregate is written with bare contributor paths and `this.` for the enclosing row.

#### Reflecting correlated aggregates

A formula's own `formula` source (above) is the one place the predicate text lives. Reflection shows it as `value`, in the internal spelling (`this.` for `outer.`).

`/tenants/{key}/reflect` additionally serves a `correlated` **array** on the formula entry, one element per correlated aggregate the closure actually contains (up to 4, the limit below). Each element names:

- the contributor `object`;
- the aggregate `function`;
- the `outer.` `paths` it correlates on (dotted, prefix stripped);
- the aggregate's `result_type`.

It does not re-derive or duplicate the predicate text, only the structural facts the compiled node itself carries. A closure composing more than one correlated aggregate (legal up to the limit below) reflects every one of them, in the order they appear, never only the first.

### History functions in reads

`entered_at(lifecycle[, state])`/`ended_at(lifecycle)` are legal inside a `formula` and inside a BQL `WHERE` clause. Their arguments name a lifecycle and a state, so they stay bare: `entered_at(status, posted)`. See "Actions" below for the underlying event log. Both lower to the identical correlated subquery, evaluated at one instant per request.

A formula naming one is always nullable: no entry into the named state yet reads NULL. It evaluates fresh on every read; no stored copy exists.

`IN` refuses a bare history-function operand, since there is no single rendering for a subquery inside an `IN` list. Compare with `=`/`IS NULL` instead, or project it.

### Formula limits

| Limit | Value |
|---|---|
| Formula composition depth | 8 |
| Correlated aggregates per formula closure | 4 |
| Read statement timeout | 10s |

## Functions

Custom code in Basel is a **function**: an author-supplied **WebAssembly Component Model** binary. The binary is a **module**, kept under `wasm/`. It is sandboxed, budgeted, and versioned against a normative WIT contract.

Where a function is attached decides what it may do, and its declared `kind` says which attachment it is for:

- **called directly** it is pure (typed compute with no database access), `"kind": "pure"`;
- **behind a validator** it checks a write (a procedural accept/reject inside `commit()`), `"kind": "validator"`;
- **on an action or transition** it reads and returns a proposal, `"kind": "action"`.

No function imports the network, the filesystem, an ambient clock, or an ambient random source. Every capability it uses is declared, scoped, and checked at metadata apply time, never discovered at invocation. A function attached somewhere its `kind` does not fit, a `pure` function something attaches, a non-pure function nothing attaches, and a module whose world does not fit where it is attached all refuse `function_attachment_mismatch`, naming the attachment and what the function or module actually is.

A named function is declared once, in `functions/<name>.json`, pointing at one export of one module; any number of actions and transitions (or validators) may name it with `run`:

```json basel-fragment
{
  "name": "next_values",
  "kind": "pure",
  "code": {"module": "wasm/compute.wasm", "export": "next-values"}
}
```

### Validators

A validator is a procedural admission check: it checks a proposed operation on its object, at the transaction's final state, and answers accept or reject — admission control at write time, not a standing guarantee over existing rows.

It is **not a persistent invariant**. A validator may read across records at check time, but nothing re-runs it later when a remote record it once read changes. That standing-guarantee job belongs to a write-local invariant instead (possibly over a rollup).

So: an author who needs a cross-record check at the endpoint declares a validator; an author who needs a guarantee over existing rows declares an invariant. The two compose, and neither substitutes for the other.

A validator attaches to an object in its `validators` object and names its code with `run`, the name of a function of kind `validator`. It declares `on`, its event subscription. The subscription is deliberately separate from its read scope: listening never implies read authority, and a traversal in scope never implies a subscription to its own links. String entries name plain record operations; `{"link": [...]}`/`{"unlink": [...]}` entries name the relationships a membership change is subscribed on, explicitly:

```json basel-fragment
{
  "name": "Widget",
  "fields": {"name": {"type": "text"}},
  "validators": {
    "check_gadget": {
      "on": ["create", {"link": ["gadgets"]}],
      "run": "check_gadget",
      "scope": {"reads": {"Gadget": {"fields": ["status"]}}, "budgets": {"rows": 32}}
    }
  }
}
```

with `functions/check_gadget.json`:

```json basel-fragment
{
  "name": "check_gadget",
  "kind": "validator",
  "code": {"module": "wasm/check.wasm", "export": "validate"}
}
```

`scope` may only NARROW the module's own embedded contract, per dimension (an omitted dimension keeps the contract's own figure) — never widen it. A `scope` that would widen refuses at apply.

`/tenants/{key}/reflect/validators` (and the same object's own `/tenants/{key}/reflect/objects/{Object}` entry) publishes the resolved EFFECTIVE scope: the contract narrowed by `scope`, not either alone. Beside it are the resolved per-invocation budgets, the bound export's WIT signature, and the module's sha256, so a client never has to fold the two together itself.

A rejecting validator's wire shape:

- status and code `422 validator_rejected`;
- element `{Object}.validators.{name}`;
- fixed `detail` `validator rejected the proposed change`;
- fixed `domain_code` `rejected`.

Runtime module codes/messages and raw function diagnostics are not public response or log channels; invocation costs retain categories and budgets.

### Pure functions

A function of kind `pure` is **called directly**, and no action or validator may name it: typed parameters (plus an optional entropy seed) to a typed result — no database imports, no reads, no snapshot, no transaction.

`POST /tenants/{key}/functions/{name}` splits arguments from execution controls, so a reserved control name can never collide with an authored parameter:

- in: `{"arguments": {...}, "execution": {"seed": "<u64 hex>"}}`
- back: `{"result": <typed>, "execution": {"seed": "<u64 hex>"}, "module": "<sha256>"}`

Entropy is **seed-as-data, not a host generator**. A module declaring the `entropy` capability has `seed: u64` as its bound export's verified FIRST parameter. The host supplies it: freshly generated, or the caller's own `execution.seed` replayed byte-for-byte. The module owns its own pseudo-random algorithm. `execution.seed` appears in EITHER envelope if and only if the capability is declared.

Refusals:

- unknown function name: `404`;
- a function attached to an action: `422 function_attachment_mismatch` (it runs when its action is invoked);
- a parameter shape or type mismatch: `422 invalid_type` (or `unknown_attribute` for a missing/unrecognized key), naming the precise dotted/indexed element (`arguments.rule.count`);
- a budget breach: `422 limit_exceeded`, naming the budget.

A pure function call carries **no audit event**. It is a read-shaped surface with invocation metrics only, exactly like a plain query.

### Functions on actions

An action — a plain action or a lifecycle transition — may name a function of kind `action` with `"run": "<name>"` beside its declared `effects`. The function runs on the object's pre-proposal snapshot and returns a bounded typed proposal, which is amended into the invocation's own batch.

It has the same scoped read host API a validator uses (`get`, `traverse-one`, `traverse-many`, `query`, `aggregate`), plus a `writes` scope of its own: the write-set half no validator has. `"scope": {reads, writes, queries, budgets}` sits on the action, so one function can run with a different scope on each action that names it.

```json basel-fragment
{
  "name": "Widget",
  "fields": {"name": {"type": "text"}},
  "actions": {
    "restock": {
      "params": {"limit": {"type": "int"}},
      "run": "restock",
      "errors": {"nothing_to_restock": "No gadgets need restocking."},
      "scope": {
        "reads": {"Gadget": {"fields": ["status"]}},
        "writes": {"Gadget": {"transitions": ["status"]}}
      }
    }
  }
}
```

#### Rejection codes

A function rejects with a code only. Declare `"errors": {"<code>": "<message>"}` beside `run`:

- at most 64 codes, each an ASCII identifier of 1–64 bytes;
- each message a nonempty literal of at most 1024 UTF-8 bytes;
- messages are never interpolated.

Omission declares no public rejection codes; `errors`, `scope` or `elevated` without `run` is invalid. An undeclared returned code fails as sanitized `function_scope_violation`; an oversized code fails the result budget. Guest rejection strings are not logged.

#### What the function may write

Two rules gate every operation the function returns before it joins the batch:

- The write-set rule: every operation is checked against the effective `writes` scope: object and verb, fields, lifecycle, relationship.
- The provenance rule: a function may only target the record it runs on, records it observed through its scoped reads, `id`-typed values inside what it observed (the input image of the record it runs on included), ids named by its typed params, and its own earlier creates; anything else fails as `function_scope_violation`.

**The snapshot rule.** The function runs on the pre-proposal snapshot before any write. A record the function both observed and writes is re-checked after the lock pass and refuses `409 conflict` if it moved.

#### Composition with declared effects

`effects` and `run` may coexist on one action. Declared `effects` compile first; the function's operations follow (positioned `function[<i>]`).

Writes to **different fields** of one record merge into one record after the write. A transition's function may update its own record beside the state change; the result is checked once by guards, invariants, authority and the version check, with one audit event.

Overlapping writes refuse:

- A field (or link, or a deleted record) written by both refuses `422 proposal_conflict`, naming both positions.
- On a transition, a function writing a field the transition itself sets refuses `422 transition_field_conflict`. It is refused at push (`invalid_function`) when the function's write scope already allows it.

Creates never conflict.

#### No reentrancy

A function runs only when its OWN action is invoked directly. A lifecycle transition reached as a sibling `transition` effect, or as an operation a function itself proposes, still changes the record's state, but does not run that transition's own function. A function can never trigger, directly or through another function's proposed operations, a second function's run.

#### Refusals

| Code | Meaning | Status |
|---|---|---|
| `function_rejected` | the function selected a declared code; `domain_code` is that code and `detail` is the action's static metadata message | 422 |
| `proposal_conflict` | effects and function wrote the same field, link or deleted record | 422 |
| `transition_field_conflict` | a transition's function wrote a field the transition itself sets | 422 |
| `limit_exceeded` | a budget breach, naming the budget and layer | 422 |
| `conflict` | the snapshot rule's record changed since it was read (`conflict:record_changed`) | 409 |
| `function_scope_violation` | a read or write outside the effective scope, an unobserved target, or an undeclared rejection code | 500-shaped |
| `function_trap` / `function_host_error` | as for validators | 500-shaped |

#### Reflection and metrics

`/tenants/{key}/reflect/functions` lists every attachment under `attachments`: element, object, action, kind, function, module sha256, effective `reads`, effective `writes`, budgets, and WIT signature.

The same fields appear inline as `function` on every action/transition entry under `/tenants/{key}/reflect/objects/{Object}`, `/reflect/actions`, and `/reflect/lifecycles`. The key is ALWAYS present, `null` only when no function is named.

A successful invocation's metrics carry `rollup_metrics.functions[<element>]` beside `validators`.

### The JSON mapping

**The JSON mapping is normative** — "types come from WIT" is not itself a stable API. Every function parameter/result, and every reflected WIT signature, follows one table:

| WIT type | JSON |
|---|---|
| `s8`..`s32`/`u8`..`u32` | plain JSON numbers |
| `s64`/`u64` | DECIMAL STRINGS (JSON numbers are only safe past that width) |
| `f64` | a JSON number, refusing NaN/±Inf at the boundary in EITHER direction |
| `bool`/`string` | verbatim |
| `option<T>` | the value or `null` |
| `variant` | `{"tag": ..., "value": ...}` (`value` is `null` for a payload-less case, never an omitted key) |
| `enum` | the case-name string |
| `list<T>` | a JSON array |
| `record` | a JSON object using the WIT field names verbatim — every declared field required, no unrecognized keys tolerated |

Type nesting past 16 refuses at apply, as do resources, handles, streams, futures, and `f32`. `/tenants/{key}/reflect/validators` and `/tenants/{key}/reflect/functions` publish every bound export's signature in this exact vocabulary.

### Budgets

Every figure below is a specification number, published here. Like every other refusal threshold in this guide, it changes only by amending the published figure — never as a silent runtime setting.

There are two layers. The first table bounds ONE invocation. The second bounds the aggregate across every validator invocation inside ONE `commit()`: a wide batch crossing several validators is bounded by the total, not merely by each invocation alone.

**Per invocation:**

| Budget | Validator | Pure | On an action |
|---|---|---|---|
| Fuel (deterministic; not "instructions") | 100M | 100M | 100M |
| Linear memory | 64 MiB | 64 MiB | 64 MiB |
| Wall clock | 100 ms | 1 s | 500 ms |
| Rows read (in scope) | 256 | — | 256 |
| Host calls | 128 | 8 (entropy only) | 128 |
| Result size | 1 KiB (reject message) | 256 KiB | 64 KiB (encoded proposal) |
| Parameter size | — | 64 KiB | — |
| Operations returned | — | — | 32 (shared with declared effects) |

**Measuring an action.** `POST .../actions/{name}?measure=true` runs the action and always rolls back: nothing commits and no audit event is written. It needs the `action.<name>.measure` permit as well as `action.<name>.invoke`, and the same `If-Match` as a real invocation. Its functions run under three times their own effective budget (fuel, wall clock, rows, host calls, result size; memory unchanged), so you can see how far over budget they go. The answer is `{measured, outcome, failure, row, invocations}`, and a refusal comes back as `failure` in a `200`. Each cost record is also kept in `/tenants/{key}/invocations`, with `measured: true` and `outcome: "measured"`.

**Per proposal (validator totals, across every invocation in one `commit()`):**

| Budget | Value |
|---|---|
| Wall clock | 2 s |
| Fuel | 1B units |
| Rows read | 1024 |
| Host calls | 512 |

Breaching either layer refuses `422 limit_exceeded`, naming both the budget and the layer, and always fails closed — a function never observes a partially completed call as though it had finished.

### Supported ABI

The normative WIT, package `basel:function@1.0.0`, is served at `GET /abi/basel-function/1.0.0/function.wit` (`text/plain`, content ETag). `GET /abi` indexes every served package version.

Basel serves every supported EXACT interface version, never merely "both majors". A module targeting anything outside the supported set refuses at apply, naming it. The current supported set, one world per place a function may be attached:

- `basel:function/validator@1.0.0` — behind a validator (it checks a write)
- `basel:function/pure@1.0.0` — called directly (a pure function)
- `basel:function/proposer@1.0.0` — on an action or transition (it reads and returns a proposal)

#### Named queries from a function

The `reads` interface carries one import beyond the four record reads: `query-by-name(name, page)` invokes a public query (`queries/<name>.json` with `"exposure": "public"`) under the invoking function's own read scope.

A function's scope names the queries it may invoke in `scope.queries`. This is a SIBLING of `scope.reads`, because `reads` is keyed by object and a `queries` key inside it could not be told from an object of that name. Apply proves each query reads nothing the scope does not already reach.

The proof covers the plan's WHOLE read, not its projection alone. A `where` decides which rows come back and an `order_by` decides their rank, and both are readable through the page, so `select`, `where` and `order_by` are checked alike. The rules:

- The query's object must be one that `scope.reads` names WITH AN EXPLICIT `fields` list. An omitted dimension means "the module's own contract", which resolution cannot see, so there would be nothing to prove against. That refusal is `invalid_function` at `<Object>.actions.<name>.scope.queries[<i>]` (and `invalid_validator` at `<Object>.validators.<name>.scope.queries[<i>]` for a validator's own scope).
- Every name must then be `id`, a field in scope, or a formula whose whole closure is in scope.
- A hop is walked only through a `ref` field or a traversal in scope, and the far object and far field must be in scope too.
- A read-time formula is allowed unchecked in `select` ALONE — nothing projects it, so a guest never observes its value. The moment the same name also appears in `where` or `order_by` it is checked on its whole closure, because there it is readable through membership and rank.
- A plan declaring `params` refuses: this import binds no parameter.

#### Building a module from HTTP access alone

1. Generate guest bindings from the served WIT with `wit-bindgen` (world `validator` or `proposer`; a pure module declares its own world with no imports).
2. Build for `wasm32-unknown-unknown`.
3. Convert the core module with `wasm-tools component new` (no WASI adapter — the closed import set is verified structurally).
4. Append exactly one custom section named `basel-contract` holding RFC 8785 canonical JSON that satisfies `GET /abi/basel-function/1.0.0/contract.schema.json`.

A Rust guest SDK, `basel-function-sdk`, exists but is not published to a registry, and nothing in it is required — the WIT and the schema are the whole contract.

#### Reflection

`/tenants/{key}/reflect/functions` lists:

- every declared function: its `code`, its `role` (`pure` or `proposer`, decided by where it is attached) and `attached_to`;
- every `wasm/` binary: its path in the tenant's metadata repository, sha256, its own declared ABI string, and every validator, directly called function and action that uses it;
- every `attachments` entry of a function to an action or transition.

### Reserved

Reserved for a later release, with its design still to be written: the scheduling and external-effects tier — scheduled actions, transactional outbox/consequence records, after-commit workers, retries and idempotency, all declared on a function. Background work after a commit is available today as a task started by a trigger, with its own lease, retries and `idempotent` (see "Tasks and triggers").

Function-to-function and function-to-action calls stay refused **permanently** (no reentrancy, any attachment — see "No reentrancy" under "Functions on actions" above). A managed source-build service stays out of scope too: Basel accepts only locally or CI-compiled modules, never builds one itself.

## Actions

An **action** is a named, typed, guarded invocable declared on an object *or* relationship: the wire form of "capabilities", not generic mutation. It is either a plain action or a lifecycle transition (an action that also moves the record's state).

Both live in the object's one `actions` object. A transition additionally declares `"transition": {"lifecycle", "from", "to"}` and so belongs to a named lifecycle; its audit identity is `transition:<Object>.<lifecycle>.<name>`. Invocation, guards, effects, parameters, and audit are otherwise identical for both. The same `POST .../actions/{name}` surface invokes either kind, on an object *or* a relationship alike.

### Discovering what a tenant declares

This guide never lists a tenant's actions. Like the type table and the grammar, it leaves that to reflection so it cannot go stale: a tenant's own actions are metadata, not part of this engine-wide document, and change with every apply.

- `GET /tenants/{key}/reflect/lifecycles` lists every declared lifecycle across every object (a relationship never has lifecycles). Each carries its managed state `attribute`, `states` (with `outcome`, `null` when none declared), `initial`, and `transitions` keyed by name. Each transition carries its own `from`/`to`/`params`/`guards`/`effects`.
- `GET /tenants/{key}/reflect/actions` lists every declared plain action, object AND relationship together. Each entry names what it is declared on under `object` or `relationship` (the key says which), alongside the same `params`/`guards`/`effects` shape.

Both also appear inline under the owning object's own `/reflect/objects/{Object}` or `/reflect/relationships/{Name}` scope (`lifecycles`/`actions` keys, keyed by name). Objects additionally carry `rollups` there: each entry's own `type` and its aggregate as `value` source, in dependency-evaluation order.

Every guard's condition and every effect's bound value render as source text, never the parsed expression. This is the same rule the plain `guards` scope follows (see "Guards" above), extended here to actions, and in the same internal spelling: reflection shows `args.subject` as `subject` and a created handle as `$ticket`.

### Effect vocabulary

An action's `effects` array compiles to one proposal, applied atomically with the record write itself. Each entry is one operation, named by `op`, applied in array order:

- `{"op": "set", "values": {...}}` assigns this record's own fields;
- `{"op": "transition", "lifecycle": ..., "to": ...}` moves another lifecycle of this record;
- `{"op": "create", "via": ..., "as"?: ..., "values": {...}}`, `{"op": "update", "via": ..., "values": {...}}`, `{"op": "link", "via": ..., "record": ..., "values"?: {...}}` and `{"op": "unlink", "via": ..., "record" | "link": ...}` reach other records through the object's declared relationships, and compile into that same proposal (see "Nested create and update" above for their record-endpoint counterpart).

`via` names the traversal: `row.<end>` from this record, or `created.<handle>.<end>` from a record created earlier in the list. A value in `values` is a typed literal or `{"expr": "<expression>"}`, whose names come from `row.`, `args.`, `bindings.`, `created.` and `actor`.

Two values name a record rather than a field:

- `actor` is the effective principal of the invocation, a `ref` to `Principal`: `{"op": "set", "values": {"owner": {"expr": "actor"}}}` makes whoever invokes the action the owner. Under delegation it is the delegator, the principal the action is done for; a stamp's `acting` is the one that acted. Only the bare name is a value: a path through it (`actor.team`) belongs to permits. An action that declares a parameter named `actor` reads that parameter instead.
- `row.<end>`, a to-one relationship end of this record, is the record at its far end, as a `ref` to that object: it can be a `link`'s `record` (`{"op": "link", "via": "created.deal.account", "record": {"expr": "row.account"}}`) or the value of a `ref` field. `row.<end>.id` is the same value. When the end holds no record the value is NULL: a `ref` field that is not nullable refuses it at push (`nullable_effect_value`), and a `link` whose `record` is NULL refuses the invocation with `validation_error`, writing nothing.

**Scope is model-visible, not runtime-discovered** (reflected as each effect's `scope`). An effect may only reach a target **through a relationship declared on the object**, and may only `update` through a declared **to-one** path. A reader of the metadata knows every action's maximum blast radius without reading any function. Naming an undeclared path is an authoring-time refusal, never a runtime surprise.

**Clearing a nullable field.** Write JSON `null`: `{"op": "set", "values": {"note": null}}`. Related `create` and `update` value maps accept the same. A clear is typed by its declared target and goes through the normal permissions, guards, validators and atomic write pipeline. A required target refuses at push with `nullable_effect_value`; formulas, rollups and lifecycle state remain unwritable. The literal `"NULL"` is the four-letter text, not a clear. Reflection displays a null value as source `NULL`.

`create` through a declared traversal both creates the related record **and** links it. Creation through a declared relationship *is* the link, so no separate `link` is needed for a record this same effects list just created.

A `create` can name its record (`"as": "ticket"`). A later `create` or `link` can then start **from** that record instead of this one, with `"via": "created.ticket.<end>"`. A `create` or `update` value can also be `{"expr": "created.ticket"}`, for a `ref` field to that record's object. The repository below shows each: `bindings` resolves the category's default team (next heading), the first `create` opens a ticket, the second adds its first message, and the `link` adds a watcher:

```json basel-repository
# file: basel.json
{"format": 2, "name": "helpdesk"}
# file: objects/desk.json
{
  "name": "Desk",
  "fields": {"name": {"type": "text"}},
  "actions": {
    "open_ticket": {
      "description": "Open a ticket with its first message and a watcher, routed to the category's team.",
      "params": {
        "subject": {"type": "text"},
        "first_message": {"type": "text", "description": "Becomes the ticket's first Message."},
        "category": {"type": "ref", "to": "Category"},
        "watcher": {"type": "ref", "to": "Member"}
      },
      "bindings": [{"name": "team", "path": "args.category.default_team"}],
      "effects": [
        {
          "op": "create",
          "description": "Later effects reach this ticket as created.ticket.",
          "via": "row.tickets",
          "as": "ticket",
          "values": {"subject": {"expr": "args.subject"}, "team": {"expr": "bindings.team"}}
        },
        {
          "op": "create",
          "via": "created.ticket.messages",
          "values": {"body": {"expr": "args.first_message"}, "about": {"expr": "created.ticket"}}
        },
        {"op": "link", "via": "created.ticket.watchers", "record": {"expr": "args.watcher"}}
      ]
    }
  }
}
# file: objects/ticket.json
{
  "name": "Ticket",
  "fields": {"subject": {"type": "text"}, "team": {"type": "ref", "to": "Team", "nullable": true}}
}
# file: objects/message.json
{
  "name": "Message",
  "fields": {"body": {"type": "text"}, "about": {"type": "ref", "to": "Ticket", "nullable": true}}
}
# file: objects/member.json
{"name": "Member", "fields": {"name": {"type": "text"}}}
# file: objects/team.json
{"name": "Team", "fields": {"name": {"type": "text"}}}
# file: objects/category.json
{"name": "Category", "fields": {"default_team": {"type": "ref", "to": "Team"}}}
# file: relationships/desk_tickets.json
{
  "name": "DeskTickets",
  "from": {"object": "Desk", "name": "tickets"},
  "to": {"object": "Ticket", "name": "desk", "cardinality": {"max": 1}}
}
# file: relationships/ticket_messages.json
{
  "name": "TicketMessages",
  "from": {"object": "Ticket", "name": "messages"},
  "to": {"object": "Message", "name": "ticket", "cardinality": {"max": 1}}
}
# file: relationships/ticket_watchers.json
{
  "name": "TicketWatchers",
  "from": {"object": "Ticket", "name": "watchers"},
  "to": {"object": "Member", "name": "watched"}
}
```

The traversal after `created.<handle>.` must be declared on the created record's object. `created.` is refused on `update` and `unlink`, because a record created in this write has nothing stored for them to reach. A `set` value cannot be `{"expr": "created.<handle>"}`; set the reference from the other record's side instead. Reflection shows the root as the scope's `from`.

`unlink` addresses the link it removes the same way a nested write's `unlink` does (see "Nested create and update" above): `record`, a declared param naming the far record, or `link`, a local link id. It must match **exactly one** link or refuses `422 ambiguous_link`.

### What an action's guards see

An action's guards, and a transition's, are checked **after its effects are applied**, against the record as the action leaves it, exactly as a record's own `update` guards see the record after the write. `row.<field>` is the value the action writes; `before.<field>` is the value it found. So a guard meaning "only if no deposit has been taken yet" on an action that sets `deposit` is `before.deposit IS NULL`. Written `row.deposit IS NULL`, it reads the deposit the action has just set and refuses every call, with the guard's own `message` as the only detail. A transition sets its own lifecycle's state, so its guards read `row.<lifecycle>` as the target state; `from` already says which states it leaves.

`basel validate` and the plan's `"advisories"` warn on this, `guard_reads_own_effect`: a guard that reads `row.<field>` where the same action's effects set `<field>` (a `set`, a `transition` of that lifecycle, or a transition's own state), naming the field and `before.<field>`. A guard can mean the written value (bounding what a param sets: `row.qty <= 10` after `set qty = args.qty`), so it is a warning, never a refusal; a guard that reads both `row.<field>` and `before.<field>` is not warned. A refusal still reports the author's `message`, unchanged: it reaches the action's callers, who are not its authors.

### Sibling transitions

An action may move a record other than its own object with `{"op": "transition", "target": ..., "lifecycle": ..., "to": ..., "args": {...}}`: one it just created in the same effects list (`"target": "created.<handle>"`), or one reachable by a declared to-one relationship (`"target": "row.<end>"`). It does so with **explicit parameter mapping only**:

- The keys of `args` are the target transition's own declared param names.
- Each value is a typed literal or `{"expr": ...}` over the invoking action's own `args.`, `bindings.` and `row.` paths. This is the identical binding scope an action guard's `assert` resolves against (see "Guards" above).
- A param may share a name with a field of the object: `args.note` is the param and `row.note` the field, and neither shadows the other (in guards, effect values and these mappings alike). The wire body still keys params by name.
- A mapping that doesn't cover every required param of the target transition is an authoring-time refusal at metadata apply, never a runtime surprise.
- The target transition's own guards still evaluate against the final state. A sibling transition moves state and binds its mapped params; it is not a guard bypass.
- The effect names a state, not a transition, so the transition that licenses it is the one whose `from` holds the record's current state. If two transitions enter the named state from a common `from`, that choice has no single answer and metadata apply refuses the effect `422 invalid_effect`, naming both transitions and the shared states. The two transitions themselves stay legal: give them disjoint `from` states, or invoke the one you mean by name.

**Fail-closed narrowing.** A sibling transition may not license a target transition that itself declares `effects` of its own. Every transition of the target lifecycle ending at the named state (regardless of `from`, since the record's state isn't known at metadata-apply time) must declare no effects, or metadata apply refuses `unsupported_construct` naming it. Cascading into the activated transition's own effects is not supported.

### Effect budget

One action invocation's compiled effects are capped at **32 operations** (before any cascade) — see the limits table under "Nested create and update" above. A breach refuses `422 limit_exceeded` naming the cap. Combined with declared reach and the standing cascade-cycle refusal, a compiled batch is finite, and its size is inspectable from metadata alone, without ever invoking it.

### Read bindings (`bindings`)

An action's `bindings` array, beside `effects` — `[{"name": "team", "path": "args.category.default_team"}]` — binds one record by name for its effects. The effects read it as `bindings.team`, a `ref` value.

- Each binding's `path` starts at a declared `ref` param (`args.<param>`) or an earlier binding in the array (`bindings.<name>`) and follows `ref` fields only.
- A binding has at most 4 segments and ends at one record, never a list or query.

The records it reads are part of the action's declared scope (reflected as `{"kind": "with", "reads": [...]}` ahead of the effects). They are checked against the **caller's** read authority. A missing record, a record the caller cannot read, or a reference field it cannot read all refuse `422 binding_not_found` alike, disclosing nothing. A NULL optional reference binds NULL. A binding that reads a different record after the lock pass than before refuses `409 conflict`.

### The transaction instant and Duration arithmetic

`NOW()` in an effect's value is the write's own transaction instant: the same value for every effect on every record of the invocation, and exactly the audit event's `occurred_at`. `TODAY()` is that instant's date in the tenant's time zone (UTC when `basel.json` declares none), so `{"op": "set", "values": {"approved_on": {"expr": "TODAY()"}}}` stamps the local day the write happened; `DATE(NOW())` is the same date.

Fixed-elapsed arithmetic:

- `Timestamp - Timestamp` is a `Duration`;
- `Timestamp ± Duration` is a `Timestamp`;
- `Duration + Duration` is a `Duration`.

A day is 24 hours; there are no calendar, business-day or zone rules. Any NULL operand gives NULL. Pause accounting, for example: `"paused_total": {"expr": "COALESCE(row.paused_total, DURATION 'PT0S') + (NOW() - row.paused_at)"}`.

### One audit event per invocation

A multi-operation effects list still writes exactly one `basel_event` row per `POST .../actions/{name}` call. The row carries the whole applied batch verbatim and every affected record's resulting version. Touching several records in one invocation (through nested writes or action effects) changes neither the event count nor the size limits of the audit contract described under "Reading history" below.

### Invoking an action

```
POST /tenants/{key}/objects/{Object}/{id}/actions/{name}
{"<declared param>": <value>, ..., "reason": "..."}   # reason optional
```

The body is the action's declared params as a flat JSON object, each typed exactly like a declared field. It may also carry the same optional top-level `reason` audit field `create`/`update`/`delete` accept.

A **declared** `reason` param (an action may name one like any other param) is the one channel once it exists. It binds normally and is type-checked like every other declared param (required unless it declares its own `optional`), and its bound value becomes the invocation's own audit `reason`. Only when the action declares **no** `reason` param is the top-level envelope field used instead. It is popped before param validation, so it can never collide with a real param.

Success is `200` with the updated record, `TypeID`-rendered exactly like `create`/`update`'s own response (see "Ids: TypeID on the wire").

### Optional and default params

Two keys describe a param, and they answer different questions: `"optional": true` says the request may omit the key, and `"nullable": true` says the value may be null. Because an omitted param binds null, a param is either required and non-null, or declares both together; one without the other is refused. A `default` (a typed literal) requires them. The `default` shapes and the metadata-resolution validation gate are exactly those a field's own `default` uses (see "Metadata grammar and type table" above). A default is refused `invalid_default` at `{Object}.actions.{name}.params.{param}.default` (or the transition equivalent) when it doesn't type-check, or, for a named-typed param, when it doesn't satisfy the named type's own `check`.

```json basel-fragment
{
  "params": {
    "subject": {"type": "text"},
    "note": {"type": "text", "optional": true, "nullable": true},
    "urgent": {"type": "bool", "optional": true, "nullable": true, "default": false}
  }
}
```

What an invocation binds:

- It omits a param declaring a `default`: that literal binds.
- It omits an optional param with no default: `NULL` binds in guard/effect scope. A guard that then evaluates `args.<param>` directly (rather than through an explicit `IS NULL`) sees `Unknown` and refuses fail-closed, exactly as a nullable field's own `NULL` does. Authors guard an optional param the same way.
- An explicit `null` is never "absent". Supplied for a required param it refuses `validation_error "required"`. Supplied for an optional one it binds `NULL`, same as omission, and never substitutes `default` (applied only when the key is missing entirely).

A sibling transition's explicit mapping (see "Sibling transitions" above) may likewise omit any optional param of the licensing candidate. Only a **required** param of every candidate ending at the named state must still be covered.

Reflection carries `optional` on every param (always present, a bool) and `default` (present only when declared, the same absent-means-none convention as a field's).

### Refusals

Refusals use the same uniform error shape as every other endpoint (see "Error shape"):

- unknown object/relationship: `422 unknown_object`;
- a malformed or wrong-`TypeID`-prefix `id`: `422 invalid_bind`/`id_prefix_mismatch`, checked before `id` is ever looked up;
- an unknown action name, or no row at `id`: `404`;
- a missing or mistyped param: `422` `validation_error`/`invalid_bind`, shaped exactly like a field type error, `element: "<Object>.<action>.<param>"`;
- a guard refusal: `422 guard_failed` with the additive `errors[]` array. The element is `"<Object>.<guard name>"`, the **same** format a plain object/relationship guard failure uses (both route through the identical evaluator), not qualified by the action name;
- a wrong-`from` transition (the record isn't currently in one of the invoked transition's declared `from` states): `409 conflict`, with `diff: {"current": "", "from": []}`.

### Reading history

`GET /tenants/{key}/objects/{Object}/{id}/history?limit=&offset=` returns a bare JSON array of that record's own audit events, newest first. `limit` defaults and is capped exactly like BQL's own pagination (see "BQL" below); `id` and `offset` follow the same conventions as everywhere else on the wire:

```json
[{"id": "evt_...",
  "occurred_at": "2026-01-01T00:00:00.000000Z",
  "operation": "transition:{Object}.{lifecycle}.{name}",
  "proposals": [{"op": "set", "attribute": "...", "value": "..."}, ...],
  "metadata_version": 3}]
```

`operation` names the endpoint: `create`/`update`/`delete` for generic CRUD, or `action:<Object>.<name>`/`transition:<Object>.<lifecycle>.<name>` for an action invocation.

Public history never returns invocation parameters, free-text reason, session or credential identifiers; canonical audit storage retains that evidence. `audit.read` does not restore private metadata.

Refusals: `404` on a nonexistent `id`; `422 unknown_object` on an unknown `Object`; `422 limit_exceeded` over the pagination cap.

The reserved, read-only `Event` pseudo-object exposes the identical history as queryable BQL state (`FROM Event`; `GP-08` taken literally: history is queryable, not just fetchable). It is reflected at `/reflect/objects/Event` (`kind: "event"`) exactly like a real object's own scope, so a client that already understands object reflection needs no new parsing logic for it.

Each event row names who acted: `effective_principal` is the principal the write was for and `acting_principal` the one that made it (the same unless a delegation separated them), the ids the history door shows. Reading `Event` needs the `audit.read` tenant action, so an audit reader can filter and count by actor in one query: `SELECT effective_principal, COUNT(*) AS events FROM Event WHERE occurred_at >= TIMESTAMP '2026-10-01T00:00:00Z' GROUP BY effective_principal` (grouping through the ad-hoc door also needs `query.aggregate`; a plain `COUNT(*)` does not). Event rows carry no reason, parameters, session or credential.

Every write path (`create`/`update`/`delete`/an action invocation) writes exactly one event per invocation, inside the same transaction as the row write itself. A record's history and its current state can never disagree about what happened.

## BQL

A `SELECT`-shaped read-only query language, stratified by precedence: `NOT` binds tighter than `AND`, which binds tighter than `OR`. Parentheses override.

**BQL is the runtime language; metadata expressions are its rooted form.** An ad hoc query (`POST /tenants/{key}/query`, `basel query`) is sent at runtime and names fields bare: `SELECT name FROM Widget WHERE stage = 'open'`. Every expression in a metadata file (a guard's `assert`, a `formula`, a `rollup`, a query file's `where`, a permit condition, a `visible_when`) uses the same grammar, operators and functions, but roots every name: `row.stage = 'open'`, `args.closes_by`, `before.amount`, `actor` (see "Format 2"). The examples in this section are runtime BQL.

```
query      := SELECT projection FROM ident [WHERE or_expr]
              [GROUP BY path (',' path)*]
              [ORDER BY ordering] [LIMIT uint] [OFFSET uint]

projection := projection_item (',' projection_item)*
projection_item := path | value_expr AS ident | group_aggregate AS ident
group_aggregate := (COUNT | SUM | MIN | MAX) '(' ('*' | path) ')'
path       := ident ('.' ident)*
value_expr := CASE WHEN or_expr THEN value_expr [WHEN ...] ELSE value_expr END
            | value_expr ('*' | '/') value_expr
            | value_expr ('+' | '-') value_expr | '-' value_expr
            | function_call | aggregate_call | path | literal

or_expr    := and_expr (OR and_expr)*
and_expr   := not_expr (AND not_expr)*
not_expr   := NOT not_expr | primary
primary    := '(' or_expr ')' | comparison

comparison := path op literal
            | path IN '(' literal (',' literal)* ')'
            | path IS [NOT] NULL

op         := '=' | '!=' | '<>' | '<' | '<=' | '>' | '>='

ordering   := order_term (',' order_term)*
order_term := path [ASC | DESC]

literal    := string | number | bool | number CURRENCY
            | DATE string | TIMESTAMP string | DURATION string | DATERANGE string | UUID string
```

**Value precedence** is primary/function/CASE, unary `-`, `*`/`/`, then `+`/`-`; comparisons sit above that value ladder, followed by `NOT`, `AND`, and `OR`. Any non-path projection requires `AS <alias>` so the result key is stable; a bare path keeps its authored dotted path.

Aggregates accept contributor-scoped value expressions: `SUM(lines->quantity * unit_price WHERE active = true)`, which a metadata file writes `SUM(row.lines -> quantity * unit_price WHERE row.active = true)`. `COUNT` alone takes no value. Money literals are currency-qualified (`12.50 USD`); open-Money aggregation requires a direct positive currency equality conjunct, and Basel never performs implicit currency conversion.

**Related records, and the forms BQL does not have.** An aggregate's traversal is one relationship end of the `FROM` object, written bare: `COUNT(contacts)` counts the related records (their end must declare `max: 1`), `COUNT(contacts=>)` the links of any relationship, `SUM(lines -> amount)` totals them. `COUNT(row.contacts)` is the metadata spelling, and a dotted traversal walks no hop; either is refused `bql_parse_error` naming the bare form. `COUNT(<field>)` outside a grouped query names no relationship end and is refused `not_a_traversal` for every caller: `COUNT(*)` counts rows, `GROUP BY` counts per group.

There is no `EXISTS` and no subquery. Rows with no related records are `WHERE COUNT(contacts) = 0`, rows with any `COUNT(contacts) > 0` or `ANY(contacts, status = 'active')`; `EXISTS(...)` and `IN (SELECT ...)` are refused `bql_parse_error` naming these. A to-many end cannot be walked with `.`: `contacts.full_name` is refused `bql_compile_error` naming the end, whoever asks; read the related records from their own object (`SELECT full_name FROM Contact WHERE account.id = '<id>'`) or aggregate them.

**Groups and totals.** `GROUP BY` turns rows into groups: `SELECT stage, COUNT(*) AS deals, SUM(amount) AS total FROM Deal WHERE won = false GROUP BY stage ORDER BY total DESC`. In a grouped query every selected item is either a group key, named in `GROUP BY` by its path or its alias, or a group aggregate with `AS`. `COUNT(*)` counts rows and `COUNT(path)` non-null values; `SUM` takes an `int`, `decimal` or Money field (0 when nothing contributes); `MIN`/`MAX` take an orderable one. Every group key must be selected, so each group carries the values that reproduce it. Grouped rows have no `id`.

A key may be a computed value grouped by its alias, which is how you bucket dates: `SELECT MONTH(close_date) AS month, COUNT(*) AS n FROM Deal GROUP BY month`. A key must be one comparable value: not a set, a whole open-Money field (group by `price.currency`), a `reference_choice`, `id`, or a `queryable: false` formula. `AVG`, `HAVING` and aggregates of expressions are not supported: declare a formula and total it.

Without `GROUP BY`, a projection of aggregates alone is one total over every row you can read: `SELECT COUNT(*) AS n FROM Deal`. `COUNT(lines)` alone, without `GROUP BY` or another aggregate, keeps its relationship meaning above.

Totals cover only rows you may read: read permits filter rows before grouping, so a group made only of hidden rows never appears, and grouping or totalling a field you cannot read is refused `unreadable_attribute`. Through `POST /tenants/{key}/query` a grouped query also needs the `query.aggregate` tenant action (the built-in `admin` holds it); without it the door answers `403 forbidden` naming `query.aggregate`. A plain row count — no `GROUP BY`, and only `COUNT(*)` in the select list, as in `SELECT COUNT(*) AS n FROM Issue WHERE status = 'open'` — needs only read access, and counts the rows you may read. A named query groups the same way without the action (see "Grouped queries" under Queries).

An open-Money total needs one currency: pin it (`WHERE price.currency = 'EUR'`, and the total is Money in euros) or group by it (`SELECT price.currency, SUM(price) AS total … GROUP BY price.currency`, one total per currency); otherwise `mixed_currency_aggregate`.

**Limits on grouped queries.** They apply to ad-hoc BQL and to named grouped queries alike, whichever door or tool sends them. Before a grouped query runs, Basel asks Postgres how many rows it would read; over **1,000,000** estimated rows it is refused `422 aggregate_too_broad`, naming the query (`query` for ad-hoc BQL, the plan for a named one) and the object: narrow it with a filter. A tenant runs at most **4** grouped queries at once; one more is refused `429 too_many_grouped_queries` with `Retry-After: 1`, and nothing ran, so send it again. Like every read, a grouped query stops at the 10 s statement timeout (`500 query_timeout`, naming the query). `basel plan` warns `slow_query` for a grouped named query over a table of about a million rows when no index leads with a field it filters on. Ungrouped queries are not subject to the estimate or the concurrency limit.

A stored `rollup` is deterministic and maintained on writes; a `formula` (see "Formulas" above) is read-time and unstored.

`TODAY()`/`NOW()` (and their zoned variants) bind to one evaluation instant per request and are legal in BQL and in a `formula` alike. A stored `rollup` is always a lone aggregate call, so a time-dependent function has nowhere to appear there, though deterministic CASE/date/string functions remain usable inside that aggregate's own arms.

**Dates follow the tenant's time zone.** `NOW()` is an instant; a date depends on where you stand. With `time_zone` declared in `basel.json`, a bare `TODAY()` is the date of that instant in the tenant's zone, `DATE(ts)` is the local date of a `Timestamp`, and `DATE_TRUNC(unit, ts)` over a `Timestamp` truncates on local boundaries (midnight, the first of the month) in that zone. Without `time_zone` all three use UTC. An explicit zone argument always wins: `TODAY('Europe/Paris')`, `DATE(created_at, 'Asia/Tokyo')`, `DATE_TRUNC('month', created_at, 'UTC')`. The same rules apply in BQL, formulas, guards and effects, and `/reflect` reports the zone in use as `time_zone: {name, declared}`.

**Calendar dates.** `ADD_MONTHS(date, n)` moves a `Date` by `n` whole months (`n` an int, negative allowed) and keeps the day of the month, stopping at the last day of a shorter month: `ADD_MONTHS(DATE '2026-01-31', 1)` is `2026-02-28` (`2028-02-29` in a leap year), and `ADD_MONTHS(DATE '2026-03-31', -1)` is `2026-02-28`. There is no `ADD_YEARS`; write `ADD_MONTHS(d, 12 * k)`. `YEAR(date)`, `MONTH(date)` (1 to 12), `DAY(date)` (1 to 31) and `WEEKDAY(date)` return an int; `WEEKDAY` is ISO, Monday = 1 through Sunday = 7.

All five take a `Date`, not a `Timestamp`, because a timestamp has no calendar day until a zone is chosen: write `YEAR(DATE(created_at))`, and `DATE()` follows the tenant's time zone as above. They are deterministic, so they are legal in formulas, rollups, guards and invariants, and a NULL argument gives NULL.

A `Duration` stays fixed elapsed time with no months or years, so `DATE_ADD(d, DURATION 'P30D')` adds 30 days and `ADD_MONTHS(d, 1)` adds a calendar month. For example, the next billing date of a monthly subscription is `ADD_MONTHS(next_invoice_date, 1)`.

Built-in functions (from the engine registry):
- `COALESCE` — query, rollup
- `LOWER` — query, rollup
- `UPPER` — query, rollup
- `TRIM` — query, rollup
- `LENGTH` — query, rollup
- `TEXT_SET_CONTAINS` — query, rollup
- `SET_CONTAINS` — query, rollup
- `SET_OVERLAPS` — query, rollup
- `CONTAINS` — query, rollup
- `STARTS_WITH` — query, rollup
- `CONCAT` — query, rollup
- `DATE_ADD` — query, rollup
- `DATE_DIFF` — query, rollup
- `DATE_TRUNC` — query, rollup
- `DATE` — query, rollup
- `TODAY` — query
- `NOW` — query
- `ROUND` — query, rollup
- `ADD_MONTHS` — query, rollup
- `YEAR` — query, rollup
- `MONTH` — query, rollup
- `DAY` — query, rollup
- `WEEKDAY` — query, rollup

`CONTAINS(text, search)` is a case-insensitive substring test returning `Bool` (both sides lower-cased; NULL if either is NULL). `STARTS_WITH(text, prefix)` is the same test pinned to the start of `text`. Either is a condition on its own: `WHERE CONTAINS("name", 'acme')`, the same as `WHERE CONTAINS("name", 'acme') = true`; so is any function that answers yes or no (`SET_CONTAINS`, `SET_OVERLAPS`), and `NOT` negates it. A function that answers anything else is a value and needs a comparison (`LENGTH("name") > 3`). A list's or record picker's `search` text compiles to these for you; send `search` rather than writing them.

`SET_CONTAINS(set, value)` is true when a `set` attribute (a multi-select or a `set` of `text`) holds `value`, compared exactly; `SET_OVERLAPS(set, value, ...)` when it holds at least one of the values. Both are null when the set is null (an empty multi-select) or a value is null, so compare them: `WHERE SET_CONTAINS(tags, 'urgent') = true`. Against a multi-select a quoted value must be one of its declared values. `TEXT_SET_CONTAINS(set, value)` is the older form for a `set` of `text` only.

**Typed literals.** `DATE '2026-08-22'`, `TIMESTAMP '2026-08-22T10:00:00Z'`, and `UUID '...'` are explicit. A plain string that is a whole date (`'2026-08-22'`) also compares with a `Date`, and one that is a whole RFC 3339 timestamp (`'2026-08-22T10:00:00Z'`) with a `Timestamp`; a date alone never stands for a timestamp. Any other plain string compared with a non-text attribute is a compile error naming both types, not a silent cast.

**A record's id may be written as returned.** A plain string holding a public id, `'issue_01h…'` exactly as every answer spells it, compares with a `ref` or `id` as that id (`WHERE parent = 'issue_01h…'`, `IN (…)` too); its prefix must be the target object's (`id_prefix_mismatch`). A bare uuid in a plain string (`WHERE id = '01a16b24-…'`) compares as that id too, so either form you hold works. A `uuid` column that holds some record's id, such as `Event.record_id`, takes the same two forms (`FROM Event WHERE record_id = 'issue_01h…'`); there a public id's prefix must be some object's, and any other is the type error. Any other string against an id is the type error above. `<>` is `!=`.

**NULL is three-valued**, as in SQL: `NOT (amount > 100)` does not match rows where `amount` is null. `IS NULL`/`IS NOT NULL` are the only null tests; `= null` is a compile error.

**`LEFT JOIN` null semantics — the single most common way to misread a result.** Traversing a nullable `ref` (e.g. `account.tier`) emits a `LEFT JOIN`, so `account.tier = 'gold'` **excludes** rows with no `account` at all — it is not equivalent to "account is missing or gold"; it is `WHERE gold`, and a null-valued join column never equals anything.

**Ordering by an enum.** `ORDER BY status` sorts an enum by the order its values are declared in (a lifecycle's states in their declared order), not alphabetically, and pages correctly with `next`. `<` and `>` on an enum stay refused: the declared order is a sort order, not a comparison.

**Deterministic pagination.** `ORDER BY` always has `id ASC` appended as a final tiebreaker, so `LIMIT`/`OFFSET` paging is stable even over a non-unique sort key. A grouped query orders by its output columns (a key's path, or any item's alias, such as `ORDER BY total DESC`) and appends its group keys, ascending, in place of `id`, so it pages over groups the same way. `LIMIT` defaults to 100 and is capped at 1000.

**Paging by cursor.** Through `POST /tenants/{key}/query`, a page whose row count reaches its `LIMIT` also answers `next`. Send the same query with `"after": <next>` for the rows after the last one: a keyset over the order keys and `id`, so rows inserted or deleted ahead of it do not shift the page as `OFFSET` would. A cursor fits only the query, tenant and metadata version that minted it: another query's or a tampered one is `invalid_cursor`, as is `after` together with `OFFSET`, and one minted before the tenant's metadata was last published is `stale_cursor` (start again from the first page). Every apply publishes a new metadata version, even one that only adds a field, so a cursor goes stale after any publish, not only after a policy change. Grouped queries carry no `next`; they page with `LIMIT`/`OFFSET`. Ordering operators on an id stay refused; that refusal points here.

| Limit | Value |
|---|---|
| Query text | 16 KiB |
| `LIMIT` | default 100, max 1000 |
| Traversal depth | 4 segments |
| Distinct joins | 12 |
| `IN` list | 500 literals |
| Predicate nodes | 200 |

Every limit is enforced at compile time, with an error naming the limit.

Which operators each attribute supports — including whether it is orderable — is served per-attribute by `/tenants/{key}/reflect`. This guide deliberately lists no operators per type, so it cannot go stale as types evolve — see "Using /reflect" below.

**`id` is a pseudo-attribute.** Bare `id` and `<path>.id` resolve in projection and `WHERE` everywhere a declared attribute would — e.g. `SELECT id, name FROM Widget`, `WHERE account.id = UUID '...'`. It accepts the same `TypeID`-or-bare-uuid literal every id-accepting boundary does (see "Ids: TypeID on the wire" above).

Its operator set is equatable-only: `=`, `!=`, `IN` — never `<`/`<=`/`>`/`>=`, and **never valid in `ORDER BY`**. It already appears there implicitly, as the tiebreaker described above, and naming it explicitly is a compile error. `/tenants/{key}/reflect` lists it as an `engine_owned` entry in every object's `attributes`, alongside every declared attribute.

**`POST /tenants/{key}/query`'s result shape** is `{"columns": [...], "rows": [[...], ...], "has_more": false}`, plus `next` when `has_more` is `true`: `rows` in `columns` order, `columns` one entry per projected path — `{"path", "type", "id_prefix"}`.

**`has_more` says the limit cut the answer.** A query answers at most its `LIMIT` rows (100 without one), and a grouped query at most that many groups. `has_more` is `true` when more matched than came back and `false` for a complete answer; it is always present. Read a `true` as "this is not the whole set": send the same query with `"after": <next>` for the rows after these, at any `LIMIT` (a grouped query has no `next`; page it with `OFFSET`), raise `LIMIT`, or narrow `WHERE`.

**An agent tool answer is at most 96 KB** (98,304 bytes of JSON), because an agent reads every byte again on each later round; the HTTP doors themselves answer in full. Past that, `basel_query` answers the rows that fit, with `has_more: true`, a `next` that resumes right after the last of them, and a `note` naming the budget; every other agent tool refuses with `answer_too_large`, the answer's `bytes`, the `budget_bytes` and `advice` on asking for less. To get more rows a call, select only the columns you need and leave out long text such as bodies.

Two habits keep a cut answer from being read as a complete one. Count with `COUNT(*)`, `SELECT COUNT(*) AS n FROM Contact WHERE tier = 'gold'`, never by counting rows; a plain row count needs no tenant action. A lookup by `IN (...)` answers at most 100 rows like any other query, so give it a `LIMIT` of at least the list's length: `SELECT id, email FROM Contact WHERE email IN ('a@x.test', 'b@x.test') LIMIT 500`.

- `path` is the dotted path exactly as authored.
- `type` is the lowercase Basel type (`"text"`, `"money"`, `"enum"`, `"ref"`, `"id"`, …). It is `"id"` for both bare `id` and any `<path>.id` projection, never `"ref"`, even though both render identically on the wire as `TypeID`s.
- `id_prefix` is the target object's `TypeID` prefix for a `"ref"`- or `"id"`-typed column, `null` for every other type, including a declared `uuid` attribute, which stays bare.

## Using /reflect

`AGENT.md` (this document) explains how to talk to Basel. `/tenants/{key}/reflect` reports what a given tenant's metadata contains — its objects, attributes, and relationships, all serialized from the resolved model the engine is currently holding. Neither duplicates the other.

### Scoping by path

The tree is reachable at any depth:

- the tenant root: `/reflect`;
- the object list: `/reflect/objects`;
- one object: `/reflect/objects/{Object}`;
- one attribute: `/reflect/objects/{Object}/attributes/{attr}`;
- the relationship list: `/reflect/relationships`;
- one relationship: `/reflect/relationships/{Name}` (see "Relationships" above).

Request whatever scope you need; nothing requires walking from the root first.

### `_links`/`_href` traversal

Every scope carries `_links` with `self`, `parent`, and `root`. Every nested element (an object in a list, an attribute in an object, a relationship target) carries its own `_href`. An agent that lands anywhere in the tree can reach everywhere else without prior knowledge of the URL structure — construct nothing by hand.

### Full names

Every object, relationship, named type and query has a full name, `namespace:short`:

- the tenant's own elements are in `core` (`core:Contact`);
- Basel's built-ins are in `basel` (`basel:Principal`, `basel:Event`);
- a vendored package's elements are in the namespace its release declares (`crm:Contact`).

**What reflection reports.** Reflection reports each such element's `name` as its full name, beside `namespace` and `provenance`. `provenance` is `{namespace}` for a `core` or `basel` element. For a packaged element it also carries `package`, `version`, `commit`, `release_digest` (from `basel.lock`) and the declaring `path`.

**Fields that name elements.** Every field whose value names one of these elements carries the full name too:

- a `ref`'s `to`, and a relationship end's `object`;
- a query's `from`/`target`, and a `select`;
- `named_type` and `interface`;
- `entity.root`/`parent`/`ancestors`/`admitted`/`concrete`;
- `origin`/`declared_by`;
- the `object`/`relationship`/`contributor` of every flattened listing.

Every `_href` is built from the full name (`/reflect/objects/core:Contact`; `:` needs no escaping in a path segment).

**What keeps its authored form.** These are not element names and keep their authored form: member names (attributes, traversals, lifecycles, actions), element paths (`Contact.validators.check`), a `type` expression, policy text, and physical names (`table`, `id_prefix`).

**Inputs accept either form.** `{Object}`, `{Name}` and a UI route's `{object}` take `Contact` or `core:Contact`. A full name in the wrong namespace answers `404`. In v0 a short name always names exactly one element of its kind, so the short form is never ambiguous.

### `kind` on every node

Every reflected object or relationship node carries `kind`: `"object"` or `"relationship"`. So the two constructs' distinct wire semantics (an object's `attributes` vs. a relationship's `from`/`to`/`properties`) are never ambiguous from the payload shape alone.

An endpoint object's own `relationships.outbound`/`.inbound` entries also show where each entry comes from:

- an entry derived from a `ref` attribute has no `declared` key, and its `_href` points to the *other object's* scope;
- an entry derived from a declared relationship carries `declared: true`, and its `_href` points into `/reflect/relationships/{Name}` instead (see "Relationships" above).

### An object's fields: one catalog

`/reflect/objects/{Object}` carries `fields`, an array listing every field once, the way format 2's `fields` catalog declares them. Each entry carries:

- `supplier`: what supplies the value — `stored`, `rollup`, `formula`, or `engine` (the engine-owned `id` and audit timestamps);
- the facts its per-kind entry carries (`type`, `queryable`, `value`, …). A rollup's entry has the stored attribute's facts plus the rollup's `value` and `consistency_scope`;
- `entries`: pointers into the same document to the per-kind entries it mirrors, such as `{"attribute": "#/attributes/3", "rollup": "#/rollups/0"}`;
- `_href`: the attribute's own scope for a stored, rollup or engine field, and the object's scope for a formula.

Authored fields come first, ordered by name across suppliers, then the engine-owned fields. The same object still lists its fields by kind as well, in `attributes` (stored and rollup fields, plus `id` and audit timestamps), `rollups` and `formulas`. Those lists are unchanged; read whichever shape suits you.

### The authors' descriptions

A declaration whose source carries a `description` reflects it as `description` on its own entry: the root (the app), an object in the listing and in its own scope, each field (in `fields` and in its per-kind list), a lifecycle and each state, an action or transition and each of its `params`, `guards`, `effects` and `result` fields, guards, locks, invariants, constraints and validators, a relationship and its two ends and properties, a role and a permit (`/reflect/authority`), a query and each of its `parameters`, a type and its fields, arms and members, and a function. The key is absent when none was written.

UI files have no per-entry scope for most of their parts, so `/reflect/ui/objects/{Object}` and `/reflect/ui/pages/{page}` carry a `descriptions` map instead, from the element each hint describes (`ui.objects.Invoice.record.sections[0]`, `ui.pages.home.root.chart`) to its text. A description is never behavior: editing one leaves `model_checksum` and the policy and UI checksums unchanged, and plans no schema change.

### No stub scopes remain

Every logic-reflect scope this document names answers a real `200` body, keyed and counted exactly like `objects`/`relationships`; none answers `501`. That includes `lifecycles` and `actions` (see "Actions") and `invariants` (see "Aggregates, rollups, and invariants").

The `/ui` actor/policy context override is reserved for a later release. Raw proposals use the authenticated authority path.

### One source, one honest caveat

Every reflection response carries the model's `model_checksum` (`sha256:...`), so you always know exactly which version you're reading. Reflection always describes the model the engine is currently holding.

During the brief window between a guarded apply's DDL commit and its registry swap, that model can be one version behind the physical schema. So "reflection is current" is not a guarantee this engine makes; "reflection and the checksum it reports agree" is.

## Apps from packages

What a package is depends on what it carries:

- a package with a UI definition, `ui/app.json` (exported as `{"path": "ui/app.json"}` in its `basel.json` `package` block), is an **app**;
- one with model elements and no UI definition is a **module**;
- one with only components is a **component library**;
- one with only presentations, assets and renderer components is a **theme**.

A package is at most one app.

### Themes

A theme's presentation is selected by full name and contract major (`"presentation": "brand:brand@1"`), and its image, font and stylesheet assets are `tenant:brand:<asset>` in tenant UI. Its presentation may list its own stylesheets (`"stylesheets": ["brand:theme"]`), which the console loads into the `presentation` cascade layer while that presentation is selected. A theme ships no loose scripts.

Only an app that lists the theme package directly sees its presentations and assets (`package_not_listed` otherwise). A theme's renderer components resolve for any consumer that depends on the package, direct or transitive, without being listed under `use`, and `basel deploy` uploads and activates them the same way. An app never lists a theme's renderers, only its own content components; a `use.components` line naming them is accepted and changes nothing. `basel validate`, `basel plan` and `basel deploy` refuse a selected presentation whose renderer would have no implementation (`presentation_renderer_unimplemented`: its manifest names no `entry` and nothing activates it), naming the presentation and the renderer, rather than deploying an app whose records cannot draw.

A renderer cannot be placed on a page (`renderer_not_placeable`); only a theme's `renderers` may name one.

### An app's own components

An app's own pages, object views, experiences and `defaults` may place the app's own components (`"component": "acme_sales.grid@1"`); those components resolve and `basel deploy` activates them for every tenant that installs the app, with no `use.components` line. Only components the app's own UI places come this way: any other export of the app, every component of a component library, and another package's component placed on the app's page still need a `use.components` line on that package.

### Installing an app

Installing a whole app means writing three things, and nothing else — everything the app itself carries is visible in the install plan before it happens:

1. **A dependency line** in the manifest's `dependencies` (`basel.json`, or `basel.yaml` when that is how the tenant spells it; a tenant's or a package's) naming the package, its `source` and a semver range. Cycles are refused. `basel build` reads the package's files except any `node_modules` directory (a symbolic link elsewhere, or an export naming a path inside `node_modules`, is refused), and validates a package against the lowest and the newest version each range allows, so a range can never claim a version the package does not work with. `basel upgrade` resolves the whole tree together, one version per package per tenant.
2. **A role assignment per person.** A package ships roles, permits and assertions granting only on its own elements, and never ships memberships — the tenant assigns people to a package's roles, or includes them in its own. An app's role may `include` a dependency's role (`sales:rep` includes `crm:contact_user`), so installing an app still costs one role per person even when it draws on several packages. An upgrade that widens a role's effective grants (a new object or action grant, a wider read or write field ceiling, a change reached through `includes`) is flagged and needs approval before it applies. Removing a role that people hold is refused, naming the count.
3. **Approvals, only if the app asks for elevated reads** — see "Elevated reads and approvals" below.

A package, or one it needs, cannot bring an object whose short name the tenant already uses (the tenant's own `Contact` beside a package's `crm:Contact`): `basel_search_catalog` marks such a listing `collides_with` (`basel catalog` prints `collides with`), and the catalog install doors (`POST /tenants/{key}/packages/plan`, which `basel packages install` and `basel_install_package` run) refuse it `ambiguous_name` before fetching anything, naming each name and the package that brings it; build the feature by hand, or rename the tenant's object first.

### Sample records

To fill an installed app (or your own objects) with made-up records, use the agent tool `basel_generate_records` rather than writing rows one by one. It is two calls, like an install. `mode: "plan"` writes nothing: from reflection it decides how each writable field is filled (names from built-in pools, an email from its owner's name on a reserved example domain, a 555-01xx phone, dates with an end after the start, an enum value, an amount in a range the field's name suggests), links each member to a parent (a contact's emails) and each relationship row to its two ends, and answers the exact counts, a sample, the fields it would leave empty without a hint, and a `plan_hash`.

`mode: "apply"` with that `plan_hash` and the same arguments writes the same records in dependency order, and regenerates any record Basel refuses (a taken unique email gets a different one); a record still refused after two more tries is reported, and the rest are written. A changed model, or records already written by that plan, refuse it `plan_changed`. List the objects with their members and relationships (for crm-core: its people and organisations, `crm:EmailAddress`, `crm:PhoneNumber` and `crm:Affiliation`); at most 1,000 records a plan.

`hints` is optional and anything left out falls back to the defaults: per object a `count`, or for a member or relationship `per: {"min": 1, "max": 3}` records per parent; per field a `pool` of values, a `template` such as `"{first_name|lower}.{last_name|slug}@acme.example"` (also `{parent.<field>}`, `{from.<field>}`, `{to.<field>}`, `{n}`), a `range`, a weighted `choice`, a fixed `value` or `empty`. `samples` takes a package's `rosetta.samples/1` file and uses its values as default pools. The same arguments always make the same records; `seed` picks another set. From the CLI: `basel work basel_generate_records --config work.json --input args.json`.

### Namespaces, app routes, and `?app=`

A package's namespace is its app's identity and URL segment: `/{tenant}/apps/{namespace}` opens it. Refusals:

- a package namespace equal to the tenant's own app `name`: `namespace_is_app_name`;
- a tenant app (`ui/apps/<name>/`) named like a package namespace: `app_name_taken`;
- an app whose release has no `title`: `missing_app_title` (that title is the app's name everywhere);
- an app with no namespace: `app_without_namespace`.

`GET /ui/app` lists every installed app — `namespace`, `title`, `route`, `audience` — for a launcher. An app's `audience` roles only limit that listing, never access to the app itself.

Every `/ui/*` GET door, and `POST /tenants/{key}/ui/queries/{id}`, take an optional `?app={namespace}` query parameter, defaulting to the tenant's own app. The checksum and cursor an app-scoped call returns are that app's own. Naming an unknown app refuses.

#### Record and list pages

An object's default view (`ui/objects`) belongs to the object's owner. An app may map one of its objects to its own record page instead with `"record_pages": {"<object>": "<page>"}`, without disturbing any other app's view of that same object.

- A page in a package with no UI definition is refused (`page_without_app`).
- An object view naming an object the package does not own is that app's own view of the object, applied inside the app only (see "App-scoped views"). A package that is not an app is refused (`object_view_not_owned`).

An object's generated list is the same default. `"list_pages": {"<object>": "<page>"}` is `record_pages`' twin: it maps the object's *list* instead. It is a different surface mode, so an app may map one object through both at once. It works on the same terms; naming an object outside the app or an unknown page refuses `unknown_list_page_object`/`unknown_list_page`. `record_pages` and `list_pages` draw from the same pool of the app's own pages, so a page either already claimed is unavailable to the other.

#### Where everything comes from

Beyond the elements above, reflection gives a `provenance` of the same shape to:

- every UI page and object view (`/reflect/ui` and its `objects/` and `pages/` doors);
- an app's UI definition (`definition`);
- every lifecycle (`/reflect/lifecycles`: its object's provenance, which declares it in the same file);
- every role and permit (`/reflect/authority`, and each permit in `/authz/declared_grant_matrix`): the owner's `policies/roles` file for a role, its `policies/<object>` file for a permit.

A tenant-owned one is `{namespace: core, path}`, naming the tenant's own file; a built-in role is `{namespace: basel}`. An object view the app does not author is `generated: true`, and its provenance is its object's, which it is derived from.

`/reflect/ui` and its two doors take `?app={namespace}` like the `/ui/*` doors and answer for that app. Its `pages` — and `/ui/pages` — also list the pages an app places through `record_pages`/`list_pages`, each marked `placed: {record: <object>}` or `{list: <object>}`, beside the routed ones.

Each package in `/reflect/packages` lists what it `contributes`: `objects`, `relationships`, `queries`, `functions`, added `fields`, `roles`, `permits` (by id), `lifecycles` and `formulas`/`rollups` (as `<object>.<name>`), its app's UI definition (`app`: `{namespace, source}`, or `null`), `pages` (routed and placed), `object_views`, and the `presentations`, `components` and `assets` vendored from it.

#### Who may open an app's UI

A role opens the app; `metadata.read` opens the metadata. A caller holding `metadata.read` opens every app's `/ui/**` surfaces, unnarrowed. Without it:

- **The tenant's own apps** (no `app`, the tenant's app name, or a further app under `ui/apps/`) admit any member holding a role other than the virtual `authenticated`.
- **An installed app package's surfaces** (`?app={namespace}`) admit anyone holding the built-in `member`, or a role that app's package owns, directly or through any role whose `includes` reaches one (`seller` including `sales:rep`).
- **An app that declares `audience`** admits only holders of one of those roles, on top of the above.

None of this opens `/reflect/**`, the Git transport, the standard UI (`?ui=standard`), the activations door or frame minting: those keep `metadata.read`.

A caller admitted this way (rather than through `metadata.read`) sees every field list narrowed to their own read ceiling: an object view's `fields`, field placements, generated views and forms, related-list columns, record pages, query contracts' `select`. A field they cannot read is not listed by name, and the launcher's `apps` lists only the apps they can open. Such a document is served `Cache-Control: private`. Data is filtered by the caller's own read policy either way.

Such a caller is also not told about what they cannot read. An object they read no row of leaves the objects catalog, navigation, pages' placements, workspace context and commands, and its own surface answers `404`. `compact` lists and reference descriptors lose hidden fields. A node shown or enabled by a condition on a hidden field is left out. Query predicates (`where_source`, `purpose.admissible`), command `guards`, formula sources, component release details, asset repository ids, unselected presentations and the links to `metadata.read` doors are removed.

**Layout and `config` are visible.** Everything else in a UI document, including every component's `config` and a field's `config`, is visible to anyone who opens the app. Never put a secret, or the name of something a role must not learn, in UI metadata.

A generated list query (`POST /ui/queries/object.<Object>.generated.list`, generated related lists included) leaves out the columns, default sort terms and sortable columns the caller cannot read, for any caller, instead of refusing. A dropped default sort pages by `id`, and a refusal that remains (a caller-supplied sort on a hidden field) names only what the caller sent. Hand-written queries still refuse `unreadable_attribute`.

### Elevated reads and approvals

An action that runs a function may declare `"elevated": {"reads": {"crm:Contact": ["email"]}}` (a sibling of `run`) to read named fields of a dependency's object beyond what the invoking user could otherwise see.

It runs only while the tenant's `basel.json` carries a matching approval, keyed by the exact element the elevated read attaches to — an action as `"Deal.check_duplicate"`, a lifecycle transition as `"Deal.stage.close"` (object, lifecycle, action). A bare function or action name is refused (`invalid_approval`). For example:

`"approve": {"@acme/crm-sales": {"Deal.check_duplicate": {"reads": {"crm:Contact": ["email"]}}}}`

The approval must list at least the requested reads, checked on every invocation. Widen the request in a new version, or revoke the approval, and the action refuses (403) until the approval catches up. An elevated read always needs an invoking user — it never runs on an engine-triggered invocation with no caller.

What it can name is narrow: never the package's own data, never the tenant's elements, never `*`, and never a write (`invalid_elevated`). One approved read discloses every row of the objects it names to whoever may invoke the action, and the plan says so.

- Each run is audited `function.elevated`.
- A new or widened elevated read is flagged for the tenant's approval under the existing `function.admit_scope` action rather than a new one, so admin role checksums do not change.
- An approval nothing asks for is a warning (`approval_unused`).
- The install plan carries `function_reach`/`elevated_read` advisories for what each package function reaches outside its own package.
- `/tenants/{key}/reflect/functions`'s `elevated_reads` names the admitting principal and plan, folded into its ETag.

### Adding to a package's object (`additions/`)

The tenant may add to an object of a package its `basel.json` lists directly, in `additions/<namespace>/<object>.json` — `additions/crm/contact.json` holding `"object": "Contact"`. It uses the object file's own keys, limited to:

- `fields`: stored fields (nullable, or with a `default`; a required one on a populated table also needs `backfill`), formulas (read-time) and rollups (each writes its own field, which is the tenant's);
- `guards` and `invariants`.

```json basel-fragment
{
  "object": "Contact",
  "fields": {
    "customer_tier": {"type": "enum", "values": ["standard", "gold"], "nullable": true},
    "is_gold": {
      "type": "bool",
      "formula": "CASE WHEN row.core:customer_tier = 'gold' THEN true ELSE false END"
    }
  }
}
```

Refused:

| Code | When |
|---|---|
| `unknown_property` | any key outside an additions file's grammar |
| `addition_key_not_allowed` | `locks` (not yet supported) |
| `addition_field_required` | a required field with no default |
| `addition_field_ref` | a `ref`, `set` or `reference_choice` field |
| `object_not_extensible` | an object its package declares `extensible: false` |
| `package_not_listed` | an unlisted package |
| `unknown_object` | a name that is not a package object |

A package may not ship `additions/` (`package_ships_additions`).

#### Subtype families

An addition may target a family root or any of its kinds (`additions/crm/party.json` with `"object": "Party"`, `additions/crm/person.json` with `"object": "Person"`). One added to a kind belongs to that kind and the kinds below it. One added to the root belongs to every kind, including kinds a later package release adds, and so do the root's tenant guards and invariants.

The column lands in the shared family table (`crm__party`), nullable when a kind added it. Each kind's view, record JSON, reflection and generated forms show its own and inherited additions only. `FROM Party` reads a root addition and refuses a kind's, as for a package kind's own field. A kind's required-with-default addition is required of that kind's rows only: its `default` fills that kind's creates and its `backfill` fills that kind's existing rows.

- A name may be added once per family: adding `segment` both to `Party` and to `Person`, or to two sibling kinds, is refused (`addition_name_in_family`, naming both files) — add it to the root to share it.
- The shadow check covers the whole family: an addition named like a package field on any member is refused at push.
- A package release that changes the `extends` of an object carrying additions, or moves an object that inherits the root's additions to another family, is refused (`addition_family_changed`).

#### Naming

A name is qualified by its owner only where it sits on something another owner owns. Everything the tenant adds to a package object is `core:<name>` — `core:customer_tier` in BQL paths, record JSON keys, permits' and roles' field lists, forms, UI query ids and reflection — stored in the column `core__customer_tier`. It is declared short in the additions file and referenced qualified everywhere else, including that file's own guards and formulas (`row.core:customer_tier`, as above); the short name is not accepted at any door.

Relationship ends follow the same rule. An end one owner's relationship puts on another owner's object is qualified by the declarer: a tenant relationship to `crm:Contact` gives `Contact.core:notes`; crm-sales' gives `Contact.sales:deals`, and the permit action `relationship.sales:deals.reference`. Ends on the declarer's own objects and on built-ins stay short. Ends are authored short; writing `core:notes` in a relationship file is refused (`invalid_identifier`).

A package field and the tenant's addition with the same short name coexist; only a new addition shadowing a field the package already has is refused at push (`addition_shadows_package_field`). Clients must accept `:` in field keys, paths and query ids.

#### Authority

An addition is governed by the tenant's roles and field ceilings. A package role's `"read_fields": {"<Object>": ["*"]}` never covers it, and no package's code sees, writes or names it: a package function `scope` or module contract naming one is refused at push (`package_foreign_element`), and a package validator skips an update that changed only additions.

The tenant's guards and invariants on a package object run on every write to it, the package's own actions and functions included, and are judged as the tenant's. A refusal names the rule by its qualified element (`Contact.core:gold_keeps_name`) and carries an additive `"owner": "tenant"`, at the top level and on its `errors[]` entry, so a failing package action points at the tenant. The plan carries a `tenant_rule_on_package_object` advisory for each such object on install, upgrade and any rule change.

A tenant rollup's recompute changes the carrier's version (a client holding the old version gets a conflict), without a history entry, as for every rollup. A tenant permit that filters on an addition still decides which rows a package function borrowing the user's permissions sees.

#### Where additions show and what they pin

Generated views and forms list the package's fields, then the additions in authored order, then added formulas; an app's hand-built page shows only what it names. Reflection gives each added element `owner: "tenant"`, namespace `core` and its `additions/` file as provenance, while the object keeps the package's.

Removing an addition drops its column, or archives it when a record holds a value, as for any field you own (see "Removing a field, object or relationship"). While it exists, an addition pins its package. Removing the package, or upgrading to a release without the object, is refused while the file exists (`unknown_object`, `package_not_listed`, or `addition_needs_package` when the addition reaches another package, as a rollup over `sales:deals` does) and after it is gone (`package_object_has_additions`).

A package may close an object with `"extensible": false`; closing an open one in a minor or patch release is a break (`object_closed_to_extension`).

### What a package's code can and cannot see

A package function's own-data privilege reaches only its own objects, and only the fields its own package added to them — never a field another owner (the tenant, or another package) added to the same object, whether through a wildcard, a whole-row read, or a write payload.

Reading a dependency's exported objects is declared in the action's `scope`, using full names only — `crm:Contact`, never `Contact`. The wrong namespace refuses `wrong_namespace`; a short name for a dependency's element refuses `unqualified_dependency_reference`. These reads are filtered by the invoking user's own read policy on every read door — `get`, a traversal, a query, a count, a named query.

Writing to a dependency's objects, including consequential writes made by an action's own effects, is judged with the user's own permits, never the action's declared grant.

A field another owner added to an object (the tenant's `additions/`, see "Adding to a package's object (`additions/`)" above) is hidden from the package's code on every object, its own or a dependency's, for reads and writes. This holds even when the user could read it and even under an approved elevated read.

Concealment is probed before authority: a reference or a direct read/update/delete/transition naming a row the invoking user cannot see answers not found, exactly as if the row did not exist.

A function's own filter on a field it cannot see fails the whole invocation as a scope violation. A permit or guard condition reaching the same hidden data instead lowers that one step to `FALSE` — never `NULL` — and keeps evaluating. That is why `NOT`/ `IS NULL` can never be used to probe for a hidden row's existence, while an ordinary empty hop (nothing there at all) keeps its usual `NULL` meaning.

Formulas, stored rollups, validators, invariants and declared effects may not reach a dependency's data at all in this release — they run with no user permissions to borrow.

Everything a package ships is public; nothing about what code the tenant installed limits what that code can see beyond these rules.

## Worked metadata examples

Every example here is checked by Basel's own tests with the same compiler `basel validate` uses. Each is a `json basel-repository` block: a set of repository files, each introduced by a `# file: <path>` line that is not part of the file. Copy each file to its path as written.

The model-only examples declare no policy; add grants appropriate to your users before letting them operate on the records.

### Lifecycle with a guarded transition and an effect

The lifecycle creates its state field. Do not also declare `status` in
`fields`. A transition is an action that names the lifecycle it moves; it is
invoked through the action endpoint and needs an `If-Match` row version. It
is not a PATCH of the lifecycle field.

```json basel-repository
# file: basel.json
{"format": 2, "name": "lifecycle_example"}
# file: objects/work_item.json
{
  "name": "WorkItem",
  "description": "One piece of work someone owns until it is closed.",
  "fields": {
    "title": {"type": "text"},
    "resolution": {"type": "text", "nullable": true, "description": "Why it was closed; written by close."}
  },
  "lifecycles": {
    "status": {
      "description": "Closed is final: there is no transition back to open.",
      "initial": "open",
      "states": [{"name": "open"}, {"name": "closed", "outcome": "success"}]
    }
  },
  "actions": {
    "close": {
      "transition": {"lifecycle": "status", "from": ["open"], "to": "closed"},
      "params": {"explanation": {"type": "text"}},
      "guards": [
        {
          "name": "needs_title",
          "description": "Closed items appear in reports by title.",
          "assert": "row.title != ''",
          "message": "A title is required before closing."
        }
      ],
      "effects": [{"op": "set", "values": {"resolution": {"expr": "args.explanation"}}}]
    }
  }
}
```

### Relationship rollups and decimal division

`COUNT(row.<traversal> WHERE <predicate>)` counts matching related rows;
`SUM(row.<traversal> -> <field> WHERE <predicate>)` sums their values. Inside
the `WHERE`, `row.` is the related row being counted. A division of integers
has a decimal result. Use a stored rollup for maintained totals; formulas are
evaluated when read and have their own expression restrictions.

```json basel-repository
# file: basel.json
{"format": 2, "name": "budget_example"}
# file: objects/work_group.json
{
  "name": "WorkGroup",
  "fields": {
    "name": {"type": "text"},
    "active_count": {"type": "int", "rollup": "COUNT(row.entries WHERE row.active = true)"},
    "active_minutes": {
      "type": "int",
      "rollup": "SUM(row.entries -> minutes WHERE row.active = true)"
    }
  }
}
# file: objects/work_entry.json
{
  "name": "WorkEntry",
  "fields": {
    "minutes": {"type": "int"},
    "active": {"type": "bool"},
    "hours": {"type": "decimal", "formula": "row.minutes / 60"}
  }
}
# file: relationships/group_entries.json
{
  "name": "GroupEntries",
  "from": {"object": "WorkGroup", "name": "entries"},
  "to": {"object": "WorkEntry", "name": "group", "cardinality": {"max": 1}}
}
```

### Member edits only while the parent is open

A guard on the member reads the parent through the relationship's `max: 1` end, so time entries freeze when their matter closes while the matter itself keeps changing: its fields stay editable and it can still move through its lifecycle. A second guard, on the relationship, stops linking or unlinking entries of a closed matter; on a relationship, `row.from` and `row.to` are the two linked records. Declaring a `document_lock` on the matter's end instead would freeze the matter's own fields as well (see "Relationships").

```json basel-repository
# file: basel.json
{"format": 2, "name": "matters_example"}
# file: objects/matter.json
{
  "name": "Matter",
  "operations": ["create", "update"],
  "fields": {
    "title": {"type": "text"},
    "closing_note": {"type": "text", "nullable": true}
  },
  "lifecycles": {
    "status": {
      "initial": "open",
      "states": [
        {"name": "open"},
        {"name": "closed", "outcome": "success"},
        {"name": "archived"}
      ]
    }
  },
  "actions": {
    "close": {"transition": {"lifecycle": "status", "from": ["open"], "to": "closed"}},
    "archive": {
      "transition": {"lifecycle": "status", "from": ["closed"], "to": "archived"},
      "effects": [{"op": "set", "values": {"closing_note": "archived"}}]
    }
  }
}
# file: objects/time_entry.json
{
  "name": "TimeEntry",
  "operations": ["create", "update", "delete"],
  "fields": {"minutes": {"type": "int"}},
  "guards": [
    {
      "name": "matter_open",
      "on": ["create", "update", "delete"],
      "assert": "row.matter.status = 'open'",
      "message": "Time entries change only while the matter is open."
    }
  ]
}
# file: relationships/matter_entries.json
{
  "name": "MatterEntries",
  "operations": ["create", "delete"],
  "from": {"object": "Matter", "name": "entries", "nested": {"create": ["create"]}},
  "to": {"object": "TimeEntry", "name": "matter", "cardinality": {"max": 1}},
  "guards": [
    {
      "name": "matter_open",
      "on": ["create", "delete"],
      "assert": "row.from.status = 'open'",
      "message": "Entries are linked only while the matter is open."
    }
  ]
}
```

### Creating a parent with its members in one request, as a non-admin

A `clerk` creates an invoice together with its lines in one request. Basel commits it atomically, and a caller other than `admin` needs every grant below. Each permit grants one action, and no tenant action is needed:

- `create` on both objects, and on the relationship, whose `write` names `from` and `to`;
- `relationship.lines.link` on the parent (`lines` is the parent's end);
- `relationship.invoice.reference` on the member object (`invoice` is the member's end). Without it the request answers a bare `404`: a target the caller may not reference is treated as not found.

A relationship has no `read` action; a role reads its links through `read_fields` (here `"InvoiceLines": ["*"]`).

```json basel-repository
# file: basel.json
{"format": 2, "name": "billing"}
# file: objects/invoice.json
{
  "name": "Invoice",
  "operations": ["create", "update"],
  "fields": {"number": {"type": "text"}}
}
# file: objects/invoice_line.json
{
  "name": "InvoiceLine",
  "operations": ["create", "update", "delete"],
  "fields": {"description": {"type": "text"}, "qty": {"type": "int"}}
}
# file: relationships/invoice_lines.json
{
  "name": "InvoiceLines",
  "operations": ["create"],
  "from": {"object": "Invoice", "name": "lines", "nested": {"create": ["create"]}},
  "to": {"object": "InvoiceLine", "name": "invoice", "cardinality": {"max": 1, "min": 1}}
}
# file: policies/roles.json
{
  "roles": {
    "clerk": {
      "id": "role_clerk",
      "read_fields": {"Invoice": ["*"], "InvoiceLine": ["*"], "InvoiceLines": ["*"]}
    }
  }
}
# file: policies/invoice.json
{
  "object": "Invoice",
  "permits": {
    "clerk_reads_invoices": {"roles": ["clerk"], "action": "read"},
    "clerk_creates_invoices": {"roles": ["clerk"], "action": "create", "write": ["number"]},
    "clerk_links_lines": {"roles": ["clerk"], "action": "relationship.lines.link"}
  }
}
# file: policies/invoice_line.json
{
  "object": "InvoiceLine",
  "permits": {
    "clerk_reads_lines": {"roles": ["clerk"], "action": "read"},
    "clerk_creates_lines": {
      "roles": ["clerk"],
      "action": "create",
      "write": ["description", "qty"]
    },
    "clerk_references_invoices": {
      "roles": ["clerk"],
      "action": "relationship.invoice.reference"
    }
  }
}
# file: policies/invoice_lines.json
{
  "object": "InvoiceLines",
  "permits": {
    "clerk_creates_links": {"roles": ["clerk"], "action": "create", "write": ["from", "to"]}
  }
}
```

The request (a runtime request body, plain JSON data):

```json
POST /tenants/{key}/objects/Invoice
{"number": "INV-1", "lines": [{"description": "Design", "qty": 2}, {"description": "Build", "qty": 5}]}
```

### Counting a many-to-many relationship by a far-record field

A rollup or formula such as `COUNT(row.tags WHERE row.priority = 'hot')` is refused when the far end of `tags` does not declare `"cardinality": {"max": 1}`: in a many-to-many relationship one record can be reached by several links, so "how many related records match" has no single answer. A link aggregate (`COUNT(row.tags=>)`, `COUNT(row.tags=> WHERE <link property> = ...)`) counts links and reads only the relationship's own properties, never a field of the far record. There are two ways to count by a far-record field:

- copy the field onto the link as a relationship property and filter on it with the link form; or
- model the link as an object with two `ref` fields and count it with a correlated aggregate, as below. The aggregate names the object it counts bare (`ItemTag`); inside its `WHERE`, `row.` is the `ItemTag` being counted and `outer.` is the formula's own record.

```json basel-repository
# file: basel.json
{"format": 2, "name": "tagging_example"}
# file: objects/item.json
{
  "name": "Item",
  "fields": {
    "title": {"type": "text"},
    "hot_tags": {
      "type": "int",
      "formula": "COUNT(ItemTag WHERE row.item = outer.id AND row.tag.priority = 'hot')"
    }
  }
}
# file: objects/tag.json
{
  "name": "Tag",
  "fields": {
    "label": {"type": "text"},
    "priority": {"type": "enum", "values": ["normal", "hot"]}
  }
}
# file: objects/item_tag.json
{
  "name": "ItemTag",
  "fields": {"item": {"type": "ref", "to": "Item"}, "tag": {"type": "ref", "to": "Tag"}}
}
```

### API and authoring details

- Ad hoc queries use `POST /tenants/{key}/query` with
  `{"bql":"SELECT title FROM WorkItem"}` and return `{columns, rows, has_more}`. BQL
  is a runtime language: its names are bare, with no `row.` root.
- A query file `queries/<snake>.json` declares its own `name` and its
  `exposure`.
- PATCH and action requests use the target row's ETag as `If-Match`; fetch
  the current record first. Preserve a failed request's exit status when
  scripting validation or deployment (for example, use shell `pipefail`).
- A `set` effect clears a nullable field with JSON `null`
  (`{"op": "set", "values": {"note": null}}`); a required field refuses it.
- A lock's `unless` condition must depend on a record field; constant
  conditions are refused. `record_label` names an object's own field, not a
  dotted path.
- For a relationship create permit, `write` includes `from` and `to`.
  Relationship properties have readable fields; do not invent a
  relationship `read` permit.
- Use a per-command Git authorization header for cloning. Do not persist an
  Authorization `http.extraHeader` and then call `basel deploy` with its own
  Git token: duplicate Authorization headers are refused.
- Lifecycle `states` is an array of `{"name": ...}` objects, and an action's
  `guards` and `effects` are arrays. See "Metadata files at a glance" for
  every key's shape.
- A `formula` is a value, not a condition: a `bool` formula is written
  `CASE WHEN row.task_count > 20 THEN true ELSE false END`, not
  `row.task_count > 20`.
- A field or traversal named after an expression keyword (`order`, `date`,
  `end`, `limit`, `desc`, `in`, `is`, `case`, `when`, or any other keyword
  of the expression grammar) is refused inside an expression with
  `expected identifier`. Write the name in double quotes, escaped inside
  the JSON string (`"assert": "row.\"order\".status = 'open'"`), or rename
  it.
- A package source in `basel.json` `dependencies` may be
  `git+file:///absolute/path/to/repo` for a package repository on the same
  machine, as well as `git+https://…`.
## Tenants

This document names no tenant: it is served without signing in, and a server's tenants are not public. Sign in, then run `basel tenants list` or `GET /accounts/me/tenants` for the tenants your account created, and `GET /tenants/{key}/whoami` to confirm your membership in one; each tenant's own surface is at `/tenants/{key}/reflect`. An operator creates a tenant with `POST /control/tenants` and `{"key": "...", "admin": {"login"|"email": "..."}}`.

