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                | FEDERATED_STAMP_REQUIRED
300                | TARGET_FEDERATED_UNSUPPORTED
301                | TARGET_AGENT_RUN_UNSUPPORTED
302                | SCOPE_BIND_PROOF_REQUIRED
303                | SCOPE_BIND_PROOF_MISMATCH
304                | SCOPE_EPOCH_IN_USE
305        ) {
306            return false;
307        }
308        matches!(
309            code,
310            MODULE_RELOADING
311                | MODULE_WARMING
312                | TARGET_UNAVAILABLE
313                | MODULE_TIMEOUT
314                | SCOPE_NOT_SYNCED
315                | SCOPE_CHANGED
316                | SESSION_ADDRESS_UNAVAILABLE
317                | BIND_BUSY
318        )
319    }
320
321    /// The scope requires a federated stamp, but the target cannot read one.
322    pub const FEDERATED_STAMP_REQUIRED: &str = "federated_stamp_required";
323    /// Only the configured federated owner with route-authorize/v1 may ask.
324    pub const ROUTE_AUTHORIZE_NOT_PERMITTED: &str = "route_authorize_not_permitted";
325
326    /// Whether the caller should evict this established route, reopen it, and
327    /// resend the request once. Consumers mapping route death to their own
328    /// custody, provider, or suspect verdict keep their own named code lists;
329    /// sharing this predicate for those meanings can change a verdict on a
330    /// protocol bump (prefrontal#59).
331    ///
332    /// Takes envelope flags so the daemon-origin check can be enabled here in
333    /// one place. Phase 2 requires first that every daemon a consumer can meet
334    /// sets DAEMON_ORIGIN on these error frames, both landed and deployed;
335    /// only then may this predicate require the bit. Requiring it sooner makes
336    /// a new SDK against an older daemon stop evicting on a genuine
337    /// `stale_route_epoch` — the failure this predicate is meant to prevent.
338    ///
339    /// The daemon emits these codes in `RouterError::to_error_frame` at
340    /// `crates/subc-daemon/src/router.rs` (UnknownChannel and StaleRouteEpoch).
341    pub fn is_established_route_dead(_flags: Flags, code: &str) -> bool {
342        matches!(code, UNKNOWN_CHANNEL | STALE_ROUTE_EPOCH)
343    }
344
345    /// Whether an error proves a retryable credit refusal on the same route.
346    /// A negotiated request window and daemon origin are both required: module
347    /// errors, and errors on routes without the opt-in, prove no non-delivery.
348    pub fn is_route_busy_retryable(flags: Flags, code: &str, route_opted_in: bool) -> bool {
349        route_opted_in && flags.is_daemon_origin() && code == ROUTE_BUSY
350    }
351
352    #[cfg(test)]
353    mod agent_command_tests {
354        #[test]
355        fn agent_declaration_refusals_have_explicit_retry_classes() {
356            for (code, retry) in [
357                ("agent_roots_full", true),
358                ("busy", true),
359                ("duplicate_correlation", true),
360                ("declaration_closed", true),
361                ("not_supervised", false),
362                ("invalid_request", false),
363                ("future_code", false),
364            ] {
365                assert_eq!(super::is_retryable_agent_commands(code), retry, "{code}");
366            }
367        }
368    }
369}
370
371pub use frame::{Frame, FrameBuildError};
372
373/// Why subc is closing a module's client routes.
374#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
375#[serde(rename_all = "snake_case")]
376pub enum RouteCloseReason {
377    Reload,
378    Restart,
379    Disable,
380    Crash,
381    /// A live route became forbidden because newly attested capability metadata
382    /// matched its supervised opening module's deny edge.
383    CapabilityDenied,
384    /// The route's scope ended: it expired, its owner ended it, or replaced it
385    /// with a higher `scope_epoch` (a new session under the same ref).
386    ScopeEnded,
387    /// The route's opener is no longer a listed carrier of its scope, or the
388    /// route's target was removed from that carrier's target list.
389    ScopeCarrierRemoved,
390    /// The scope's `delegates` went from true to false, or its `agent_id`,
391    /// `on_behalf_of_agent`, `flow_id` or `run_id` changed.
392    ScopeDelegationChanged,
393    /// The scope's parent ended, so its stamp no longer names a live parent.
394    ScopeParentEnded,
395}
396
397/// Per-route bind identity shared by client-facing and module-facing control.
398///
399/// Every field here is client-supplied and unattested. Use these claims for
400/// attribution, never authorization; gate on the daemon-stamped [`Principal`]
401/// instead.
402///
403/// Protocol 0.34 identities carry no project fields. For project-free openers,
404/// project attribution comes from the admitted session [`scope::ScopeStamp`]'s
405/// `workdir` and optional `project_id`; without these fields there is no project
406/// attribution. During migration, daemon 0.39 also accepts legacy opener project
407/// fields and prefers the legacy root over the scope workdir for internal root
408/// attribution and compatibility bind fields. Decoding remains lenient so
409/// readers can ignore project fields sent by older daemons during migration.
410/// See [`scope::BIND_NO_PROJECT_CAPABILITY`] for target opt-in to project-free
411/// bind identities.
412#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
413#[non_exhaustive]
414pub struct BindIdentity {
415    pub harness: String,
416    pub session: String,
417    /// The opener's claim about the kind of build it is, sent on `route.open`.
418    /// [`BUILD_CLASS_PRODUCTION`] marks a production build whose integrity the
419    /// opener has verified.
420    ///
421    /// Like every other field here it is unattested. The daemon recognizes
422    /// `callosum` as the caller module ID eligible for this claim. It honours
423    /// the claim only when the opener's principal is
424    /// `Reserved { module_id: "callosum" }`, and only the exact value
425    /// [`BUILD_CLASS_PRODUCTION`]; any other value counts as absent. From any
426    /// other opener it is ignored. The daemon never relays it to the target
427    /// module: the identity on `route.bind` never carries it.
428    ///
429    /// An absent build-class claim is omitted from the wire. A reader that
430    /// predates this field drops it, which grants nothing.
431    /// Set it on the public field after [`BindIdentity::new`].
432    #[serde(default, skip_serializing_if = "Option::is_none")]
433    pub build_class: Option<String>,
434}
435
436/// The only [`BindIdentity::build_class`] value the daemon honours.
437pub const BUILD_CLASS_PRODUCTION: &str = "production";
438
439impl BindIdentity {
440    /// Constructs a project-free attribution identity.
441    ///
442    /// Use this instead of a struct literal so future additive identity fields do
443    /// not force construction-site migrations across the fleet.
444    pub fn new(harness: impl Into<String>, session: impl Into<String>) -> Self {
445        Self {
446            harness: harness.into(),
447            session: session.into(),
448            build_class: None,
449        }
450    }
451}
452
453/// Caller fact stamped by subc on each route.bind relayed to a module.
454#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
455#[serde(tag = "kind", rename_all = "snake_case")]
456pub enum Principal {
457    /// A daemon-spawned module proved possession of its launch nonce.
458    Reserved { module_id: String },
459    /// No consumer identity was presented; the caller is a direct key-holder.
460    Direct,
461    /// Reserved vocabulary for a future degraded/no-key-auth mode.
462    Unverified,
463}
464
465/// Explicit target for a route open/bind operation.
466///
467/// RouteTarget.kind ↔ ProviderRole mapping:
468///
469/// | RouteTarget.kind | required ProviderRole | disambiguator |
470/// |---|---|---|
471/// | `tool_provider` | `ToolProvider` | v1: ≤1 per module |
472/// | `management_surface` | `ManagementSurface` | v1: ≤1 per module |
473/// | `internal_service` | `InternalService` | `service_id` (multiple allowed) |
474///
475/// `ProviderRole::PipelineStage` is intentionally unroutable; pipeline modules
476/// are wired by an orchestrator rather than opened directly by clients.
477#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
478#[serde(tag = "kind", rename_all = "snake_case")]
479pub enum RouteTarget {
480    ToolProvider {
481        module_id: String,
482    },
483    ManagementSurface {
484        module_id: String,
485    },
486    InternalService {
487        module_id: String,
488        service_id: String,
489    },
490}
491
492/// Envelope protocol version this build speaks.
493pub const PROTOCOL_VERSION: u8 = 2;
494
495/// The version of THIS crate (`subc-protocol`) as compiled into the linking
496/// binary — the fleet's shared wire-vocabulary version, and the value
497/// `ManifestProvenance.wire_crate_version` declares. Not the version of a
498/// module's own envelope or payload crates: those are different numbering
499/// spaces, and declaring one here produces a confident wrong answer at any
500/// version gate (insula shipped exactly that before the referent was written
501/// down). `env!` makes it a property of the compiled binary, not of whatever
502/// source tree sits beside it at run time.
503pub const SUBC_PROTOCOL_CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");
504
505/// Oldest envelope protocol version this build accepts.
506pub const MIN_SUPPORTED_VERSION: u8 = 2;
507
508/// Env var subc sets on each supervised child telling it the module_id it is
509/// supervised under, so it can register under that id.
510pub const SUBC_MODULE_ID_ENV: &str = "SUBC_MODULE_ID";
511
512/// Env var subc sets, on each spawn of a `reserved` module only, to a fresh
513/// one-time launch nonce. The child echoes it in `ModuleHelloBody::launch_nonce`;
514/// subc accepts a reserved module_id's HELLO only when the nonce matches the one it
515/// last injected for that id. Non-reserved modules never receive it.
516pub const SUBC_LAUNCH_NONCE_ENV: &str = "SUBC_LAUNCH_NONCE";
517
518/// Fixed header length for `PROTOCOL_VERSION` 2.
519pub const HEADER_LEN: usize = 21;
520
521/// Bytes of the frozen prefix (`len` u32 + `ver` u8) that are stable across
522/// every envelope version. A reader needs only these to learn the version and
523/// thus the full header length.
524pub const FROZEN_PREFIX_LEN: usize = 5;
525
526/// Maximum frame body accepted before allocation.
527///
528/// This 64 MiB starting cap prevents a malformed header from forcing an
529/// unbounded allocation. Future protocol versions can negotiate or encode a
530/// different cap while preserving the frozen prefix.
531pub const MAX_FRAME_BODY_LEN: u32 = 64 * 1024 * 1024;
532
533/// Largest frame, `HEADER_LEN` included, that the daemon delivers from a module
534/// to a client: a reply, stream frame, error, reverse request or push. A module
535/// sizes what it sends to a client against this, not against
536/// `MAX_FRAME_BODY_LEN`.
537///
538/// A larger module frame is never forwarded to the client. A reply, stream
539/// frame or error that is too large ends its request with a `frame_too_large`
540/// error; a reverse request that is too large is answered with an error to the
541/// module; an unsolicited push that is too large closes the client connection.
542///
543/// Requests from a client to a module are not held to this limit; they are
544/// bounded only by `MAX_FRAME_BODY_LEN`.
545pub const MAX_DELIVERED_FRAME_LEN: usize = 4 * 1024 * 1024;
546
547/// Canonical JSON body for all subc-generated `ERROR` frames.
548///
549/// `detail` is an optional machine-parsable surface for refusals whose remedy
550/// needs more than a code (e.g. a producer-published backoff number, an
551/// observed-vs-configured size pair). Absent detail serializes to nothing, so
552/// bodies without it are byte-identical to the pre-detail wire and older
553/// readers simply never see the field. Producers document each code's detail
554/// fields where the code is defined; `detail` must never carry secrets.
555#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
556pub struct ErrorBody {
557    pub code: String,
558    pub message: String,
559    #[serde(default, skip_serializing_if = "Option::is_none")]
560    pub detail: Option<serde_json::Value>,
561}
562
563/// Credit snapshot attached to a daemon's never-forwarded `route_busy` error.
564/// `request_in_flight` counts all admitted requests, including watches.
565#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
566pub struct RouteBusyDetail {
567    pub reason: String,
568    pub request_in_flight: usize,
569    pub watch_in_flight: usize,
570    pub request_window: usize,
571    #[serde(default, skip_serializing_if = "Option::is_none")]
572    pub watch_window: Option<usize>,
573}
574
575impl ErrorBody {
576    /// A detail-less error body; the common case.
577    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
578        Self {
579            code: code.into(),
580            message: message.into(),
581            detail: None,
582        }
583    }
584
585    /// Attach a machine-parsable detail object to this error.
586    pub fn with_detail(mut self, detail: serde_json::Value) -> Self {
587        self.detail = Some(detail);
588        self
589    }
590}
591
592/// Module-to-subc `HELLO` body used during module registration.
593#[derive(Clone, Serialize, Deserialize, PartialEq)]
594pub struct ModuleHelloBody {
595    pub manifest: manifest::ModuleManifest,
596    pub protocol_ver: u8,
597    #[serde(default)]
598    pub control_ops: Option<Vec<String>>,
599    /// One-time launch nonce, echoed back from the `SUBC_LAUNCH_NONCE` environment
600    /// variable the daemon injected when it spawned this process. Only a daemon-spawned
601    /// process for a `reserved` module receives a nonce; subc accepts a reserved
602    /// `module_id`'s HELLO only when this matches the nonce it last injected for that
603    /// id, so a different process cannot register as a reserved module while the real
604    /// one is down/restarting. Absent (`serde(default)`) for non-reserved modules and
605    /// self-connecting providers, which are never nonce-checked.
606    #[serde(default, skip_serializing_if = "Option::is_none")]
607    pub launch_nonce: Option<String>,
608}
609
610// Hand-written so the launch nonce is never printed. The nonce is the credential
611// that attributes a connection to a supervised module, and a derived Debug would
612// write it into any log line or panic message that formats this value. Same
613// reasoning as ConnectionInfo's Debug in subc-transport.
614impl fmt::Debug for ModuleHelloBody {
615    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616        f.debug_struct("ModuleHelloBody")
617            .field("manifest", &self.manifest)
618            .field("protocol_ver", &self.protocol_ver)
619            .field("control_ops", &self.control_ops)
620            .field(
621                "launch_nonce",
622                &self
623                    .launch_nonce
624                    .as_ref()
625                    .map(|nonce| format!("<{} bytes redacted>", nonce.len())),
626            )
627            .finish()
628    }
629}
630
631/// subc-to-module `HELLO_ACK` body used during module registration.
632#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
633pub struct ModuleHelloAckBody {
634    pub negotiated_ver: u8,
635    pub subc_ops: Vec<String>,
636    pub subc_capabilities: Vec<String>,
637    /// The module's resolved storage descriptor, when the daemon's central config
638    /// configures managed storage. Carried opaquely here (subc-protocol stays a
639    /// thin wire crate with no storage/database dependency); a module that uses
640    /// managed storage deserializes it into `cortexkit_store_types::StorageDescriptor`
641    /// and hands it to `cortexkit-store`. Absent when no storage is configured, and
642    /// `serde(default)` so an older module simply ignores it.
643    #[serde(default, skip_serializing_if = "Option::is_none")]
644    pub storage: Option<serde_json::Value>,
645    /// The daemon's machine id (see [`MachineId`]): a name for this machine,
646    /// never an authority. Nothing may admit a peer, grant trust or skip a check
647    /// because two messages carry the same value.
648    ///
649    /// Carried as a plain string so one malformed value cannot fail the whole
650    /// registration reply; a module validates it with [`MachineId::parse`].
651    /// Absent from a daemon that predates the machine id, which a module must
652    /// read as exactly that, never as "no machine" and never as a reason to mint
653    /// its own.
654    #[serde(default, skip_serializing_if = "Option::is_none")]
655    pub machine_id: Option<String>,
656}
657
658/// Frame kind (`type` byte at offset 5).
659///
660/// `CANCEL`, `PING`, `PONG`, and `GOODBYE` are pure-header frames (`len == 0`);
661/// only `HELLO`/`HELLO_ACK` and the RPC payloads carry bodies.
662#[derive(Debug, Clone, Copy, PartialEq, Eq)]
663#[repr(u8)]
664pub enum FrameType {
665    Request = 0,
666    Response = 1,
667    Push = 2,
668    StreamData = 3,
669    StreamEnd = 4,
670    Error = 5,
671    Cancel = 6,
672    Ping = 7,
673    Pong = 8,
674    Hello = 9,
675    HelloAck = 10,
676    Goodbye = 11,
677}
678
679impl FrameType {
680    /// Map the raw `type` byte to a `FrameType`, or `None` if unknown.
681    pub fn from_u8(b: u8) -> Option<Self> {
682        Some(match b {
683            0 => Self::Request,
684            1 => Self::Response,
685            2 => Self::Push,
686            3 => Self::StreamData,
687            4 => Self::StreamEnd,
688            5 => Self::Error,
689            6 => Self::Cancel,
690            7 => Self::Ping,
691            8 => Self::Pong,
692            9 => Self::Hello,
693            10 => Self::HelloAck,
694            11 => Self::Goodbye,
695            _ => return None,
696        })
697    }
698
699    pub fn is_pure_header(self) -> bool {
700        matches!(self, Self::Cancel | Self::Ping | Self::Pong | Self::Goodbye)
701    }
702}
703
704/// Scheduling priority carried in `flags` bits 1-2. subc schedules on this
705/// without parsing the body.
706#[derive(Debug, Clone, Copy, PartialEq, Eq)]
707#[repr(u8)]
708pub enum Priority {
709    Passive = 0,
710    Interactive = 1,
711    Background = 2,
712}
713
714impl Priority {
715    fn from_bits(bits: u8) -> Option<Self> {
716        Some(match bits {
717            0 => Self::Passive,
718            1 => Self::Interactive,
719            2 => Self::Background,
720            _ => return None,
721        })
722    }
723}
724
725/// Admission behavior carried in `flags` bits 4-5.
726#[derive(Debug, Clone, Copy, PartialEq, Eq)]
727#[repr(u8)]
728pub enum AdmissionClass {
729    Normal = 0,
730    Expedite = 1,
731    Sheddable = 2,
732}
733
734impl AdmissionClass {
735    fn from_bits(bits: u8) -> Option<Self> {
736        Some(match bits {
737            0 => Self::Normal,
738            1 => Self::Expedite,
739            2 => Self::Sheddable,
740            _ => return None,
741        })
742    }
743}
744
745const FLAG_BINARY: u8 = 0b0000_0001; // bit 0
746const FLAG_PRIORITY_MASK: u8 = 0b0000_0110; // bits 1-2
747const FLAG_PRIORITY_SHIFT: u8 = 1;
748const FLAG_LAST: u8 = 0b0000_1000; // bit 3
749const FLAG_ADMISSION_MASK: u8 = 0b0011_0000; // bits 4-5
750const FLAG_ADMISSION_SHIFT: u8 = 4;
751pub const FLAG_DAEMON_ORIGIN: u8 = 0b0100_0000;
752/// A request credit the client explicitly declares as a held-open subscription.
753pub const FLAG_SUBSCRIPTION: u8 = 0b1000_0000;
754
755/// The `flags` byte (offset 6): binary, priority, last, admission, daemon origin, subscription.
756#[derive(Debug, Clone, Copy, PartialEq, Eq)]
757pub struct Flags(pub u8);
758
759impl Flags {
760    /// Build flags with the default [`AdmissionClass::Normal`] class.
761    pub fn new(binary: bool, priority: Priority, last: bool) -> Self {
762        let mut b = 0u8;
763        if binary {
764            b |= FLAG_BINARY;
765        }
766        b |= (priority as u8) << FLAG_PRIORITY_SHIFT;
767        if last {
768            b |= FLAG_LAST;
769        }
770        Flags(b)
771    }
772
773    /// Return these flags with a typed admission class.
774    pub fn with_admission_class(mut self, admission_class: AdmissionClass) -> Self {
775        self.0 =
776            (self.0 & !FLAG_ADMISSION_MASK) | ((admission_class as u8) << FLAG_ADMISSION_SHIFT);
777        self
778    }
779
780    /// Body is raw bytes (bulk lane) rather than JSON-RPC.
781    pub fn is_binary(self) -> bool {
782        self.0 & FLAG_BINARY != 0
783    }
784
785    /// Final frame of a streamed message.
786    pub fn is_last(self) -> bool {
787        self.0 & FLAG_LAST != 0
788    }
789
790    /// Decode the priority bits, or `None` if they hold a reserved value.
791    pub fn priority(self) -> Option<Priority> {
792        Priority::from_bits((self.0 & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT)
793    }
794
795    /// Decode the admission-class bits, or `None` if they hold `0b11`.
796    pub fn admission_class(self) -> Option<AdmissionClass> {
797        AdmissionClass::from_bits((self.0 & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT)
798    }
799
800    /// True when a request was explicitly opened as a held-open subscription.
801    pub fn is_subscription(self) -> bool {
802        self.0 & FLAG_SUBSCRIPTION != 0
803    }
804
805    /// True when the frame was authored by the daemon.
806    pub fn is_daemon_origin(self) -> bool {
807        self.0 & FLAG_DAEMON_ORIGIN != 0
808    }
809
810    /// Return these flags with daemon origin asserted.
811    pub fn with_daemon_origin(mut self) -> Self {
812        self.0 |= FLAG_DAEMON_ORIGIN;
813        self
814    }
815
816    /// Return these flags with daemon origin cleared.
817    pub fn without_daemon_origin(self) -> Self {
818        Self(self.0 & !FLAG_DAEMON_ORIGIN)
819    }
820}
821
822/// A decoded envelope header. The body is the `len` bytes that follow it.
823#[derive(Debug, Clone, Copy, PartialEq, Eq)]
824pub struct EnvelopeHeader {
825    /// Number of body bytes after the header.
826    pub len: u32,
827    /// Envelope version.
828    pub ver: u8,
829    /// Frame kind.
830    pub ty: FrameType,
831    /// Flag bits.
832    pub flags: Flags,
833    /// Sender-local route slot; 0 is the control channel.
834    pub channel: u16,
835    /// Sender-local binding epoch; 0 is reserved for the control channel.
836    pub epoch: u32,
837    /// Correlation id.
838    pub corr: u64,
839}
840
841impl EnvelopeHeader {
842    /// Serialize the header to its fixed 21-byte little-endian form.
843    pub fn encode(&self) -> [u8; HEADER_LEN] {
844        let mut buf = [0u8; HEADER_LEN];
845        buf[0..4].copy_from_slice(&self.len.to_le_bytes());
846        buf[4] = self.ver;
847        buf[5] = self.ty as u8;
848        buf[6] = self.flags.0;
849        buf[7..9].copy_from_slice(&self.channel.to_le_bytes());
850        buf[9..13].copy_from_slice(&self.epoch.to_le_bytes());
851        buf[13..21].copy_from_slice(&self.corr.to_le_bytes());
852        buf
853    }
854}
855
856/// Why a header could not be decoded.
857#[derive(Debug, Clone, Copy, PartialEq, Eq)]
858pub enum DecodeError {
859    /// Fewer than `FROZEN_PREFIX_LEN` bytes — cannot even read `len`/`ver`.
860    TooShortForPrefix { have: usize },
861    /// `ver` is not a version this build understands.
862    UnsupportedVersion { ver: u8 },
863    /// Version known but fewer than its header length is present.
864    TooShortForHeader { have: usize, need: usize },
865    /// `type` byte is not a known `FrameType`.
866    UnknownFrameType { byte: u8 },
867    /// A reserved flag bit is set (retained for older decoder error compatibility).
868    ReservedFlagBits { flags: u8 },
869    /// Priority bits 1-2 hold the reserved value `0b11`.
870    ReservedPriorityBits { flags: u8 },
871    /// Admission bits 4-5 hold the reserved value `0b11`.
872    ReservedAdmissionClass { flags: u8 },
873    /// SHEDDABLE is set on a frame type that must be delivered.
874    SheddableIllegalFrameType { ty: FrameType, flags: u8 },
875    /// Channel 0 carried an epoch other than its reserved epoch 0.
876    NonzeroEpochOnControlChannel { epoch: u32 },
877    /// A pure-header frame declared body bytes.
878    PureHeaderFrameWithBody { ty: FrameType, len: u32 },
879}
880
881impl fmt::Display for DecodeError {
882    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883        match self {
884            Self::TooShortForPrefix { have } => {
885                write!(f, "header shorter than frozen prefix: have {have} bytes")
886            }
887            Self::UnsupportedVersion { ver } => write!(f, "unsupported envelope version {ver}"),
888            Self::TooShortForHeader { have, need } => {
889                write!(
890                    f,
891                    "header too short for version: have {have} bytes, need {need}"
892                )
893            }
894            Self::UnknownFrameType { byte } => write!(f, "unknown frame type byte {byte}"),
895            Self::ReservedFlagBits { flags } => {
896                write!(f, "reserved flag bits set in flags 0b{flags:08b}")
897            }
898            Self::ReservedPriorityBits { flags } => {
899                write!(f, "reserved priority bits set in flags 0b{flags:08b}")
900            }
901            Self::ReservedAdmissionClass { flags } => {
902                write!(f, "reserved admission class set in flags 0b{flags:08b}")
903            }
904            Self::SheddableIllegalFrameType { ty, flags } => write!(
905                f,
906                "SHEDDABLE admission class is illegal on {ty:?} in flags 0b{flags:08b}"
907            ),
908            Self::NonzeroEpochOnControlChannel { epoch } => {
909                write!(f, "control channel carried nonzero epoch {epoch}")
910            }
911            Self::PureHeaderFrameWithBody { ty, len } => {
912                write!(
913                    f,
914                    "pure-header frame {ty:?} declared non-zero body length {len}"
915                )
916            }
917        }
918    }
919}
920
921impl Error for DecodeError {}
922
923/// How many header bytes a given envelope version occupies. Driven by the
924/// frozen prefix: read `ver`, then learn the full header length here.
925fn header_len_for_version(ver: u8) -> Option<usize> {
926    match ver {
927        PROTOCOL_VERSION => Some(HEADER_LEN),
928        _ => None,
929    }
930}
931
932/// Decode an envelope header from the front of `bytes`, following the
933/// frozen-prefix discipline:
934/// 1. need at least the 5-byte prefix to read `len` + `ver`;
935/// 2. dispatch the full header length on `ver`;
936/// 3. need the full header present; then parse the rest.
937///
938/// Never panics on malformed input — returns a typed [`DecodeError`].
939pub fn decode_header(bytes: &[u8]) -> Result<EnvelopeHeader, DecodeError> {
940    if bytes.len() < FROZEN_PREFIX_LEN {
941        return Err(DecodeError::TooShortForPrefix { have: bytes.len() });
942    }
943    let ver = bytes[4];
944    let need = header_len_for_version(ver).ok_or(DecodeError::UnsupportedVersion { ver })?;
945    if bytes.len() < need {
946        return Err(DecodeError::TooShortForHeader {
947            have: bytes.len(),
948            need,
949        });
950    }
951
952    let len = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
953    let ty =
954        FrameType::from_u8(bytes[5]).ok_or(DecodeError::UnknownFrameType { byte: bytes[5] })?;
955    let flags = Flags(bytes[6]);
956    if flags.priority().is_none() {
957        return Err(DecodeError::ReservedPriorityBits { flags: bytes[6] });
958    }
959    let admission_class = flags
960        .admission_class()
961        .ok_or(DecodeError::ReservedAdmissionClass { flags: bytes[6] })?;
962    if admission_class == AdmissionClass::Sheddable
963        && !matches!(ty, FrameType::Push | FrameType::StreamData)
964    {
965        return Err(DecodeError::SheddableIllegalFrameType {
966            ty,
967            flags: bytes[6],
968        });
969    }
970    if ty.is_pure_header() && len != 0 {
971        return Err(DecodeError::PureHeaderFrameWithBody { ty, len });
972    }
973    let channel = u16::from_le_bytes([bytes[7], bytes[8]]);
974    let epoch = u32::from_le_bytes([bytes[9], bytes[10], bytes[11], bytes[12]]);
975    if channel == 0 && epoch != 0 {
976        return Err(DecodeError::NonzeroEpochOnControlChannel { epoch });
977    }
978    let corr = u64::from_le_bytes([
979        bytes[13], bytes[14], bytes[15], bytes[16], bytes[17], bytes[18], bytes[19], bytes[20],
980    ]);
981
982    Ok(EnvelopeHeader {
983        len,
984        ver,
985        ty,
986        flags,
987        channel,
988        epoch,
989        corr,
990    })
991}
992
993#[cfg(test)]
994mod tests {
995    use super::*;
996
997    fn hdr(len: u32, ty: FrameType, flags: Flags, channel: u16, corr: u64) -> EnvelopeHeader {
998        hdr_with_epoch(len, ty, flags, channel, u32::from(channel != 0), corr)
999    }
1000
1001    fn hdr_with_epoch(
1002        len: u32,
1003        ty: FrameType,
1004        flags: Flags,
1005        channel: u16,
1006        epoch: u32,
1007        corr: u64,
1008    ) -> EnvelopeHeader {
1009        EnvelopeHeader {
1010            len,
1011            ver: PROTOCOL_VERSION,
1012            ty,
1013            flags,
1014            channel,
1015            epoch,
1016            corr,
1017        }
1018    }
1019
1020    /// Modules size their replies against this limit and the TypeScript and
1021    /// Swift clients mirror it, so changing it must be a deliberate edit here
1022    /// as well as in the constant.
1023    #[test]
1024    fn max_delivered_frame_len_is_four_mebibytes_including_the_header() {
1025        assert_eq!(MAX_DELIVERED_FRAME_LEN, 4_194_304);
1026    }
1027
1028    #[test]
1029    fn bind_identity_round_trips_json() {
1030        let identity = BindIdentity::new("opencode", "session-1");
1031
1032        let encoded = serde_json::to_vec(&identity).unwrap();
1033        let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
1034
1035        assert_eq!(decoded, identity);
1036    }
1037
1038    #[test]
1039    fn legacy_bind_identity_project_fields_are_ignored() {
1040        let decoded: BindIdentity = serde_json::from_value(serde_json::json!({
1041            "project_root": "/tmp/project",
1042            "project_id": "pj-a1b2c3d4",
1043            "harness": "opencode",
1044            "session": "session-1"
1045        }))
1046        .unwrap();
1047
1048        assert_eq!(decoded, BindIdentity::new("opencode", "session-1"));
1049    }
1050
1051    #[test]
1052    fn bind_identity_omits_both_project_fields() {
1053        let encoded = serde_json::to_value(BindIdentity::new("opencode", "session-1")).unwrap();
1054
1055        assert!(encoded.get("project_id").is_none());
1056        assert!(encoded.get("project_root").is_none());
1057    }
1058
1059    #[test]
1060    fn wire_crate_version_is_a_numeric_three_component_version() {
1061        let components = SUBC_PROTOCOL_CRATE_VERSION.split('.').collect::<Vec<_>>();
1062
1063        assert!(!SUBC_PROTOCOL_CRATE_VERSION.is_empty());
1064        assert_eq!(components.len(), 3);
1065        assert!(components
1066            .iter()
1067            .all(|component| !component.is_empty() && component.parse::<u64>().is_ok()));
1068    }
1069
1070    #[test]
1071    fn route_target_variants_round_trip_json() {
1072        let targets = [
1073            RouteTarget::ToolProvider {
1074                module_id: "aft".to_string(),
1075            },
1076            RouteTarget::ManagementSurface {
1077                module_id: "memory".to_string(),
1078            },
1079            RouteTarget::InternalService {
1080                module_id: "bus".to_string(),
1081                service_id: "dm".to_string(),
1082            },
1083        ];
1084
1085        for target in targets {
1086            let encoded = serde_json::to_vec(&target).unwrap();
1087            let decoded: RouteTarget = serde_json::from_slice(&encoded).unwrap();
1088            assert_eq!(decoded, target);
1089        }
1090    }
1091
1092    #[test]
1093    fn error_body_round_trips_json() {
1094        let body = ErrorBody {
1095            code: "config_divergence".to_string(),
1096            message: "active config differs".to_string(),
1097            detail: None,
1098        };
1099
1100        let encoded = serde_json::to_vec(&body).unwrap();
1101        let decoded: ErrorBody = serde_json::from_slice(&encoded).unwrap();
1102
1103        assert_eq!(decoded, body);
1104    }
1105
1106    #[test]
1107    fn round_trip_request() {
1108        let h = hdr(
1109            1234,
1110            FrameType::Request,
1111            Flags::new(false, Priority::Interactive, false),
1112            42,
1113            0xDEAD_BEEF_0000_0001,
1114        );
1115        let decoded = decode_header(&h.encode()).unwrap();
1116        assert_eq!(h, decoded);
1117    }
1118
1119    #[test]
1120    fn round_trip_all_frame_types() {
1121        for b in 0u8..=11 {
1122            let ty = FrameType::from_u8(b).unwrap();
1123            let h = hdr(0, ty, Flags::new(false, Priority::Passive, false), 0, 0);
1124            assert_eq!(decode_header(&h.encode()).unwrap().ty, ty);
1125        }
1126    }
1127
1128    #[test]
1129    fn pure_header_frame_has_zero_len() {
1130        // CANCEL carries only header (len = 0) + the target corr.
1131        let h = hdr(
1132            0,
1133            FrameType::Cancel,
1134            Flags::new(false, Priority::Passive, false),
1135            7,
1136            99,
1137        );
1138        let d = decode_header(&h.encode()).unwrap();
1139        assert_eq!(d.len, 0);
1140        assert_eq!(d.corr, 99);
1141    }
1142
1143    #[test]
1144    fn flags_round_trip() {
1145        let f = Flags::new(true, Priority::Background, true)
1146            .with_admission_class(AdmissionClass::Expedite);
1147        assert!(f.is_binary());
1148        assert!(f.is_last());
1149        assert_eq!(f.priority(), Some(Priority::Background));
1150        assert_eq!(f.admission_class(), Some(AdmissionClass::Expedite));
1151        let h = hdr(8, FrameType::StreamData, f, 1, 1);
1152        assert_eq!(decode_header(&h.encode()).unwrap().flags, f);
1153    }
1154
1155    #[test]
1156    fn daemon_origin_flags_decode_and_round_trip() {
1157        let old = hdr(0, FrameType::Error, Flags(0), 7, 1);
1158        let old_decoded = decode_header(&old.encode()).unwrap();
1159        assert!(!old_decoded.flags.is_daemon_origin());
1160
1161        let daemon = hdr(0, FrameType::Error, Flags(0).with_daemon_origin(), 7, 1);
1162        let daemon_decoded = decode_header(&daemon.encode()).unwrap();
1163        assert!(daemon_decoded.flags.is_daemon_origin());
1164        assert_eq!(daemon_decoded.flags.without_daemon_origin(), Flags(0));
1165        assert!(Flags(0).with_daemon_origin().is_daemon_origin());
1166    }
1167
1168    #[test]
1169    fn little_endian_and_frozen_prefix_layout() {
1170        let h = hdr_with_epoch(
1171            0x0403_0201,
1172            FrameType::Request,
1173            Flags(0),
1174            0x0605,
1175            0x0a09_0807,
1176            0x1211_100f_0e0d_0c0b,
1177        );
1178        let buf = h.encode();
1179        assert_eq!(&buf[0..4], &[1, 2, 3, 4]);
1180        assert_eq!(buf[4], PROTOCOL_VERSION);
1181        assert_eq!(&buf[7..9], &[5, 6]);
1182        assert_eq!(&buf[9..13], &[7, 8, 9, 10]);
1183        assert_eq!(&buf[13..21], &[11, 12, 13, 14, 15, 16, 17, 18]);
1184        assert_eq!(buf.len(), HEADER_LEN);
1185    }
1186
1187    #[test]
1188    fn reject_too_short_for_prefix() {
1189        assert_eq!(
1190            decode_header(&[0, 0, 0, 0]),
1191            Err(DecodeError::TooShortForPrefix { have: 4 })
1192        );
1193    }
1194
1195    #[test]
1196    fn reject_too_short_for_header() {
1197        // Valid 5-byte prefix but the v2 header is truncated.
1198        let mut b = [0u8; 10];
1199        b[4] = PROTOCOL_VERSION;
1200        assert_eq!(
1201            decode_header(&b),
1202            Err(DecodeError::TooShortForHeader {
1203                have: 10,
1204                need: HEADER_LEN
1205            })
1206        );
1207    }
1208
1209    #[test]
1210    fn reject_unsupported_version() {
1211        let mut b = [0u8; HEADER_LEN];
1212        b[4] = 1;
1213        assert_eq!(
1214            decode_header(&b),
1215            Err(DecodeError::UnsupportedVersion { ver: 1 })
1216        );
1217    }
1218
1219    #[test]
1220    fn reject_unknown_frame_type() {
1221        let mut b = [0u8; HEADER_LEN];
1222        b[4] = PROTOCOL_VERSION;
1223        b[5] = 99;
1224        assert_eq!(
1225            decode_header(&b),
1226            Err(DecodeError::UnknownFrameType { byte: 99 })
1227        );
1228    }
1229
1230    #[test]
1231    fn subscription_flag_decodes_and_tags_the_request() {
1232        let mut b = [0u8; HEADER_LEN];
1233        b[4] = PROTOCOL_VERSION;
1234        b[5] = FrameType::Request as u8;
1235        b[6] = FLAG_SUBSCRIPTION;
1236        let decoded = decode_header(&b).unwrap();
1237        assert!(decoded.flags.is_subscription());
1238    }
1239
1240    #[test]
1241    fn reject_reserved_priority_bits() {
1242        let mut b = [0u8; HEADER_LEN];
1243        b[4] = PROTOCOL_VERSION;
1244        b[5] = FrameType::Request as u8;
1245        b[6] = 0b0000_0110; // priority bits 1-2 are reserved value 0b11
1246        assert_eq!(
1247            decode_header(&b),
1248            Err(DecodeError::ReservedPriorityBits { flags: 0b0000_0110 })
1249        );
1250    }
1251
1252    #[test]
1253    fn reject_pure_header_frame_with_body_len() {
1254        let h = hdr(
1255            1,
1256            FrameType::Ping,
1257            Flags::new(false, Priority::Passive, false),
1258            0,
1259            1,
1260        );
1261        assert_eq!(
1262            decode_header(&h.encode()),
1263            Err(DecodeError::PureHeaderFrameWithBody {
1264                ty: FrameType::Ping,
1265                len: 1
1266            })
1267        );
1268    }
1269
1270    #[test]
1271    fn epoch_boundaries_round_trip() {
1272        for (channel, epoch) in [(0, 0), (1, 1), (u16::MAX, u32::MAX)] {
1273            let h = hdr_with_epoch(
1274                0,
1275                FrameType::Request,
1276                Flags::new(false, Priority::Passive, false),
1277                channel,
1278                epoch,
1279                9,
1280            );
1281            assert_eq!(decode_header(&h.encode()).unwrap(), h);
1282        }
1283    }
1284
1285    #[test]
1286    fn admission_classes_accept_three_values_and_reject_reserved_value() {
1287        for (ty, admission_class) in [
1288            (FrameType::Request, AdmissionClass::Normal),
1289            (FrameType::Request, AdmissionClass::Expedite),
1290            (FrameType::Push, AdmissionClass::Sheddable),
1291            (FrameType::StreamData, AdmissionClass::Sheddable),
1292        ] {
1293            let flags = Flags::new(false, Priority::Interactive, false)
1294                .with_admission_class(admission_class);
1295            let h = hdr(0, ty, flags, 1, 2);
1296            assert_eq!(decode_header(&h.encode()).unwrap().flags, flags);
1297        }
1298
1299        let mut h = hdr(
1300            0,
1301            FrameType::Push,
1302            Flags::new(false, Priority::Passive, false),
1303            1,
1304            2,
1305        )
1306        .encode();
1307        h[6] |= 0b0011_0000;
1308        assert_eq!(
1309            decode_header(&h),
1310            Err(DecodeError::ReservedAdmissionClass { flags: h[6] })
1311        );
1312    }
1313
1314    #[test]
1315    fn sheddable_rejected_on_every_illegal_frame_type() {
1316        let flags = Flags::new(false, Priority::Passive, false)
1317            .with_admission_class(AdmissionClass::Sheddable);
1318        for ty in [
1319            FrameType::Request,
1320            FrameType::Response,
1321            FrameType::StreamEnd,
1322            FrameType::Error,
1323            FrameType::Cancel,
1324            FrameType::Ping,
1325            FrameType::Pong,
1326            FrameType::Hello,
1327            FrameType::HelloAck,
1328            FrameType::Goodbye,
1329        ] {
1330            let h = hdr(0, ty, flags, 1, 2);
1331            assert_eq!(
1332                decode_header(&h.encode()),
1333                Err(DecodeError::SheddableIllegalFrameType { ty, flags: flags.0 })
1334            );
1335        }
1336    }
1337
1338    #[test]
1339    fn nonzero_epoch_on_control_channel_is_rejected() {
1340        let h = hdr_with_epoch(
1341            0,
1342            FrameType::Request,
1343            Flags::new(false, Priority::Passive, false),
1344            0,
1345            u32::MAX,
1346            2,
1347        );
1348        assert_eq!(
1349            decode_header(&h.encode()),
1350            Err(DecodeError::NonzeroEpochOnControlChannel { epoch: u32::MAX })
1351        );
1352    }
1353}
1354
1355#[cfg(test)]
1356mod launch_nonce_redaction_tests {
1357    use super::*;
1358
1359    #[test]
1360    fn hello_body_debug_never_prints_the_nonce() {
1361        let body = ModuleHelloBody {
1362            manifest: manifest::ModuleManifest::builder("broca", "0.1.0").build(),
1363            protocol_ver: 2,
1364            control_ops: None,
1365            launch_nonce: Some("nonce-f00dfeed1234abcd".to_string()),
1366        };
1367        let printed = format!("{body:?}");
1368        assert!(printed.contains("broca"), "{printed}");
1369        assert!(
1370            !printed.contains("nonce-f00dfeed1234abcd"),
1371            "launch nonce printed: {printed}"
1372        );
1373    }
1374}