> ## Documentation Index
> Fetch the complete documentation index at: https://docs.reilabs.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Configure a Machina Domain

> Define state, goal, action, and timing contracts, then configure a numeric trajectory learner on the production API.

Use this guide to turn a control task into an explicit numeric contract. You will create an owned Domain, configure its trajectory mechanism, and connect it to your executor.

<Info>
  These examples use the production API address and adapt the trajectory request schema and reference client. They have not been run against production. The response fields shown are those used by the client.
</Info>

## Choose the API surface

| What your application needs                             | Interface                                                                                |
| ------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| Acquire a bounded numeric action sequence               | `trajectory/configure` with `episode_credit`, then `propose` and `observe`               |
| Select, shorten, or reorder acquired executions         | `confirmed_execution` with `selection`, `deletion`, or `ordering`                        |
| Learn context-dependent offsets around an acquired base | `contextual_execution`, then candidate `evaluate` and comparison `observe`               |
| Choose a named discrete policy after each observation   | The separate [Domain query and feedback workflow](/docs/neuroadapt/discovery-sequential) |

Creating a Domain does not configure its trajectory learner. For the numeric pipeline, the mechanism lives inside the `config` object sent to `/trajectory/configure`. It does not belong inside `DomainCreateRequest.learning`, `query_templates`, or a generic `/schemas` request.

## Production URL and authentication

```text theme={null}
https://rei-neuroadapt-api.reilabs.org/api/v1
```

Send `Authorization: Bearer <Unit API Key>` and `Content-Type: application/json`. Keep the key server-side. The bearer token determines the owner; omit body `session_id` and never send a trusted owner header to select a tenant.

## Define the vector schema

Consider a planar platform with two continuous control coordinates. This small example has four state coordinates and up to eight commands. Replace these choices with your own measured interface.

| Array           | Index | Meaning                 | Example convention                       |
| --------------- | ----: | ----------------------- | ---------------------------------------- |
| `state`         |     0 | Measured x position     | Position divided by 1 metre              |
| `state`         |     1 | Measured y position     | Position divided by 1 metre              |
| `state`         |     2 | Measured x velocity     | Velocity divided by 1 metre/second       |
| `state`         |     3 | Measured y velocity     | Velocity divided by 1 metre/second       |
| `goal`          |     0 | Desired x position      | Same coordinates and scale as `state[0]` |
| `goal`          |     1 | Desired y position      | Same coordinates and scale as `state[1]` |
| Each action row |     0 | First actuator command  | Normalized to `[-1, 1]`                  |
| Each action row |     1 | Second actuator command | Normalized to `[-1, 1]`                  |

The goal is a desired state, not a successful control sequence. `goal_indices: [0, 1]` maps the two goal coordinates into the state vector. Every index must be smaller than `state_dimensions`; the goal length must equal the number of goal indices.

Keep names, units, ordering, scaling, and invalid-measurement rules in an application-owned manifest. The trajectory API receives numeric arrays; it cannot infer the physical meaning of an array position.

## Separate API configuration from executor configuration

| Native configuration                                                                                                     | Application-owned settings                                                                                                                             |
| ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| State/action dimensions, goal indices, logical horizon, mechanism, retention capacity, pending limit, seed, outcome mode | Coordinate meanings, sensor scale, physical action bounds, command duration, actuator decoder, reset logic, safety stops, padding, outcome calculation |

For this example, the application holds each command for 0.5 seconds and uses a fixed eight-slot execution window. If structural deletion shortens the logical sequence, it appends neutral commands to the unused slots. That preserves the physical duration while the logical command list changes.

`command_duration`, `action_bounds`, and `padding` are not fields in the referenced trajectory configuration schema. Do not insert them into the API body. Implement and version them in your executor. A neutral command means the declared neutral actuator input; it does not imply that the moving platform stops immediately.

For a concrete outcome contract, define completion as finishing within `0.05` metres of the goal with speed at most `0.1` metres/second. Assess it after the eight-slot window, or at a declared earlier task-terminal state. A safety stop does not count as completion. The acquisition reward and structural `completion` objective both use `float(completed)`. These tolerances are example application settings; choose and keep fixed the values appropriate to your task.

## Create and configure

Choose a fresh run-specific Domain ID. POST to `https://rei-neuroadapt-api.reilabs.org/api/v1/domains`:

```json theme={null}
{
  "domain_id": "control-example-UNIQUE-acquisition",
  "description": "Bounded two-actuator sequence acquisition"
}
```

Then POST `{}` to `/domains/control-example-UNIQUE-acquisition/trajectory/state`. The reference client requires `status: "not_configured"` before configuring a fresh trajectory learner. This check concerns trajectory state; it does not assert that every possible Domain subsystem is empty.

POST to `/domains/control-example-UNIQUE-acquisition/trajectory/configure`, relative to the production base:

