# Bellona Remote Adapter SDK

> Scope: the published, versioned interface a **third-party author** implements
> to add a new tool (a DCC, a renderer, a service) to the Bellona Remote Creative
> Control Plane — the `RemoteAdapter` contract, how to write an adapter, the
> conformance suite that gates it, packaging + telemetry + the policy sandbox
> boundary, and the SDK's **versioning, deprecation, and migration** policy.
>
> Implemented in `libs/bellona/remote-adapters/src/` (`180.C.32.01–32.07`). The
> companion **[Adapter Distribution](./adapter-distribution.md)** doc
> (`180.C.32.09`) covers signing, the signed registry, and the ad-hoc trust
> model. The SDK builds ON the wire protocol `@bellona/remote-protocol` and is a
> strict superset of the in-process host registration shape the remote host
> already routes commands to.

## 1. Why a contract

The remote host already proves the adapter SHAPE: every host integration
(Blender, Unreal, browser, file) is a `{ adapter, capabilities, commandHandlers,
health }` registration the in-process registry routes commands to. That shape is
real but **un-contracted** — a third-party author has no published interface to
implement, no guarantee their adapter handles preflight / idempotency /
cancellation / timeout / rollback the way the platform expects, and no way to
prove it before shipping.

`180.C.32.01` formalises that proven shape into a stable, versioned contract:
`RemoteAdapter` (`contract.ts`). The bridge `toRemoteHostRegistration(adapter)`
(`host-compat.ts`) wraps a contract adapter as the host's
`RemoteHostAdapterRegistration` structurally — so an SDK-built adapter registers
with the existing host, and a host adapter is expressible as a `RemoteAdapter`
because it already provides exactly these pieces.

## 2. The `RemoteAdapter` contract — the seven concerns

`RemoteAdapter` (`contract.ts`) owns the seven concerns every remote adapter must
handle end-to-end:

| # | Concern | Contract surface |
| --- | --- | --- |
| 1 | **Capability handshake** | `capabilities(): AdapterCapabilityHandshake` — the descriptor, the advertised `RemoteCapability[]`, the per-command `AdapterCommandRollbackDeclaration[]`, and the closed set of risk classes. |
| 2 | **Command dispatch** | `dispatch(command, options?): Promise<RemoteAdapterDispatchOutcome>` — execute one command, return a typed result. |
| 3 | **Progress + result** | `ctx.emitProgress(update)` streams `RemoteCommandProgress`; the assembled `RemoteCommandResult` is the final return. |
| 4 | **Audit hooks** | `ctx.captureEvidence({ evidence, artifact? })` registers the evidence/artifacts a mutating command produced. |
| 5 | **Policy preflight** | `preflight(command): AdapterPreflightResult` — allow/deny BEFORE execution, surfacing required scopes + the wire `RemoteErrorCode` a deny maps to. |
| 6 | **Rollback metadata** | per-command rollback declarations in the handshake + `rollbackStrategyFor(commandName)` — every mutating command declares a valid `RemoteRollbackStrategy`; read-only commands declare `null`. |
| 7 | **Health reporting** | `health(): AdapterHealthReport` — the adapter's health for the fleet. |

`init()` / `shutdown(reason?)` bracket the dispatch lifecycle so an adapter can
open and close real resources (a DCC connection, a browser context); both are
idempotent by contract, and `lifecycle()` reports the current
`AdapterLifecyclePhase` (`constructed → initializing → ready → shutting-down →
stopped`).

The contract is pinned by `ADAPTER_SDK_CONTRACT_VERSION` (currently `'1.0.0'`),
which the registry and gateway use to refuse an adapter built against an
incompatible revision (see §6).

### What `dispatch` enforces (so the author doesn't have to)

The factory-built `dispatch` (`define-adapter.ts`) runs a fixed lifecycle around
the author's handler, and these are **enforced**, not advisory:

- **Targeting** — an envelope addressing a different `adapterId` / `capabilityId`
  is refused (`validation.failed`), never silently mis-routed.
- **Contract consistency** — the envelope's `riskClass` and
  `metadata.<REMOTE_ROLLBACK_STRATEGY_METADATA_KEY>` must match what the handshake
  advertised for the command; a read-only command may not smuggle a rollback
  strategy.
- **Idempotency** — a repeated `idempotencyKey` replays the recorded outcome
  WITHOUT re-running the handler; the same key with a *different* request body is
  a `duplicate-idempotency-key` conflict (only deterministic-terminal failures are
  cached — a timeout/cancellation is not).
