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