```json theme={null}
{
  "config": {
    "mechanism": "episode_credit",
    "state_dimensions": 4,
    "action_dimensions": 2,
    "goal_indices": [0, 1],
    "horizon": 8,
    "capacity": 128,
    "max_pending": 1,
    "seed": 1,
    "outcome_mode": "reward"
  }
}
```

The dimensions and resource settings above are an example profile, not universal tuning recommendations.

### Acquisition fields

| Field               | Required / schema default    | Meaning and constraint                                                        |
| ------------------- | ---------------------------- | ----------------------------------------------------------------------------- |
| `mechanism`         | Defaults to `episode_credit` | Set explicitly to identify the interface                                      |
| `state_dimensions`  | Required                     | Integer, 1–128; length of every state row                                     |
| `action_dimensions` | Required                     | Integer, 1–32; length of every action row                                     |
| `goal_indices`      | Required                     | Nonempty integer indices into the state vector; validate their range locally  |
| `horizon`           | Required                     | Integer, 1–256; maximum logical sequence length                               |
| `capacity`          | Default 128                  | Integer, 1–512; configured retention capacity, not acquisition episode budget |
| `max_pending`       | Default 16                   | Integer, 1–64; example uses one outstanding proposal                          |
| `seed`              | Default 0                    | Integer, 0–2,147,483,647; learner seed, separate from environment reset seeds |
| `outcome_mode`      | Default `goal_error`         | `goal_error` or `reward`; example supplies a measured higher-is-better reward |

These limits come from the reference request schema. A deployed service can impose lower account or runtime limits. Read and save the resolved configuration; do not assume schema maxima are available capacity.

For `reward`, explicitly return the application's measured outcome after execution. Keep its direction and scale fixed. Use `goal_error` only with an adapter that implements the deployed goal-error contract; changing the string does not change your scorer automatically.

### Optional acquisition profile

The reference sequence client explicitly enables the following options. They are supported field names from that configuration, not settings required for every task:

```json theme={null}
{
  "coherent_edits": true,
  "global_recall": true,
  "executed_prefix_mutation": true,
  "progress_guided_mutation": true,
  "sequence_compaction": true,
  "outcome_tier_exploration": true,
  "retain_prefix_failures": false
}
```

This is a configuration fragment to merge into `config` before initial configuration, not a separate endpoint or a live patch request. The minimal example leaves native defaults in place. Enable progress-related options only with a defined, measured per-command outcome stream; do not manufacture intermediate outcomes from the terminal value. Save the full resolved settings with the run.

## Shared Python request helper

The following helper uses the Python standard library. Set `ADAPT1_API_KEY` in the server process environment. All later snippets use these functions and the same `PREFIX`.

```python theme={null}
import json
import os
import uuid
from urllib.request import Request, urlopen

BASE = "https://rei-neuroadapt-api.reilabs.org/api/v1"
PREFIX = "control-" + uuid.uuid4().hex[:16]
ACQUISITION_DOMAIN = PREFIX + "-acquisition"

def post(path, body):
    encoded = json.dumps(body, allow_nan=False).encode("utf-8")
    if len(encoded) > 1024 * 1024:
        raise ValueError("Request exceeds the reference 1 MiB body limit")
    request = Request(
        BASE + path,
        data=encoded,
        method="POST",
        headers={
            "Authorization": "Bearer " + os.environ["ADAPT1_API_KEY"],
            "Content-Type": "application/json",
        },
    )
    # Deliberately no automatic mutation retry.
    with urlopen(request, timeout=180) as response:
        return json.load(response)

def trajectory(domain, operation, body=None):
    return post(
        f"/domains/{domain}/trajectory/{operation}",
        {} if body is None else body,
    )

def create_stage(domain, config):
    post("/domains", {"domain_id": domain})
    state = trajectory(domain, "state")
    if state.get("status") != "not_configured":
        raise RuntimeError("Expected a fresh trajectory learner")
    receipt = trajectory(domain, "configure", {"config": config})
    configured_state = trajectory(domain, "state")
    if configured_state.get("status") == "not_configured":
        raise RuntimeError("Trajectory configuration was not applied")
    return receipt, configured_state
```

Generate `PREFIX` once, then persist and reload it to resume. Regenerating it creates a new lineage. The helper performs HTTP requests; it is not a simulator, scheduler, durable journal, or retry manager. Add request-intent and response recording before using it for a long run, as described in [Retained use and recovery](/docs/machina/retained-use).

## Choose the next guide

<CardGroup cols={2}>
  <Card title="Acquire a sequence" href="/docs/machina/acquisition">Propose, execute, validate, and return actual trajectory observations.</Card>
  <Card title="Structural stages" href="/docs/machina/structural-stages">Export acquired records and run selection, deletion, and ordering.</Card>
  <Card title="Contextual refinement" href="/docs/machina/refinement">Configure contexts and evaluate candidate offsets around a retained base.</Card>
  <Card title="Retained use and recovery" href="/docs/machina/retained-use">Use learned state without writes and reconcile interrupted operations.</Card>
</CardGroup>
