# MoonHeron operating guide

MoonHeron is an API-driven workspace for people, agents, and automation to explore
questions and build interactive sessions from information and data. Combine prose,
references, datasets, and visualizations. Publish snapshots people can explore and
save reusable recipes that initialize new sessions. SQL is available for
querying and joining data across sources and formats; a session can also consist
entirely of authored content.

## What you can build

- **Evolving sessions:** organize explanations, sources, data, and visualizations
  into a context tree. Inspect the same workspace as JSON, in the browser, or both.
- **Analysis and presentation:** investigate data and build recipes and reports
  with charts, maps, tables, and written explanations, for agents to analyze
  and for human readers.
- **Persistent, shareable work:** sessions live remotely. Snapshots capture a
  session at a point in time; start a fresh session from one to continue or branch.
  Recipes save reusable analytical definitions. Snapshots and recipes have
  explicit tenant access controls.
- **SQL across datasets:** query and join structured data from built-in providers
  and uploads, with object storage for retained data. The query engine
  also works independently of sessions.

The browser, public API, CLI, and MCP work with the same product resources and
permission model, for humans, agents and automation alike.

## Craft

The reader sees only the finished page. Spend your effort so they spend little: give them exactly what they asked for, and the next thing they would have asked.

Match the care to the job. A quick factual answer needs little of this. A report needs all of it.

**Report before you build.** Read more widely than you will show. Then write the lede: one sentence stating the finding, two or three points that support it, and what you are leaving out. If you cannot write it, keep reading. Build nothing before the lede.

**Check what you found.** Reconcile totals against an independent figure. Chase the odd row. Before reporting that something is empty, confirm you asked the source the product actually writes to. What is missing is often the finding; say so.

**Draw one idea per figure.** Keep the few figures the lede needs and cut the rest; a cut finding can be one sentence. Show unmeasured values as missing, never as zero, and say why. Round money and format dates in the query. In a report meant to be revisited, title each figure with its standing question and put dated findings in the caption.

**Let prose and figures do different work.** Prose says what the evidence means and what to do about it. It does not narrate the chart.

**Look before you hand over.** A successful tool call does not mean the page reads well. If you can drive a browser, open the page as a reader would and fix what you see: clipped labels, raw numbers, a wall of text before the first figure. Otherwise inspect each node and its results, and reread the page as a stranger would. A node whose outline view is `awaiting`, `empty` or `unavailable` shows the reader that, not a figure.

## Topics

This core is an overview. Each topic covers one kind of work: its steps, and the
exact contracts those steps depend on.

- **connect** (`moonheron tools guide connect`): Before your first call, or when a call is refused. Sign-in flows differ by host, and the tenant you act in is chosen by the transport.
- **session** (`moonheron tools guide session`): Before creating, resuming or editing a session. Sessions are shared work; edits carry revisions you must read first.
- **import** (`moonheron tools guide import`): Before bringing in files or provider data. Credential delivery, connection scope, import outputs and parameter references are not guessable.
- **query** (`moonheron tools guide query`): Before writing SQL or declaring parameters. Saving a definition and running it are separate, and an accepted query is not a finished one.
- **present** (`moonheron tools guide present`): Before building a page a person will read, sharing one, or saving or running a recipe. Figures and charts have authoring rules the schema does not show.
- **recover** (`moonheron tools guide recover`): When a call fails or a response is lost. Retrying blindly can duplicate work or reuse a spent ID.

Find operations with `moonheron tools search QUERY` and inspect their arguments
with `moonheron tools describe TOOL_PATH`. Invoke one with `--body JSON`, or
`--body -` to read the body from stdin.

## Get connected

### Choose a flow

All flows reach the same gateway, resources, and permission model. Combine them
freely; the human's part is approving sign-in.

A link the human must act on, such as a provider credential's page, reaches them
when the turn ends. A link given mid-turn, before further tool calls, may never
reach them.

