# state

> Distributed key-value state management — registers the `state::*` functions and `state::on-changed`, a private function observers watch for every committed change.

| field | value |
|-------|-------|
| version | 0.23.1 |
| type | binary |
| license | Apache-2.0 |
| repo | https://github.com/iii-hq/workers |
| supported_targets | x86_64-apple-darwin, aarch64-apple-darwin, x86_64-pc-windows-msvc, aarch64-pc-windows-msvc, x86_64-unknown-linux-gnu, aarch64-unknown-linux-gnu, x86_64-unknown-linux-musl, armv7-unknown-linux-gnueabihf |
| author | iii |

## installation

```sh
iii trigger compose::add worker=state@0.23.1
```

## configuration

```yaml
- adapter:
    config:
      store_method: file_based
    name: kv
```

## dependencies

- `configuration` @ `latest`

## readme

# state

Distributed key-value state storage with scope-based organization and an
observable change event. Values are addressed by a `scope` (namespace) and a
`key`, shared across every worker connected to the engine, and persisted
through a pluggable adapter (`kv` or `redis`). Callers reach the store
through `state::set`, `state::get`, `state::delete`, `state::update`,
`state::compare-and-set`, `state::list`, `state::list_keys` and
`state::list_groups` (the [Functions](#functions) table lists every function
the worker provides), and after every
successful mutation the worker calls `state::on-changed` with a
`state:created`, `state:updated`, or `state:deleted` event, so downstream
functions observe data changes without polling. This worker is the
standalone migration of the engine's legacy built-in state service.

## Install

Workers can reserve private scopes with `state::claim-namespace`. Their internal
`<worker>::state::compare-and-set` accessor accepts `durable: true` to flush the
adapter before acknowledging the operation. It also flushes an unmatched retry,
so a cleanup that previously changed memory but failed to persist can be retried
safely. The default is `false`; the public state API is unchanged. Durability
follows the configured adapter's existing flush guarantees.
The private response includes `durable: true` only after a requested flush
succeeds, allowing callers to detect workers that do not support the option.

```bash
iii call compose::add worker=state
```

`iii call compose::add` resolves the worker and its dependencies, writes
exact declarations to `worker-compose.yaml`, and reconciles the Compose project.

## Functions

| Function | Input | Returns | Fires |
|---|---|---|---|
| `state::set` | `{ scope, key, value }` (`data` accepted as an alias for `value`) | `{ old_value, new_value }` | `state:created` (new key) or `state:updated` |
| `state::get` | `{ scope, key }` | the value, or `null` | — |
| `state::delete` | `{ scope, key }` | the deleted value, or `null` | `state:deleted` (even when the key did not exist) |
| `state::update` | `{ scope, key, ops }` — ordered atomic ops: `set`, `merge`, `increment`, `decrement`, `append`, `remove` | `{ old_value, new_value, errors }` | `state:created` or `state:updated` |
| `state::compare-and-set` | `{ scope, key, expected?, value }` — writes `value` only when the stored value equals `expected`; without `expected`, only when the key is absent | `{ swapped, current? }` — `current` is the stored value when the swap did not happen | `state:created` or `state:updated` when it swaps |
| `state::barrier` | `{ event, condition_config: { id, expect, key_from?, carry? } }` — records one arrival at the barrier `id`: `expect` is a count or the list of arrival keys, `key_from` a JSON pointer to the arrival key in `event` (default `/key`), `carry` a JSON pointer to the value to keep (default: the whole event) | `{ decision: "allow", payload, reason }` exactly once, on the arrival that completes the set (`payload` carries every arrival's value); `{ decision: "skip", reason }` otherwise | — |
| `state::claim-namespace` | `{ functions_prefix, scopes }` — `functions_prefix` must equal the calling worker's name | `{ claimed, scopes, functions }` — the scopes leave the public `state::*` functions and `state::on-changed`; `claimed` is `false` when the worker already owned them all; `functions` names its accessors (next row) | — |
| `<prefix>::state::get`, `<prefix>::state::list`, `<prefix>::state::compare-and-set` | as `state::get`, `state::list` and `state::compare-and-set`, limited to the scopes the worker `<prefix>` claimed; `compare-and-set` also takes `durable` (see [Install](#install)) | as their public counterparts; `compare-and-set` adds `durable` | — (internal: registered by the first `state::claim-namespace` of `<prefix>`, and at every boot for each namespace claimed before) |
| `state::list` | `{ scope }` | flat array of every value in the scope | — |
| `state::list_keys` | `{ scope }` | `{ keys }` — the keys stored in the scope, adapter order (additive; no builtin counterpart — added for the console state UI, whose per-item navigation `state::list`'s values-only shape cannot drive) | — |
| `state::list_groups` | `{}` | `{ groups }` — sorted, deduplicated scope names | — |
| `state::ui-content` | `{ path }` | `{ content, content_type }` — content function for the injected console UI (internal; see [Console UI](#console-ui)) | — |
| `state::on-changed` | the change event (see [Observing changes](#observing-changes)) | the same event | — (observe it; private: only this worker calls it) |
| `state::on-config-change` | the `configuration:updated` event of the worker's entry (ignored) | `{ ok: true }` — internal: the target of the worker's observer of `configuration::on-updated`; it re-reads the entry and applies it (see [Configuration](#configuration)) | — |

The `harness_binding` and `harness_binding_owner` scopes are reserved
control-plane state: public functions reject direct access, omit them from
group listings, and never emit their bookkeeping writes as state events.

## Console UI

The worker ships its console UI into any running console (the injectable-UI
protocol, `iii/tech-specs/2026-07-17-injectable-ui`) — three contributions,
one module each under `ui/src/`:

| Module | Slot | What it does |
|---|---|---|
| `ui/src/page/` | `host.pages` | the state-manager page (page `state-manager`): browse scopes → keys → edit one value as JSON and save it back with `state::set` |
| `ui/src/configuration/` | `host.configForms` | deliberate form for the `state` entry in global Settings (adapter picker, persistence, change-event gate, limits) |
| `ui/src/function-call-message/` | `host.functionCalls` | how `state::set` / `state::get` calls render in chat and the traces span view (overrides the console's built-in family for those two ids; errors and other `state::*` ids fall through) |

`ui/page.tsx` is the esbuild entry: a thin `setup(host)` composing the three
registrations plus the shared scoped stylesheet (`ui/src/lib/styles.ts`).

The page is **live**: it observes `state::on-changed` once per tab (no
filters = every scope/key, `capture: ['output']`, the console host handing
the handler the event) with a per-tab handler as
the target (`iii::state-ui::events::<browserId>`), and applies the
created/updated/deleted events in place — new scopes and keys appear as
they are written, an open item editor updates in place when clean, and
unsaved edits are never clobbered (a "changed on the server" notice offers
the incoming value instead). The observer is disposed with the page; the
`iii::` prefix keeps the per-event invocations out of the trace feed.

- Build: esbuild over `ui/page.tsx` and `ui/styles.css` (`cd ui && pnpm
  build`; `build.rs` does this automatically) with `react` and
  `@iii-dev/console-ui` external — they resolve through the console's
  import map at runtime. Types come from the workspace-linked
  `packages/console-ui` (repo-root pnpm workspace).
- Deployment: boot observes `ade::ui::asset` twice, with args
  `{ kind: 'script', path: 'state/page.js' }` and
  `{ kind: 'style', path: 'state/styles.css' }`, both targeting
  `state::ui-content`; the ADE worker fetches, hashes, and serves the assets,
  and drops them when this worker disconnects. The
  stylesheet is scoped under `[data-iii-ui="state"]` and mounted as a
  `<link>` (styles-before-scripts on boot, link-swap on change).
- Dev loop: run `cd ui && pnpm watch` and start the worker with
  `III_STATE_UI_WATCH=1` — it polls `ui/dist/` and replaces a changed
  asset's observer, hot-swapping it in every open console tab.

## Observing changes

`state::on-changed` is the change event. After every committed write the
worker calls it with the event, and its handler returns that event, so
observers see it as the call's `input` and `output`.

| Function | Args | Delivery | Event |
|---|---|---|---|
| `state::on-changed` | none; filter on `input.scope`, `input.key`, `input.event_type` | iii delivers every call to each observer whose filters match | `{ type: "state", event_type, scope, key, old_value, new_value }` |

```typescript
iii.registerFunction('orders::on-status-change', ({ output: event }: { output: StateEvent }) => {
  // event: { type, event_type, scope, key, old_value, new_value }
})

const observer = iii.observe(
  {
    function_id: 'state::on-changed',
    filters: { 'input.scope': { $eq: 'orders' }, 'input.key': { $eq: 'status' } },
    capture: ['output'],
  },
  'orders::on-status-change',
)
await observer.ready()
```

The target receives the `Observed` envelope; its `output` is the event:

```json
{
  "type": "state",
  "event_type": "state:updated",
  "scope": "orders",
  "key": "status",
  "old_value": { "status": "pending" },
  "new_value": { "status": "shipped" }
}
```

- `event_type` is one of `state:created`, `state:updated`, `state:deleted`;
  `old_value` is `null` for created keys and `new_value` is `null` for
  deleted keys.
- Filters read any field of the event: `input.scope`, `input.key`,
  `input.event_type`, `input.old_value.*`, `input.new_value.*`. With no
  filters an observer receives every change.
- The target receives the `Observed` envelope; with `caller` captured (the
  default capture is `input`, `output`, `caller`) its `caller.function_id` is the `state::*` function that made the write
  and `caller.parent` the worker (and function) that called it. Filters on
  `caller.parent.worker_name` select or skip one writer's changes.
- Every committed write emits: `state::set`, `state::update`,
  `state::delete` (even of a missing key) and a swapped
  `state::compare-and-set`. Private namespaces never emit, and
  `events_enabled: false` silences the function.
- Delivery is asynchronous: targets run after the write completes, and a
  target's failure never rolls the write back. With nobody observing,
  nothing is built or called.
- The function is private: any call from another worker is refused with
  `FORBIDDEN`, so its observers see real changes only. The observer's
  metadata reaches the target as the call's metadata sidecar.

## Configuration

| Field | Default | Description |
|---|---|---|
| `adapter` | `kv` | Storage adapter: `kv` (in-process; `store_method: file_based` — the default, persisting under `file_path`, default `data/state` relative to `III_COMPOSE_DIR` — or `in_memory`, volatile) or `redis` (`redis_url`, default `redis://localhost:6379`). Restart-tier: a runtime change is logged and takes effect at the next worker start. |
| `events_enabled` | `true` | Call `state::on-changed` after every committed write. Applied live. |
| `max_value_bytes` | unset (no limit) | Reject `state::set` writes whose JSON-serialized value exceeds this many bytes (`VALUE_TOO_LARGE`). Minimum `1`. Applied live. |
| `save_interval_ms` | `5000` | Persistence flush cadence (ms) for the file-backed `kv` adapter. `100`–`3600000`. Applied live by respawning the adapter's save loop (hot-retune; no-op for in-memory/redis). |

Configuration is owned by the `configuration` worker — edit it from the
console (**Configuration → Workers → state**) or seed it once via the
worker's config block in `config.yaml` on first boot. `events_enabled` and
`max_value_bytes` apply on the next write, `save_interval_ms` hot-retunes
the save loop, and `adapter` takes effect on the next restart. An entry or
seed written by a release before 0.26 names the `events_enabled` knob
differently; the worker rewrites the stored entry to the field names above
when it boots, before it reads it.

### Requires removing the legacy built-in state service

The legacy built-in state service also owns the `state::*` functions. Two owners of the same surface on one engine collide —
whichever registers last wins — so this worker requires it to be
absent: omit it from the engine's `config.yaml` (a config that doesn't list
a worker won't run it).

On boot, this worker queries the engine for connected workers and refuses to
start with a clear error if the legacy built-in is still active, so a stale config
fails loudly instead of silently racing the built-in worker for ownership of
`state::*`.

**Store migration:** if the builtin used a file-based `kv` store, point this
worker's `adapter.config.file_path` at the builtin's existing directory
(the default engine config used `./data/state_store.db`). The on-disk format
(one rkyv `.bin` file per scope) is identical, so the existing data loads
as-is — no export/import step.

## Latency

The builtin ran in-process inside the engine, so a `state::*` call cost
microseconds; as a standalone worker every call crosses the engine⇄worker
WebSocket, which puts round-trips in the low-millisecond range. That
order-of-magnitude delta is inherent to the migration and applies to every
externalized builtin. A formal benchmark was waived by project decision
(2026-07-06).

## Parity vs builtin

| Behavior | Builtin | This worker |
|---|---|---|
| Function ids | `state::set/get/delete/update/list/list_groups` | same (exact) |
| `set` input | `{scope, key, value}` (`data` alias) | same |
| Events | `state:created`/`updated`/`deleted`, payload `{type:"state", event_type, scope, key, old_value, new_value}` | same, as the input and output of `state::on-changed` |
| Selecting events | `scope` / `key` equality, `condition_function_id` | observer filters on any event field (`input.scope`, `input.key`, `input.event_type`, …) |
| Per-subscriber metadata | forwarded to handlers via call_with_metadata | the observer's `metadata`, delivered by iii as the sidecar |
| Store adapters | kv (in_memory/file_based), redis, bridge | kv, redis (bridge not ported — see docs/adr/0001) |
| kv on-disk format | rkyv `.bin` per scope | identical — builtin data loads as-is |
| `save_interval_ms` | default 5000ms, floor 100ms, hot-retune | same |
| `max_value_bytes` | guards `set` only, `VALUE_TOO_LARGE` | same (code is the message prefix) |
| Error codes | coded `ErrorBody` (`SET_ERROR`, ...) | code as message prefix (SDK handler errors carry a message) |
| Durability | store dies with the ENGINE process | store dies with the WORKER process (ADR 0001; file_based/redis unchanged) |
| Latency | in-process µs | engine⇄worker WS round-trip (low ms) — formal benchmark waived by project decision 2026-07-06 |
| Telemetry (`track_state_*`) | engine-internal counters | none — out of scope for this migration; lands with the shared worker observability story |

## skills

This version ships 1 skill file for agents, also browsable on the worker page:

- [`SKILL.md`](https://iii.dev/registry/workers/state?tab=skills&skill=SKILL.md&version=0.23.1)

### SKILL.md

# state

The `state` worker is a server-side key/value store. Values are addressed by a `scope` (namespace) and a `key`, shared across every worker connected to the engine, and persisted through a pluggable adapter (`kv` or `redis`). Callers reach the core store through six `state::*` functions called with `iii.call({ function_id: 'state::...', payload })`. The worker also exposes `state::list_keys` and the internal `state::ui-content` function. Install it with `iii call compose::add worker=state`; it replaces the engine's legacy built-in state service, which must be removed from the engine config first.

State does not push updates to SDK clients. After every successful mutation the worker calls `state::on-changed` with a `state:created`, `state:updated`, or `state:deleted` event; functions that observe it react to data changes without polling. The `kv` adapter (default) supports `file_based` persistence (the default) or a volatile `in_memory` mode; `redis` proxies to a Redis backend. The function surface is identical across adapters.

## When to Use

- Two or more functions need shared state without standing up a separate database.
- A counter or per-entity document needs atomic partial updates instead of read-modify-write.
- A write in one function should cause side effects elsewhere (cache invalidation, audit logs, notifications, projections).
- You want a specific `scope`/`key` watched and reacted to only when that slot changes.

## Boundaries

- Schema-free by design — every value is opaque JSON. Use the `configuration` worker when entries need a registered JSON Schema and validation.
- Reads (`state::get`, `state::list`, `state::list_groups`) never emit `state::on-changed`; only `set`/`update`/`delete` and a swapped `compare-and-set` do.
- Delivery to observers is asynchronous and does not roll back the write on a target's failure; a delete of a missing key still emits `state:deleted` with a null old value.
- Stream-shaped, broadcast-to-subscribers data belongs in the engine's stream surface, not here.
- The store lives in the worker process: the `kv` `in_memory` backend is lost when the worker stops. The default `file_based` backend (and `redis`) survives restarts.

## Functions

- `state::set` — write or replace the value at a `scope`/`key`; emits `state:created` or `state:updated`.
- `state::get` — read one value by `scope` and `key`.
- `state::delete` — remove a key and emit `state:deleted` with the prior value.
- `state::update` — apply ordered atomic ops (`set`, `merge`, `increment`, `decrement`, `append`, `remove`) to the stored value.
- `state::list` — enumerate every value stored in a scope.
- `state::list_groups` — enumerate which scopes currently contain data.
- `state::on-changed` — the change event: observe it, never call it (private to the state worker).

## Observing changes

Observe `state::on-changed` when a function should run automatically after a value changes — without polling `state::get`. It takes no args: select changes with filters on `input.scope`, `input.key` and `input.event_type` (any event field works, including `input.new_value.*`).

Reach for it when:

- A write in one worker should drive side effects in another (audit logs, cache invalidation, notifications, projections).
- You want only some changes: filters select them, for example `{ 'input.event_type': { $eq: 'state:deleted' } }`.

If you only need the new value inside the same function that wrote it, use the mutator's returned `old_value` / `new_value` instead of observing.

### How to observe

1. Register a handler: `iii.registerFunction('orders::on-status-change', handler)`.
2. Observe the change event with it:

```typescript
iii.observe(
  {
    function_id: 'state::on-changed',
    filters: {
      'input.scope': { $eq: 'orders' },  // omit to match every scope
      'input.key': { $eq: 'status' },    // omit to match every key in the scope
    },
    capture: ['output'],
  },
  'orders::on-status-change',
)
```

Filters take explicit operators (`$eq`, `$in`, `$ne`, …). To watch several specific keys, use `{ 'input.key': { $in: ['status', 'total'] } }`. Mutations that emit: `state::set`, `state::update`, `state::delete`, a swapped `state::compare-and-set`.

The handler receives the `Observed` envelope; with `capture: ['output']` its `output` is the event `{ type: "state", event_type, scope, key, old_value, new_value }`, where `event_type` is one of `state:created`, `state:updated`, or `state:deleted`. Add `'caller'` to the capture to also get `caller.parent`, the worker that wrote. Pass `{ metadata }` as the third argument of `iii.observe` to hand the handler a sidecar with every event.

## api reference

```json
{
  "functions": [
    {
      "description": "Fan-in gate for an observer condition: record one arrival and answer `skip` until the expected set has arrived, then `allow` exactly once carrying every arrival's payload.",
      "metadata": {},
      "name": "state::barrier",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "BarrierConfig": {
            "description": "The caller-authored half: what this barrier is and how to read an arrival out of the event.",
            "properties": {
              "carry": {
                "default": null,
                "description": "JSON pointer into the event for the value to accumulate (default: the whole event).",
                "type": [
                  "string",
                  "null"
                ]
              },
              "expect": {
                "allOf": [
                  {
                    "$ref": "#/definitions/Expect"
                  }
                ],
                "description": "A count, or the exact set of arrival keys."
              },
              "id": {
                "description": "Barrier identity. Two observers sharing an id share the barrier — that is how several predecessors feed one downstream.",
                "type": "string"
              },
              "key_from": {
                "default": null,
                "description": "JSON pointer into the event for the arrival key (default `/key`); a pointer that resolves to nothing is an error.",
                "type": [
                  "string",
                  "null"
                ]
              }
            },
            "required": [
              "expect",
              "id"
            ],
            "type": "object"
          },
          "Expect": {
            "anyOf": [
              {
                "format": "uint64",
                "maximum": 10000,
                "minimum": 1,
                "type": "integer"
              },
              {
                "items": {
                  "type": "string"
                },
                "maxItems": 10000,
                "minItems": 1,
                "type": "array"
              }
            ],
            "description": "What the barrier is waiting for: a COUNT, or a named set. A named set is stricter and better: it catches the arrival that was never going to come."
          }
        },
        "description": "The condition-contract envelope. `event` is the fired event; the rest of the envelope (binding, context) is accepted and ignored so the same function works as a condition and as a direct call.",
        "properties": {
          "condition_config": {
            "anyOf": [
              {
                "$ref": "#/definitions/BarrierConfig"
              },
              {
                "type": "null"
              }
            ]
          },
          "event": {
            "default": null
          }
        },
        "title": "BarrierInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "The typed decision a condition returns.",
        "oneOf": [
          {
            "properties": {
              "decision": {
                "enum": [
                  "allow"
                ],
                "type": "string"
              },
              "payload": true,
              "reason": {
                "type": "string"
              }
            },
            "required": [
              "decision",
              "reason"
            ],
            "type": "object"
          },
          {
            "properties": {
              "decision": {
                "enum": [
                  "skip"
                ],
                "type": "string"
              },
              "reason": {
                "type": "string"
              }
            },
            "required": [
              "decision",
              "reason"
            ],
            "type": "object"
          }
        ],
        "title": "Decision"
      }
    },
    {
      "description": "Reserve a private state namespace for the calling worker (its own worker name only): its scopes leave public state::* and state::on-changed, and `<prefix>::state::{get, list, compare-and-set}` accessors are registered. Idempotent.",
      "metadata": {},
      "name": "state::claim-namespace",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Input for [`CLAIM_NAMESPACE_ID`]. The handler resolves the caller (see `caller_worker_id`) to its worker NAME and requires it to equal `functions_prefix`. `_caller_worker_id` is kept for 0.24 engines, which identify the caller only there, and is read only on such an engine.",
        "properties": {
          "_caller_worker_id": {
            "default": null,
            "type": [
              "string",
              "null"
            ]
          },
          "functions_prefix": {
            "description": "Must equal the calling worker's name.",
            "type": "string"
          },
          "scopes": {
            "description": "Storage scopes to reserve for this namespace.",
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "functions_prefix",
          "scopes"
        ],
        "title": "ClaimNamespaceInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "claimed": {
            "description": "False when the namespace already owned everything asked for.",
            "type": "boolean"
          },
          "functions": {
            "description": "The accessor ids now serving this namespace.",
            "items": {
              "type": "string"
            },
            "type": "array"
          },
          "scopes": {
            "description": "Every scope this namespace owns after the call.",
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "claimed",
          "functions",
          "scopes"
        ],
        "title": "ClaimNamespaceResult",
        "type": "object"
      }
    },
    {
      "description": "Atomically set a value only if it currently equals `expected` (omit `expected` to mean 'only if absent'). Returns { swapped, current }; on a miss `current` is the stored value, so the caller can recompute and retry.",
      "metadata": {},
      "name": "state::compare-and-set",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Everything a function handler needs; one Arc cloned per registration.",
        "properties": {
          "expected": {
            "default": null,
            "description": "The value the caller believes is there. Omit to mean \"expect absent\" — the set-if-absent form."
          },
          "key": {
            "type": "string"
          },
          "scope": {
            "type": "string"
          },
          "value": true
        },
        "required": [
          "key",
          "scope",
          "value"
        ],
        "title": "CompareAndSetInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "current": {
            "description": "What is actually stored, when the swap did not happen."
          },
          "swapped": {
            "type": "boolean"
          }
        },
        "required": [
          "swapped"
        ],
        "title": "CompareAndSetResult",
        "type": "object"
      }
    },
    {
      "description": "Delete the value stored at a key in a state scope",
      "metadata": {},
      "name": "state::delete",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "key": {
            "description": "Identifier for the value to delete within the scope.",
            "type": "string"
          },
          "scope": {
            "description": "Namespace that groups related keys.",
            "type": "string"
          }
        },
        "required": [
          "key",
          "scope"
        ],
        "title": "StateDeleteInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "The value that was deleted (read before delete), or null if it did not exist.",
        "title": "StateDeleteResponse",
        "type": [
          "string",
          "number",
          "boolean",
          "object",
          "array",
          "null"
        ]
      }
    },
    {
      "description": "Read the value stored at a key in a state scope",
      "metadata": {},
      "name": "state::get",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "key": {
            "description": "Identifier for the value within the scope.",
            "type": "string"
          },
          "scope": {
            "description": "Namespace that groups related keys.",
            "type": "string"
          }
        },
        "required": [
          "key",
          "scope"
        ],
        "title": "StateGetInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "The raw value stored at scope/key, or null if absent.",
        "title": "StateGetResponse",
        "type": [
          "string",
          "number",
          "boolean",
          "object",
          "array",
          "null"
        ]
      }
    },
    {
      "description": "List every value stored in a state scope",
      "metadata": {},
      "name": "state::list",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "scope": {
            "description": "Namespace whose keys should be listed as a group.",
            "type": "string"
          }
        },
        "required": [
          "scope"
        ],
        "title": "StateGetGroupInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "The values in the given scope, as a JSON array (or null on the rare serialization failure).",
        "title": "StateListResponse",
        "type": [
          "string",
          "number",
          "boolean",
          "object",
          "array",
          "null"
        ]
      }
    },
    {
      "description": "List all state scopes (groups) that hold values",
      "metadata": {},
      "name": "state::list_groups",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "title": "StateListGroupsInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "groups": {
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "groups"
        ],
        "title": "StateListGroupsResult",
        "type": "object"
      }
    },
    {
      "description": "List the keys stored in a state scope",
      "metadata": {},
      "name": "state::list_keys",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "scope": {
            "description": "Namespace whose keys should be listed as a group.",
            "type": "string"
          }
        },
        "required": [
          "scope"
        ],
        "title": "StateGetGroupInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "keys": {
            "description": "Keys stored in the scope, in the adapter's natural order.",
            "items": {
              "type": "string"
            },
            "type": "array"
          }
        },
        "required": [
          "keys"
        ],
        "title": "StateListKeysResult",
        "type": "object"
      }
    },
    {
      "description": "One call per committed state change (state::set, state::update, state::delete, a swapped state::compare-and-set). The handler returns the change event it is called with, { type, event_type, scope, key, old_value, new_value }, so observers observe it as input and output. Observe it with no args and filter on input.scope / input.key / input.event_type; caller.function_id is the state function that wrote, and caller.parent the worker that called it. Private: only the state worker calls it. Private namespaces never emit, and `events_enabled: false` silences it.",
      "metadata": {},
      "name": "state::on-changed",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "StateEventType": {
            "enum": [
              "state:created",
              "state:updated",
              "state:deleted"
            ],
            "type": "string"
          }
        },
        "description": "One committed state change: the input and output of `state::on-changed`.",
        "properties": {
          "event_type": {
            "allOf": [
              {
                "$ref": "#/definitions/StateEventType"
              }
            ],
            "description": "`state:created`, `state:updated` or `state:deleted`."
          },
          "key": {
            "description": "The changed key.",
            "type": "string"
          },
          "new_value": {
            "description": "The value after the change; `null` for a deleted key."
          },
          "old_value": {
            "description": "The value before the change; `null` for a created key."
          },
          "scope": {
            "description": "Scope of the changed key.",
            "type": "string"
          },
          "type": {
            "description": "Always `state`.",
            "type": "string"
          }
        },
        "required": [
          "event_type",
          "key",
          "new_value",
          "scope",
          "type"
        ],
        "title": "StateEventData",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "StateEventType": {
            "enum": [
              "state:created",
              "state:updated",
              "state:deleted"
            ],
            "type": "string"
          }
        },
        "description": "One committed state change: the input and output of `state::on-changed`.",
        "properties": {
          "event_type": {
            "allOf": [
              {
                "$ref": "#/definitions/StateEventType"
              }
            ],
            "description": "`state:created`, `state:updated` or `state:deleted`."
          },
          "key": {
            "description": "The changed key.",
            "type": "string"
          },
          "new_value": {
            "description": "The value after the change; `null` for a deleted key."
          },
          "old_value": {
            "description": "The value before the change; `null` for a created key."
          },
          "scope": {
            "description": "Scope of the changed key.",
            "type": "string"
          },
          "type": {
            "description": "Always `state`.",
            "type": "string"
          }
        },
        "required": [
          "event_type",
          "key",
          "new_value",
          "scope",
          "type"
        ],
        "title": "StateEventData",
        "type": "object"
      }
    },
    {
      "description": "Internal: reload state configuration from the authoritative store on change.",
      "metadata": {
        "internal": true
      },
      "name": "state::on-config-change",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "title": "ConfigChangeRequest",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "ok": {
            "type": "boolean"
          }
        },
        "required": [
          "ok"
        ],
        "title": "ConfigChangeAck",
        "type": "object"
      }
    },
    {
      "description": "Store or write a value at a key in a state scope; it persists across sessions",
      "metadata": {},
      "name": "state::set",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "properties": {
          "key": {
            "description": "Identifier for the value within the scope.",
            "type": "string"
          },
          "scope": {
            "description": "Namespace that groups related keys (e.g. `users`, `orders`).",
            "type": "string"
          },
          "value": {
            "description": "Arbitrary JSON value to store. Replaces any existing value at `scope`/`key`."
          }
        },
        "required": [
          "key",
          "scope",
          "value"
        ],
        "title": "StateSetInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Result of a stream set operation.",
        "properties": {
          "new_value": {
            "description": "The value after the update"
          },
          "old_value": {
            "description": "Previous value (if it existed)."
          }
        },
        "required": [
          "new_value"
        ],
        "title": "StreamSetResult",
        "type": "object"
      }
    },
    {
      "description": "Serve the state worker's injected console UI assets (the target of its ade::ui::asset observers; the console calls it through each asset's observer with {path}).",
      "metadata": {
        "internal": true
      },
      "name": "state::ui-content",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Input of the content function: the console asks for one asset by path.",
        "properties": {
          "path": {
            "description": "The asset path from the observer's args (e.g. `state/page.js`).",
            "type": "string"
          }
        },
        "required": [
          "path"
        ],
        "title": "UiContentInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "description": "Output of the content function.",
        "properties": {
          "content": {
            "description": "The asset source, verbatim.",
            "type": "string"
          },
          "content_type": {
            "description": "MIME type the console should serve the asset with.",
            "type": "string"
          }
        },
        "required": [
          "content",
          "content_type"
        ],
        "title": "UiContentResult",
        "type": "object"
      }
    },
    {
      "description": "Update part of a stored value: set, merge, increment, append or remove fields",
      "metadata": {},
      "name": "state::update",
      "request_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "MergePath": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "items": {
                  "type": "string"
                },
                "type": "array"
              }
            ],
            "description": "Path target for a [`UpdateOp::Merge`] operation. Accepts either a single string (legacy / first-level field) or an array of literal segments (nested path).\n\nPath normalization rules applied by the engine: - absent / `Single(\"\")` / `Segments(vec![])` → root merge - `Single(\"foo\")` is equivalent to `Segments(vec![\"foo\".into()])` - `Segments([\"a\", \"b\", \"c\"])` walks three literal keys, never interpreting dots specially. `Segments(vec![\"a.b\".into()])` is a single literal key named `\"a.b\"`.\n\n**Variant ordering is load-bearing.** `#[serde(untagged)]` tries variants in declaration order, `Single` MUST come before `Segments` so a JSON string deserializes into `Single` rather than failing the array match first."
          },
          "UpdateOp": {
            "description": "Operations that can be performed atomically on a stream value",
            "oneOf": [
              {
                "description": "Set a value at path (overwrite)",
                "properties": {
                  "path": {
                    "type": "string"
                  },
                  "type": {
                    "enum": [
                      "set"
                    ],
                    "type": "string"
                  },
                  "value": true
                },
                "required": [
                  "path",
                  "type"
                ],
                "type": "object"
              },
              {
                "description": "Merge object into existing value (object-only). Path may be omitted (root merge), a single first-level key, or an array of literal segments for nested merge. See [`MergePath`].",
                "properties": {
                  "path": {
                    "anyOf": [
                      {
                        "$ref": "#/definitions/MergePath"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "type": {
                    "enum": [
                      "merge"
                    ],
                    "type": "string"
                  },
                  "value": true
                },
                "required": [
                  "type",
                  "value"
                ],
                "type": "object"
              },
              {
                "description": "Increment numeric value",
                "properties": {
                  "by": {
                    "format": "int64",
                    "type": "integer"
                  },
                  "path": {
                    "type": "string"
                  },
                  "type": {
                    "enum": [
                      "increment"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "by",
                  "path",
                  "type"
                ],
                "type": "object"
              },
              {
                "description": "Decrement numeric value",
                "properties": {
                  "by": {
                    "format": "int64",
                    "type": "integer"
                  },
                  "path": {
                    "type": "string"
                  },
                  "type": {
                    "enum": [
                      "decrement"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "by",
                  "path",
                  "type"
                ],
                "type": "object"
              },
              {
                "description": "Append an element to an array or concatenate a string at the optional path. Path may be omitted (root append), a single first-level key, or an array of literal segments for nested append. See [`MergePath`] for the variant shape.",
                "properties": {
                  "path": {
                    "anyOf": [
                      {
                        "$ref": "#/definitions/MergePath"
                      },
                      {
                        "type": "null"
                      }
                    ]
                  },
                  "type": {
                    "enum": [
                      "append"
                    ],
                    "type": "string"
                  },
                  "value": true
                },
                "required": [
                  "type",
                  "value"
                ],
                "type": "object"
              },
              {
                "description": "Remove a field",
                "properties": {
                  "path": {
                    "type": "string"
                  },
                  "type": {
                    "enum": [
                      "remove"
                    ],
                    "type": "string"
                  }
                },
                "required": [
                  "path",
                  "type"
                ],
                "type": "object"
              }
            ]
          }
        },
        "properties": {
          "key": {
            "description": "Identifier for the value to update within the scope.",
            "type": "string"
          },
          "ops": {
            "description": "Ordered list of update operations applied atomically to the existing value.",
            "items": {
              "$ref": "#/definitions/UpdateOp"
            },
            "type": "array"
          },
          "scope": {
            "description": "Namespace that groups related keys.",
            "type": "string"
          }
        },
        "required": [
          "key",
          "ops",
          "scope"
        ],
        "title": "StateUpdateInput",
        "type": "object"
      },
      "response_schema": {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "definitions": {
          "UpdateOpError": {
            "description": "Per-op error reported by an atomic update operation.",
            "properties": {
              "code": {
                "description": "Stable error code, e.g. `\"merge.path.too_deep\"`.",
                "type": "string"
              },
              "doc_url": {
                "description": "Optional documentation URL for this error class.",
                "type": [
                  "string",
                  "null"
                ]
              },
              "message": {
                "description": "Human-readable description with concrete numbers when applicable.",
                "type": "string"
              },
              "op_index": {
                "description": "Index of the offending op within the original `ops` array.",
                "format": "uint",
                "minimum": 0,
                "type": "integer"
              }
            },
            "required": [
              "code",
              "message",
              "op_index"
            ],
            "type": "object"
          }
        },
        "description": "Result of an atomic update operation",
        "properties": {
          "errors": {
            "description": "Errors encountered while applying ops. Successfully applied ops are still reflected in `new_value`. Field is omitted from JSON when empty for backward compatibility.",
            "items": {
              "$ref": "#/definitions/UpdateOpError"
            },
            "type": "array"
          },
          "new_value": {
            "description": "The value after the update"
          },
          "old_value": {
            "description": "Previous value (if it existed)."
          }
        },
        "required": [
          "new_value"
        ],
        "title": "StreamUpdateResult",
        "type": "object"
      }
    }
  ]
}
```
