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