# Bellona Remote Control — Developer Guide (180.C.29.03)

How to extend the Remote Creative Control Plane: add a command, an adapter, an MCP
tool, a policy rule, an approval gate, audit evidence, and the tests that prove
each is real. Read the [Architecture](./architecture.md) first; this guide assumes
you know the gateway/host/protocol split.

Everything below references real code as `path/to/file.ts:Symbol`. The golden
rule, enforced by the schema itself: **the protocol package
(`@bellona/remote-protocol`) owns every wire shape.** A new command, scope, or
audit type is added *there first*, then consumed by the gateway/host.

---

## 1. Add a new command to an existing adapter

A command is `namespace.verb[.noun]`. Example: add `blender.collection.rename`.

1. **Define the command name + payload schema** in the protocol package
   (`libs/bellona/remote-protocol/src/blender.ts` for Blender) — export a
   `RemoteBlender…CommandName` constant and a Zod schema for its arguments/result.
   Keep it `.strict()`.

2. **Pick a risk class deliberately** (`RemoteCommandRiskClassSchema` in
   `command.ts`). A rename mutates, so it is at least `safe-mutation`. The envelope
   schema will then *require* you to declare:
   - a `metadata.rollbackStrategy` (one of `RemoteRollbackStrategySchema`), and
   - for `destructive`/`privileged`, dry-run support
     (`metadata.dryRunSupported` + `metadata.dryRunPlanId`) and
     `approvalRequired=true`.

   These are enforced in `RemoteCommandEnvelopeSchema.superRefine` — you cannot
   construct an under-governed envelope.

3. **Advertise it on the adapter capability.** In the adapter's
   `RemoteHostAdapterRegistration` (see §2) add the command name to a
   `RemoteCapability.commandNames` and list any extra permission scopes the
   capability needs in `permissionScopes`.

4. **Write the handler** keyed by the full command name in the adapter's
   `commandHandlers` map (signature
   `(command, context?) => RemoteCommandArguments | Promise<…>`).

5. **Verify the policy derives the right scopes.** `policy.ts` infers required
   scopes from the command *name verbs* — `rename` is in `mutatingCommandTerms`,
   so a Blender mutating command picks up `project.write` automatically. If your
   verb is novel, add it to the appropriate term set in `policy.ts`
   (`mutatingCommandTerms` / `destructiveCommandTerms` / `arbitraryCodeTerms` / …)
   so `getRemoteCommandRequiredPermissionScopes` classifies it.

6. **Compensating actions for `browser`/`desktop` safe-mutations.** If your
   command is a mutating `browser.*` or `desktop.*` command, register its
   protocol-owned compensating action in `browser-compensating-actions.ts` /
   `desktop-compensating-actions.ts` — the envelope schema refuses the command
   until `metadata` names it.

---

## 2. Add a new adapter

An adapter is a `RemoteHostAdapterRegistration`
(`apps/bellona/remote-host/src/adapter-registry.ts`). The fake Blender adapter
(`createFakeBlenderAdapterRegistration`, same file) is the minimal worked example
— read it end to end; it is ~60 lines and registers `blender.scene.query`.

```ts
import {
  type RemoteHostAdapterRegistration,
} from '@bellona/remote-host'; // re-exported from src/index.ts

export function createMyAdapterRegistration(): RemoteHostAdapterRegistration {
  return {
    adapter: { id: 'adapter:my-thing-local', /* …RemoteAdapter fields… */ },
    capabilities: [
      {
        id: 'capability:my-thing',
        adapterId: 'adapter:my-thing-local',
        namespace: 'blender',                  // an existing RemoteCommandNamespace
        commandNames: ['blender.collection.rename'],
        permissionScopes: ['project.write'],   // must be declared on the device too
        status: 'available',
        /* …RemoteCapability fields… */
      },
    ],
    commandHandlers: new Map([
      ['blender.collection.rename', async (command) => {
        // real work here; return RemoteCommandArguments
        return { renamed: true };
      }],
    ]),
    health: { /* RemoteHostAdapterHealth */ },
    stop: async () => { /* tidy up */ },
  };
}
```

Register it:

- **By default for every host:** add it to the constructor of
  `InMemoryRemoteHostAdapterRegistry` (`adapter-registry.ts`, where the existing
  adapters are registered).
- **Per-process / per-test:** call
  `registry.registerAdapter(createMyAdapterRegistration())` after
  `createInMemoryRemoteHostAdapterRegistry(...)`. Pass
  `{ registerDefaultFakeAdapters: false }` to start from a clean registry.

The registry's `routeCommand` (`adapter-registry.ts`) matches an incoming
envelope's command name to the advertising capability — you never touch the
command executor. New OS-level process launch or screen capture goes through
`@bellona/host-runtime` (see [Host Permission Abstraction](./host-permission-abstraction.md)),
not a `process.platform` branch in your adapter.

---

