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

# fleet-rlm architecture

> How fleet-rlm layers a FastAPI SSE transport, a turn coordinator, one native dspy.RLM per run, and a Daytona interpreter into a single certified pipeline.

fleet-rlm is a Daytona-backed native `dspy.RLM` runtime with a FastAPI SSE transport in front of it. The backend is a thin coordination shell. One Run drives one fresh native `dspy.RLM` inside one interpreter context, and every observable behavior traces back to that pairing.

<Note>
  The client surface is the pi-tui terminal client at `tools/fleet-tui/`, launched by [`fleet cli`](/fleet-rlm/reference/cli). There is no WebSocket execution surface, no SPA, and no `/api/v1` prefix in the current codebase.
</Note>

## Layers at a glance

```mermaid theme={null}
graph TB
    TUI["fleet-tui terminal client<br/>tools/fleet-tui/"] --> API["FastAPI SSE transport<br/>api/app.py · api/routes/* · api/sse.py · api/ui_stream.py"]
    API --> CHAT["Turn coordination<br/>chat/turn_coordinator.py · chat/run_lifecycle.py · chat/run_preparation.py · chat/run_execution.py"]
    CHAT --> RLM["Native RLM runner<br/>rlm/runner.py · rlm/dspy_contract.py · rlm/recursive_calls.py · rlm/recursive_batch.py"]
    RLM --> DAYTONA["Daytona substrate<br/>daytona/interpreter.py · daytona/workspace_gateway.py · daytona/recursive_child_runtime.py"]
    API --> SESSIONS["Sessions & assistant parts<br/>sessions/catalog.py · sessions/committed_turn.py · sessions/assistant_parts.py"]
    API --> SKILLS["Bundled Skill catalog<br/>skills/catalog.py · skills/manifest.py · skills/resolver.py"]
    CHAT --> PERSIST["Persistence<br/>persistence/repositories/turns.py · persistence/run_codec.py · persistence/run_claim_decisions.py"]
```

The Run coordination lane is the live center. Transport, persistence, and Skills all attach to it, and none of them replace it.

## Runtime flow of one turn

1. The client posts to `POST /api/sessions/{session_id}/turns` with an `Idempotency-Key` header.
2. The transport resolves a deterministic local scope and validates the Turn input.
3. Attachment ownership and exact Skill selection are validated before any Run work begins.
4. `TurnCoordinator.open()` begins the SSE stream, coordinates heartbeat, terminal ordering, and cleanup.
5. `RunLifecycle.begin()` performs an atomic Run claim or a replay of an already-settled Run.
6. `DefaultRunPreparer.prepare()` assembles context, tools, and environment resources for the Run.
7. `RLMRunner` runs one fresh native `dspy.RLM` inside one interpreter context.
8. Runtime Events stream from the native trajectory, the interpreter, and the host-tool boundaries.
9. `RunLifecycle.finish()` validates the typed result and the private snapshot, promotes Artifact Candidate bytes on Daytona only, and commits Turn, Run, Checkpoint, and Artifact atomically or settles the failure.
10. The Run emits any `artifact.created*` events and then exactly one `run.completed` terminal event.
11. `TurnCoordinator` runs cleanup and the Interpreter Lease is released.

<Warning>
  Exactly one `run.completed` terminal event is emitted per Run. Terminal ordering is owned by `TurnCoordinator` and is not the responsibility of the runner or the lifecycle.
</Warning>

## Root delegation ladder

Delegation inside one Run is a fixed four-step ladder:

1. **Python** — deterministic work inside the interpreter context.
2. **Native `llm_query` / `llm_query_batched`** — semantic work at the native boundary.
3. **`rlm_query`** — one iterative isolated subproblem.
4. **Root-only `rlm_query_batched`** — ordered independent child RLMs.