- **Timeout + cancellation** — the handler races the command's `timeoutMs`
  (injectable scheduler) and observes `ctx.signal`; a handler that ignores
  cancellation and keeps running cannot leak late progress/evidence — the context
  is **sealed** on resolution and a post-seal emission throws.
- **Audit integrity** — every captured evidence/artifact must be attributed to
  the dispatched `commandId`/`sessionId`; a capability with `evidenceRequired`
  forces a completing mutating command to have registered at least one evidence
  row.
- **Typed errors** — a non-taxonomy throw is wrapped as `internal.error` rather
  than leaking an ad-hoc string; failures render `failed` / `denied` /
  `timed-out` / `cancelled` results carrying a typed `RemoteCommandError`.

## 3. Writing an adapter

`defineRemoteAdapter(spec)` (`define-adapter.ts`) is the factory. It validates the
descriptor + capabilities + per-command rollback declarations fail-loud at
construction (via `AdapterCapabilityHandshakeSchema`) and binds the command map
into a contract-conforming `RemoteAdapter`. The spec:

```ts
defineRemoteAdapter({
  adapter,            // a RemoteAdapter descriptor (validated by RemoteAdapterSchema)
  capabilities,       // RemoteCapability[] this adapter advertises
  commands: [         // RemoteAdapterCommandSpec[] — every advertised command
    {
      commandName: 'file.text.write',
      riskClass: 'safe-mutation',
      rollbackStrategy: 'snapshot_restore', // REQUIRED for a mutating command; null for read-only
      handler: async (ctx) => {             // RemoteAdapterCommandHandler
        ctx.emitProgress({ status: 'running', percent: 50 });
        // ...do real work, observe ctx.signal, ctx.captureEvidence({...})...
        return { bytesWritten };            // the command OUTPUT record
      },
    },
  ],
  onInit, onShutdown, // optional resource lifecycle (wrapped idempotent)
  health, preflight,  // optional overrides; sensible defaults provided
});
```

The default `preflight` is a real, conservative scope gate: it derives the
command's required scopes from the protocol policy
(`requiredScopesForCommand` → `getRemoteCommandRequiredPermissionScopes`) and
denies (`policy.denied`) any command whose required scopes are not a subset of
the capability's declared scopes. An author overrides it for a domain-specific
check (e.g. a path-grant).

### The reference example — copy this

`createTextFileAdapter(options)` (`text-file-adapter.ts`, `180.C.32.07`) is the
adapter a third-party author copies to learn the contract. It is **real** — it
reads and writes actual UTF-8 text files inside a sandboxed directory — yet small
enough to read end-to-end. It demonstrates all seven concerns: a `file`-namespace
capability advertising `file.text.read` / `file.text.write` / `file.text.append`;
handlers that perform real `fs` I/O and emit accepted→running→completed progress;
write/append registering evidence whose `sha256` is the hash of the bytes
actually written; a preflight that refuses a path escaping the sandbox before any
I/O; `write` declaring `snapshot_restore` and `append` declaring `undo_stack`;
and a health probe that reports whether the sandbox directory is writable.

## 4. The conformance suite — how a third party proves their adapter

`runAdapterConformance(adapter, fixtures)` (`conformance.ts`, `180.C.32.02`)
drives ANY `RemoteAdapter` through the contract and returns an
`AdapterConformanceReport` of `AdapterConformanceCheck`s. It exercises the real
behaviour — the capability handshake is internally consistent; a read-only
command does not declare rollback while every mutating command does; a denied
preflight blocks dispatch; a cancelled command resolves `cancelled`; a command
exceeding its timeout resolves `timed-out` (via the injected deterministic
scheduler); idempotent replay returns the recorded outcome; evidence is attributed
to the dispatched command; a non-taxonomy throw becomes `internal.error`.

A third-party author builds fixtures for their own adapter and runs the suite as
part of their CI. For the file-shaped case,
`buildTextFileConformanceFixtures({...})` produces the read/write command
envelopes + expectations; an author writing a different adapter assembles the
equivalent `AdapterConformanceFixtures` for their commands. A package will not be
accepted into the signed registry (see the distribution doc) unless its
conformance report is green.

## 5. Packaging, telemetry, and the policy sandbox boundary

These three modules wrap a contract adapter for production without the author
writing the plumbing.