## 3. Add an MCP tool

The MCP gateway (`libs/bellona/mcp-gateway`) exposes a **curated** subset of
remote-control operations to agent runtimes over stdio. The current tool set is
`BELLONA_MCP_REMOTE_CONTROL_TOOL_NAMES`
(`libs/bellona/mcp-gateway/src/remote-control-tools.ts`):
`device.list`, `session.start`, `session.stop`, `blender.scene.info`,
`blender.create_primitive`, `browser.navigate`, `browser.snapshot`,
`desktop.screenshot`. Resources are in
`remote-control-resources.ts` (`BELLONA_MCP_REMOTE_CONTROL_RESOURCE_URIS`).

To add a tool:

1. Add the tool name to `BELLONA_MCP_REMOTE_CONTROL_TOOL_NAMES` and register its
   schema + handler in `registerBellonaRemoteControlMcpTools`
   (`remote-control-tools.ts`). The handler calls the injected
   `BellonaMcpRemoteControlGateway` (with methods `dispatchCommand`, `listDevices`,
   `startSession`, `stopSession`) — i.e. it ultimately dispatches a real protocol
   command through the same gateway the SDK/CLI use. The MCP server is a *tool
   surface over the gateway*, not a second authority.

2. Tools register **only when a `remoteControlGateway` is wired** into
   `createBellonaMcpGatewayServer` / `connectBellonaMcpGatewayStdioServer`
   (`stdio-server.ts`). With no gateway wired the stdio server starts but exposes
   no remote-control tools — by design. Bind it to an authenticated gateway client
   session via `remoteControlAuthSession`
   (`BellonaMcpGatewayAuthSessionBindingOptions`).

3. Mark read-only vs mutating + idempotency honestly in the tool annotations —
   the existing definitions do (`device.list` is read-only idempotent;
   `session.start` is mutating non-idempotent).

---

## 4. Add a policy rule (required permission scope)

Authorization is `evaluateRemoteCommandPolicy`
(`libs/bellona/remote-protocol/src/policy.ts`), a pure function over `(command,
device)`. It computes required scopes, resolves them against the device's granted
permissions, and returns `allowed | requires-approval | denied`.

Two ways to extend it:

- **By verb.** Scopes are derived from the command-name tokens. Add your verb to
  the relevant set near the top of `policy.ts`: `mutatingCommandTerms`,
  `destructiveCommandTerms`, `arbitraryCodeTerms`, `shellTerms`,
  `publishingTerms`, `financialTerms`, `readCommandTerms`, `desktopObserveTerms`,
  `desktopInputTerms`. e.g. adding `transcode` to `mutatingCommandTerms` makes any
  `…​.transcode` command require write scopes.

- **By namespace.** Extend the namespace branches in
  `getRemoteCommandRequiredPermissionScopes` (e.g. the `desktop` branch adds
  `desktop.observe` / `desktop.input`; the `browser` branch infers
  `browser.profile.real` vs `browser.profile.isolated` from the `profile`
  argument; the `file` branch splits read vs write).

If a scope should also force a dry-run, add it to `dryRunRequiredScopes` in the
same file (maps a scope to a `RemoteDryRunRequiredRiskClass`).

A new *scope value* itself is added to `RemotePermissionScopeSchema`
(`libs/bellona/remote-protocol/src/device.ts`); the device must then grant it for
the policy to allow the command.

---

## 5. Add / change an approval gate

Approvals are a gateway concern. The flow:

1. The dispatcher
   (`apps/bellona/remote-gateway/src/command-dispatcher.ts:dispatchCommand`) runs
   `evaluateRemoteCommandPolicy`. A `requires-approval` decision (or
   `command.approvalRequired === true`) creates an approval request via
   `approval-service.ts:createCommandApprovalRequest`.
2. The request is `pending` until an operator decides through
   `POST /v1/approvals/{requestId}/decisions` →
   `approval-service.ts:decideApproval` (`approved | denied | cancelled`), or it
   `expire`s after `BELLONA_REMOTE_GATEWAY_APPROVAL_REQUEST_TTL_MS`
   (`expireApprovalRequests`, swept on a timer in `app.ts`).
3. On `approved`, the registered continuation handler
   (`setApprovalContinuationHandler`) resumes dispatch
   (`command-dispatcher.ts:continueApprovedCommand`).

To **force approval** for a class of commands, give them a `destructive` /
`privileged` risk class (the envelope schema then *requires*
`approvalRequired=true`), or have your policy branch return `requires-approval`
for the relevant scopes. To require *N approvers* / forbid certain risk classes at
the org level, use `organization-control.ts` (the `risky-approval` surface). The
operator-side UI is `apps/bellona/control-room/src/approval-queue.ts`
(`applyControlRoomApprovalAction`).

---

## 6. Emit audit evidence