Recursive children remain one native level deep. `RLM_NATIVE_CHILD_DEPTH = 1` is a fixed product invariant, not a tunable policy value. Fleet reserves the shared recursive budget atomically and controls sibling concurrency through `recursion_max_parallel_children`. See [Recursive RLM](/fleet-rlm/concepts/recursive-rlm) for the child scheduling contract.

## Layers in detail

### FastAPI transport — `src/fleet_rlm/api/`

`app.create_app()` builds the FastAPI app and eagerly constructs the immutable bundled Skill catalog. The lifespan validates settings and installs exactly one complete Daytona runtime inventory. The transport does not contain business logic.

| File                  | Role                                                                         |
| --------------------- | ---------------------------------------------------------------------------- |
| `api/app.py`          | App factory, lifespan, Skill catalog construction, Daytona inventory install |
| `api/routes/*`        | REST routes including the Turn submission endpoint                           |
| `api/sse.py`          | Validates each projected `RuntimeEvent` frame at the SSE boundary            |
| `api/ui_stream.py`    | Owns the typed discriminated live Fleet UI chunk union                       |
| `api/openapi.py`      | Derives OpenAPI from the same models used by SSE and UI stream               |
| `api/dependencies.py` | Shared request-scoped dependencies                                           |

### Turn coordination — `src/fleet_rlm/chat/`

The chat package owns the per-Turn lifecycle. `TurnCoordinator` sequences the SSE stream. `RunLifecycle` owns the Run claim, the private result snapshot, Artifact publication, atomic Turn Commit, and post-commit Memory promotion. Memory promotion is bounded and settled before the Run lease is released.

| File                       | Role                                                                    |
| -------------------------- | ----------------------------------------------------------------------- |
| `chat/turn_coordinator.py` | SSE stream, heartbeat, terminal ordering, cleanup                       |
| `chat/run_lifecycle.py`    | Atomic Run claim, replay, finish, artifact promotion, Memory settlement |
| `chat/run_preparation.py`  | `DefaultRunPreparer` — context, tools, environment resources            |
| `chat/run_execution.py`    | Bridges preparation output into the runner                              |
| `chat/session_context.py`  | Session-scoped identity, scope, and permission carrier                  |

### Native RLM runner — `src/fleet_rlm/rlm/`

`RLMRunner` runs one fresh native `dspy.RLM` per Run. Within one Run, interpreter calls reuse one context so Python state persists across RLM iterations. Every later Run receives a fresh context.

| File                     | Role                                                          |
| ------------------------ | ------------------------------------------------------------- |
| `rlm/runner.py`          | `RLMRunner` — one native RLM per Run, one interpreter context |
| `rlm/dspy_contract.py`   | Typed contract between Fleet and the native `dspy.RLM`        |
| `rlm/instructions.py`    | System instructions surfaced to the native trajectory         |
| `rlm/recursive_calls.py` | `rlm_query` boundary and child Run wiring                     |
| `rlm/recursive_batch.py` | Root-only `rlm_query_batched` scheduling                      |

### Daytona substrate — `src/fleet_rlm/daytona/`

Daytona owns provisioning, lifecycle, filesystem, and Workspace operations through one process-owned `AsyncDaytona`. `WorkspaceVolumeGateway.open_workspace()` scopes each grouped I/O to one ephemeral Sandbox that is deleted before the context exits.

| File                                 | Role                                                         |
| ------------------------------------ | ------------------------------------------------------------ |
| `daytona/interpreter.py`             | Interpreter Lease, execution context, native trajectory host |
| `daytona/workspace_agent.py`         | Workspace-side agent surface                                 |
| `daytona/workspace_gateway.py`       | `WorkspaceVolumeGateway` — ephemeral Sandbox scoping         |
| `daytona/workspace_memory.py`        | Durable Memory promotion targets                             |
| `daytona/workspace_fs.py`            | Workspace filesystem helpers                                 |
| `daytona/recursive_child_runtime.py` | Recursive child Run substrate                                |
| `daytona/provisioning.py`            | One process-owned `AsyncDaytona` and inventory install       |
| `daytona/session_manager.py`         | Session-scoped sandbox coordination                          |

