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