Skip to main content

subc_protocol/
lib.rs

1//! subc wire contract.
2//!
3//! This crate is the single source of truth for the subc <-> module wire,
4//! shared by subc-core and AFT. It defines the **envelope** (the fixed
5//! 21-byte routing header subc splices on), the canonical subc-generated body
6//! schemas such as [`ErrorBody`], and the capability manifest. JSON-RPC request
7//! and response bodies remain module-owned opaque payloads to subc.
8//!
9//! ## The envelope (locked — see docs/subc-core-architecture.md §4.8)
10//!
11//! ```text
12//!  offset  size  field     type    purpose
13//!    0      4    len       u32     # of BODY bytes after this 21-byte header
14//!    4      1    ver       u8      envelope version
15//!    5      1    type      u8      frame kind (see FrameType)
16//!    6      1    flags     u8     bit0 BINARY · bits1-2 PRIORITY · bit3 LAST · bits4-5 ADMISSION · bit6 DAEMON_ORIGIN · bit7 SUBSCRIPTION
17//!    7      2    channel   u16     route = (component, session); 0 = subc itself
18//!    9      4    epoch     u32     per-slot binding epoch; 0 on channel 0
19//!   13      8    corr      u64     correlation id; CANCEL carries the target call's corr
20//!   21 -> body
21//! ```
22//!
23//! Little-endian (same-machine, native, no byte-swap on the hot path).
24//!
25//! **Frozen prefix (the versioning invariant):** `len` (u32 @ 0) and `ver`
26//! (u8 @ 4) keep fixed meaning + position in *every* future version. A reader
27//! of any version can therefore always read the first 5 bytes, learn `ver`,
28//! look up that version's header length, read the rest, and splice `len` body
29//! bytes. `decode_header` enforces this discipline.
30
31#![forbid(unsafe_code)]
32
33use std::{error::Error, fmt, path::PathBuf};
34
35use serde::{Deserialize, Serialize};
36
37pub use machine_id::{MachineId, MachineIdError};
38
39pub mod call_mode;
40pub mod frame;
41pub mod machine_id;
42pub mod manifest;
43pub mod scope;
44pub mod session;
45pub mod tool_call;
46
47/// Canonical error codes emitted by subc.
48///
49/// Error frames remain extensible strings, but these daemon-owned route-open
50/// outcomes need identical spelling across the daemon and SDK retry policies.
51pub mod error_codes {
52    use crate::Flags;
53
54    pub const UNKNOWN_CHANNEL: &str = "unknown_channel";
55    pub const STALE_ROUTE_EPOCH: &str = "stale_route_epoch";
56    /// A module reply exceeds the client connection's whole egress byte budget.
57    /// TERMINAL for this request: the module already received it, and retrying
58    /// unchanged would produce the same oversized reply. The route stays open.
59    pub const FRAME_TOO_LARGE: &str = "frame_too_large";
60    pub const UNKNOWN_MODULE: &str = "unknown_module";
61    pub const MODULE_REMOVED: &str = "module_removed";
62    /// The target module's endpoint is draining for a reload, restart or disable.
63    ///
64    /// On the data plane (an `ERROR` frame answering a `REQUEST` on a bound route)
65    /// this code is a PRE-SEND GUARANTEE: the daemon returns it only when the
66    /// request could not take a route credit because the endpoint is draining,
67    /// and it returns it BEFORE forwarding, so the module never received the
68    /// request. A caller may therefore re-dispatch the same request once the
69    /// route is reopened without risking a duplicated side effect, exactly as it
70    /// may after `unknown_channel`. The daemon keeps this guarantee:
71    /// `supervisor_reload_rejects_new_work_during_drain` asserts the module's
72    /// event journal never records the rejected request. A request the module
73    /// already received is answered by the module (or its route closes with
74    /// `route.closed`), never by this code.
75    pub const MODULE_RELOADING: &str = "module_reloading";
76    pub const MODULE_WARMING: &str = "module_warming";
77    pub const TARGET_UNAVAILABLE: &str = "target_unavailable";
78    /// A flow-scoped route targets a module that does not provide
79    /// either `flow-scopes/v1` or `call-modes/v1`. TERMINAL: decoding `flow_id`
80    /// alone does not promise flow behaviour, and removing it would silently
81    /// change the identity.
82    pub const TARGET_FLOW_UNSUPPORTED: &str = "target_flow_unsupported";
83    /// An agent-run-scoped route targets a module providing neither
84    /// `agent-run-scopes/v1` nor `call-modes/v1`, or a delegating run targets a
85    /// module without `call-modes/v1`. TERMINAL: removing `run_id` or delegation
86    /// would silently change the identity or authority under which the route acts.
87    pub const TARGET_AGENT_RUN_UNSUPPORTED: &str = "target_agent_run_unsupported";
88    pub const MODULE_TIMEOUT: &str = "module_timeout";
89    /// The target module is declared as speaking no subc wire protocol
90    /// (`protocol: "none"` in daemon config), so it has no control lane and can
91    /// never accept a route. The daemon supervises its process and nothing else.
92    ///
93    /// TERMINAL, and deliberately neither of its two neighbours. It is not
94    /// `unknown_module`, which means "no module of this id is registered or
95    /// supervised here" and is likewise terminal; retrying here would storm the
96    /// daemon forever, because the answer is a property of the module's
97    /// declaration rather than of its current state. It is not `module_removed` either: the module is configured,
98    /// running, and supervised. Only an edit to its configuration can change
99    /// this answer, and a caller cannot wait that out.
100    pub const MODULE_NO_PROTOCOL: &str = "module_no_protocol";
101    /// A request field is malformed. The error's `detail.field` names the field
102    /// (for a `route.open`, `role_versions`). TERMINAL: the same request will be
103    /// refused the same way every time, so only a corrected request can succeed.
104    pub const INVALID_REQUEST: &str = "invalid_request";
105
106    /// A `route.open` named a scope whose owner is configured but has not
107    /// synced since this daemon incarnation started. RETRYABLE: after a daemon
108    /// restart a carrier's open can arrive before the owner re-syncs, and the
109    /// carrier waits within its own deadline. See `docs/designs/daemon-scopes.md`.
110    pub const SCOPE_NOT_SYNCED: &str = "scope_not_synced";
111    /// A scoped `route.open` was admitted, but the scope record changed before
112    /// the module's bind committed. Nothing was sent on the route, so the caller
113    /// may re-open against the current record: RETRYABLE.
114    pub const SCOPE_CHANGED: &str = "scope_changed";
115    /// A scoped `route.open` named no `scope_epoch`. Every opener names one,
116    /// the owner included, so an old call can never be carried into a newer
117    /// session that reused the ref. TERMINAL.
118    pub const SCOPE_EPOCH_REQUIRED: &str = "scope_epoch_required";
119    /// A scoped `route.open` named a ref the owner's synced set does not hold,
120    /// or an owner that is not a configured module. TERMINAL.
121    pub const SCOPE_NOT_LIVE: &str = "scope_not_live";
122    /// A scoped `route.open` named a `scope_epoch` that is not the live one, or
123    /// the scope ended between admission and commit. TERMINAL.
124    pub const SCOPE_ENDED: &str = "scope_ended";
125    /// The opener of a scoped `route.open` is neither the scope's owner nor a
126    /// listed carrier, or it is a targeted carrier and the target module is not
127    /// in its list. TERMINAL.
128    pub const SCOPE_NOT_CARRIER: &str = "scope_not_carrier";
129    /// A scope with a bind-proof hash requires every opener, including its
130    /// owner, to present the proof. TERMINAL.
131    pub const SCOPE_BIND_PROOF_REQUIRED: &str = "scope_bind_proof_required";
132    /// The proof is malformed or does not match the scope's hash. TERMINAL.
133    pub const SCOPE_BIND_PROOF_MISMATCH: &str = "scope_bind_proof_mismatch";
134    /// An idle-only epoch/proof replacement found routes, admitted binds or
135    /// connected presence under the live epoch. Per-record refusal. TERMINAL.
136    pub const SCOPE_EPOCH_IN_USE: &str = "scope_epoch_in_use";
137    /// Raised by a carrier, never by the daemon: the daemon does not advertise
138    /// `scopes/v1`, so the carrier fails the call instead of opening an
139    /// unscoped route.
140    pub const SCOPE_UNSUPPORTED: &str = "scope_unsupported";
141
142    /// `scope.sync` or `scope.apply` came from a connection that is not the
143    /// owner's sync authority: another connection of the same launch holds it,
144    /// or this connection's launch is no longer the owner's current one (a
145    /// blue/green swap candidate before cutover, or an incumbent after it).
146    pub const SCOPE_SYNC_NOT_AUTHORITY: &str = "scope_sync_not_authority";
147    /// `scope.apply` came from a connection that has not taken sync authority
148    /// through an accepted full `scope.sync`. The whole call changes nothing.
149    pub const SCOPE_SYNC_REQUIRED: &str = "scope_sync_required";
150    /// `scope.sync` or `scope.apply` carried a generation no larger than the last
151    /// one the authority accepted. The whole call is refused and nothing changes.
152    pub const SCOPE_SYNC_STALE: &str = "scope_sync_stale";
153    /// `scope.sync` or `scope.apply` exceeds the owner's live-scope limit.
154    /// The whole call is refused and nothing changes.
155    pub const SCOPE_LIVE_LIMIT_EXCEEDED: &str = "scope_live_limit_exceeded";
156    /// One record in a `scope.sync` or `scope.apply` carried more attribute bytes
157    /// than a scope may hold. The whole call is refused and nothing changes.
158    pub const SCOPE_ATTRIBUTES_TOO_LARGE: &str = "scope_attributes_too_large";
159
160    // Per-record refusals: each is reported against one record in the
161    // `scope.sync` or `scope.apply` reply. A refusal itself does not change the
162    // ref or undo expiry processing; other records in the call still apply.
163
164    /// The record lowers the `scope_epoch` the daemon holds for its ref.
165    pub const SCOPE_EPOCH_REGRESSED: &str = "scope_epoch_regressed";
166    /// The record names an `(owner, ref, scope_epoch)` that already ended in
167    /// this daemon incarnation; an ended session cannot come back.
168    pub const SCOPE_EPOCH_ENDED: &str = "scope_epoch_ended";
169    /// The record's deadline has passed, or this ref at this epoch was ended by
170    /// expiry and its tombstone is still held. The same session epoch cannot
171    /// return.
172    pub const SCOPE_EXPIRED: &str = "scope_expired";
173    /// The record adds, removes or changes the deadline of a live scope at the
174    /// same epoch. A different deadline requires a new session epoch.
175    pub const SCOPE_EXPIRY_IMMUTABLE: &str = "scope_expiry_immutable";
176    /// The record's deadline is more than `scope::MAX_SCOPE_EXPIRY_AHEAD_MS`
177    /// ahead of the daemon's current Unix wall clock.
178    pub const SCOPE_EXPIRY_TOO_FAR: &str = "scope_expiry_too_far";
179    /// The record changes `kind` at the same `scope_epoch`.
180    pub const SCOPE_KIND_CHANGED: &str = "scope_kind_changed";
181    /// The record sets authority-controlled attributes and its owner is not
182    /// listed in `scope_authority_owners`, or combines `on_behalf_of_agent` with
183    /// `agent_id`, `delegates`, `flow_id` or `run_id`.
184    pub const SCOPE_ATTRIBUTE_NOT_PERMITTED: &str = "scope_attribute_not_permitted";
185    /// The record's parent link is not permitted: the parent's owner has synced
186    /// and the parent is not live at the named epoch, the syncing owner is
187    /// neither the parent's owner nor in its `child_owners`, or the link would
188    /// close a cycle.
189    pub const SCOPE_PARENT_NOT_PERMITTED: &str = "scope_parent_not_permitted";
190    /// A targeted carrier entry lists no target modules, or more than
191    /// `scope::MAX_CARRIER_TARGETS`.
192    pub const SCOPE_CARRIER_TARGETS_INVALID: &str = "scope_carrier_targets_invalid";
193    /// The record sets `delegates` without an `agent_id` to delegate.
194    pub const SCOPE_DELEGATES_WITHOUT_AGENT: &str = "scope_delegates_without_agent";
195    /// The record sets `run_id` without `agent_id`, the agent this run is on
196    /// behalf of.
197    pub const SCOPE_RUN_ID_WITHOUT_AGENT: &str = "scope_run_id_without_agent";
198    /// The record sets both `run_id` and `flow_id`; a run scope is not a flow scope.
199    pub const SCOPE_RUN_ID_WITH_FLOW_ID: &str = "scope_run_id_with_flow_id";
200    /// Legacy refusal for a record setting `run_id` with `delegates`.
201    /// No longer emitted by validation: run records may delegate, and route
202    /// admission instead requires a target providing `call-modes/v1`.
203    pub const SCOPE_RUN_ID_DELEGATES: &str = "scope_run_id_delegates";
204
205    /// An `operator.confirm` was declined or withdrawn. `detail.reason` is
206    /// `person`, `backoff`, `route_closed`, `module_closed` or `caller_cancelled`.
207    pub const OPERATOR_DECLINED: &str = "operator_declined";
208    /// An `operator.confirm` could not prompt or complete. `detail.reason` is
209    /// `no_presence`, `timeout`, `module_limit`, `queue_full`, `queue_wait`,
210    /// `provider_stuck`, `unsupported_platform` or `provider_error`.
211    pub const OPERATOR_PRESENCE_UNAVAILABLE: &str = "operator_presence_unavailable";
212    /// The summary of an `operator.confirm` breaks the daemon's summary rules.
213    pub const OPERATOR_SUMMARY_INVALID: &str = "operator_summary_invalid";
214    /// An `operator.confirm` is not from a nonce-proven module connection for
215    /// an open route with a verified opener on that connection.
216    pub const OPERATOR_REQUEST_NOT_PERMITTED: &str = "operator_request_not_permitted";
217
218    /// Whether a `route.open` refusal carrying `code` may be retried in place
219    /// within the caller's deadline, or is terminal for the target as named.
220    ///
221    /// This lives beside the codes because every consumer with its own
222    /// connection layer needs the same answer: a copied list breaks loudly on
223    /// a renamed code and silently on an added one. The SDKs call this; the
224    /// golden `decision_tables.json` (`route_open_retryable`) is the record
225    /// the daemon and every SDK are tested against, and the test in
226    /// `golden_json.rs` holds this function to it.
227    ///
228    /// Unknown codes are terminal: a refusal this crate has never heard of
229    /// must not be retried on the strength of a match-all arm.
230    ///
231    /// `unknown_module` is terminal: it now means only "no module of this id
232    /// is registered or supervised here" — a typo, or a peer not deployed on
233    /// this host. The daemon reports a configured-but-late target with its own
234    /// retryable codes (`module_warming`, `target_unavailable`), so a caller
235    /// that races an unsupervised module's HELLO owns its own retry; retrying
236    /// in place only papers over that race for one narrow window.
237    pub fn is_retryable_route_open(code: &str) -> bool {
238        if matches!(
239            code,
240            TARGET_FLOW_UNSUPPORTED
241                | TARGET_AGENT_RUN_UNSUPPORTED
242                | SCOPE_BIND_PROOF_REQUIRED
243                | SCOPE_BIND_PROOF_MISMATCH
244                | SCOPE_EPOCH_IN_USE
245        ) {
246            return false;
247        }
248        matches!(
249            code,
250            MODULE_RELOADING
251                | MODULE_WARMING
252                | TARGET_UNAVAILABLE
253                | MODULE_TIMEOUT
254                | SCOPE_NOT_SYNCED
255                | SCOPE_CHANGED
256        )
257    }
258
259    /// Whether the caller should evict this established route, reopen it, and
260    /// resend the request once. Consumers mapping route death to their own
261    /// custody, provider, or suspect verdict keep their own named code lists;
262    /// sharing this predicate for those meanings can change a verdict on a
263    /// protocol bump (prefrontal#59).
264    ///
265    /// Takes envelope flags so the daemon-origin check can be enabled here in
266    /// one place. Phase 2 requires first that every daemon a consumer can meet
267    /// sets DAEMON_ORIGIN on these error frames, both landed and deployed;
268    /// only then may this predicate require the bit. Requiring it sooner makes
269    /// a new SDK against an older daemon stop evicting on a genuine
270    /// `stale_route_epoch` — the failure this predicate is meant to prevent.
271    ///
272    /// The daemon emits these codes in `RouterError::to_error_frame` at
273    /// `crates/subc-daemon/src/router.rs` (UnknownChannel and StaleRouteEpoch).
274    pub fn is_established_route_dead(_flags: Flags, code: &str) -> bool {
275        matches!(code, UNKNOWN_CHANNEL | STALE_ROUTE_EPOCH)
276    }
277}
278
279pub use frame::{Frame, FrameBuildError};
280
281/// Why subc is closing a module's client routes.
282#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
283#[serde(rename_all = "snake_case")]
284pub enum RouteCloseReason {
285    Reload,
286    Restart,
287    Disable,
288    Crash,
289    /// A live route became forbidden because newly attested capability metadata
290    /// matched its supervised opening module's deny edge.
291    CapabilityDenied,
292    /// The route's scope ended: it expired, its owner ended it, or replaced it
293    /// with a higher `scope_epoch` (a new session under the same ref).
294    ScopeEnded,
295    /// The route's opener is no longer a listed carrier of its scope, or the
296    /// route's target was removed from that carrier's target list.
297    ScopeCarrierRemoved,
298    /// The scope's `delegates` went from true to false, or its `agent_id`,
299    /// `on_behalf_of_agent`, `flow_id` or `run_id` changed.
300    ScopeDelegationChanged,
301    /// The scope's parent ended, so its stamp no longer names a live parent.
302    ScopeParentEnded,
303}
304
305/// Per-route bind identity shared by client-facing and module-facing control.
306///
307/// EVERY FIELD HERE IS CLIENT-SUPPLIED AND UNATTESTED. The daemon canonicalizes
308/// `project_root` as a path but does not verify that the caller has any relation
309/// to it, and `harness`, `session`, and `project_id` are strings the caller chose.
310/// A client holding the connection key can present any values it likes.
311///
312/// This sits directly above `Principal`, which is the opposite: stamped BY the
313/// daemon from a launch nonce it minted. The two travel together on every
314/// `route.bind`, so a module reading them side by side is reading one fact it can
315/// trust and four it cannot. THE DISTINCTION IS INVISIBLE FROM THE TYPES, which
316/// is why it is written here.
317///
318/// So these fields are for SCOPING AND ATTRIBUTION -- which project's state to
319/// open, which session to thread, what to log -- and never for authorization. A
320/// module that grants capability on `harness` or trusts `project_root` to bound
321/// what a caller may reach has built an authorization check on a value the caller
322/// controls. Gate on `Principal` instead, and where a module needs a caller fact
323/// subc does not stamp, it must establish that fact itself rather than believe
324/// this struct.
325#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
326#[non_exhaustive]
327pub struct BindIdentity {
328    pub project_root: PathBuf,
329    pub harness: String,
330    pub session: String,
331    /// The entorhinal-registered project id (`pj-…`) for `project_root`, when
332    /// the root is a registered project. Aliases count as registered projects;
333    /// implicit roots do not. Absent means "no stable id, key on the triple",
334    /// not "unknown".
335    ///
336    /// A producer sends the id on every bind of a session or on none. A producer
337    /// that alternates between `Some(id)` and `None` across binds silently forks
338    /// the consumer's lineage into separate stores, with no error at either end.
339    /// Therefore, a producer that cannot answer consistently must answer `None`
340    /// consistently.
341    ///
342    /// Resolve this at most once per session, before its first bind, and persist
343    /// the outcome with the session. ALF's resolver has real `Resolved`, `Unavailable`,
344    /// and `Disabled` outcomes: if unavailable at cold start is re-resolved on a
345    /// later bind, the session can alternate from `None` to `Some(id)`. Send only
346    /// registered or alias resolutions, never implicit, unavailable, or disabled
347    /// fallback ids.
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub project_id: Option<String>,
350}
351
352impl BindIdentity {
353    /// Constructs an identity with no registered project id.
354    ///
355    /// Use this instead of a struct literal so future additive identity fields do
356    /// not force construction-site migrations across the fleet.
357    pub fn new(
358        project_root: impl Into<PathBuf>,
359        harness: impl Into<String>,
360        session: impl Into<String>,
361    ) -> Self {
362        Self {
363            project_root: project_root.into(),
364            harness: harness.into(),
365            session: session.into(),
366            project_id: None,
367        }
368    }
369}
370
371/// Caller fact stamped by subc on each route.bind relayed to a module.
372#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
373#[serde(tag = "kind", rename_all = "snake_case")]
374pub enum Principal {
375    /// A daemon-spawned module proved possession of its launch nonce.
376    Reserved { module_id: String },
377    /// No consumer identity was presented; the caller is a direct key-holder.
378    Direct,
379    /// Reserved vocabulary for a future degraded/no-key-auth mode.
380    Unverified,
381}
382
383/// Explicit target for a route open/bind operation.
384///
385/// RouteTarget.kind ↔ ProviderRole mapping:
386///
387/// | RouteTarget.kind | required ProviderRole | disambiguator |
388/// |---|---|---|
389/// | `tool_provider` | `ToolProvider` | v1: ≤1 per module |
390/// | `management_surface` | `ManagementSurface` | v1: ≤1 per module |
391/// | `internal_service` | `InternalService` | `service_id` (multiple allowed) |
392///
393/// `ProviderRole::PipelineStage` is intentionally unroutable; pipeline modules
394/// are wired by an orchestrator rather than opened directly by clients.
395#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
396#[serde(tag = "kind", rename_all = "snake_case")]
397pub enum RouteTarget {
398    ToolProvider {
399        module_id: String,
400    },
401    ManagementSurface {
402        module_id: String,
403    },
404    InternalService {
405        module_id: String,
406        service_id: String,
407    },
408}
409
410/// Envelope protocol version this build speaks.
411pub const PROTOCOL_VERSION: u8 = 2;
412
413/// The version of THIS crate (`subc-protocol`) as compiled into the linking
414/// binary — the fleet's shared wire-vocabulary version, and the value
415/// `ManifestProvenance.wire_crate_version` declares. Not the version of a
416/// module's own envelope or payload crates: those are different numbering
417/// spaces, and declaring one here produces a confident wrong answer at any
418/// version gate (insula shipped exactly that before the referent was written
419/// down). `env!` makes it a property of the compiled binary, not of whatever
420/// source tree sits beside it at run time.
421pub const SUBC_PROTOCOL_CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");
422
423/// Oldest envelope protocol version this build accepts.
424pub const MIN_SUPPORTED_VERSION: u8 = 2;
425
426/// Env var subc sets on each supervised child telling it the module_id it is
427/// supervised under, so it can register under that id.
428pub const SUBC_MODULE_ID_ENV: &str = "SUBC_MODULE_ID";
429
430/// Env var subc sets, on each spawn of a `reserved` module only, to a fresh
431/// one-time launch nonce. The child echoes it in `ModuleHelloBody::launch_nonce`;
432/// subc accepts a reserved module_id's HELLO only when the nonce matches the one it
433/// last injected for that id. Non-reserved modules never receive it.
434pub const SUBC_LAUNCH_NONCE_ENV: &str = "SUBC_LAUNCH_NONCE";
435
436/// Fixed header length for `PROTOCOL_VERSION` 2.
437pub const HEADER_LEN: usize = 21;
438
439/// Bytes of the frozen prefix (`len` u32 + `ver` u8) that are stable across
440/// every envelope version. A reader needs only these to learn the version and
441/// thus the full header length.
442pub const FROZEN_PREFIX_LEN: usize = 5;
443
444/// Maximum frame body accepted before allocation.
445///
446/// This 64 MiB starting cap prevents a malformed header from forcing an
447/// unbounded allocation. Future protocol versions can negotiate or encode a
448/// different cap while preserving the frozen prefix.
449pub const MAX_FRAME_BODY_LEN: u32 = 64 * 1024 * 1024;
450
451/// Largest frame, `HEADER_LEN` included, that the daemon delivers from a module
452/// to a client: a reply, stream frame, error, reverse request or push. A module
453/// sizes what it sends to a client against this, not against
454/// `MAX_FRAME_BODY_LEN`.
455///
456/// A larger module frame is never forwarded to the client. A reply, stream
457/// frame or error that is too large ends its request with a `frame_too_large`
458/// error; a reverse request that is too large is answered with an error to the
459/// module; an unsolicited push that is too large closes the client connection.
460///
461/// Requests from a client to a module are not held to this limit; they are
462/// bounded only by `MAX_FRAME_BODY_LEN`.
463pub const MAX_DELIVERED_FRAME_LEN: usize = 4 * 1024 * 1024;
464
465/// Canonical JSON body for all subc-generated `ERROR` frames.
466///
467/// `detail` is an optional machine-parsable surface for refusals whose remedy
468/// needs more than a code (e.g. a producer-published backoff number, an
469/// observed-vs-configured size pair). Absent detail serializes to nothing, so
470/// bodies without it are byte-identical to the pre-detail wire and older
471/// readers simply never see the field. Producers document each code's detail
472/// fields where the code is defined; `detail` must never carry secrets.
473#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
474pub struct ErrorBody {
475    pub code: String,
476    pub message: String,
477    #[serde(default, skip_serializing_if = "Option::is_none")]
478    pub detail: Option<serde_json::Value>,
479}
480
481impl ErrorBody {
482    /// A detail-less error body; the common case.
483    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
484        Self {
485            code: code.into(),
486            message: message.into(),
487            detail: None,
488        }
489    }
490
491    /// Attach a machine-parsable detail object to this error.
492    pub fn with_detail(mut self, detail: serde_json::Value) -> Self {
493        self.detail = Some(detail);
494        self
495    }
496}
497
498/// Module-to-subc `HELLO` body used during module registration.
499#[derive(Clone, Serialize, Deserialize, PartialEq)]
500pub struct ModuleHelloBody {
501    pub manifest: manifest::ModuleManifest,
502    pub protocol_ver: u8,
503    #[serde(default)]
504    pub control_ops: Option<Vec<String>>,
505    /// One-time launch nonce, echoed back from the `SUBC_LAUNCH_NONCE` environment
506    /// variable the daemon injected when it spawned this process. Only a daemon-spawned
507    /// process for a `reserved` module receives a nonce; subc accepts a reserved
508    /// `module_id`'s HELLO only when this matches the nonce it last injected for that
509    /// id, so a different process cannot register as a reserved module while the real
510    /// one is down/restarting. Absent (`serde(default)`) for non-reserved modules and
511    /// self-connecting providers, which are never nonce-checked.
512    #[serde(default, skip_serializing_if = "Option::is_none")]
513    pub launch_nonce: Option<String>,
514}
515
516// Hand-written so the launch nonce is never printed. The nonce is the credential
517// that attributes a connection to a supervised module, and a derived Debug would
518// write it into any log line or panic message that formats this value. Same
519// reasoning as ConnectionInfo's Debug in subc-transport.
520impl fmt::Debug for ModuleHelloBody {
521    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522        f.debug_struct("ModuleHelloBody")
523            .field("manifest", &self.manifest)
524            .field("protocol_ver", &self.protocol_ver)
525            .field("control_ops", &self.control_ops)
526            .field(
527                "launch_nonce",
528                &self
529                    .launch_nonce
530                    .as_ref()
531                    .map(|nonce| format!("<{} bytes redacted>", nonce.len())),
532            )
533            .finish()
534    }
535}
536
537/// subc-to-module `HELLO_ACK` body used during module registration.
538#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
539pub struct ModuleHelloAckBody {
540    pub negotiated_ver: u8,
541    pub subc_ops: Vec<String>,
542    pub subc_capabilities: Vec<String>,
543    /// The module's resolved storage descriptor, when the daemon's central config
544    /// configures managed storage. Carried opaquely here (subc-protocol stays a
545    /// thin wire crate with no storage/database dependency); a module that uses
546    /// managed storage deserializes it into `cortexkit_store_types::StorageDescriptor`
547    /// and hands it to `cortexkit-store`. Absent when no storage is configured, and
548    /// `serde(default)` so an older module simply ignores it.
549    #[serde(default, skip_serializing_if = "Option::is_none")]
550    pub storage: Option<serde_json::Value>,
551    /// The daemon's machine id (see [`MachineId`]): a name for this machine,
552    /// never an authority. Nothing may admit a peer, grant trust or skip a check
553    /// because two messages carry the same value.
554    ///
555    /// Carried as a plain string so one malformed value cannot fail the whole
556    /// registration reply; a module validates it with [`MachineId::parse`].
557    /// Absent from a daemon that predates the machine id, which a module must
558    /// read as exactly that, never as "no machine" and never as a reason to mint
559    /// its own.
560    #[serde(default, skip_serializing_if = "Option::is_none")]
561    pub machine_id: Option<String>,
562}
563
564/// Frame kind (`type` byte at offset 5).
565///
566/// `CANCEL`, `PING`, `PONG`, and `GOODBYE` are pure-header frames (`len == 0`);
567/// only `HELLO`/`HELLO_ACK` and the RPC payloads carry bodies.
568#[derive(Debug, Clone, Copy, PartialEq, Eq)]
569#[repr(u8)]
570pub enum FrameType {
571    Request = 0,
572    Response = 1,
573    Push = 2,
574    StreamData = 3,
575    StreamEnd = 4,
576    Error = 5,
577    Cancel = 6,
578    Ping = 7,
579    Pong = 8,
580    Hello = 9,
581    HelloAck = 10,
582    Goodbye = 11,
583}
584
585impl FrameType {
586    /// Map the raw `type` byte to a `FrameType`, or `None` if unknown.
587    pub fn from_u8(b: u8) -> Option<Self> {
588        Some(match b {
589            0 => Self::Request,
590            1 => Self::Response,
591            2 => Self::Push,
592            3 => Self::StreamData,
593            4 => Self::StreamEnd,
594            5 => Self::Error,
595            6 => Self::Cancel,
596            7 => Self::Ping,
597            8 => Self::Pong,
598            9 => Self::Hello,
599            10 => Self::HelloAck,
600            11 => Self::Goodbye,
601            _ => return None,
602        })
603    }
604
605    pub fn is_pure_header(self) -> bool {
606        matches!(self, Self::Cancel | Self::Ping | Self::Pong | Self::Goodbye)
607    }
608}
609
610/// Scheduling priority carried in `flags` bits 1-2. subc schedules on this
611/// without parsing the body.
612#[derive(Debug, Clone, Copy, PartialEq, Eq)]
613#[repr(u8)]
614pub enum Priority {
615    Passive = 0,
616    Interactive = 1,
617    Background = 2,
618}
619
620impl Priority {
621    fn from_bits(bits: u8) -> Option<Self> {
622        Some(match bits {
623            0 => Self::Passive,
624            1 => Self::Interactive,
625            2 => Self::Background,
626            _ => return None,
627        })
628    }
629}
630
631/// Admission behavior carried in `flags` bits 4-5.
632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
633#[repr(u8)]
634pub enum AdmissionClass {
635    Normal = 0,
636    Expedite = 1,
637    Sheddable = 2,
638}
639
640impl AdmissionClass {
641    fn from_bits(bits: u8) -> Option<Self> {
642        Some(match bits {
643            0 => Self::Normal,
644            1 => Self::Expedite,
645            2 => Self::Sheddable,
646            _ => return None,
647        })
648    }
649}
650
651const FLAG_BINARY: u8 = 0b0000_0001; // bit 0
652const FLAG_PRIORITY_MASK: u8 = 0b0000_0110; // bits 1-2
653const FLAG_PRIORITY_SHIFT: u8 = 1;
654const FLAG_LAST: u8 = 0b0000_1000; // bit 3
655const FLAG_ADMISSION_MASK: u8 = 0b0011_0000; // bits 4-5
656const FLAG_ADMISSION_SHIFT: u8 = 4;
657pub const FLAG_DAEMON_ORIGIN: u8 = 0b0100_0000;
658/// A request credit the client explicitly declares as a held-open subscription.
659pub const FLAG_SUBSCRIPTION: u8 = 0b1000_0000;
660
661/// The `flags` byte (offset 6): binary, priority, last, admission, daemon origin, subscription.
662#[derive(Debug, Clone, Copy, PartialEq, Eq)]
663pub struct Flags(pub u8);
664
665impl Flags {
666    /// Build flags with the default [`AdmissionClass::Normal`] class.
667    pub fn new(binary: bool, priority: Priority, last: bool) -> Self {
668        let mut b = 0u8;
669        if binary {
670            b |= FLAG_BINARY;
671        }
672        b |= (priority as u8) << FLAG_PRIORITY_SHIFT;
673        if last {
674            b |= FLAG_LAST;
675        }
676        Flags(b)
677    }
678
679    /// Return these flags with a typed admission class.
680    pub fn with_admission_class(mut self, admission_class: AdmissionClass) -> Self {
681        self.0 =
682            (self.0 & !FLAG_ADMISSION_MASK) | ((admission_class as u8) << FLAG_ADMISSION_SHIFT);
683        self
684    }
685
686    /// Body is raw bytes (bulk lane) rather than JSON-RPC.
687    pub fn is_binary(self) -> bool {
688        self.0 & FLAG_BINARY != 0
689    }
690
691    /// Final frame of a streamed message.
692    pub fn is_last(self) -> bool {
693        self.0 & FLAG_LAST != 0
694    }
695
696    /// Decode the priority bits, or `None` if they hold a reserved value.
697    pub fn priority(self) -> Option<Priority> {
698        Priority::from_bits((self.0 & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT)
699    }
700
701    /// Decode the admission-class bits, or `None` if they hold `0b11`.
702    pub fn admission_class(self) -> Option<AdmissionClass> {
703        AdmissionClass::from_bits((self.0 & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT)
704    }
705
706    /// True when a request was explicitly opened as a held-open subscription.
707    pub fn is_subscription(self) -> bool {
708        self.0 & FLAG_SUBSCRIPTION != 0
709    }
710
711    /// True when the frame was authored by the daemon.
712    pub fn is_daemon_origin(self) -> bool {
713        self.0 & FLAG_DAEMON_ORIGIN != 0
714    }
715
716    /// Return these flags with daemon origin asserted.
717    pub fn with_daemon_origin(mut self) -> Self {
718        self.0 |= FLAG_DAEMON_ORIGIN;
719        self
720    }
721
722    /// Return these flags with daemon origin cleared.
723    pub fn without_daemon_origin(self) -> Self {
724        Self(self.0 & !FLAG_DAEMON_ORIGIN)
725    }
726}
727
728/// A decoded envelope header. The body is the `len` bytes that follow it.
729#[derive(Debug, Clone, Copy, PartialEq, Eq)]
730pub struct EnvelopeHeader {
731    /// Number of body bytes after the header.
732    pub len: u32,
733    /// Envelope version.
734    pub ver: u8,
735    /// Frame kind.
736    pub ty: FrameType,
737    /// Flag bits.
738    pub flags: Flags,
739    /// Sender-local route slot; 0 is the control channel.
740    pub channel: u16,
741    /// Sender-local binding epoch; 0 is reserved for the control channel.
742    pub epoch: u32,
743    /// Correlation id.
744    pub corr: u64,
745}
746
747impl EnvelopeHeader {
748    /// Serialize the header to its fixed 21-byte little-endian form.
749    pub fn encode(&self) -> [u8; HEADER_LEN] {
750        let mut buf = [0u8; HEADER_LEN];
751        buf[0..4].copy_from_slice(&self.len.to_le_bytes());
752        buf[4] = self.ver;
753        buf[5] = self.ty as u8;
754        buf[6] = self.flags.0;
755        buf[7..9].copy_from_slice(&self.channel.to_le_bytes());
756        buf[9..13].copy_from_slice(&self.epoch.to_le_bytes());
757        buf[13..21].copy_from_slice(&self.corr.to_le_bytes());
758        buf
759    }
760}
761
762/// Why a header could not be decoded.
763#[derive(Debug, Clone, Copy, PartialEq, Eq)]
764pub enum DecodeError {
765    /// Fewer than `FROZEN_PREFIX_LEN` bytes — cannot even read `len`/`ver`.
766    TooShortForPrefix { have: usize },
767    /// `ver` is not a version this build understands.
768    UnsupportedVersion { ver: u8 },
769    /// Version known but fewer than its header length is present.
770    TooShortForHeader { have: usize, need: usize },
771    /// `type` byte is not a known `FrameType`.
772    UnknownFrameType { byte: u8 },
773    /// A reserved flag bit is set (retained for older decoder error compatibility).
774    ReservedFlagBits { flags: u8 },
775    /// Priority bits 1-2 hold the reserved value `0b11`.
776    ReservedPriorityBits { flags: u8 },
777    /// Admission bits 4-5 hold the reserved value `0b11`.
778    ReservedAdmissionClass { flags: u8 },
779    /// SHEDDABLE is set on a frame type that must be delivered.
780    SheddableIllegalFrameType { ty: FrameType, flags: u8 },
781    /// Channel 0 carried an epoch other than its reserved epoch 0.
782    NonzeroEpochOnControlChannel { epoch: u32 },
783    /// A pure-header frame declared body bytes.
784    PureHeaderFrameWithBody { ty: FrameType, len: u32 },
785}
786
787impl fmt::Display for DecodeError {
788    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
789        match self {
790            Self::TooShortForPrefix { have } => {
791                write!(f, "header shorter than frozen prefix: have {have} bytes")
792            }
793            Self::UnsupportedVersion { ver } => write!(f, "unsupported envelope version {ver}"),
794            Self::TooShortForHeader { have, need } => {
795                write!(
796                    f,
797                    "header too short for version: have {have} bytes, need {need}"
798                )
799            }
800            Self::UnknownFrameType { byte } => write!(f, "unknown frame type byte {byte}"),
801            Self::ReservedFlagBits { flags } => {
802                write!(f, "reserved flag bits set in flags 0b{flags:08b}")
803            }
804            Self::ReservedPriorityBits { flags } => {
805                write!(f, "reserved priority bits set in flags 0b{flags:08b}")
806            }
807            Self::ReservedAdmissionClass { flags } => {
808                write!(f, "reserved admission class set in flags 0b{flags:08b}")
809            }
810            Self::SheddableIllegalFrameType { ty, flags } => write!(
811                f,
812                "SHEDDABLE admission class is illegal on {ty:?} in flags 0b{flags:08b}"
813            ),
814            Self::NonzeroEpochOnControlChannel { epoch } => {
815                write!(f, "control channel carried nonzero epoch {epoch}")
816            }
817            Self::PureHeaderFrameWithBody { ty, len } => {
818                write!(
819                    f,
820                    "pure-header frame {ty:?} declared non-zero body length {len}"
821                )
822            }
823        }
824    }
825}
826
827impl Error for DecodeError {}
828
829/// How many header bytes a given envelope version occupies. Driven by the
830/// frozen prefix: read `ver`, then learn the full header length here.
831fn header_len_for_version(ver: u8) -> Option<usize> {
832    match ver {
833        PROTOCOL_VERSION => Some(HEADER_LEN),
834        _ => None,
835    }
836}
837
838/// Decode an envelope header from the front of `bytes`, following the
839/// frozen-prefix discipline:
840/// 1. need at least the 5-byte prefix to read `len` + `ver`;
841/// 2. dispatch the full header length on `ver`;
842/// 3. need the full header present; then parse the rest.
843///
844/// Never panics on malformed input — returns a typed [`DecodeError`].
845pub fn decode_header(bytes: &[u8]) -> Result<EnvelopeHeader, DecodeError> {
846    if bytes.len() < FROZEN_PREFIX_LEN {
847        return Err(DecodeError::TooShortForPrefix { have: bytes.len() });
848    }
849    let ver = bytes[4];
850    let need = header_len_for_version(ver).ok_or(DecodeError::UnsupportedVersion { ver })?;
851    if bytes.len() < need {
852        return Err(DecodeError::TooShortForHeader {
853            have: bytes.len(),
854            need,
855        });
856    }
857
858    let len = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
859    let ty =
860        FrameType::from_u8(bytes[5]).ok_or(DecodeError::UnknownFrameType { byte: bytes[5] })?;
861    let flags = Flags(bytes[6]);
862    if flags.priority().is_none() {
863        return Err(DecodeError::ReservedPriorityBits { flags: bytes[6] });
864    }
865    let admission_class = flags
866        .admission_class()
867        .ok_or(DecodeError::ReservedAdmissionClass { flags: bytes[6] })?;
868    if admission_class == AdmissionClass::Sheddable
869        && !matches!(ty, FrameType::Push | FrameType::StreamData)
870    {
871        return Err(DecodeError::SheddableIllegalFrameType {
872            ty,
873            flags: bytes[6],
874        });
875    }
876    if ty.is_pure_header() && len != 0 {
877        return Err(DecodeError::PureHeaderFrameWithBody { ty, len });
878    }
879    let channel = u16::from_le_bytes([bytes[7], bytes[8]]);
880    let epoch = u32::from_le_bytes([bytes[9], bytes[10], bytes[11], bytes[12]]);
881    if channel == 0 && epoch != 0 {
882        return Err(DecodeError::NonzeroEpochOnControlChannel { epoch });
883    }
884    let corr = u64::from_le_bytes([
885        bytes[13], bytes[14], bytes[15], bytes[16], bytes[17], bytes[18], bytes[19], bytes[20],
886    ]);
887
888    Ok(EnvelopeHeader {
889        len,
890        ver,
891        ty,
892        flags,
893        channel,
894        epoch,
895        corr,
896    })
897}
898
899#[cfg(test)]
900mod tests {
901    use super::*;
902
903    fn hdr(len: u32, ty: FrameType, flags: Flags, channel: u16, corr: u64) -> EnvelopeHeader {
904        hdr_with_epoch(len, ty, flags, channel, u32::from(channel != 0), corr)
905    }
906
907    fn hdr_with_epoch(
908        len: u32,
909        ty: FrameType,
910        flags: Flags,
911        channel: u16,
912        epoch: u32,
913        corr: u64,
914    ) -> EnvelopeHeader {
915        EnvelopeHeader {
916            len,
917            ver: PROTOCOL_VERSION,
918            ty,
919            flags,
920            channel,
921            epoch,
922            corr,
923        }
924    }
925
926    /// Modules size their replies against this limit and the TypeScript and
927    /// Swift clients mirror it, so changing it must be a deliberate edit here
928    /// as well as in the constant.
929    #[test]
930    fn max_delivered_frame_len_is_four_mebibytes_including_the_header() {
931        assert_eq!(MAX_DELIVERED_FRAME_LEN, 4_194_304);
932    }
933
934    #[test]
935    fn bind_identity_with_project_id_round_trips_json() {
936        let mut identity = BindIdentity::new("/tmp/project", "opencode", "session-1");
937        identity.project_id = Some("pj-a1b2c3d4".to_string());
938
939        let encoded = serde_json::to_vec(&identity).unwrap();
940        let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
941
942        assert_eq!(decoded, identity);
943    }
944
945    #[test]
946    fn bind_identity_without_project_id_round_trips_json() {
947        let identity = BindIdentity::new("/tmp/project", "opencode", "session-1");
948
949        let encoded = serde_json::to_vec(&identity).unwrap();
950        let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
951
952        assert_eq!(decoded, identity);
953    }
954
955    #[test]
956    fn legacy_bind_identity_without_project_id_decodes() {
957        let decoded: BindIdentity = serde_json::from_value(serde_json::json!({
958            "project_root": "/tmp/project",
959            "harness": "opencode",
960            "session": "session-1"
961        }))
962        .unwrap();
963
964        assert_eq!(decoded.project_id, None);
965    }
966
967    #[test]
968    fn bind_identity_none_omits_project_id_instead_of_serializing_null() {
969        let encoded =
970            serde_json::to_value(BindIdentity::new("/tmp/project", "opencode", "session-1"))
971                .unwrap();
972
973        assert!(encoded.get("project_id").is_none());
974    }
975
976    #[test]
977    fn wire_crate_version_is_a_numeric_three_component_version() {
978        let components = SUBC_PROTOCOL_CRATE_VERSION.split('.').collect::<Vec<_>>();
979
980        assert!(!SUBC_PROTOCOL_CRATE_VERSION.is_empty());
981        assert_eq!(components.len(), 3);
982        assert!(components
983            .iter()
984            .all(|component| !component.is_empty() && component.parse::<u64>().is_ok()));
985    }
986
987    #[test]
988    fn route_target_variants_round_trip_json() {
989        let targets = [
990            RouteTarget::ToolProvider {
991                module_id: "aft".to_string(),
992            },
993            RouteTarget::ManagementSurface {
994                module_id: "memory".to_string(),
995            },
996            RouteTarget::InternalService {
997                module_id: "bus".to_string(),
998                service_id: "dm".to_string(),
999            },
1000        ];
1001
1002        for target in targets {
1003            let encoded = serde_json::to_vec(&target).unwrap();
1004            let decoded: RouteTarget = serde_json::from_slice(&encoded).unwrap();
1005            assert_eq!(decoded, target);
1006        }
1007    }
1008
1009    #[test]
1010    fn error_body_round_trips_json() {
1011        let body = ErrorBody {
1012            code: "config_divergence".to_string(),
1013            message: "active config differs".to_string(),
1014            detail: None,
1015        };
1016
1017        let encoded = serde_json::to_vec(&body).unwrap();
1018        let decoded: ErrorBody = serde_json::from_slice(&encoded).unwrap();
1019
1020        assert_eq!(decoded, body);
1021    }
1022
1023    #[test]
1024    fn round_trip_request() {
1025        let h = hdr(
1026            1234,
1027            FrameType::Request,
1028            Flags::new(false, Priority::Interactive, false),
1029            42,
1030            0xDEAD_BEEF_0000_0001,
1031        );
1032        let decoded = decode_header(&h.encode()).unwrap();
1033        assert_eq!(h, decoded);
1034    }
1035
1036    #[test]
1037    fn round_trip_all_frame_types() {
1038        for b in 0u8..=11 {
1039            let ty = FrameType::from_u8(b).unwrap();
1040            let h = hdr(0, ty, Flags::new(false, Priority::Passive, false), 0, 0);
1041            assert_eq!(decode_header(&h.encode()).unwrap().ty, ty);
1042        }
1043    }
1044
1045    #[test]
1046    fn pure_header_frame_has_zero_len() {
1047        // CANCEL carries only header (len = 0) + the target corr.
1048        let h = hdr(
1049            0,
1050            FrameType::Cancel,
1051            Flags::new(false, Priority::Passive, false),
1052            7,
1053            99,
1054        );
1055        let d = decode_header(&h.encode()).unwrap();
1056        assert_eq!(d.len, 0);
1057        assert_eq!(d.corr, 99);
1058    }
1059
1060    #[test]
1061    fn flags_round_trip() {
1062        let f = Flags::new(true, Priority::Background, true)
1063            .with_admission_class(AdmissionClass::Expedite);
1064        assert!(f.is_binary());
1065        assert!(f.is_last());
1066        assert_eq!(f.priority(), Some(Priority::Background));
1067        assert_eq!(f.admission_class(), Some(AdmissionClass::Expedite));
1068        let h = hdr(8, FrameType::StreamData, f, 1, 1);
1069        assert_eq!(decode_header(&h.encode()).unwrap().flags, f);
1070    }
1071
1072    #[test]
1073    fn daemon_origin_flags_decode_and_round_trip() {
1074        let old = hdr(0, FrameType::Error, Flags(0), 7, 1);
1075        let old_decoded = decode_header(&old.encode()).unwrap();
1076        assert!(!old_decoded.flags.is_daemon_origin());
1077
1078        let daemon = hdr(0, FrameType::Error, Flags(0).with_daemon_origin(), 7, 1);
1079        let daemon_decoded = decode_header(&daemon.encode()).unwrap();
1080        assert!(daemon_decoded.flags.is_daemon_origin());
1081        assert_eq!(daemon_decoded.flags.without_daemon_origin(), Flags(0));
1082        assert!(Flags(0).with_daemon_origin().is_daemon_origin());
1083    }
1084
1085    #[test]
1086    fn little_endian_and_frozen_prefix_layout() {
1087        let h = hdr_with_epoch(
1088            0x0403_0201,
1089            FrameType::Request,
1090            Flags(0),
1091            0x0605,
1092            0x0a09_0807,
1093            0x1211_100f_0e0d_0c0b,
1094        );
1095        let buf = h.encode();
1096        assert_eq!(&buf[0..4], &[1, 2, 3, 4]);
1097        assert_eq!(buf[4], PROTOCOL_VERSION);
1098        assert_eq!(&buf[7..9], &[5, 6]);
1099        assert_eq!(&buf[9..13], &[7, 8, 9, 10]);
1100        assert_eq!(&buf[13..21], &[11, 12, 13, 14, 15, 16, 17, 18]);
1101        assert_eq!(buf.len(), HEADER_LEN);
1102    }
1103
1104    #[test]
1105    fn reject_too_short_for_prefix() {
1106        assert_eq!(
1107            decode_header(&[0, 0, 0, 0]),
1108            Err(DecodeError::TooShortForPrefix { have: 4 })
1109        );
1110    }
1111
1112    #[test]
1113    fn reject_too_short_for_header() {
1114        // Valid 5-byte prefix but the v2 header is truncated.
1115        let mut b = [0u8; 10];
1116        b[4] = PROTOCOL_VERSION;
1117        assert_eq!(
1118            decode_header(&b),
1119            Err(DecodeError::TooShortForHeader {
1120                have: 10,
1121                need: HEADER_LEN
1122            })
1123        );
1124    }
1125
1126    #[test]
1127    fn reject_unsupported_version() {
1128        let mut b = [0u8; HEADER_LEN];
1129        b[4] = 1;
1130        assert_eq!(
1131            decode_header(&b),
1132            Err(DecodeError::UnsupportedVersion { ver: 1 })
1133        );
1134    }
1135
1136    #[test]
1137    fn reject_unknown_frame_type() {
1138        let mut b = [0u8; HEADER_LEN];
1139        b[4] = PROTOCOL_VERSION;
1140        b[5] = 99;
1141        assert_eq!(
1142            decode_header(&b),
1143            Err(DecodeError::UnknownFrameType { byte: 99 })
1144        );
1145    }
1146
1147    #[test]
1148    fn subscription_flag_decodes_and_tags_the_request() {
1149        let mut b = [0u8; HEADER_LEN];
1150        b[4] = PROTOCOL_VERSION;
1151        b[5] = FrameType::Request as u8;
1152        b[6] = FLAG_SUBSCRIPTION;
1153        let decoded = decode_header(&b).unwrap();
1154        assert!(decoded.flags.is_subscription());
1155    }
1156
1157    #[test]
1158    fn reject_reserved_priority_bits() {
1159        let mut b = [0u8; HEADER_LEN];
1160        b[4] = PROTOCOL_VERSION;
1161        b[5] = FrameType::Request as u8;
1162        b[6] = 0b0000_0110; // priority bits 1-2 are reserved value 0b11
1163        assert_eq!(
1164            decode_header(&b),
1165            Err(DecodeError::ReservedPriorityBits { flags: 0b0000_0110 })
1166        );
1167    }
1168
1169    #[test]
1170    fn reject_pure_header_frame_with_body_len() {
1171        let h = hdr(
1172            1,
1173            FrameType::Ping,
1174            Flags::new(false, Priority::Passive, false),
1175            0,
1176            1,
1177        );
1178        assert_eq!(
1179            decode_header(&h.encode()),
1180            Err(DecodeError::PureHeaderFrameWithBody {
1181                ty: FrameType::Ping,
1182                len: 1
1183            })
1184        );
1185    }
1186
1187    #[test]
1188    fn epoch_boundaries_round_trip() {
1189        for (channel, epoch) in [(0, 0), (1, 1), (u16::MAX, u32::MAX)] {
1190            let h = hdr_with_epoch(
1191                0,
1192                FrameType::Request,
1193                Flags::new(false, Priority::Passive, false),
1194                channel,
1195                epoch,
1196                9,
1197            );
1198            assert_eq!(decode_header(&h.encode()).unwrap(), h);
1199        }
1200    }
1201
1202    #[test]
1203    fn admission_classes_accept_three_values_and_reject_reserved_value() {
1204        for (ty, admission_class) in [
1205            (FrameType::Request, AdmissionClass::Normal),
1206            (FrameType::Request, AdmissionClass::Expedite),
1207            (FrameType::Push, AdmissionClass::Sheddable),
1208            (FrameType::StreamData, AdmissionClass::Sheddable),
1209        ] {
1210            let flags = Flags::new(false, Priority::Interactive, false)
1211                .with_admission_class(admission_class);
1212            let h = hdr(0, ty, flags, 1, 2);
1213            assert_eq!(decode_header(&h.encode()).unwrap().flags, flags);
1214        }
1215
1216        let mut h = hdr(
1217            0,
1218            FrameType::Push,
1219            Flags::new(false, Priority::Passive, false),
1220            1,
1221            2,
1222        )
1223        .encode();
1224        h[6] |= 0b0011_0000;
1225        assert_eq!(
1226            decode_header(&h),
1227            Err(DecodeError::ReservedAdmissionClass { flags: h[6] })
1228        );
1229    }
1230
1231    #[test]
1232    fn sheddable_rejected_on_every_illegal_frame_type() {
1233        let flags = Flags::new(false, Priority::Passive, false)
1234            .with_admission_class(AdmissionClass::Sheddable);
1235        for ty in [
1236            FrameType::Request,
1237            FrameType::Response,
1238            FrameType::StreamEnd,
1239            FrameType::Error,
1240            FrameType::Cancel,
1241            FrameType::Ping,
1242            FrameType::Pong,
1243            FrameType::Hello,
1244            FrameType::HelloAck,
1245            FrameType::Goodbye,
1246        ] {
1247            let h = hdr(0, ty, flags, 1, 2);
1248            assert_eq!(
1249                decode_header(&h.encode()),
1250                Err(DecodeError::SheddableIllegalFrameType { ty, flags: flags.0 })
1251            );
1252        }
1253    }
1254
1255    #[test]
1256    fn nonzero_epoch_on_control_channel_is_rejected() {
1257        let h = hdr_with_epoch(
1258            0,
1259            FrameType::Request,
1260            Flags::new(false, Priority::Passive, false),
1261            0,
1262            u32::MAX,
1263            2,
1264        );
1265        assert_eq!(
1266            decode_header(&h.encode()),
1267            Err(DecodeError::NonzeroEpochOnControlChannel { epoch: u32::MAX })
1268        );
1269    }
1270}
1271
1272#[cfg(test)]
1273mod launch_nonce_redaction_tests {
1274    use super::*;
1275
1276    #[test]
1277    fn hello_body_debug_never_prints_the_nonce() {
1278        let body = ModuleHelloBody {
1279            manifest: manifest::ModuleManifest::builder("broca", "0.1.0").build(),
1280            protocol_ver: 2,
1281            control_ops: None,
1282            launch_nonce: Some("nonce-f00dfeed1234abcd".to_string()),
1283        };
1284        let printed = format!("{body:?}");
1285        assert!(printed.contains("broca"), "{printed}");
1286        assert!(
1287            !printed.contains("nonce-f00dfeed1234abcd"),
1288            "launch nonce printed: {printed}"
1289        );
1290    }
1291}