- **Packaging** (`packaging.ts`, `180.C.32.04`). `buildAdapterPackage(input,
  signingKey)` mints a signed bundle: a canonical, HMAC-SHA256-signed manifest
  pinning the adapter id + version + the SDK contract version it was built
  against, the declared namespaces/commands, the declared permission-scope set,
  and a `sha256` over every shipped file. `verifyAdapterPackage(pkg, adapter,
  trustedKeys, options)` is the runtime integrity check: trusted key + HMAC match,
  contract MAJOR, file hashes (tamper), and — crucially —
  **declared-vs-actual reconciliation** against the LIVE adapter (an undeclared
  command, a phantom namespace, or a scope ESCALATION beyond the signed manifest
  each fail with a specific verdict). This is the foundation the distribution
  model (`32.09`) builds publisher-trust and org-scope policy on top of.

- **Telemetry** (`telemetry-hooks.ts`, `180.C.32.05`). `bridgeAdapterTelemetry(
  adapter, sink)` wraps an adapter so EVERY dispatch auto-emits the exact
  `180.C.28.01` gateway metric names (`remote_gateway.command.count` /
  `.duration_ms` / `.failure_count`, `remote_gateway.adapter.health_state`) — the
  author writes no telemetry, and the adapter lands on the SAME dashboards/alerts
  as a first-party one. The values are MEASURED (count = 1, latency =
  `result.durationMs`, failure = 1 on non-success, health = 1/0), never invented.

- **Policy sandbox** (`policy-sandbox.ts`, `180.C.32.06`). `sandboxAdapterDispatch(
  adapter, command, ctx, guards)` is the platform's enforcement boundary AROUND
  the adapter handler. An adapter cannot be trusted to police itself, so the
  sandbox runs the platform preflight (device policy
  `evaluateRemoteCommandPolicy`, the default-deny sensitive-path guard
  `isSensitiveProtectedPath`, and org control `evaluateOrganizationControl`)
  BEFORE the handler; enforces the approval gate; appends the audit entries
  ITSELF from platform-evaluated facts (an adapter that emits no audit still
  produces a record); and re-validates the returned result, refusing an
  out-of-namespace or scope-escalating command even if the adapter would have run
  it. The adapter's own preflight (concern 5) can only ADD a deny — never override
  a platform deny.

```
author code:   defineRemoteAdapter(spec)  ──►  RemoteAdapter
platform wrap: bridgeAdapterTelemetry( sandboxAdapterDispatch-guarded dispatch )
distribution:  buildAdapterPackage ─► verifyAdapterForInstall ─► (host registers)
```

## 6. Versioning policy

The SDK contract revision is `ADAPTER_SDK_CONTRACT_VERSION` (`contract.ts`), a
frozen `MAJOR.MINOR.PATCH` string (currently `'1.0.0'`) that matches the protocol
version format. It is the version a package manifest records
(`AdapterPackageManifest.contractVersion`) and the registry/gateway pin against.

| Bump | Meaning for the `RemoteAdapter` contract | Compatibility |
| --- | --- | --- |
| **MAJOR** (`1.x.x → 2.0.0`) | A **breaking** change to the contract: a method signature changes, a required field is added/removed, a behavioural guarantee `dispatch` enforces is altered such that an existing adapter no longer conforms. | An adapter built against a different MAJOR is **refused**. |
| **MINOR** (`1.0.x → 1.1.0`) | A **backward-compatible** addition: a new OPTIONAL contract method or field, a new optional dispatch option, a new conformance check that an existing conforming adapter still passes. | A host on `1.1` accepts a `1.0` adapter; a `1.1` adapter SHOULD degrade on a `1.0` host (the new surface is optional). |
| **PATCH** (`1.0.0 → 1.0.1`) | A fix with **no** contract-shape change: a clarified guarantee, a tightened validation that rejects only previously-invalid input, a bug fix in the factory. | Fully interchangeable within a MAJOR. |

### Host ↔ adapter contract-version compatibility