See [Daytona runtime](/fleet-rlm/concepts/daytona-runtime) for the substrate deep cut.

### Composition — `src/fleet_rlm/composition/`

Composition modules assemble runtime inventories for tests and specialized entry points. The lifespan never installs these directly, and tests import them explicitly.

| File                     | Role                                 |
| ------------------------ | ------------------------------------ |
| `composition/common.py`  | Shared composition primitives        |
| `composition/daytona.py` | Daytona-backed inventory composition |
| `composition/testing.py` | Test-only inventories                |

### Persistence — `src/fleet_rlm/persistence/`

Schema is Alembic-managed. The Turn repository is the durable seam between coordination and storage.

| File                                 | Role                            |
| ------------------------------------ | ------------------------------- |
| `persistence/repositories/turns.py`  | Turn write and read repository  |
| `persistence/run_codec.py`           | Run payload encoding            |
| `persistence/run_claim_decisions.py` | Atomic Run claim decisions      |
| `persistence/run_liveness.py`        | Run liveness and lease tracking |
| `persistence/run_final_state.py`     | Final Run state materialization |
| `persistence/run_queries.py`         | Run read queries                |
| `persistence/session_catalog.py`     | Session and Turn catalog reads  |
| `persistence/sandbox_bindings.py`    | Sandbox binding records         |

### Sessions and assistant parts — `src/fleet_rlm/sessions/`

`sessions/assistant_parts.py` owns the closed Pydantic `AssistantPart` vocabulary for durable assistant content. Any new assistant content shape lives here first.

| File                          | Role                                       |
| ----------------------------- | ------------------------------------------ |
| `sessions/catalog.py`         | Session catalog primitives                 |
| `sessions/committed_turn.py`  | Committed Turn view                        |
| `sessions/assistant_parts.py` | Closed Pydantic `AssistantPart` vocabulary |
| `sessions/history_tools.py`   | History surfacing for the runner           |

### Skills — `src/fleet_rlm/skills/`

The bundled Skill catalog is immutable and is constructed eagerly during `create_app()`. Bundled Skills are `dspy-rlm`, `long-context`, `workspace-files`, `data-analysis`, and `report-builder`. Each Skill's contract lives in its bundled `SKILL.md` and its resolver in `src/fleet_rlm/skills/`.

## Reading order

Read these files in order when you need to understand the live backend:

1. `src/fleet_rlm/api/app.py`
2. `src/fleet_rlm/api/routes/turns.py`
3. `src/fleet_rlm/chat/turn_coordinator.py`
4. `src/fleet_rlm/chat/run_lifecycle.py`
5. `src/fleet_rlm/rlm/runner.py`
6. `src/fleet_rlm/daytona/interpreter.py`

## Source of truth

<CardGroup cols={2}>
  <Card title="Transport and lifespan" href="/fleet-rlm/reference/http-api">
    `src/fleet_rlm/api/` — routes, SSE, UI stream, OpenAPI derivation.
  </Card>

  <Card title="Turn coordination" href="/fleet-rlm/concepts/sessions-persistence">
    `src/fleet_rlm/chat/` — coordinator, lifecycle, preparation, execution.
  </Card>

  <Card title="Daytona substrate" href="/fleet-rlm/concepts/daytona-runtime">
    `src/fleet_rlm/daytona/` — interpreter, workspace gateway, recursive child runtime.
  </Card>

  <Card title="Runtime configuration" href="/fleet-rlm/reference/configuration">
    `config/fleet.toml` — the certified runtime configuration surface.
  </Card>
</CardGroup>

When the docs disagree with the code, trust the code and the generated contracts. The canonical HTTP schema is [`openapi.yaml`](https://github.com/qredence/fleet-rlm/blob/main/openapi.yaml).