The audit log is **hash-chained and tamper-evident** — do not invent your own
hashing. Append through `apps/bellona/remote-gateway/src/audit-log.ts:appendEntry`
(`RemoteGatewayAuditEntryInput`), which computes the entry hash with the single
authoritative `computeRemoteAuditEntryHash`
(`libs/bellona/remote-protocol/src/audit-chain.ts`) and links `previousHash`.

- An entry carries `type` (a `RemoteAuditEntryType` — e.g. `command.received`,
  `command.dispatched`, `command.completed`, `approval.requested`,
  `approval.decided`, `policy.denied`, `artifact.registered`,
  `evidence.captured`, `session.*`), the full `actorChain`, and `evidenceIds` /
  `artifactIds`.
- To add a new audit type, extend `RemoteAuditEntryType` in the protocol package,
  then append entries of that type at the right point in the gateway.
- **Evidence files / artifacts** are registered via `POST /v1/artifacts`
  (`artifact-registry.ts`) with their SHA-256 + size; reference their ids in the
  audit entry's `artifactIds`. Verify a session's chain end-to-end with
  `verifyAuditChain` / export it with `GET /v1/audit/export` (canonical-json or
  jsonl, self-verifying). For a high-trust session, `assertHighTrustCommandChained`
  refuses to leave a command unchained.

---

## 7. Tests — prove it is real

The codebase tests domain correctness, not just data flow. Patterns to follow:

- **Protocol schemas** — assert invariants. e.g. a `destructive` command without
  `approvalRequired` must `throw` at parse; a `direct_lan` route without
  `lanVerified` must fail (`command.test.ts`, `transport.test.ts`).
- **Policy** — assert exact scope lists + decisions for concrete commands
  (`policy.ts` has a sibling test; e.g. `blender.object.delete` ⇒
  `command.execute.destructive` + `project.write`, decision gated on grants).
- **Adapter + executor round-trip** — `apps/bellona/remote-host/src/adapter-registry.test.ts`
  and `command-executor.test.ts` route a real envelope through the fake adapter and
  assert the emitted progress/result events. Both pass on the Linux CI box (no
  Mac/Blender needed).
- **Gateway ↔ host WebSocket** — `apps/bellona/remote-gateway/src/host-connections.test.ts`
  drives the real `/v1/hosts/connect` handshake + `command.dispatch` end to end.
- **Full in-process round-trip script** —
  `apps/bellona/remote-host/scripts/blender-scene-info-remote-smoke.ts` boots a
  gateway + host, issues a real host token, dispatches `blender.scene.query`, and
  reads the hash-chained audit + unified timeline (used by the
  [Quickstart](./quickstart.md)). It runs on this box; the real Blender adapter
  falls back to deterministic output when no live Blender is present
  (`"fallback": true`).

Run them (no Nx required — call vitest directly from the package dir):

```bash
# gateway WS round-trip
cd apps/bellona/remote-gateway && npx vitest run src/host-connections.test.ts
# host adapter + executor
cd apps/bellona/remote-host  && npx vitest run src/adapter-registry.test.ts src/command-executor.test.ts
# protocol policy/envelope invariants
cd libs/bellona/remote-protocol && npx vitest run src/policy.test.ts src/command.test.ts
```

Mock at dependency boundaries (network, clock, a live DCC), never fake the thing
under test. An honest fail-loud seam (a provider that `throw`s `not_configured`)
is correct, not a stub — see the host runtime's `NullHostRuntime`
([Host Permission Abstraction §4](./host-permission-abstraction.md)).

---

## 8. Extension-point quick reference

| To add… | Edit | Key symbol |
| --- | --- | --- |
| A command | `remote-protocol/src/<ns>.ts` + adapter capability | command-name const + `RemoteCapability.commandNames` |
| An adapter | `remote-host/src/adapter-registry.ts` (or your own file) | `RemoteHostAdapterRegistration`, `registerAdapter` |
| An MCP tool | `mcp-gateway/src/remote-control-tools.ts` | `BELLONA_MCP_REMOTE_CONTROL_TOOL_NAMES`, `registerBellonaRemoteControlMcpTools` |
| A policy rule | `remote-protocol/src/policy.ts` | term sets + `getRemoteCommandRequiredPermissionScopes` |
| A permission scope | `remote-protocol/src/device.ts` | `RemotePermissionScopeSchema` |
| An approval gate | `remote-gateway/src/{command-dispatcher,approval-service}.ts` | `dispatchCommand`, `decideApproval` |
| An audit type | `remote-protocol/src/audit-chain.ts` + gateway append | `RemoteAuditEntryType`, `appendEntry` |
| A host platform | `host-runtime/src/host-platform.ts` (+ provider/launcher) | `PLATFORM_PERMISSION_MATRIX`, `createHostRuntime` |

See also the [bridge coexistence / deprecation plan](./bridge-coexistence-and-deprecation-plan.md)
and the [compatibility matrix](./compatibility-matrix.md).