Compatibility is decided on the **MAJOR** axis, mirroring the
`180.C.29.15` protocol negotiation concepts (see
[Protocol Evolution](./protocol-evolution.md) §3). The check lives in
`verifyAdapterPackage`: the host passes its `supportedContractMajor` (defaulting
to the SDK's MAJOR, `Number(ADAPTER_SDK_CONTRACT_VERSION.split('.')[0])`), and a
package whose manifest `contractVersion` MAJOR differs yields the
`contract-version-incompatible` verdict — exactly the adapter-SDK analogue of a
protocol peer below the support floor being refused at the handshake. The
distribution gate (`verifyAdapterForInstall`) surfaces the same condition as a
first-class `refused-contract-incompatible` install refusal.

This is deliberately a MAJOR-only gate (not the richer per-component
`negotiateProtocolVersion` drift window): the adapter contract is a single
in-process interface, not two independently-deployed runtimes, so a shared MAJOR
is the necessary and sufficient compatibility condition. The MINOR/PATCH
additivity rules above are what make "same MAJOR ⇒ compatible" hold.

## 7. Deprecation policy

A contract field, a dispatch option, or a contract method is deprecated through
the **announce → sunset** discipline the protocol already uses for commands and
fields (`RemoteDeprecationRegistry`, `protocol-evolution.ts`, `180.C.29.15`).
There is one deprecation mechanism in Bellona; the adapter SDK reuses it rather
than inventing a parallel one.

1. **Announce** in a MINOR bump. The replacement is shipped alongside the
   deprecated surface; the deprecated surface keeps working. A `RemoteDeprecation`
   records the `announcedInVersion`, a (strictly newer) `sunsetInVersion`, a
   `reason`, and the `replacementCommandName` / `replacementFieldPath` +
   `migrationGuideUri`. `registry.check(target, runtimeVersion)` returns
   `deprecated` (allowed, **with a warning** the host surfaces/logs) from the
   announce version until the sunset.
2. **Sunset** in the next MAJOR bump. Once the runtime is at/after
   `sunsetInVersion`, `check` returns `sunset` (NOT allowed) and
   `assertCommandNotSunset(...)` throws a `RemoteDeprecationSunsetError` —
   fail-loud, never a silent no-op.

The sunset window MUST span at least one MAJOR: a surface deprecated in `1.1`
sunsets no earlier than `2.0.0`. That guarantees an author always has a release in
which BOTH the old and new surface exist, so they can migrate without a flag day.
Field-level deprecation also honours severity escalation — a sunset command
sunsets its fields too (a field check can never "escape" a sunset command), per
the registry's more-severe-wins rule.

## 8. Migration guide — moving an adapter across a contract MAJOR

When the SDK contract bumps MAJOR (e.g. `1.x → 2.0.0`), an existing adapter must
be migrated. The concrete steps:

1. **Read the changelog + the deprecation list.** Every breaking change shipped
   in `2.0.0` was announced as a `RemoteDeprecation` during the `1.x` line. List
   them with the registry (`registry.list()`); each carries its replacement and
   `migrationGuideUri`.
2. **Update the dependency** to the `2.x` SDK and rebuild against the new
   `RemoteAdapter` interface. The TypeScript compiler surfaces every changed
   signature — a MAJOR bump is exactly the set of changes the type system now
   rejects.
3. **Adopt the replacements** for each sunset surface (the new method/field/option
   the deprecation named). Where a default changed, set it explicitly.
4. **Re-run conformance** (`runAdapterConformance`) against the `2.x` suite. The
   suite is the source of truth for "does this adapter conform to the new
   contract" — green is the bar, not a manual reading.
5. **Re-stamp the package.** Re-build with `buildAdapterPackage`; the manifest's
   `contractVersion` now records `2.0.0`. A host on MAJOR 2 accepts it; a host
   still on MAJOR 1 keeps installing your last `1.x` package (publish both during
   the overlap).
6. **Bump your adapter's OWN version** (`adapterVersion`) — the adapter version and
   the contract version are independent axes. A contract MAJOR bump that you adopt
   is at least a MINOR of your adapter (new behaviour), often a MAJOR if your own
   command surface changed.

A worked, file-by-file walkthrough of a `v1 → v2` migration of the reference
text-file adapter lives in
**[Adapter SDK Migration Guide](./adapter-sdk-migration-guide.md)**.

## 9. Tests

`libs/bellona/remote-adapters/src/*.test.ts` assert the real behaviour:

- `define-adapter.test.ts` / `conformance.test.ts` — the full dispatch lifecycle
  and every conformance check (preflight deny, timeout, cancellation, idempotent
  replay, evidence attribution, typed errors).
- `packaging.test.ts` — a valid signed package verifies; a tampered file, an
  altered manifest, an untrusted key, an incompatible contract MAJOR, a scope
  escalation, an undeclared command, and a phantom namespace each fail with their
  specific verdict.
- `host-compat.test.ts` — an SDK adapter bridges to a host registration and a
  failed dispatch surfaces the taxonomy code.
- `telemetry-hooks.test.ts` / `policy-sandbox.test.ts` — auto-telemetry emits the
  measured 28.01 series, and the sandbox enforces preflight/approval/audit/scope
  around an adversarial adapter.
- `distribution.test.ts` (`32.09`) — the signed-registry install path, the ad-hoc
  override + trust downgrade, and the forbidden-scope / tampered / untrusted
  refusals (see the distribution doc).
