|
| 1 | +# Gateway Protocol Drift Guard |
| 2 | + |
| 3 | +> Source of truth: [`openclaw/openclaw` — `packages/gateway-protocol/src/schema/{sessions,commands}.ts`](https://github.com/openclaw/openclaw/tree/main/packages/gateway-protocol/src/schema) |
| 4 | +
|
| 5 | +## Why this exists |
| 6 | + |
| 7 | +The Windows companion can silently drift from the upstream OpenClaw gateway |
| 8 | +protocol — when methods or session fields change upstream but the Windows client |
| 9 | +(`OpenClawGatewayClient`) keeps sending the old shapes. Because the gateway |
| 10 | +tolerates unknown/extra fields, such drift ships without any test failing. |
| 11 | + |
| 12 | +The **drift guard** pins a hand-maintained mirror of the upstream gateway protocol |
| 13 | +for the `sessions` / `files` / `commands` / compaction surface and fails the test |
| 14 | +suite whenever the typed client and the pinned schema diverge. |
| 15 | + |
| 16 | +The typed client implements the richer protocol surface — |
| 17 | +`commands.list`, the extended `sessions.patch` field set, `sessions.files.list`/ |
| 18 | +`get`, and `sessions.compaction.list`/`get`/`branch`/`restore` — across |
| 19 | +`OpenClawGatewayClient.Protocol.cs` and the DTO/payload builders in |
| 20 | +`GatewayProtocolModels.cs`. This guard pins that whole surface. |
| 21 | + |
| 22 | +It is intentionally **deterministic and repo-contained**: it requires neither a |
| 23 | +clone of the upstream `openclaw/openclaw` repo nor any network access, so it runs |
| 24 | +in the normal `OpenClaw.Shared.Tests` suite. It **complements** the behavioural |
| 25 | +parser tests in `GatewayProtocolModelsTests` (which parse sample JSON and assert |
| 26 | +DTO mapping) by statically guarding the method / request-field / response-envelope |
| 27 | +*surface*, so an upstream rename or a dropped API is caught even when the parser |
| 28 | +unit tests still pass on their fixed sample payloads. |
| 29 | + |
| 30 | +## Files |
| 31 | + |
| 32 | +| File | Role | |
| 33 | +| --- | --- | |
| 34 | +| `tests/OpenClaw.Shared.Tests/Protocol/gateway-protocol-snapshot.json` | The pinned canonical schema mirror. **Edit this when upstream changes.** | |
| 35 | +| `tests/OpenClaw.Shared.Tests/Protocol/GatewayProtocolDriftTests.cs` | The guard. Cross-checks the snapshot against `OpenClawGatewayClient*.cs` + `GatewayProtocolModels.cs`. | |
| 36 | + |
| 37 | +## What the guard checks |
| 38 | + |
| 39 | +1. **Method surface** (`ScopedMethodSurface_matches_snapshot`) |
| 40 | + - Every in-scope method the client actually *wires* — request methods it |
| 41 | + **dispatches** (a method literal passed as a call argument to any dispatcher, |
| 42 | + e.g. `TrySendTrackedRequestAsync("sessions.patch", …)`, |
| 43 | + `TryRequestPayloadAsync("commands.list", …)`, or the private |
| 44 | + `MutateCompactionAsync("sessions.compaction.branch", …)` forwarder), plus |
| 45 | + notifications it **handles** via `case "…":` — must be pinned in the snapshot. |
| 46 | + - Every method pinned `windowsUsage: "used"` must still be wired in the way its |
| 47 | + `kind` implies: a **request** must still be *dispatched* (a leftover `case` |
| 48 | + label, a `method is "…"` predicate, or a log sentence is not enough), a |
| 49 | + **notification** must still be *handled*. Dropping one is the classic |
| 50 | + drift regression. |
| 51 | + - A `planned` method must **not** already be wired — if the client starts using |
| 52 | + it, the guard forces you to flip it to `used` and verify its response shape. |
| 53 | + (None currently — the typed client wires the whole surface.) |
| 54 | +2. **`sessions.list` response shape** (`SessionsList_responseShape_matches_snapshot`) |
| 55 | + - The session wire-fields the client parses (scoped to the two session-parsing |
| 56 | + methods) must exactly equal the snapshot's `responseFields` (both directions). |
| 57 | +3. **Request parameters** (`RequestParameterNames_arePresentInConstructionRegion`) |
| 58 | + - For each `used` request method, the set of wire keys the client actually |
| 59 | + constructs in the request-construction region must **exactly equal** the pinned |
| 60 | + `requestFields` (modulo a per-method `allowedExtraRequestFields` allowlist). |
| 61 | + The comparison is **bidirectional**: |
| 62 | + - **missing** (pinned − constructed): the client no longer sends a field the |
| 63 | + schema expects — e.g. renaming a wire key while the old name survives as a |
| 64 | + local/parameter (`new { sessionKey = key }` when `key` is still pinned) is |
| 65 | + caught, because the check compares *constructed keys*, not token presence. |
| 66 | + - **unexpected** (constructed − pinned − allowed): the client still constructs |
| 67 | + a stale/extra key that is no longer in the schema. Strict gateways |
| 68 | + (`additionalProperties:false`) reject the whole request on an unknown field, |
| 69 | + so this is real drift. Set `allowedExtraRequestFields` on a method to declare |
| 70 | + an intentional client-only extra the gateway tolerates. |
| 71 | + - A constructed wire key is an anonymous-object member (`new { sessionKey = key, |
| 72 | + path }`) or a dictionary string key (`payload["model"] = …`) in the region. |
| 73 | + - The region is the enclosing block of an actual dispatch call, or — when the |
| 74 | + payload is built by a helper rather than inline — the explicit |
| 75 | + `requestFieldsSource` builder body (the extended `sessions.patch` fields are |
| 76 | + checked against `SessionPatch.ToPayload`; the compaction `branch`/`restore` |
| 77 | + params against `MutateCompactionAsync`). `requestFieldsSource` must resolve |
| 78 | + **uniquely** to a body that actually constructs keys, and a dispatch from an |
| 79 | + expression-bodied member (where the region would degrade to the whole type) |
| 80 | + **fails closed** asking for a `requestFieldsSource`. |
| 81 | +4. **Response envelope** (`ResponseEnvelopes_areReadByClient`) |
| 82 | + - For each `used` method that pins a `responseEnvelope`, the client must read |
| 83 | + that property — `TryGetProperty("…")` **or** `TryGetArray(payload, "…")` — |
| 84 | + **inside that method's own parser body** (pinned via `responseEnvelopeSource`), |
| 85 | + so one parser reading the same property name (e.g. several read `"checkpoint"`) |
| 86 | + cannot satisfy a different method's envelope. An upstream envelope rename forces |
| 87 | + client reconciliation. |
| 88 | +5. **Snapshot integrity** (`Snapshot_isWellFormed_andCoversFoundationShapes`) |
| 89 | + - The snapshot stays well-formed, keeps covering every protocol-foundation shape |
| 90 | + (`commands.list`, `sessions.list`/`patch`/`compact`, `agents.files.list`/`get`, |
| 91 | + `sessions.files.list`/`get`, `sessions.compaction.list`/`get`/`branch`/ |
| 92 | + `restore`), and keeps its honesty invariant: `provisionalResponseFields` may |
| 93 | + only be set while `windowsUsage: "planned"`. |
| 94 | +6. **Tri-state clear contract** (`TriStateClearContract_isWiredInClient`) |
| 95 | + - Upstream `SessionsPatchParamsSchema` types every `sessions.patch` field as |
| 96 | + `Union([<value>, Null])`, where an explicit null **removes** a session |
| 97 | + override. The client models this with a tri-state `PatchField<T>`: **unset** |
| 98 | + (null reference) → omitted, a **value** → sent (blank string omitted), and |
| 99 | + `SessionPatch.Clear` → **explicit JSON null**. For any method declaring |
| 100 | + `requestFieldSemantics: "tristate-nullable"`, this guard statically verifies |
| 101 | + the builder source still wires the clear→null routing, the blank-omit guard, |
| 102 | + and the value-state gate, and that the `PatchField<T>` type still exposes its |
| 103 | + three states — so a refactor that removes the machinery is caught structurally |
| 104 | + here, independent of the behavioural emission tests. (Runtime emission is |
| 105 | + covered by `GatewayProtocolModelsTests`.) |
| 106 | + |
| 107 | +> Extraction is intent-specific and resilient: request-method literals are read |
| 108 | +> from real dispatch call sites (excluding logging sinks) and notifications from |
| 109 | +> `case` labels — not comments, `method is "…"` predicates, or log strings. Each |
| 110 | +> source is preprocessed into two index-aligned views: a *code* view with comments |
| 111 | +> blanked (literal extraction, so commented-out code never counts) and a *masked* |
| 112 | +> view with comments **and** string/char literals blanked (brace structure, so |
| 113 | +> braces inside literals/comments cannot desync the matcher). A self-check asserts |
| 114 | +> the masked view stays brace-balanced. |
| 115 | +
|
| 116 | +### Enforced vs. documentation-only fields |
| 117 | + |
| 118 | +Not every field in the snapshot is cross-checked against the client. Refreshers |
| 119 | +should know which edits are actually validated: |
| 120 | + |
| 121 | +| Snapshot field | Enforced against the client? | |
| 122 | +| --- | --- | |
| 123 | +| `methods[].method` (in-scope) | **Yes** — must match what the client dispatches/handles. | |
| 124 | +| `windowsUsage` (`used`/`planned`) | **Yes** — drives the dispatch/handle requirement and the planned-not-wired check. | |
| 125 | +| `sessions.list.responseFields` | **Yes** — exact set vs. the session parser. | |
| 126 | +| `requestFields` of `used` request methods | **Yes** — bidirectional: must exactly equal the wire keys constructed in the region (missing **and** unexpected both fail). | |
| 127 | +| `allowedExtraRequestFields` | **Yes** — exempts the listed client-only extras from the "unexpected" direction; everything else still fails. | |
| 128 | +| `requestFieldsSource` | **Yes** — must resolve uniquely to a body that constructs keys; that body is the region. | |
| 129 | +| `responseEnvelope` of `used` methods | **Yes** — must be read (`TryGetProperty`/`TryGetArray`) by the pinned parser. | |
| 130 | +| `responseEnvelopeSource` | **Yes** — required when `responseEnvelope` is pinned; must resolve uniquely to the parser body that reads the envelope (no whole-client fallback). | |
| 131 | +| `tristateContract` (markers + state members) | **Yes** — for `requestFieldSemantics: "tristate-nullable"`, the builder source must implement every marker and the `PatchField<T>` type must expose every state. | |
| 132 | +| `kind`, `scopePrefixes`, foundation coverage | **Yes** — snapshot-integrity invariants. | |
| 133 | +| `itemFields` (per-item descriptor fields) | **No** — documentation-only; behaviour covered by `GatewayProtocolModelsTests` parsers. | |
| 134 | +| `_comment`, `_note`, `_itemFieldsNote`, provenance | **No** — documentation-only. | |
| 135 | + |
| 136 | + |
| 137 | +## Tri-state clear contract (`sessions.patch`) |
| 138 | + |
| 139 | +Upstream `SessionsPatchParamsSchema` types every `sessions.patch` field as |
| 140 | +`Union([<value>, Null])`. A field can therefore be in one of three states, and the |
| 141 | +Windows client mirrors this with the tri-state `PatchField<T>`: |
| 142 | + |
| 143 | +| State | How the client expresses it | Wire result | |
| 144 | +| --- | --- | --- | |
| 145 | +| **unset** | leave the `PatchField<T>` default / assign a null reference | field **omitted** from the request | |
| 146 | +| **set** | assign a value (`patch.Model = "gpt-5"`) | field sent with the value (a **blank** string is omitted per `NonEmptyString`) | |
| 147 | +| **clear** | assign the sentinel (`patch.Model = SessionPatch.Clear`) | field sent as **explicit JSON `null`** (removes the session override) | |
| 148 | + |
| 149 | +The drift guard pins this contract in the snapshot under |
| 150 | +`sessions.patch.tristateContract` and checks it statically (Guard 6): the |
| 151 | +`SessionPatch` builder must keep the clear→null routing, the blank-omit guard, and |
| 152 | +the value-state gate, and `PatchField<T>` must keep its `IsSpecified`/`IsClear`/ |
| 153 | +`HasValue` states. The actual JSON emission for each state is covered behaviourally |
| 154 | +by `GatewayProtocolModelsTests` (`SessionPatch_ToPayload_ClearEmitsExplicitNull*`, |
| 155 | +`…MixesSetAndClearAndUnset`, `PatchField_TriStateFlags`) and end-to-end by |
| 156 | +`GatewayProtocolLiveRoundTripTests` (a loopback-WebSocket test capturing the real |
| 157 | +wire frames) — the guard is the static, upstream-mirrored complement, not a duplicate. |
| 158 | + |
| 159 | +## `windowsUsage` semantics |
| 160 | + |
| 161 | +| Value | Meaning | |
| 162 | +| --- | --- | |
| 163 | +| `used` | The client dispatches/handles this method today. The guard **requires** it to remain wired up. | |
| 164 | +| `planned` | Defined upstream but not yet consumed by the Windows client. The shape is pinned so future adoption matches upstream, but the client is not required to use it yet. (None currently — the typed client wires the whole surface.) | |
| 165 | + |
| 166 | +## How to refresh the snapshot when upstream changes |
| 167 | + |
| 168 | +When the upstream gateway protocol changes (a new `sessions.*` method, a renamed |
| 169 | +session field, a new `commands.list` descriptor field, etc.): |
| 170 | + |
| 171 | +1. Open the upstream schema on `main`: |
| 172 | + - `packages/gateway-protocol/src/schema/sessions.ts` |
| 173 | + - `packages/gateway-protocol/src/schema/commands.ts` |
| 174 | +2. Update `tests/OpenClaw.Shared.Tests/Protocol/gateway-protocol-snapshot.json`: |
| 175 | + - Add/rename/remove methods under `methods[]`. |
| 176 | + - Update `requestFields` / `responseFields` / `responseEnvelope` to match the |
| 177 | + wire field names. Field/method names may use letters, digits and underscores. |
| 178 | + - When a method's request payload is built by a helper rather than inline at the |
| 179 | + dispatch site (e.g. `SessionPatch.ToPayload`, `MutateCompactionAsync`), point |
| 180 | + `requestFieldsSource` at a unique fragment of that builder's declaration so |
| 181 | + Guard C searches the right body. |
| 182 | + - When a method pins a `responseEnvelope`, also set `responseEnvelopeSource` to a |
| 183 | + unique fragment of the parser body that reads it (Guard D requires it). |
| 184 | + - If upstream changes a field's nullability semantics (e.g. a field becomes |
| 185 | + `Union([<value>, Null])`, making explicit null a "clear" signal), update the |
| 186 | + `tristateContract` markers for that method and confirm the client's tri-state |
| 187 | + `PatchField<T>` builder still implements them (Guard 6). |
| 188 | + - Bump `snapshotUpdated` to today's date and set `upstreamCommit` to the exact |
| 189 | + upstream schema commit SHA you mirrored (so the pin is reproducible/auditable; |
| 190 | + `upstreamRef: "main"` alone is not). |
| 191 | + - For a method upstream added that the Windows client doesn't consume yet, set |
| 192 | + `windowsUsage: "planned"`; pin its shape and, if the response fields are not |
| 193 | + yet verified against upstream, set `provisionalResponseFields: true`. |
| 194 | +3. Run the guard: |
| 195 | + ```powershell |
| 196 | + $env:OPENCLAW_REPO_ROOT = (Get-Location).Path |
| 197 | + dotnet test ./tests/OpenClaw.Shared.Tests/OpenClaw.Shared.Tests.csproj --filter GatewayProtocolDriftTests |
| 198 | + ``` |
| 199 | +4. If the guard fails, reconcile the typed client (`OpenClawGatewayClient.cs`, |
| 200 | + `OpenClawGatewayClient.Protocol.cs`, and the DTOs in `GatewayProtocolModels.cs` / |
| 201 | + `SessionInfo` in `Models.cs`) with the new schema — that reconciliation is the |
| 202 | + whole point of the guard. Update the snapshot only to reflect upstream, never to |
| 203 | + silence a real client gap. |
| 204 | + |
| 205 | +## Known limitation: snapshot ↔ upstream staleness |
| 206 | + |
| 207 | +Every guard checks the client against the **snapshot**, not against upstream |
| 208 | +directly (a deliberate trade-off for the offline/repo-contained guarantee). If |
| 209 | +upstream changes and nobody refreshes the snapshot, the tests stay green while the |
| 210 | +client silently drifts from real upstream — the original regression class, moved |
| 211 | +up one level. |
| 212 | + |
| 213 | +Mitigations: |
| 214 | + |
| 215 | +- The snapshot records `upstreamVerified` (date + the exact `sessions.ts`/`commands.ts` |
| 216 | + blob SHAs the pin was checked against) so each verification is auditable and |
| 217 | + reproducible. **Last verified 2026-06-23** against `openclaw/openclaw` main: |
| 218 | + all enforced request fields / response envelopes / the `sessions.patch` tri-state |
| 219 | + nullable contract matched exactly; the snapshot is a deliberate subset (see the |
| 220 | + `upstreamVerified.result` note for the upstream-only `sessions.patch` fields the |
| 221 | + Windows client does not yet implement). |
| 222 | +- Treat a gateway-protocol bump in upstream as a trigger to re-verify and refresh, |
| 223 | + the same way `docs/gateway-node-integration.md` is refreshed. |
| 224 | +- Re-verify by fetching `packages/gateway-protocol/src/schema/{sessions,commands}.ts` |
| 225 | + from `openclaw/openclaw` main, diffing against the pinned methods/fields, and |
| 226 | + updating `upstreamVerified` with the new blob SHAs. |
| 227 | + |
| 228 | +## Scope |
| 229 | + |
| 230 | +The guard deliberately covers only the `sessions` / `files` / `commands` / |
| 231 | +compaction surface (`scopePrefixes` in the snapshot), which is where the |
| 232 | +drift-critical session and command APIs live. Other gateway namespaces |
| 233 | +(`cron.*`, `config.*`, `device.pair.*`, …) are out of scope for this guard. |
0 commit comments