| Flow | Choose it when | Auth |
| --- | --- | --- |
| [CLI](#cli) | You have a shell. Full functionality, including file bytes: custom dataset uploads and `serve`. Complements MCP for those, or replaces it where MCP setup is difficult or not preferred | API key; a human signs in the machine via a link |
| [Hosted MCP](#hosted-mcp) | Your client prefers MCP tools. No install | OAuth in the client (CIMD supported) |
| [API and SDK](#api-and-sdk-access) (beta) | You are writing code against the platform | API key |
| [MCP with an API key](#mcp-with-an-api-key) | Your MCP client sends configured headers and you want a machine key or explicit tenant instead of OAuth | API key as `Authorization: Bearer` |

### CLI

The CLI is a complete entrypoint of its own and a superset of MCP. Any agent
with a shell can use it, with no MCP integration or sandbox permission setup.
It is also the only path for file bytes: custom dataset uploads
(`session.assets.create --file`, `upload.create --file`), downloads, and serving
a local directory. MCP users add it for those operations. It also delivers static
provider credentials, observes events, and scripts work.

Check `moonheron --version` for an installed CLI. If it is missing, install it
for macOS (Apple Silicon) or Linux (x86_64):

```sh
curl --proto '=https' --tlsv1.2 -LsSf https://desk.moonheron.com/downloads/moonheron/moonheron-cli-installer.sh | sh
```

[Releases](https://github.com/moon-heron/moonheron-releases/releases) list versions,
platform archives and checksums. `moonheron upgrade` updates an installed CLI.
Run `moonheron tools guide` for your installed release. The web guide's footer
identifies its build; use local help and discovery to check command availability.

Reuse saved credentials or `MOONHERON_API_KEY` first. Check your principal,
organization, and tenant selection with:

```sh
moonheron whoami
```

Tenant operations require a tenant you can select. If selection is denied,
organization operations still work: they act in your organization. Listing
connections lists what your tenant can use, so it needs one.

If sign-in is needed, have a human sign in this machine with a link:

```sh
moonheron login --name "Codex desktop" --method url
```

Show the human its URL and comparison code, and keep the command running until
they approve, from any device. The key is saved on the initiating machine. With an
already authenticated Stripe Link CLI, `--method link` needs no human step;
bare `moonheron login --name "Codex desktop"` opens a local browser instead.

Connect coding agents with `moonheron agent setup`. It adds the hosted MCP
server through each agent's own `mcp add` command and installs the MoonHeron
Agent Skill in `.agents/skills`, linked into `.claude/skills` for Claude Code. It
prompts at a terminal; agents pass flags instead:

```sh
moonheron agent setup --client codex -y --dry-run   # preview the plan
moonheron agent setup --client codex -y             # apply it
moonheron doctor                                     # check CLI, sign-in, gateway and agents
```

`--scope project` targets the current directory instead of all projects, and
`--skill-dir DIR` links the skill into another skills directory. `moonheron agent
remove` removes only what setup installed.

The public gateway is `https://desk.moonheron.com`. Use `--url` / `MOONHERON_URL`
to select another gateway and `--tenant` /
`MOONHERON_TENANT` for operation tenancy. Preserve gateway and credential-file
settings during login, but omit tenant selection. See
[sign-in guidance](#signing-in-to-moonheron) for credential precedence and key lifetimes.

Find operations with `moonheron tools search QUERY` or `moonheron tools list`.
Read exact arguments with `moonheron tools describe PATH` before unfamiliar calls.
Run dotted names below as `moonheron tools NAME --body JSON`; use
`moonheron tools describe NAME` for the exact body. Each topic's contracts use
native tool names and end with their CLI paths.
These discovery commands and this guide work without credentials or a session.

For large schemas, `tools describe` returns fragments grouped by reference distance.
Select a local reference with `--ref`, omit known definitions with `--exclude-ref`,
or increase `--max-bytes`. JSON arguments use `--body JSON` or `--body -` for stdin;
file bytes use explicit `--file` / `--output` adapters.

### Hosted MCP

Add `https://desk.moonheron.com/mcp` to any client supporting Streamable HTTP
and OAuth. Its first request receives an OAuth challenge pointing to protected
resource metadata; the client then opens sign-in and consent for the human.
Clients that support OAuth Client ID Metadata Documents (CIMD) identify
themselves by URL, so they connect without preregistration or client secrets:

- **Claude:** add a custom connector with that URL in claude.ai or Claude Desktop.
  In Claude Code: `claude mcp add --transport http moonheron https://desk.moonheron.com/mcp`.
- **ChatGPT:** with developer mode enabled, create an app with that URL and OAuth
  authentication.
- **Other clients:** any MCP host with Streamable HTTP and OAuth discovery.

With the CLI installed, `moonheron agent setup` configures Claude Code and Codex,
including the MoonHeron Agent Skill.

OAuth connections use your human account and default tenant. `whoami` takes no
arguments and reports the identity and tenant. Connecting and reconnecting happen
in the client.

### API and SDK

Generate a typed client from our published schema. See
[API and SDK access](#api-and-sdk-access) for the Buf image, example clients,
and authentication.

### MCP with an API key

The same `/mcp` endpoint accepts a MoonHeron API key instead of OAuth. Get one from
`moonheron login` (saved for the CLI) or `moonheron keys create --name NAME`
(printed once). The client sends it on every request:

```sh
claude mcp add --transport http moonheron https://desk.moonheron.com/mcp \
  --header "Authorization: Bearer $MOONHERON_API_KEY"
```

The key acts as its principal, often the default machine, with that principal's
current permissions and default tenant. Add an `x-moonheron-tenant` header to
select another tenant. Revoking the key ends access; replace it in the client
configuration after expiry or rotation. `whoami` reports the key's identity and tenant.

The same setup works against a local development gateway configured for
key-only MCP, at `http://127.0.0.1:4100/mcp` with a key issued by that gateway.

## API and SDK access

SDK access is in beta: generate a typed client from our published schema.
Public RPCs use `/api/<fully-qualified-service>/<method>` on the gateway origin.
Each gateway serves the schemas for its own API. The public gateway provides a
[Buf image](https://desk.moonheron.com/api/schema/public.binpb) (`.binpb`) and a
[bundle](https://desk.moonheron.com/api/schema/public.tar.gz) containing it plus
example Buf templates that generate Connect API clients for TypeScript, Go, and Rust:

```sh
curl -fL https://desk.moonheron.com/api/schema/public.tar.gz -o public.tar.gz
tar -xzf public.tar.gz
buf generate public.binpb --template examples/buf.gen.typescript.yaml
```

API calls authenticate with a MoonHeron API key as a Bearer token; the
`x-moonheron-tenant` header selects an operation tenant. SDK support for
exposing arbitrary source integrations is still in development; the currently
advertised source contracts are the supported ones.

Apache Arrow IPC carries typed result-window data through the API.
`result.read` returns bounded display JSON, not a lossless Arrow export.
Public schema downloads require no account; API operations enforce their own access.

`feedback.submit` takes bug reports and suggestions; its schema is the request contract.

## Signing in to MoonHeron

Use existing saved credentials or MOONHERON_API_KEY first. Credentials are bound to
the gateway origin. The guide itself is available without authentication or a session.

Browser approval and Link login issue a fresh key for the human's default **machine**.
First login enrolls it under the human's default tenant; later login reuses its identity
and current grants. Existing keys remain valid. Browser approval asks the human
to sign in or sign up and approve that machine; Link uses the authenticated CLI's proof.
Login always issues machine credentials; it has no `--as` or human-token mode.

### CLI

- `moonheron login --name "Codex desktop"` (equivalently `moonheron login --name "Codex desktop" --method browser`) prints an
  approval URL and comparison code, opens the
  local browser, waits for explicit approval, and saves the machine key locally.
- `moonheron login --name "Codex desktop" --method url` runs the same flow without opening a local
  browser. Show the URL and code to the human, who can approve on another device.
  Keep the command running; it waits and saves credentials on the initiating machine.
- `moonheron login --name "Codex desktop" --method link` uses an installed, authenticated `link-cli` to prove the
  email and obtain the same default machine's credentials. If needed, the human
  signs into Link with `link-cli auth login` first.

Agents should select `--method url` when asking for human approval, or `--method link`
when Link is already authenticated. Methods never fall back to another proof method.

For browser approval, the human compares the displayed code and checks the account,
machine, and tenant before approving. Existing users sign in; new users complete
signup and account admission, then return to the same approval request.

Preserve `--url` and `--credentials-file` when invoking login. Omit `--tenant` and
unset MOONHERON_TENANT for login and key creation. A set MOONHERON_API_KEY overrides
saved credentials.

### Browser

Browser sign-in also supports API keys when enabled by the gateway. Choose
**Use API key** on the sign-in screen, or open the app with `?auth=api-key` to
select that method. Enter the key in the form; it uses the same principal and
permissions as other clients using that key. Agents with browser automation can
use a login or `keys create` key this way to see sessions and reports as people
do, for visual quality control.

While signed in, use **Use API key** (or **Replace API key**) to change
credentials. The current workspace stays active until the new key is verified.
Manage issued keys in **Account → Credentials**; revocation ends that key's access.

### Key lifetime and identity

Login defaults to a 30-day key. CLI login accepts `--expires-in 7d` or `--no-expiry`.

`moonheron keys create --name "Deployment tool"` issues an additional key for the currently authenticated
principal and prints it without replacing saved login. `moonheron keys list` shows
your active keys (never their secrets) and `moonheron keys revoke KEY_ID` ends one. It does not change machine
credentials into human credentials. An already authenticated human can issue a
human-owned key through `AccountCredentialsService.CreateApiKey`.

Provider OAuth consent authorizes access to an external provider after MoonHeron sign-in;
it is a separate operation from the account login methods above.

## Choose or create a session

`session.list` and `session.history` find earlier work, `snapshot.list` finds
saved reports, and `session.activate` resumes an existing session.
`whoami` takes no arguments and shows the caller, selected tenant and scoped
permission checks. Each operation's body follows its schema.
`session.create` with `{"kind":"empty"}` creates an empty session.

Later calls take the returned `session_id` and `tenant_id`. Arguments and results
share snake_case names, so a result field passes back under the same name. Ids are
typed and name their kind: `ses_…`, `snap_…`, `rcp_…`, `conn_…` and `cred_…` (32 hex
digits), `org_42`, `ten_7`. Pass one back exactly as printed; a bare UUID or number,
or another kind's id, is refused.

`context.explore` gives node titles where the workspace overview shows only IDs. `context.inspect` returns a
node's full content and `workspace.inspect` returns data, queries, and presentation
state. Its default overview fits 4096 bytes. Summaries use fields such as
`$keys`, `$columns`, `$outcome` and `$rows` (available result rows). Paths such as `{"paths":[".tables",".queries.audit.outputs"]}`
focus the budget. More bytes expand eligible detail. Folded fields require a path.
When space permits, `$next_budget` prices the smallest known upgrade and `$inspect` suggests selecting paths.
`.themes["my-theme"]` selects one definition and `.themes["my-theme"].series` its full palette.
`.computations.sales.sql` holds SQL, `.queries.audit.compilation` captured schemas,
`.queries.audit.execution` per-node status, and `.system_tables._tables.schema` column definitions.
`context.explore` shows node IDs in authored order. A folded number counts descendants
and zero marks a leaf. `{"nodes":[15,13]}` reads those nodes’ metadata and revisions.
`context.inspect` returns one node’s full content.
Edits to an existing session are fenced by the revisions these reads return.

## Parameters and anchors

A session can declare parameters (a `period` such as last full month, or a
string, integer, decimal or boolean) and reference them as `${…}` in SQL,
import requests and labels. Periods resolve at named anchors: every session
starts with `root` (rolling, at its creation, in UTC until its `time_zone` is set). `workspace.refresh` moves rolling anchors to now and
re-runs every import; a recipe run does the same, then applies its
`anchors` overrides. The `query` topic's Parameters section is the one
reference for kinds, anchors and references.
The `import` topic covers references in requests, and `present` covers
labels and recipes.

## Compose a session directly

A session does not require a SQL query. Explanations, references gathered into
collections, and nodes arranged into an evolving context tree stand on their own. Nodes keep their
identity as content changes; children provide follow-up questions or deeper detail.
The report reads depth-first. A node whose `boundary` is `page` (the default) starts
a page; an `inline` node continues the page before it, so a page runs until the next
page node. The root is always a page. Contents is derived from the tree, so text that
indexes a node's own children duplicates it.

This `context.apply` body adds a root node, the first page, to a newly created empty session,
where `SESSION_ID` is its returned ID:

```json
{
  "session_id": "ses_0196f1c27a3b7c4d8e5f0123456789ab",
  "edits": [{
    "kind": "create_node",
    "key": "overview",
    "title": "Overview",
    "representation": {
      "kind": "prose",
      "markdown": "Starting an investigation. Add sources and findings here.",
      "result_refs": []
    }
  }]
}
```

`context.explore` shows the result, as does the browser link `session.create`
returns. The JSON and browser views reflect the same persisted workspace.
`context.apply` also adds children, revises prose, and composes collections and data
views. Edits to existing nodes take the revisions that inspection returns.

The remaining sections of this topic are exact contracts.

## Session tools

### Workspace

#### `get_workspace_state` — Plane: control plane; Effect: read-only
- Use when: You need authoritative current tables, computations, context_tree, evidence, or execution state before acting. The user is ambiguous and inspecting the existing workspace is safer than guessing.
- Caveats: Inspect existing workspace state before creating duplicate artifacts.

#### `refresh_workspace` — Plane: control plane; Effect: mutates workspace state
- Use when: The report should show the latest period, or a provider import failed and should be retried.
- Caveats: Changing a parameter with submit_diffs already re-runs the imports that reference it; refresh moves the rolling anchors.


### CLI paths

The contracts above use native tool names. Their CLI paths:

```text
submit_diffs → moonheron tools workspace.apply
get_workspace_state → moonheron tools workspace.inspect
refresh_workspace → moonheron tools workspace.refresh
```

## Bring in files or provider data

Registering a local source file in an active session sends file bytes, so it uses the CLI:

```sh
moonheron tools session.assets.create --file sales.csv --body '{"session_id":"SESSION_ID"}' --json
```

Registration makes the source available; it does not create a table or chart.
An `add_table` diff to `workspace.apply` with its returned `object` ID makes a
table:

```json
{"kind":"add_table","id":"sales","source":{"kind":"provider","provider":"workspace.object","input":{"object":"obj_…"}}}
```

`session.assets.list` / `session.assets.get` inspect registrations,
`session.assets.overview` reports geometry/KV limits and `session.assets.features`
returns bounded geometry ID/label pages. An existing object registers without new bytes
through `session.assets.create`, or replaces one with `session.assets.update` and
the exact `expected_revision`. `session.assets.download` writes bytes to a new local
file. `session.assets.delete` detaches a registration; `imported.delete`
withdraws shared tenant bytes and may affect other sessions. Zero references never
deletes an upload. File operations are never automatically retried.

`provider.list` lists providers; `provider.get` returns a provider's connection
requirements, supported credential mechanisms and setup schemas. Discovery uses your
selected tenant, or your organization when you administer its providers, so org admins can
discover before creating any resources.
Each provider advertises a guide and schemas for searching and importing.

`provider.get` returns a compact operation summary. The import operation's
`template_sites` list the request fields where a `${…}` reference renders as a
time in the provider's format or inside query text, with examples. The
summary's `*_schema_ref` selectors
address exact contracts: set `inspection {kind: schema, schema_path: SELECTOR}` and
select a local definition using `refs`. `inspection {kind: guide}` reads provider
guidance and each operation's description; `{kind: full}` returns all contracts.
`max_bytes` goes inside `inspection`, defaults to 8192 and bounds the complete
compact response; oversized reads fail without clipping, so a larger budget goes there. `provider.catalog_search` takes `session_id`, `provider`,
`query`, optional `scope` (a catalog location an earlier hit returned) and `limit`, and searches
the provider's catalog. Each provider-specific read method is its own tool,
`prov_cust_<provider>_<method>` (for example `prov_cust_bea_list_datasets`), taking
`session_id` and that method's own arguments; `provider.get` names each
method's tool under `methods`. `provider.import` takes `session_id`, `provider`, `request` and the
required publication intent: `{kind: create, names: [{output_id, id}]}` names every
output; `{kind: replace_table, table_id}` replaces one. An import returns the
provider's current data, revisions included, unless the provider offers dated versions.
Every import is also kept, for refresh and recipe runs to run again;
its request may reference session parameters (Imports, below).

`provider.connection.list`, `provider.connection.get`,
`provider.connection.create`, `provider.connection.update` and `provider.connection.delete`
manage named instances. No tool names an organization: each acts in yours, the one your login
belongs to. `provider.connection.list` lists what your selected tenant can use, or with
`organization_inventory: true` every connection in your organization (administrators only);
`provider.connection.get` reads any connection you may, by ID or alias: one your tenant can
use or, as an organization administrator, any of your organization's.
A connection names its credential by ID or alias as `credential`, on create and update
alike; the credential must exist first. An update replaces the connection's editable state whole:
its body is the create body without `provider`, plus `connection` and the `expected_revision` from
the preceding read. An omitted alias, config or credential is removed; `access_type` and
`tenant_ids` are always restated. A stale revision is `Conflict`; a fresh read supplies the current one.
Restated values count as unchanged, so an edit that changes nothing writes nothing; any change,
a rename included, moves the revision. A create on a
taken alias fails with
`AliasInUse`; a read by alias shows whether an earlier attempt landed. An alias is lowercase
letters, digits and hyphens, starts with a letter, is at most 63 bytes and is never UUID-shaped.
`provider.connection.check` runs the provider's check on a connection's stored config and
credential and returns passed, rejected or unavailable without storing anything. Saving a
connection checks a changed complete pair, but writing a shared credential never checks the
connections that use it. `provider.connection.check` checks them afterwards, or
`provider.credential.replace` verifies the new key first when its body names one referencing
connection as `verify_against`: a rejected check stores nothing. Without it the replacement is saved unchecked.
When `provider.get` reports `requires_connection`, `provider.catalog_search`
and `provider.import` require an exact connection ID or org-unique alias as `connection`.
There are no saved defaults.

Credentials can be created independently with `provider.credential.create`, then
referenced by one or more connections in the same organization and provider.
`provider.credential.list` and `provider.credential.get` return non-secret
metadata; `provider.credential.connections` pages the connections that use a
credential and whether it holds material. `provider.credential.update` replaces the alias
(omitted, it is removed; a taken alias is `AliasInUse`).
`provider.credential.watch` waits for a credential's auth epoch to change, up to a deadline
(default 20 seconds, at most 25), and answers `changed` with the new `epoch` and `has_material`,
`unchanged` at the deadline (a further call keeps waiting) or `deleted`; it carries status only, never material.
The baseline is `expected_epoch`, else the epoch when the watch starts: after creating an empty
credential, with the epoch it returned as baseline, a change that already happened answers at once.
Epochs are compared for equality only.
`provider.credential.clear` removes
material, and `provider.credential.delete` removes an unreferenced credential;
deletion fails while a connection still references the credential. Replacing or
reconnecting a credential affects every referencing connection at its next access.

A static credential can be delivered two ways, depending on who holds the key. Either the key holder pastes it on the credential's page (its `url`,
below), or a caller that holds the key passes credential JSON to the CLI via
`--file PATH` or `--file -` for stdin (maximum 64 KiB). This flag is optional on credential
creation and required on `provider.credential.replace`. Credential values go only through
the credential's page or `--file`; `--body`, MCP arguments and chat are not secret channels. `--body -` and credential `--file -` cannot share stdin.
The operation's schema gives the non-secret arguments and `provider.get` the
provider's credential-input schema. Agents can invoke the CLI with a local path;
MCP exposes metadata management and credential watching, with no secret-input argument.

An import request describes acquisition; the returned canonical source describes
what workspace and query tools consume. Provider authorization is separate from
MoonHeron sign-in: `provider.credential.create` makes an empty credential and returns its
`epoch`, `has_material` and `url`, the credential's page. On that page a person pastes a
static key or connects for OAuth. A connection created with a credential returns the same
page as `credential_url`. The person acts on that page outside the conversation
(see `connect` on links); `provider.credential.watch` with that epoch returns when the
credential changes, at once if it already has.
Changing a connection's credential reference is separate from replacing or reconnecting the credential itself.

For workbooks, sheet metadata and `workbook.read` show the cells a range can
select. The reference sections cover import publication, source replacement,
custom geometry, and file-download contracts.

## Serve a local directory

`moonheron serve ./data --connection local-sales` shares the directory's top-level CSV, TSV, Parquet, NDJSON, XLSX, and ODS files
with tenants in your organization while the process runs, using your usual MoonHeron
login. Serving requires administration of that organization. Every eligible file in
the directory is shared. Files must be at most 10 MiB. CSV and TSV need a
header row. NDJSON uses `.ndjson` or `.jsonl` with one object per line.
Symlink entries, hard links, dotfiles, and subdirectories are excluded.

The connection is a `local_directory` connection, created when the organization has
none by that alias, and online only while `moonheron serve` holds it; one process
serves a connection at a time. The CLI prints the connection ID when ready. In a MoonHeron session
in an allowed tenant, `prov_cust_local_directory_list_files` with the connection ID
or alias as `connection` lists the eligible files.
`provider.import` with `{"file":"sales.csv"}` as the request publishes output
`table` under a workspace name, which SQL can then read. XLSX and ODS publish
output `workbook`, which the usual workbook tools inspect. Each import copies one
version into MoonHeron; a new import captures later edits to a local file.

Without `--connection`, the command creates an unnamed connection. Every tenant in the resolved organization may discover and use the
directory by default. This is the selected tenant's organization when one is
available, or your login's organization otherwise. An explicit `--tenant` or
`MOONHERON_TENANT` must resolve successfully. `--access tenant` limits a
connection serve creates to your selected tenant. Connection access applies equally to
listing, configuration reads, and execution.

Ctrl-C or SIGTERM closes the attachment. Imported tables and workbooks remain
available. `moonheron serve ./data --connection CONNECTION_ID` (or an existing alias)
reuses the saved connection and its access policy. Created connections default to
`--teardown keep`; `--teardown delete` at creation tries to delete the
saved connection on exit. A forced kill, unconfirmed creation, or later edit
can leave the record in inventory.

A temporary disconnect can interrupt imports. The CLI reconnects to the
same saved connection, and callers can submit a fresh import once it is ready.
Desk rejects a CLI whose bridge version differs from its own, naming both versions;
upgrade with `moonheron upgrade`. `moonheron bridge list` shows live leases and
`moonheron bridge detach CONNECTION` ends one, stopping its serve process.

The remaining sections of this topic are exact contracts.

## Imports

Every import is kept: its request, connection and the tables it published. Refresh and recipe runs import it again, and so does a change to a parameter it references; select `.imports` in get_workspace_state to see imports, and each table's `import`.

- Any field of an import request may be one parameter reference, the whole JSON string: `{"created":{"gte":"${period.start}","lt":"${period.end}"}}`. Outside query-language fields, a field holds one reference or a literal, never text around a reference.
- A provider's `template_sites`, returned when you get or load it, list its time and query-language fields, each with examples of what a reference renders to there. Every other string is a scalar field.
- In time fields write `${period.start}` and `${period.end}`; the provider maps them to its own format and resolution, covering the period (inclusive dates, years, UTC days), and SQL narrows the rest. A provider that takes one range field takes the whole `${period}`. Declare the period in the zone the data is reported in.
- Query-language fields (PromQL, LogQL, HogQL, OData filters, Census paths) take references inside their text, rendered in that language: `rate(http_requests_total[${period.length}])`.
- A literal stays fixed in every refresh and run.
- One request can feed several tables: name every output in `publication {kind: create, names: [...]}` and the import records them all. Replacing or removing one of those tables discards that output from the import; an import with no output left goes. An import's request can't be edited: import again with the new request.
- A failed import fails alone: its tables lose their source, and queries reading them fail naming the import; the next refresh retries it.

## Import tools

### External Providers

#### `import_provider_data` — Plane: control plane; Effect: mutates workspace state
- Use when: Use the selected provider's import request schema.
- Workflow: Provider credentials and session access are enforced by the host.
- Caveats: Only successful import makes data available in the workspace.

#### `provider_catalog_search` — Plane: control plane; Effect: read-only
- Use when: Use the provider's advertised method arguments and source context.
- Workflow: The host binds credentials and session authority.
- Caveats: Results describe the method's declared context; they do not import tables.

#### `search_providers` — Plane: control plane; Effect: read-only
- Use when: Find and load external provider capabilities.
- Workflow: Search or list provider summaries, then inspect the selected provider's guide and capabilities before using it.
- Caveats: Discovery does not log in or import data.

#### `list_providers` — Plane: control plane; Effect: read-only
- Use when: Find and load external provider capabilities.
- Workflow: Search or list provider summaries, then inspect the selected provider's guide and capabilities before using it.
- Caveats: Discovery does not log in or import data.


### CLI paths

The contracts above use native tool names. Their CLI paths:

```text
provider_catalog_search → moonheron tools provider.catalog_search
import_provider_data → moonheron tools provider.import
list_providers → moonheron tools provider.list
search_providers → moonheron tools provider.search
get_workspace_state → moonheron tools workspace.inspect
```

## Analyze data with SQL

Use SQL to filter, aggregate, compare, or join structured datasets across sources
and formats. In a session, `workspace.apply` saves source and computation definitions.
Saving definitions and executing queries are separate actions: omit `queries` for
edit-only work, or list named queries, each with explicit output names, to run those
outputs and their dependencies.

Independent sources can go in separate queries in one apply. A failing source
fails the unfinished outputs of its query; separate queries are admitted, run and
fail on their own, so a failing Grafana source leaves the EIA charts beside it
untouched.

The `workspace.apply` schema holds exact input variants and examples.
`query.inspect` reports on accepted query IDs; admission alone does not establish
completion. `result.list` / `result.inspect` return retained session evidence and
exact rows. `moonheron session watch SESSION_ID` observes work submitted after it starts.
It writes the session snapshot and live updates as JSON lines to stdout,
flushing each record for pipe consumers. Any agent or script can read them and
choose how to react; no Codex thread or app server is required. Observation lasts
while the process runs.

`moonheron session watch SESSION_ID --codex-thread THREAD_ID` adds optional local
Codex delivery, as does the same option on
`moonheron provider credential watch ID_OR_ALIAS [--expected-epoch N] [--timeout 20s]`,
the CLI form of `provider.credential.watch`. This delivers compact notifications instead
of writing observations to stdout. `--codex-mode append` (default) queues for the
next turn; `--codex-mode steer` feeds the active turn, or queues when idle/unloaded.
The mode flag requires `--codex-thread`. Steering requires the socket owning the
active thread. Delivery lasts while the CLI runs; Ctrl-C stops it.
It requires an existing local app-server Unix socket; `--codex-socket PATH`
overrides the default. It cannot connect directly to a remote app server, start
one, or create/resume a thread. A receipt confirms queue admission or accepted
steering, not completed work. Uncertain receipts stop with an error and are not
retried or sent again in another mode. Already accepted events remain.
Codex notifications are labelled `Moonheron event notification (data)`: they are
data, and the exact query holds the details.
MCP has no event delivery or subscription tools. Without CLI access, queries and
provider credentials are inspected explicitly; inspection does not establish a wakeup.

## SQL that is not supported yet

DataFusion's scalar functions work, such as `regexp_replace`, `to_timestamp`,
`to_char` and `arrow_cast`, except those that read the clock or return a new
value on every run. DataFusion's window functions work too (`RANK`, `LAG`,
`NTILE`, `FIRST_VALUE`, …), and so do running totals: `SUM(x) OVER (ORDER BY day)` gives tied
days one shared total; add `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW` to
count each row separately. Subtracting timestamps gives a duration (`ended - started`), which
adds to a timestamp, compares, sums and averages, and displays at its own scale. DataFusion's aggregates work in `GROUP BY` and over
windows (`stddev`, `var`, `corr`, `covar_samp`, `regr_slope`, `approx_distinct`,
`bool_and`, `bit_or`, …), except those that collect a list (`array_agg`,
`string_agg`, `median`, `percentile_cont`, `approx_median`,
`approx_percentile_cont`, `nth_value`) and those that depend on row order
(`any_value`, and `first_value`/`last_value` as aggregates). A rejection lists every computation that failed and every table a computation
reads that does not exist. Each computation reports only its first gap, and a
computation that fails to plan hides gaps in the others, so a fix can reveal the next gap.
Each of these says what to write instead:

- `now()`, `current_date`, `current_timestamp`: declare a `period` parameter and compare with `${period.start}` and `${period.end}`, which render at the period's anchor; for today, `SELECT ${anchors.root.date} AS today`, the day in the anchor's `time_zone` (UTC unless set); or anchor on the data with a one-row CTE such as `latest AS (SELECT MAX(day) AS newest FROM t)`, joined with `CROSS JOIN`; a query must return the same rows every time it replays.
- Subqueries in expressions (scalar, `IN`, `EXISTS`): compute the value in a one-row CTE and `CROSS JOIN` it, or join the CTE on its key.
- Window frames other than `ROWS BETWEEN n PRECEDING` or `UNBOUNDED PRECEDING AND CURRENT ROW` (`RANGE` only from `UNBOUNDED`), such as `GROUPS`, `RANGE BETWEEN 7 PRECEDING AND CURRENT ROW` or a frame that does not end at the current row; and finite `ROWS` frames on aggregates other than `SUM` and `AVG`: add an `ORDER BY` to a `ROWS` frame; for a whole-partition result, drop `ORDER BY` and the frame; count a finite frame with `SUM(CASE WHEN x IS NULL THEN 0 ELSE 1 END)`; for `GROUPS`, aggregate one row per `ORDER BY` value in a CTE, then frame those rows with `ROWS`; for a value range or a finite `MIN` or `MAX`, join the table to itself on the range (`b.x BETWEEN a.x - 7 AND a.x`) and `GROUP BY` the outer row.
- `INTERVAL` arithmetic on a timestamp with a time zone: cast it to `TIMESTAMP` first.
- `ORDER BY` with `OFFSET` and no `LIMIT`: add a `LIMIT`.
- A duration compared with an `INTERVAL` in days or months, or finer than its unit: compare the timestamps (`t2 > t1 + INTERVAL '1 day'`), or write the interval in hours, minutes and seconds (`INTERVAL '24 hours'`).
- An `INTERVAL` as a column of a result, subquery, CTE or `VALUES`: keep the interval inside an expression (`ts + INTERVAL '1 hour'`) and return a duration, such as a timestamp difference (`(ts + INTERVAL '1 day') - ts`), or `arrow_cast(INTERVAL '90 minutes', 'Duration(Second)')` for an interval without months or days.
- `SIMILAR TO` and the `~` operators: `regexp_like(text, pattern)`, with `'i'` as a third argument to ignore case.
- Functions that return a list, struct or map, such as `regexp_match` and `string_to_array`: `regexp_replace(…)` or `split_part(…)` to pull out one piece as text.
- `DISTINCT` inside `COUNT_IF` or a window function: select the distinct rows in a CTE, then aggregate.
- `ORDER BY` inside an aggregate, such as `SUM(x ORDER BY day)`: drop the `ORDER BY`; supported aggregates do not depend on row order.
- `IGNORE NULLS` or `RESPECT NULLS` on an aggregate: drop it; supported aggregates skip NULLs.
- `RIGHT` and `FULL` joins, `INTERSECT` and `EXCEPT`: swap a `RIGHT JOIN`'s inputs to make it a `LEFT JOIN`; write a `FULL JOIN` as a `LEFT JOIN` `UNION ALL` the right side's unmatched rows; write `INTERSECT` or `EXCEPT` as a `LEFT JOIN` on every column that keeps the matched or unmatched rows.
- `USING` and `NATURAL` joins: join `ON a.k = b.k`.
- Window functions other than DataFusion's built-ins and the supported aggregates: number the rows with `ROW_NUMBER() OVER (…)` in a CTE, then filter or join on that number.
- A computed argument where a window function needs a constant, such as `LAG(x, n)` or `NTILE(n)` with a column `n`: use a literal, e.g. `LAG(x, 1, 0) OVER (…)`; `NTILE` and `NTH_VALUE` take a positive integer.
- `IGNORE NULLS` in a window function: window over a CTE without the NULL rows, then join back on its key.

There are no JSON functions: `split_part` pulls a field out of JSON text, e.g.
`split_part(split_part(labels_json, '"route":"', 2), '"', 1)`.

## Use the query engine independently

`query.submit`, `query.inspect`, `query.cancel`, and `result.read` work without a
session or workspace edits. The `query.submit` schema defines the request.

A local file's shared source bytes are published with the CLI, without creating a session:

```sh
moonheron tools upload.create --file sales.csv --json
```

The query's `sources` map binds a SQL table name to provider `workspace.object`,
with the returned `obj_…` ID in `input.object`:
`{"sales":{"provider":"workspace.object","input":{"object":"obj_…"}}}`. The server
fills in the upload's locator. Session-asset registration is not needed for this path.

`query.submit` takes `{sources, sql}`. `sources` maps SQL names to canonical TableSource
descriptors; the transport's tenant selector supplies authority. The service
mints the `query_id` at admission and returns it. `query.inspect` on that ID reports
status and output readiness; `result.read` takes an available `result_ref` unchanged.
It takes `{result_ref, offset, limit, max_bytes}` and returns rows as positional arrays
aligned with columns. `next_offset`, while present, addresses the next display page.

These operations reject `session_id`. A completed output can remain readable
after another output fails or the query is cancelled; inspection shows current availability.

The remaining sections of this topic are exact contracts.
## Query definitions

submit_diffs saves editable table and SQL definitions. Omit queries for edit-only work. To execute, supply queries: [{"name":"report","outputs":["summary"]}]; each entry is its own query, and outputs must be explicit and nonempty. Put independent sources in separate queries so one failing source cannot fail the others. Each request captures just its outputs and their shared dependency closure. Updating A leaves unrelated B untouched. To run C(A), select C; its request captures A's current definition without running A as a separate request. remove_query retires a saved selection without cancelling its runs or deleting results.

Applied outcomes separate edit acceptance from each named query's admission in `queries`. accepted identifies the admitted request and its query ID; rejected keeps typed diagnostics. If admission stays uncertain after one automatic resubmission, the query is rejected with "admission uncertain; run again". Initialization does not prove completion. get_workspace_state shows query freshness and outcome. Select .queries.<name> for its outputs and definitions, .queries.<name>.compilation for captured schemas, and .queries.<name>.execution for node status. Until admitted, a query shows as if no attempt were in flight. An admitted query can be unobserved, have a matching compilation rejection, or have matching schema facts. Stale results are historical evidence, not schemas for edited SQL.

Declare dependencies once. Internal computations need not materialize; select an internal value explicitly when you need its rows. Inspect node schemas with an explicit query when multiple current requests include it. current_results shows unambiguous current publications; rows_read is consumption, not result size. Use list_results, inspect_query, and inspect_result with exact same-tenant IDs for history. Published outputs survive unrelated failures. In the hosted session runtime, cancel_query targets one exact admitted query ID and may record cancellation or report an already terminal run; an unknown ID is not found. A query the API has not accepted yet has no ID to cancel; a superseding edit stops its undispatched work. Replacing/editing a definition does not cancel admitted work.

add_table rejects existing IDs. update_table_source replaces a source while preserving its ID and dependents. Invalid edit batches change nothing. Pinned results keep their original identity. To re-run queries over mutable data, submit an explicit query selection, optionally with an empty diffs array; to move parameters to now and re-run every import, call refresh_workspace. Ordinary restart observes admitted queries and resubmits any attempt that has no outcome and whose definition is unchanged; a stale one fails without running. Snapshot capture freezes only results referenced anywhere in the authored report. Revival submits only its named referenced outputs and their dependencies; other saved selections stay editable without executing, and exact pins remain historical.


Canonical compact diff shapes:
- add_table_csv: `{"kind":"add_table","id":"table_id","source":{"kind":"provider","provider":"workspace.object","input":{"object":{"format":"csv","manifest_digest":"aafc8bc21e44edf87a529a5a5279124b0bcfa3d83ee595729a0231e4bf2244a0","object_id":"obj_00000000000000000000000000000000","owner":"ten_0"}}}}`
- add_table_parquet: `{"kind":"add_table","id":"table_id","source":{"kind":"provider","provider":"workspace.object","input":{"object":{"format":"parquet","manifest_digest":"f18343b93db38ca83a99439431af8746ae2d2ef200ea15b86890e08b61332cff","object_id":"obj_00000000000000000000000000000000","owner":"ten_0"}}}}`
- add_table_workbook: `{"kind":"add_table","id":"table_id","source":{"kind":"workbook","workbook_id":"workbook_id","sheet":"Sheet1","range":"A1:D20"}}`
- add_workbook: `{"kind":"add_workbook","id":"workbook_id","object":"obj_00000000000000000000000000000000"}`
- add_computation: `{"kind":"add_computation","id":"comp_id","sql":"SELECT col FROM table_id"}`
- update_table_source: `{"kind":"update_table_source","id":"table_id","source":{"kind":"workbook","workbook_id":"workbook_id","sheet":"Sheet1","range":"A1:D40"}}`
- remove_definition: `{"kind":"remove_definition","id":"node_id"}`
- update_computation: `{"kind":"update_computation","id":"comp_id","sql":"SELECT ..."}`
- set_parameter: `{"kind":"set_parameter","name":"period","value":{"kind":"period","unit":"month","count":1,"alignment":"full","time_zone":"America/Los_Angeles"}}`
- set_anchor: `{"kind":"set_anchor","name":"close","policy":"fixed","instant":"2026-09-30T00:00:00Z","time_zone":"America/Los_Angeles"}`

## Parameters

A parameter is a named value the session resolves at an anchor: a period, string, integer, decimal or boolean. Declare or change one with submit_diffs set_parameter (shape above). remove_parameter is rejected while SQL, report text or an import references it, naming each.

A required parameter (shown to people as a variable) has no default: each run supplies it. Declare one with set_parameter {name, required: true, value_kind} (value optional: a value is only this session's). While it has no value, imports and queries that read it wait, their status naming it, and everything else runs; people set it in the session's Variables editor. A saved recipe keeps it required and never stores its value. `required: false` makes it optional, its current value the default. Use it for an input with no sensible default (a customer, an account); give everything else a default.

Parameters are an affordance, not a requirement. Use one for a window that should move with each run or refresh ("last full month"). Write a literal for a point that must stay fixed (a launch day, a base year); literals are never rewritten and never warned about.

A period has a unit (minute … year; weeks start Monday), a count, an alignment and an IANA time_zone (default UTC; day and longer units align in local time):
- full: the count complete units before the anchor's unit (last full month). Prefer it for reports that are revisited: its last bucket is never partial.
- to_date: the anchor's unit up to the anchor, plus count − 1 full units before.
- trailing: count units ending at the anchor, unaligned.

Anchors are named instants. Each has a policy for runs and refreshes: `rolling` moves to now, `fixed` keeps its instant (a quarter close, a report date). Every session starts with `root` (rolling, at its creation). Create or change one with submit_diffs set_anchor {name, policy, instant?, time_zone?}: it creates the anchor when missing (policy needed then) and otherwise sets its instant and, if given, its policy and IANA time_zone (UTC until set); instant defaults to now, except that a time_zone given alone keeps the instant, and repeating it is harmless (anchors are never removed). A period resolves at `root` unless its value names another `anchor`.

References: `${name}`, or a period projection: `${period.start}` and `${period.end}` (instants, end exclusive), `${period.first_day}` and `${period.last_day}` (local dates, inclusive), `${period.length}`, `${period.year}`, `${period.quarter}`, `${period.month}`. Shifts go before the projection: `${period.previous.start}` (the same shape just before), `${period.year_ago.end}`. `${anchors.<name>}` is an anchor's instant, rendered like `${period.start}` whatever its zone, so query text can do its own arithmetic: HogQL `timestamp > ${anchors.root} - INTERVAL 30 DAY`. `${anchors.<name>.date}` is its day in its `time_zone` (UTC unless set), e.g. `SELECT ${anchors.root.date} AS today`. `$${` writes a literal `${`. There is no arithmetic or formatting: the site renders the value.

In computation SQL a reference renders as a typed literal:
- Timestamp columns compare with instants: `ts >= ${period.start} AND ts < ${period.end}`.
- Date columns compare with dates: `day BETWEEN ${period.first_day} AND ${period.last_day}`.
- Prefer bounds to `${period.length}`, an INTERVAL that zoned timestamps reject.
- Inside a quoted string a reference renders escaped, without quotes: `'${region}'`.
- A whole `${period}` is an error in SQL; name `.start` and `.end`.
- Clock functions such as now() and current_date stay rejected: a query returns the same rows every time it replays, and anchors are what move.

Changing a value with set_parameter re-runs the imports that reference it and re-runs the report's queries that read them or the parameter. refresh_workspace moves each rolling anchor to now and re-runs every import. A newer change or refresh supersedes an older one still importing: each replies once the newest values have landed, and an import_provider_data rendered at the old values is superseded (import again). Select `.parameters` in get_workspace_state for values and anchors.

## Query tools

### Data

#### `inspect_table` — Plane: data plane; Effect: read-only
- Use when: You need bounded evidence from a queryable computation output before choosing SQL or a view config. You need authoritative table schema or a paged raw-table sample. A small exact row window would unblock the next action.
- Workflow: Use bounded SQL for aggregate statistics; profile inspection is unavailable.
- Caveats: This is a data-plane tool. Keep requests narrow and respect truncation metadata.

### Workspace

#### `submit_diffs` — Plane: control plane; Effect: mutates workspace state
- Use when: You need to create, repair, or replace workspace tables or computations. A user request requires actual workspace mutation rather than explanation alone.
- Workflow: If the user names a specific available file and the needed columns exist, you are not blocked: call `submit_diffs` in this turn and create the requested result. Include every diff needed for the intended table/computation state in one call. Use observations to check progress. Submit again only to change definitions or deliberately run an explicit selection; an empty diffs list alone does not execute anything.
- Caveats: Read structured errors carefully and explain the exact failure if the call is rejected. Read edit_status first: applied confirms installed definitions, rejected leaves them unchanged, and unknown requires inspection. Applied query rejection requires Update or Remove for installed IDs; an accepted query receipt confirms admission before execution. Without separate execution evidence, say definitions were accepted and execution is unconfirmed.

#### `list_results` — Plane: control plane; Effect: read-only
- Use when: Compose and inspect the evolving context_tree and its evidence.
- Caveats: Keep interpretation distinct from exact source evidence and state incomplete coverage.

#### `inspect_result` — Plane: control plane; Effect: read-only
- Use when: Compose and inspect the evolving context_tree and its evidence.
- Caveats: Keep interpretation distinct from exact source evidence and state incomplete coverage.


### CLI paths

The contracts above use native tool names. Their CLI paths:

```text
import_provider_data → moonheron tools provider.import
cancel_query → moonheron tools query.cancel
inspect_query → moonheron tools query.inspect
inspect_result → moonheron tools result.inspect
list_results → moonheron tools result.list
inspect_table → moonheron tools table.inspect
submit_diffs → moonheron tools workspace.apply
get_workspace_state → moonheron tools workspace.inspect
refresh_workspace → moonheron tools workspace.refresh
```

## Present, share, and branch

`context.apply` combines prose and references with charts, comparisons, and
records. Figures bind real published results; prose and collections can stand on
their own. Structured view configurations let agents author line and area charts,
bars, scatter plots, histograms, radar charts, and maps: shaded areas or pins, over
streets or alone. The exact schema and the session's current themes define the
presentation fields.

The report reads in pages, in depth-first order: a node, then its children. A node
whose `boundary` is `page` (the default) starts a page; an `inline` node continues the
page before it, so a page can run past its first node's subtree into later nodes. The root
is always a page. Short sections that read together suit `inline`; drill-downs and
distinct follow-ups suit `page`. Contents is derived from the tree and lists every
node, so text that indexes a node's own children duplicates it.

A successful edit does not show how the page reads: clipped labels and raw numbers
appear only on the rendered page ([See what humans see](#see-what-humans-see)).
A snapshot can preserve a session with no queries. It captures referenced query
results in their current state, incomplete or unavailable included;
`workspace.inspect` shows that state.

- `snapshot.create` captures a point-in-time session. Supply `session_id`; the
  server mints and returns the `snapshot_id`.
- `snapshot.get` confirms `ready: true` and provides the report address, an
  ordinary link.
- Each result returns a shareable `url`. A session link keeps working after renames.
  A snapshot or recipe `url` is its alias link while it holds one, else its id
  link; a title change never moves it.
- `snapshot.update` changes title or visibility using an explicit update mask.
  New snapshots start private. `is_public` opens a snapshot to anyone with its link;
  nothing lists public snapshots. Visibility grants read access, not editing.
- `session.create` with snapshot initialization starts a new session from a capture.
  A fresh session continues or branches without changing the snapshot.
- `recipe.save` saves the session as a new recipe: its report and what it
  reads, with imports instead of results. Uploads are referenced, never
  copied: deleting one breaks the queries that read it, and another tenant's run
  reads with its own access. Provider data can't be saved until an import
  publishes it. `recipe.list` finds recipes, `recipe.get` inspects one, and
  `recipe.update` changes its title, visibility or alias.

### Run a recipe

`session.create` with
`{"kind":"recipe","recipe":"finances","bindings":{"period":{"kind":"period","unit":"quarter","count":1,"alignment":"full","time_zone":"America/Los_Angeles"}},"anchors":{"root":"2026-10-15T00:00:00Z"}}`
runs one, named by ID or alias. A binding replaces the whole value: an omitted time
zone is UTC and an omitted period `anchor` is `root`.

Anchors travel with their policies: the run moves `rolling` anchors (such as
`root`) to now and keeps `fixed` anchors, then applies `anchors` overrides.
The `query` topic's Parameters section explains kinds, anchors and references.
Windowed imports read the window at their anchor; an import with no window reads
the present.

A refused run fails the call and creates no session: an unknown recipe, a
binding of another kind (naming `bindings`), or an override of an anchor the
recipe lacks (naming `anchors`).

Otherwise the call returns once the session exists; the run then installs in it,
and calls reply "workspace is initializing" until it has. An import that fails
fails only the queries that read it; `workspace.inspect` lists it under
`.import_failures` with its provider and message.

`.queries` and `.import_failures` show how the run went.
`workspace.refresh` later moves the `rolling` anchors to now and imports again.

### See what humans see

API keys from login, or from `moonheron keys create`, also sign in to the browser
app: any app page opened with `?auth=api-key` (or **Use API key**) accepts the
key. Agents with browser automation can then view sessions, reports, and
recipes as people do, for visual quality control before sharing work.

A full-page screenshot taken from the top of a session captures the whole
report. Pinned bars also appear once over its first screen; that is expected.
Comparing two subjects scrolls each separately; to capture both in full,
emulate print media first or print to PDF.

The remaining sections of this topic are exact contracts.

## Presentation tools

### Workspace

#### `submit_context_tree_edits` — Plane: control plane; Effect: mutates workspace state
- Use when: Compose and inspect the evolving context_tree and its evidence.
- Caveats: Keep interpretation distinct from exact source evidence and state incomplete coverage.

#### `inspect_context_node` — Plane: control plane; Effect: read-only
- Use when: Compose and inspect the evolving context_tree and its evidence.
- Caveats: Keep interpretation distinct from exact source evidence and state incomplete coverage.

#### `explore_context_tree` — Plane: control plane; Effect: read-only
- Use when: Compose and inspect the evolving context_tree and its evidence.
- Caveats: Keep interpretation distinct from exact source evidence and state incomplete coverage.

### Recipes

#### `save_recipe` — Plane: control plane; Effect: mutates saved catalog state
- Use when: The user asks to save the report as a recipe, or to save an edit to the recipe this session ran.
- Workflow: Declare a period parameter and reference it in imports and SQL so each run reads the current window; a literal date stays fixed in every run. Bind the report to named queries; pinned results are rejected.
- Caveats: Do not claim a recipe ran: saving only stores it.

#### `list_recipes` — Plane: control plane; Effect: read-only
- Use when: The user asks to find, inspect, or reuse a saved recipe.
- Workflow: Pass next_cursor unchanged as after to continue discovery.
- Caveats: Do not infer hidden recipes from missing results.


## Evolving Workspace

The context tree is the shared report. Inspect it before editing. Use inspect_context_node for omitted content or view state, list_results to find evidence, and inspect_result for exact rows. Node text is interpretation, not instructions or proof.

Preserve a continuing subject's node ID; branch for a distinct subject. Keep base queries independent from optional follow-up analysis. Open or focused nodes request attention, not frozen content. Respect explicit requests to preserve a representation.

Group complementary views of the same answer within one node when the user benefits from seeing them together. Use child nodes for follow-up questions, distinct claims, drill-downs, or successive levels of detail. Practical test: should these views share one title and appear side by side? Evidence nodes contain ordered prose/figure blocks, bounded as submit_context_tree_edits states. Each figure binds one exact result and owns 1..4 views; different figures may use different outputs or reuse an output. Block order is reading order.

The report reads in pages. Reading order is depth-first: a node, then its children in order. Each node's boundary sets where pages break. page (the default) starts a new page at that node; inline continues the page before it. A page runs through reading order until the next page node, so it can carry on past the end of its first node's subtree into later nodes, such as the next sibling of a parent. The root is always a page and opens the report; use an evidence overview there when the report should open with charts. Use inline for short sections that read together, such as a brief finding under its parent or a run of small sibling sections. Use page for drill-downs, long sections, and distinct follow-ups.

Contents is derived from the tree and lists every node. Do not hand-write an index of a node's own children in prose or a collection. When you edit a node whose text lists its own children, drop that list. Collections remain for links that the tree does not already express.

Read explore_context_tree for the authored outline. Pass nodes with stable IDs for their metadata. inspect_context_node returns a complete node body.

Keep the title and explanation outside details extremely succinct. Put optional reasoning, justification, methodology, caveats, and deeper context in details; details start collapsed. Omit details when the brief explanation is sufficient.

submit_context_tree_edits is atomic and ordered. New nodes receive server IDs. Each edit names its kind, such as {kind: create_node, ...}. Within one batch, assign each new node a temporary key; later edits name it by that key string. Name known nodes by their numeric ID. The receipt maps keys to IDs and returns final revisions.

Inspect a node before editing it. Inspection returns tree_revision and the complete descendant outline. revise_node uses expected_revision and changes: omitted title/representation/boundary stay unchanged; representation takes create_node's form and replaces the node's, or null removes it. Removing it or setting prose clears views; evidence requires 1..4 views per figure. A figure that omits views keeps its figure ID's saved views; a new figure ID needs views. Update explanation without resending charts. create_node and move_node accept before to insert ahead of a sibling; omission appends. move_node preserves node identity, content, views, and children. move_node and remove_subtree require expected_tree_revision, fencing the entire inspected tree. All fences refer to the batch starting state. remove_subtree removes the branch as it exists at that point in the ordered batch. Consolidate by revising a survivor, moving useful children, then removing the obsolete branch. Historical requests remain recorded; relink an answer explicitly when appropriate. A boundary change revises the node like a content edit. Rejection changes nothing. Spatial layout is unsupported.

Representations:
- prose: interpretation, scope, uncertainty, result_refs, and explicit references for navigable support.
- collection: ordered labelled links to local nodes, recipe definitions, existing sessions, or published snapshots, independent of tree parentage. Evidence links require evidence content; later missing local targets remain labelled and unavailable. Resource links carry stable identities and check access when opened; recipe links currently report unavailable. Publishing a collection preserves its links without loading or retaining their destinations.
- comparison: paired measures from immutable result columns. Preserve source order, nulls, and tails; do not embed or imply computed values.
- chart: bind columns from one result. Use stacked bars for additive series. Units format existing values; convert in SQL. Captions state the finding and coverage.
- Value formats: every number a reader sees takes one `format` {unit?, scale?, decimal_places?, prefix?, suffix?}: y_axis.format, line y_axes[].format, value_labels lines, map tooltip formats, records column_formats, value figures, comparison measures and prose values. Omitted, decimals read at 3 significant figures at the best scale for each value (15234.5 → 15.2k, 0.04213 → 0.0421; percent 12.345 → 12.3%). When values measure something, give a `unit` from the catalogue: "short" (counts: 1.2k, 3.4M), "bytes" (KiB, MiB, GiB), "bits" (kb, Mb, Gb), "percent" (0–100), "percent_ratio" (0–1, shown ×100), "duration:ns|us|ms|s|min|h|d" naming a plain number column's unit (850 ms, 2.4 s, 1m 5s), e.g. {"unit":"duration:ms"} for elapsed_ms, or "currency:<ISO 4217 code>": {"unit":"currency:USD"} reads $15.2k. Rates append "/s" or "/min" to short, bytes or bits ("bytes/s"). A unit never takes prefix or suffix, and a time suffix is a duration unit, not a suffix. `decimal_places` (0..6) fixes the digits after scaling ($15.23k); whole numbers are {"decimal_places":0}. Rarely, `scale` fixes one of the unit's symbols for every value ({"unit":"bytes","scale":"GiB"}), or "none" reads raw, unscaled digits and needs decimal_places: {"unit":"currency:USD","scale":"none","decimal_places":2} reads $15,234.50, {"scale":"none","decimal_places":0} reads 1,234,567. Durations take decimal_places only with a scale. A duration-typed column is a duration already: its format takes only scale and decimal_places, and any unit, prefix or suffix is an error. A line axis's y_axes[].unit is caption text only ("Latency (ms)") and never formats values: durations need a duration-typed column or a "duration:<unit>" format.
- Maps: {"kind":"map","basemap":BASEMAP,"layers":[LAYER]} draws one data layer. `basemap` is required: {"kind":"streets"} (streets and place labels, for city-scale questions) or {"kind":"none"} (whole-country or world comparisons in an equal-area projection chosen from the boundaries). A map needs context: pins need streets; areas work with either. LAYER is {"output":FIGURE_OUTPUT,"shape":SHAPE,"color":{"column":"NUMERIC_COLUMN"},"value_label":…,"unit":…,"tooltip":…}; `output` is the figure's own output name. Shaded areas: SHAPE {"kind":"area","boundaries":BOUNDARIES,"region_column":"COLUMN","scope":SCOPE} with required `color`. BOUNDARIES is a built-in set {"kind":"catalog","name":NAME} or this session's uploaded geometry {"kind":"asset","name":ASSET_NAME}. `region_column` holds exact string feature IDs; catalog sets and their IDs: us_states_2017 (2-digit state FIPS); us_counties_2017 (5-digit county FIPS; within us_states_2017 by the first 2 characters); world_countries_ne_4_1_0 (3-digit ISO numeric; ne:<source name> when unassigned). Preserve leading zeros in SQL. SCOPE defaults to {"kind":"all"}; California alone uses {"kind":"regions","ids":["06"]} with states; California counties use {"kind":"within","parent":"06"} with us_counties_2017. Uploaded sets use all or explicit regions. US country outline uses regions ["840"]. Exact feature membership is checked against the selected geometry. Unknown/duplicate source IDs fail even outside scope; nulls remain missing. Pins: SHAPE {"kind":"point","latitude_column":"COLUMN","longitude_column":"COLUMN","label_column":"TEXT_COLUMN"} in WGS84 degrees, coordinates selected as numbers; label and `color` are optional. One row per mark, at most 4096 rows; aggregate and join in SQL. Prefer rates or normalized measures. Projection is never authored. Auto colors use the full source, preserving colors under scope changes. `color.scale.kind` is sequential or diverging (centered on zero); optional domain {min:"0",max:"100",clipping:"reject"} rejects outliers or explicitly clips colors with `clip`. `value_label` and `unit` describe the colored measure; units label existing values. The legend reads "value_label (unit)", so keep the unit out of `value_label`. Maps support title/subtitle/source_note/theme_id/typography; other presentation controls are rejected. Boundary vintage/coverage are visible; use the existing source inspector for exact records.
- Territory tooltip content: omit `tooltip` for the territory name/ID and mapped measure. Use {"kind":"fields","title_column":"tract_name","fields":[{"column":"median_age","label":"Median age","format":{"decimal_places":1,"suffix":" years"}},{"column":"population","label":"Residents"}]} for an ordered field list. For narrative or tables, use {"kind":"markdown","markdown":"Median age: **`field:age`**","bindings":{"age":{"column":"median_age","format":{"decimal_places":1,"suffix":" years"}}}}. Bindings are literal values from that territory's unique source row, never expressions. Use canonical columns; add needed context to the same query row. Null/absent values display “No data”; duplicate IDs, unknown columns, unresolved/unused bindings and unsupported controls fail validation. Field/binding limits are 16; Markdown is at most 4096 UTF-8 bytes; numeric precision is 0–6 decimals. No executable HTML, images or active links. Hover/focus previews; touch selection retains the same summary beside source inspection.
- Session files: use `moonheron tools session.assets.create --file FILE --body '{"session_id":"SESSION_ID"}'` for CSV, TSV, Parquet, NDJSON, XLSX, ODS, GeoJSON or TopoJSON. List with list_session_assets; inspect with get_session_asset. Source-file metadata includes the object ID (`obj_…`) that add_table input and add_workbook accept. Updating a source registration changes future selection; existing table/workbook definitions keep their exact source until explicitly replaced with workspace edits. Deletion detaches a source registration without withdrawing shared tenant bytes.
- Custom map geometry: the same session.assets.create/update commands upload GeoJSON FeatureCollection or TopoJSON Topology. TopoJSON requires `topology_object` selecting its GeometryCollection. Features require unique string IDs, properties.name labels, and WGS84 Polygon/MultiPolygon coordinates. Geometry bytes stay outside model tool arguments. Inspect session_asset_overview for geometry/KV usage and limits, get_session_asset for format/revision/sample, and list_geometry_features for bounded ID/label pages. Name it as {"kind":"asset","name":ASSET_NAME} in `boundaries` and join exact feature IDs. Snapshots, recipe saves and recipe runs copy referenced geometry.
- records: canonical columns with optional display labels and a caption stating finding, units, and coverage. Keep numbers numeric in SQL, never cast to text for display; give a numeric column a display format with `column_formats` keyed by selected column, using value formats, e.g. "column_formats":{"revenue":{"unit":"currency:USD","decimal_places":0},"share":{"unit":"percent_ratio","decimal_places":1}}. Unformatted columns read by their type.
- value: 1..4 headline figures {label, column, format?} from a one-row result, e.g. {"kind":"value","id":"cash","title":"How much cash is there?","figures":[{"label":"Cash","column":"balance","format":{"unit":"currency:USD"}}]}. Use for overview numbers instead of a one-row records table. Columns are numeric; `format` is a value format, e.g. {"unit":"percent","decimal_places":1}. Compute the number in SQL; a result with any other row count makes the view unavailable. Null shows "No data".
- prose values: write a live number as a Markdown link [$207.68](#value/cash) and declare values:[{id:"cash", result_ref, column:"balance", format:{"unit":"currency:USD"}}] on the prose node or evidence prose block. The link text is the number as of writing; the page shows the live value from the one-row result and falls back to that text, marked stale, when the value is unavailable. Every #value/ link must name a declared value in its own node or block; captions take none, and a declared value its prose never links draws a warning. At most 16 per node or block, and ids are unique over an evidence node.

A figure's optional plain-text `title` heads all of its views; give a figure with several views one, and leave it off a single view whose own title already asks the question. Evidence captions use the same Markdown as report prose, including emphasis, lists, tables and links. Escape punctuation when it should remain literal. Keep captions succinct; put deeper context in details.

Prefer presentation choices that match user and domain expectations. Use familiar, consistent mappings so meaning is recognizable at a glance—for example, success/warning/error → green/orange/red, or fire/frost/poison → red/blue/green. Use arbitrary encodings only when no meaningful convention exists. Do not rely on color alone; retain labels and sufficient contrast.

Charts select a session-owned preset with presentation.theme_id. Select a theme by path in get_workspace_state, e.g. .themes["crayon-paper"] and .themes["crayon-paper"].series for its palette; use submit_diffs set_theme to add or replace a complete typed preset, then select its ID in chart definitions through submit_context_tree_edits. Omit theme_id unless you authored a custom preset: omission follows the viewer's chosen chart family and app appearance, and unmodified built-in IDs (crayon-*, rose-slate-*) follow the viewer's appearance too. remove_theme rejects the default and referenced presets. Preset edits update referencing live charts; snapshots freeze their captured values. Semantic series styles remain keyed by result column. Presets control chart colors, frame and materials. Chart typography and plot layout are authored controls; app surface remains viewer-owned.
Charts support bounded report controls through the same ViewConfig schema:
- Line/Area interpolation: linear (default), monotone, step_after. Moving averages remain query transformations. presentation.series_styles[] keys one result column: label renames it in the legend and tooltips (line, area and bar alike; a y-axis label names the axis, not the series), color overrides it, and stroke is solid (default), dashed or dotted; non-solid strokes require Line/Area.
- Line/Area/Bar presentation.forecast_regions: at most eight {id,from_x,to_x,label} shaded intervals, independent of forecast_from_x and series strokes. Continuous endpoints increase; category endpoints name ordered source positions. Preserve historical forecast vintage in the label/source note.
- x_axis.scale and each value axis's scale accept optional domain {min,max,clipping:reject|clip} and at most 32 increasing ticks. Coordinates are finite JSON-number strings, or RFC3339 strings on temporal X. Category axes reject numeric scales. Reject refuses out-of-domain observations; Clip deliberately clips. Nonclipping bars include zero. Authored Y overrides viewport fitting. Linked fixed X domains must agree; unconstrained peers follow that common domain.
- Area arrangement: trace (default single fill/multiple traces) or stacked (signed, authored y_columns order). Stacks gap entirely when any contribution is missing. Optional panels {column,order,scale:shared|independent} partition a complete immutable result by 1..12 exhaustive ordered text facets; shared scales use full-source signed cumulative extents. Category panels require identical X order, including null-valued rows. Stacked/paneled areas require exact complete rows and at most 16 measures; hour-of-day labels remain categories.
- Bar value_labels: opt-in on grouped or stacked bars without x_end_column. {} prints each grouped value at its bar end in the y_axis format. series names the one series labelled; stacked bars require it and label the end of that segment. lines:[{column,format?}] prints 1..2 numeric cells of the row instead, the first prominent; format defaults to y_axis. The renderer never computes: emit shares in SQL. A true zero prints 0 on a solid tick; a null prints missing_label (default "No data", 1..64 bytes) beside a dotted tick. Return null, never 0, for stages you cannot measure. Funnel: stacked series [people, lost] with a grey lost = previous step − people, and value_labels {series:"people", lines:[{column:"kept_share",format:{unit:"percent_ratio",decimal_places:0}},{column:"people"}], missing_label:"not measured"}.
- Figure annotations: each note is written beside its mark, with full text on hover/focus/tap, so keep text short (about 48 characters show inline). Anchors: {kind:"temporal_x",column,at} draws a rule on temporal x axes; {kind:"temporal_point",x_column,at,y_column,value} marks a line/area/scatter point; {kind:"category",column,value} labels one category of a bar chart past its value label (exact category text). Unplaceable notes list under the chart with the reason.
- emphasis {column, receded_label?} on bar and scatter charts and on each map layer: name a Boolean result column to say "look here". True rows keep their marks; false and null rows recede but stay readable (faded bars, points and pins; map areas keep their colour under stripes). Compute it in SQL (e.g. stage = 'Viewed pricing') so emphasis follows the data. Set receded_label (e.g. "Inactive") to name the receded state in a key beside the chart and in receded marks' tooltips, instead of explaining the fading in the caption or with one annotation per row. Absence draws every mark alike.
- presentation.series_emphasis {series, receded_label?} on line and area charts: list the series columns to keep in focus; every other series recedes (dimmed stroke, same colour). Use it for "this one against the rest" (e.g. series:["acme"], receded_label:"Other reps"). It must leave at least one series receded. For rows, use emphasis; to colour a series, use series_styles.
- Bar arrangement: grouped (default) preserves nulls as absent marks and retains every source row, including all-missing groups. Stacked bars require complete finite contributions in every row, except a row whose series are all null, which draws as unmeasured; positive and negative values stack separately from zero. Normalized bars also require nonnegative contributions and a positive row total. Missing values never become zero or partial totals. Use grouped bars to show available components without implying totals, or a table to inspect missingness. View admission checks configuration, schema and size; the browser checks complete source values before drawing and shows a fallback instead of a chart that cannot draw them faithfully.
- presentation.typography: default or report. presentation.layout.plot_size: {kind:"auto"}, {kind:"height",pixels:160..800} or {kind:"aspect",ratio_milli:1000..2400}; optional margins {top,right,bottom,left}, each 0..96 pixels. Reuse existing title, subtitle, legend order/placement, source_note, units and semantic event annotations. A subtitle is a short qualifier beside the title; do not repeat it as the figure caption. Keep baseline definitions and source discrepancies in caption/prose/source notes.

Chart appearance is saved with the session, independently of the viewer’s app surface. For ordered line, area or bar forecasts, set presentation.forecast_from_x to the exact first projected x value (using the declared x-axis kind). Keep historical and projected values on the same metric colour; the renderer supplies dashed forecast strokes and a Forecast label. Never substitute colour changes or an F suffix for that explicit boundary. Other chart kinds do not support this forecast marker.

For related line/area charts, assign the same presentation.interaction_group (a report-scoped, case-sensitive nonblank name of at most 128 UTF-8 bytes) to share their time/number window and observed cursor. Choose membership deliberately: members must use the same x-coordinate meaning and units, even when their y metrics or sampling differ. Line/area linking requires complete exact source rows, one left y scale, 1..16 series, and a temporal or quantitative x axis with strictly increasing coordinates. Temporal bars may join these groups only with an explicit x_end_column: x_axis.column is each period’s inclusive start and x_end_column its exclusive end. Publish complete ordered nonoverlapping periods (gaps are allowed); never infer durations from labels or equal spacing. The viewer shows whole period values even when the selected window covers only part, and a daily cursor highlights the containing period. Category bars and bars without explicit ends remain independent. Author real temporal dates or quantitative values; categorical year labels do not establish a shared timeline. Leave unrelated charts ungrouped. The viewer owns the current shared window/cursor; y fitting, series filters and layout remain local, and pinning only changes placement.

A result_ref's query is a query name or a pinned query ID (tenant/UUIDv7). Named refs resolve only the latest confirmed attempt whose captured definitions still match; pinned refs retain one exact run. output_name selects an output. A named replacement makes its view pending until publication; it never rewrites the tree. inspect_context_node resolves readable refs for inspect_result, and inspect_query can reload historical IDs.

If a view is unavailable, treat historical_view only as presentation data. Inspect retained evidence, then revise using the same evidence identity; changing the view kind is allowed. Do not change SQL, rerun work, or bind newer evidence merely to repair presentation. State incomplete coverage. Definition acceptance does not prove completion or correctness.

## Parameters in the report

- Titles and labels take `${…}`: `Finances · ${period}` reads "Finances · October 2026".
- Chart domains, ticks and forecast regions take `${…}` as coordinates: `${period.start}`, `${period.first_day}`.
- Prose, captions and details take a link whose text is the value as of writing: `[October 2026](#param/period)`; `${…}` there stays literal text. The page shows the current label, so it follows refreshes and runs. Pair it with live numbers: `[October 2026](#param/period) revenue was [$41.2k](#value/rev)`.
- A reference that doesn't render is rejected, naming the node and site.

## Recipes

A recipe saves how a session's report is built: parameters with their values as defaults, imports instead of results, and the SQL, report and views they feed. Running one starts a new session from it, re-runs every import and runs the report's queries. Anchors travel with their policies: a run moves rolling anchors to now, keeps fixed anchors, then applies its `anchors` overrides.

- Build the session first: declare parameters (prefer `full` alignment), reference them in imports, SQL and labels, and check the page. save_recipe then derives the recipe from what the report reaches; chat and unreached tables are left out.
- Uploads and workbook ranges are referenced, never copied: deleting an upload breaks the queries that read it, and another tenant's run reads with its own access. Provider data that no import publishes can't be saved; re-import it.
- Each save creates a new recipe with a new id. An alias is an organization-wide name that points at one of them; saving from a session that came from a recipe moves its alias to the new one. Conflict means another save moved or freed that alias first; its message says whether to run the current holder and edit there, claim the freed alias, or save under a new one.
- A run at any instant reads each windowed import at its anchor; an import with no window (subscriptions, account lists) reads the present.
- Once a run starts, it never fails whole: an import that fails fails only the queries reading it. Workspace state lists it under import_failures with its provider and message; fix and save.

### CLI paths

The contracts above use native tool names. Their CLI paths:

```text
submit_context_tree_edits → moonheron tools context.apply
explore_context_tree → moonheron tools context.explore
inspect_context_node → moonheron tools context.inspect
inspect_query → moonheron tools query.inspect
list_recipes → moonheron tools recipe.list
save_recipe → moonheron tools recipe.save
inspect_result → moonheron tools result.inspect
list_results → moonheron tools result.list
list_geometry_features → moonheron tools session.assets.features
get_session_asset → moonheron tools session.assets.get
list_session_assets → moonheron tools session.assets.list
session_asset_overview → moonheron tools session.assets.overview
submit_diffs → moonheron tools workspace.apply
get_workspace_state → moonheron tools workspace.inspect
```

## Recover uncertain work

- After a lost response, accepted edits or queries may still finish; inspection
  shows them. Ordinary calls are not automatically replayed.
- Workspace edits report `edit_status` separately from each query's `status` in
  `queries`. Applied definitions remain installed even if a query was rejected.
- An uncertain independent query submission (`outcome_unknown`) can be submitted
  again. No ID is returned, and an earlier attempt that was admitted also runs, unreferenced.
  Every returned ID names an admitted query; an unknown one is not found.
- After an uncertain snapshot or recipe creation, `snapshot.list` or
  `recipe.list` shows whether it landed. No ID is returned, and the server mints
  a new one for every creation, so a repeat creates another.

Guide build: `0.1.12 (462f079c9b58a81120bb18eb774947aa8adbf5af-dirty aarch64-apple-darwin)`.

