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