Skip to main content

subc_daemon/
control.rs

1use std::{
2    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
3    fmt,
4    path::PathBuf,
5    sync::{Arc, Mutex},
6    time::{Duration, Instant as StdInstant},
7};
8
9use serde::{Deserialize, Serialize};
10use subc_control::{
11    ops, CapabilityRequirementStatus, CatalogEntry, ClientControlPush, ClientControlRequest,
12    ClientControlResponse, ConsumerIdentity, DaemonBuildProvenance, DaemonObservedProcess,
13    ModuleDeclaredProvenance, ModuleProtocol, NotReadyReason, PollKind, RouteCloseReason,
14    SpawnCursor, StderrCaptureState, StderrTail, StderrTailEntry, SupervisorDaemonProvenance,
15    SupervisorEntry, SupervisorHealthEntry, SupervisorModuleProvenance, SupervisorObservedProcess,
16    SupervisorRescanResult, SupervisorRoute, SupervisorRouteConsumer, SupervisorRouteModule,
17};
18use subc_protocol::{
19    error_codes,
20    manifest::{
21        validate_hello_capability_grammar, validate_hello_self_signal_declarations,
22        CapabilityDeclarations, CapabilityNeed, Concurrency, ManifestProvenance, ModuleManifest,
23        ProviderRole,
24    },
25    session::{
26        HealthReport, ModuleControlPush, ModuleControlRequest, ModuleControlRequestFromModule,
27        ModuleControlResponse, ModuleControlResponseToModule, MODULE_CONTROL_OP_HEALTH_CHECK,
28        MODULE_TO_SUBC_OP_CATALOG_UPDATE,
29    },
30    BindIdentity, ErrorBody, Flags, FrameType, ModuleHelloAckBody, ModuleHelloBody, Principal,
31    Priority, RouteTarget, PROTOCOL_VERSION,
32};
33use tokio::time::{timeout_at, Instant};
34use tracing::{debug, info, warn};
35
36use crate::{
37    capability_requirements::{
38        log_duplicate_claim_events, log_requirement_events, CapabilityRequirementEvaluator,
39        CapabilityVerdict, DuplicateClaimSource, RegisteredModule, RequirementStatus,
40        RuntimeModule,
41    },
42    daemon_config::RestartRequiredSection,
43    forwarding::{
44        CloseReason, EndpointRoute, ForwardingError, ForwardingTable, GoodbyeTarget,
45        ModuleControlRpcCompletion, ModuleControlRpcOutcome, ModuleEndpointId,
46        PendingModuleControlRpc, RouteBindRelayOutcome, RoutePollSnapshot, RouteRelease,
47    },
48    observability::{
49        ROUTE_OPEN_REFUSED_DECLARED_NOT_READY, ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED,
50    },
51    provenance::{
52        process_start_time, spawned_file_identity, ExecutableIdentityProbe, SpawnedFileIdentity,
53    },
54    registry::{ChannelState, ConnectionId, Registry, RegistryError},
55    router::{RouteCtx, RouterError},
56    server::MAX_PENDING_ROUTE_BINDS_PER_TARGET,
57    stderr_tail::{CaptureState, TailEntry},
58    supervise::{
59        validate_spec, ModuleProcessLiveness, ReservedHelloRejection, SpawnSubscribeRefusal,
60        SupervisorHandle, SwapHelloAdmission,
61    },
62    ConnectedClients, DaemonCounters, Frame, ProjectRootId, Supervisor,
63};
64
65/// Lowest envelope version this subc build will negotiate.
66///
67/// Module HELLO negotiation is exact: peers must use the daemon's locked
68/// protocol version. Older and newer peers receive `version_unsupported` and
69/// are not registered.
70pub const MIN_SUPPORTED_VERSION: u8 = PROTOCOL_VERSION;
71
72const CAP_MANIFEST_REGISTRATION: &str = "manifest_registration_v1";
73const CAP_CHANNEL_LIFECYCLE: &str = "channel_lifecycle_v1";
74const CAP_PING_PONG: &str = "ping_pong_v1";
75const CAP_SESSION_ATTACH: &str = "session_attach_v1";
76const CAP_ADMISSION_FACTS_RELAY: &str = "admission_facts_relay_v1";
77
78const SUBC_CONTROL_OPS: &[&str] = &[
79    ops::SERVER_DESCRIBE,
80    ops::CATALOG_LIST,
81    ops::ROUTE_OPEN,
82    ops::ROUTE_POLL,
83    ops::ROUTE_CLOSING,
84    ops::ROUTE_CLOSED,
85    ops::SUPERVISOR_LIST,
86    ops::SUPERVISOR_RESTART,
87    ops::SUPERVISOR_SWAP,
88    ops::SUPERVISOR_RELOAD,
89    ops::SUPERVISOR_RESCAN,
90    ops::SUPERVISOR_RELEASE_RESERVED,
91    ops::SUPERVISOR_SET_ENABLED,
92    ops::SUPERVISOR_HEALTH_PROBE,
93    ops::SUPERVISOR_HEALTH,
94    ops::SUPERVISOR_STDERR_TAIL,
95    ops::SUPERVISOR_TERMINALS,
96    ops::SUPERVISOR_ROUTES,
97    ops::SUPERVISOR_PROVENANCE,
98    ops::SUPERVISOR_SPAWN_SNAPSHOT,
99    ops::SUPERVISOR_SPAWN_SUBSCRIBE,
100];
101
102const MODULE_TO_SUBC_CONTROL_OPS: &[&str] =
103    &[MODULE_TO_SUBC_OP_CATALOG_UPDATE, "supervisor.live_roots"];
104
105const MODULE_BASELINE_CONTROL_OPS: &[&str] = &["route.bind", "route.status"];
106
107/// How long subc waits for a module to ack a relayed route.bind before returning
108/// `module_timeout`. The ack waits on the module's own configure, which for AFT
109/// includes a synchronous bounded project walk (up to ~20k files) plus gitignore
110/// and DB-open work — on a cold page cache or a large repo that legitimately
111/// exceeds a couple of seconds. The default is generous because rejecting a VALID
112/// bind is far worse than waiting on a slow one; a consumer that wants a tighter
113/// bound retries the bind itself (the sanctioned warm-bind-retry pattern).
114pub const DEFAULT_ROUTE_BIND_RELAY_TIMEOUT: Duration = Duration::from_secs(12);
115
116/// How many CONSECUTIVE full-budget relay timeouts against one target module
117/// open that module's bind-relay breaker.
118///
119/// Three, so that the breaker is NOT REACHABLE INSIDE ONE CLIENT CALL. Both
120/// SDKs default to a 30s request deadline and the relay budget defaults to 12s,
121/// so three consecutive full-budget timeouts take ~36s to observe: every client
122/// whose open contributed to opening the breaker had already given up on its
123/// own. That is what makes opening the breaker unable to turn a call that would
124/// have succeeded into a refusal — it can only make an already-failing module
125/// fail faster.
126///
127/// Two would be reachable inside one default deadline. One would convict a
128/// module on a single cold-cache bind, which is exactly the valid-but-slow case
129/// `DEFAULT_ROUTE_BIND_RELAY_TIMEOUT`'s own doc comment exists to protect.
130pub const DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD: u32 = 3;
131
132/// How long a module's bind-relay breaker stays open before exactly one
133/// `route.open` is let through as a probe.
134///
135/// Bounded BELOW by the relay budget: a cooldown at or under the 12s budget
136/// re-pays a full-budget stall almost continuously, and the breaker stops being
137/// a saving worth its own state. Bounded ABOVE by the SDKs' 30s default request
138/// deadline: a client that starts retrying after the module recovers has to get
139/// a probe opportunity inside its own deadline, or the breaker converts a
140/// recovered module into a failed call — the failure it exists to prevent,
141/// pointed the other way.
142///
143/// 20s sits between those with room on both sides, and it caps what a wedged
144/// module can cost at one full-budget wait per 20s ACROSS THE WHOLE DAEMON
145/// rather than one per `route.open` per connection. The stall that motivated
146/// this, with its measurements, is written up in
147/// `docs/designs/route-open-head-of-line.md`: 268 opens against one module each
148/// waited the whole budget out.
149pub const DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN: Duration = Duration::from_secs(20);
150
151const DEFAULT_HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
152const SLOW_CONTROL_DISPATCH_THRESHOLD: Duration = Duration::from_secs(1);
153
154#[derive(Clone)]
155struct DaemonProvenanceFacts {
156    build: DaemonBuildProvenance,
157    pid: Option<u32>,
158    started_at_ms: Option<u64>,
159    start_clock: Option<crate::clock::StartClock>,
160    executable_path: Option<PathBuf>,
161    executable_identity: Option<SpawnedFileIdentity>,
162    process_start_time: Option<u64>,
163    probe: ExecutableIdentityProbe,
164}
165
166impl Default for DaemonProvenanceFacts {
167    fn default() -> Self {
168        Self {
169            build: DaemonBuildProvenance {
170                build_git_sha: None,
171                build_lock_digest: None,
172            },
173            pid: None,
174            started_at_ms: None,
175            start_clock: None,
176            executable_path: None,
177            executable_identity: None,
178            process_start_time: None,
179            probe: ExecutableIdentityProbe::default(),
180        }
181    }
182}
183
184#[derive(Debug, Clone)]
185struct SupervisorRescanContext {
186    supervisor: Supervisor,
187    config_path: PathBuf,
188    configured_port: Option<u16>,
189    storage_config: Option<crate::daemon_config::StorageConfig>,
190    admission_facts_carrier_module_id: Option<String>,
191    admission_facts_targets: Option<Vec<String>>,
192}
193
194/// Real channel-0 control handler for subc itself.
195#[derive(Clone)]
196pub struct ControlHandler {
197    registry: Arc<Registry>,
198    forwarding: Arc<ForwardingTable>,
199    process_liveness: Option<Arc<dyn ModuleProcessLiveness>>,
200    supervisor: SupervisorHandle,
201    subc_capabilities: Arc<[String]>,
202    /// Daemon-wide route.bind relay budget. Used as the fallback when the
203    /// target module has no per-module override in
204    /// `route_bind_relay_timeouts`.
205    route_bind_relay_timeout: Duration,
206    /// Per-module route.bind relay budget overrides, keyed by module id. When
207    /// `handle_route_open` resolves the deadline for a target module, a
208    /// per-module entry wins over the daemon-wide value above.
209    route_bind_relay_timeouts: BTreeMap<String, Duration>,
210    /// Per-target-module bind-relay breaker state. Shared with the forwarding
211    /// table, which is where a new module connection resets it.
212    route_bind_breakers: RouteBindBreakers,
213    /// Live relay admissions keyed by target module. Shared through the
214    /// forwarding table so cloned or separately built handlers enforce one cap.
215    route_bind_concurrency: RouteBindConcurrency,
216    /// Consecutive relay timeouts that open a module's breaker.
217    route_bind_breaker_threshold: u32,
218    /// How long a breaker stays open before one probe is admitted.
219    route_bind_breaker_cooldown: Duration,
220    health_probe_timeout: Duration,
221    /// Central storage policy. When set, each registering module receives its
222    /// resolved storage descriptor in HELLO_ACK; `None` leaves the field absent.
223    storage_config: Option<crate::daemon_config::StorageConfig>,
224    /// The machine id established at boot, served on every HELLO_ACK and on
225    /// `server.describe`. Fixed for the daemon's lifetime: `ck machine adopt`
226    /// changes the file, never this value. `None` serves no id.
227    machine_id: Option<crate::machine_id::MachineId>,
228    admission_facts_carrier_module_id: Option<String>,
229    admission_facts_targets: Option<Vec<String>>,
230    rescan: Option<SupervisorRescanContext>,
231    connected_clients: ConnectedClients,
232    counters: DaemonCounters,
233    capability_evaluator: Arc<CapabilityRequirementEvaluator>,
234    daemon_provenance: DaemonProvenanceFacts,
235    #[cfg(test)]
236    control_dispatch_delay: Option<Duration>,
237    #[cfg(test)]
238    provenance_probe_override: Option<subc_control::RunningImageAgreement>,
239}
240
241impl fmt::Debug for ControlHandler {
242    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
243        f.debug_struct("ControlHandler")
244            .field("registry", &self.registry)
245            .field("forwarding", &self.forwarding)
246            .field("process_liveness", &self.process_liveness.is_some())
247            .field("supervisor", &self.supervisor)
248            .field("subc_capabilities", &self.subc_capabilities)
249            .finish()
250    }
251}
252
253struct RouteOpenRequest {
254    target: RouteTarget,
255    identity: BindIdentity,
256    consumer_identity: Option<ConsumerIdentity>,
257    consumer_capabilities: Option<Vec<String>>,
258    admission_facts: Option<serde_json::Value>,
259}
260
261struct RouteBindReservationGuard {
262    forwarding: Arc<ForwardingTable>,
263    endpoint: ModuleEndpointId,
264    relay_corr: u64,
265    armed: bool,
266}
267
268struct ModuleControlRpcGuard {
269    forwarding: Arc<ForwardingTable>,
270    endpoint: ModuleEndpointId,
271    corr: u64,
272    armed: bool,
273}
274
275impl ModuleControlRpcGuard {
276    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, corr: u64) -> Self {
277        Self {
278            forwarding,
279            endpoint,
280            corr,
281            armed: true,
282        }
283    }
284
285    fn disarm(&mut self) {
286        self.armed = false;
287    }
288}
289
290impl Drop for ModuleControlRpcGuard {
291    fn drop(&mut self) {
292        if self.armed {
293            let _ = self
294                .forwarding
295                .cancel_module_control_rpc(self.endpoint, self.corr);
296        }
297    }
298}
299
300impl RouteBindReservationGuard {
301    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, relay_corr: u64) -> Self {
302        Self {
303            forwarding,
304            endpoint,
305            relay_corr,
306            armed: true,
307        }
308    }
309
310    fn release_and_disarm(&mut self) {
311        if !self.armed {
312            return;
313        }
314        if let Ok(Some(target)) = self.forwarding.abort_pending_relay(
315            self.endpoint,
316            self.relay_corr,
317            RouteBindRelayOutcome::ModuleGone("route.open handler canceled".to_string()),
318        ) {
319            send_goodbye_target_best_effort(&target, "canceled route.bind");
320        }
321        self.armed = false;
322    }
323
324    fn disarm(&mut self) {
325        self.armed = false;
326    }
327}
328
329impl Drop for RouteBindReservationGuard {
330    fn drop(&mut self) {
331        self.release_and_disarm();
332    }
333}
334
335/// Per-target-module circuit breaker around the `route.bind` relay.
336///
337/// The connection reader is serial per connection, so a module whose `on_bind`
338/// sits on the ack blocks every LATER frame on the connections that call it,
339/// including calls to unrelated modules. This does not make any module's bind
340/// fast; it stops the daemon paying the full budget again and again for a
341/// condition it has already observed.
342///
343/// State is keyed by TARGET MODULE and shared by every connection: a wedged
344/// module wedges everyone, so what one connection learned should protect the
345/// rest.
346///
347/// THE MAP IS EMPTY WHILE THE FLEET IS HEALTHY. An entry appears only when a
348/// relay to that module has actually timed out, and is removed again when a
349/// relay is accepted or the module reconnects, so it cannot grow with traffic
350/// or with modules that behave.
351///
352/// # Why a `std` mutex here is not the head-of-line defect again
353///
354/// Acquisition never awaits. The critical section is a hash lookup plus a few
355/// integer updates, with no I/O and no `.await` inside it, so a reader task
356/// cannot be descheduled behind it the way it can behind
357/// `tokio::sync::Mutex::lock().await` or a semaphore permit. It is the same
358/// primitive, held for the same kind of work, as the refusal counter this very
359/// path already increments.
360///
361/// It is also NOT on the data-plane splice path: only `route.open` and module
362/// registration touch it, so bound-route frames gain no state check and no
363/// contention.
364#[derive(Debug, Clone, Default)]
365pub(crate) struct RouteBindBreakers {
366    modules: Arc<Mutex<HashMap<String, ModuleBreakerState>>>,
367}
368
369#[derive(Debug, Clone, Default)]
370pub(crate) struct RouteBindConcurrency {
371    modules: Arc<Mutex<HashMap<String, usize>>>,
372}
373
374struct RouteBindConcurrencyGuard {
375    concurrency: RouteBindConcurrency,
376    module_id: String,
377}
378
379impl RouteBindConcurrency {
380    /// Admit without waiting. Waiting here would move the bind stall from the
381    /// module reply to a semaphore and restore reader head-of-line blocking.
382    fn try_admit(&self, module_id: &str, limit: usize) -> Result<RouteBindConcurrencyGuard, usize> {
383        let mut modules = self
384            .modules
385            .lock()
386            .expect("route.bind concurrency mutex poisoned");
387        let in_flight = modules.entry(module_id.to_string()).or_default();
388        if *in_flight >= limit {
389            return Err(*in_flight);
390        }
391        *in_flight += 1;
392        Ok(RouteBindConcurrencyGuard {
393            concurrency: self.clone(),
394            module_id: module_id.to_string(),
395        })
396    }
397}
398
399impl Drop for RouteBindConcurrencyGuard {
400    fn drop(&mut self) {
401        let mut modules = self
402            .concurrency
403            .modules
404            .lock()
405            .expect("route.bind concurrency mutex poisoned");
406        let remove = {
407            let in_flight = modules
408                .get_mut(&self.module_id)
409                .expect("admitted route.bind has a concurrency entry");
410            *in_flight -= 1;
411            *in_flight == 0
412        };
413        if remove {
414            modules.remove(&self.module_id);
415        }
416    }
417}
418
419#[derive(Debug, Default)]
420struct ModuleBreakerState {
421    /// Relay timeouts observed with no accepted relay in between.
422    consecutive_timeouts: u32,
423    /// `Some` while the breaker is open: the instant the cooldown expires and
424    /// the next arrival may probe. `None` means closed.
425    cooldown_until: Option<Instant>,
426    /// A half-open probe has been admitted and has not settled yet. This is
427    /// what makes the probe EXACTLY ONE: the flag is set under the same lock
428    /// that read the cooldown, so concurrent opens arriving at the moment the
429    /// cooldown expires cannot all decide that they are the probe.
430    probe_in_flight: bool,
431}
432
433/// What the breaker decided for one `route.open`, before any relay work.
434enum RouteBindAdmission<'a> {
435    Admitted {
436        guard: RouteBindBreakerGuard<'a>,
437        /// This open is the single half-open probe, so the transition is worth
438        /// one log line.
439        probe: bool,
440    },
441    Refused {
442        consecutive_timeouts: u32,
443        /// What is left of the cooldown. Zero when the refusal is because the
444        /// one probe is already in flight rather than because the cooldown has
445        /// not elapsed.
446        retry_in: Duration,
447        probe_in_flight: bool,
448    },
449}
450
451/// An outstanding admission, which must be told how its relay settled.
452///
453/// `Drop` settles it as inconclusive, so an early return between admission and
454/// the relay -- or the whole handler being cancelled when the client
455/// disconnects -- releases a half-open probe slot instead of leaving the
456/// breaker wedged half-open with no further probes.
457struct RouteBindBreakerGuard<'a> {
458    breakers: RouteBindBreakers,
459    module_id: &'a str,
460    settled: bool,
461}
462
463impl RouteBindBreakerGuard<'_> {
464    /// The module answered within the budget and took the bind. THE ONLY
465    /// OUTCOME THAT CLEARS THE COUNT. Returns true when this closed an open
466    /// breaker, which is a transition worth logging.
467    fn record_accepted(&mut self) -> bool {
468        self.settled = true;
469        self.breakers.record_accepted(self.module_id)
470    }
471
472    /// The relay burned the whole budget with no answer. THE ONLY ARM THAT
473    /// COUNTS TOWARD OPENING.
474    fn record_timeout(&mut self, threshold: u32, cooldown: Duration) -> Option<BreakerOpened> {
475        self.settled = true;
476        self.breakers
477            .record_timeout(self.module_id, threshold, cooldown)
478    }
479
480    /// Everything else: the module REJECTED the bind, its connection went away
481    /// mid-relay, or the waiter was cancelled.
482    ///
483    /// None of these is evidence that a module is slow, and each already has
484    /// its own refusal with its own code. A module that rejects a bind in
485    /// microseconds is healthy and must never be convicted for it; a module
486    /// that died has said nothing about the module that replaces it. So these
487    /// neither increment nor reset the count -- they only release a probe slot.
488    fn record_inconclusive(&mut self) {
489        self.settled = true;
490        self.breakers.record_inconclusive(self.module_id);
491    }
492}
493
494impl Drop for RouteBindBreakerGuard<'_> {
495    fn drop(&mut self) {
496        if !self.settled {
497            self.breakers.record_inconclusive(self.module_id);
498        }
499    }
500}
501
502/// The breaker moved to open, reported so the caller can log it outside the
503/// lock. Opening is rare and load-bearing; the refusals that follow are
504/// frequent and are counted rather than logged.
505struct BreakerOpened {
506    consecutive_timeouts: u32,
507    /// True when a failed probe re-opened an already-open breaker, which reads
508    /// very differently in a log from a first opening.
509    reopened_after_probe: bool,
510}
511
512impl RouteBindBreakers {
513    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, ModuleBreakerState>> {
514        self.modules
515            .lock()
516            .expect("route.bind breaker mutex poisoned")
517    }
518
519    /// Decide whether this `route.open` may attempt its relay. Takes the map
520    /// lock and nothing else, and never awaits.
521    fn admit<'a>(&self, module_id: &'a str) -> RouteBindAdmission<'a> {
522        let admitted = |probe| RouteBindAdmission::Admitted {
523            guard: RouteBindBreakerGuard {
524                breakers: self.clone(),
525                module_id,
526                settled: false,
527            },
528            probe,
529        };
530
531        let mut modules = self.lock();
532        let Some(state) = modules.get_mut(module_id) else {
533            return admitted(false);
534        };
535        let Some(cooldown_until) = state.cooldown_until else {
536            return admitted(false);
537        };
538        if state.probe_in_flight {
539            return RouteBindAdmission::Refused {
540                consecutive_timeouts: state.consecutive_timeouts,
541                retry_in: Duration::ZERO,
542                probe_in_flight: true,
543            };
544        }
545        let now = Instant::now();
546        if now < cooldown_until {
547            return RouteBindAdmission::Refused {
548                consecutive_timeouts: state.consecutive_timeouts,
549                retry_in: cooldown_until - now,
550                probe_in_flight: false,
551            };
552        }
553        state.probe_in_flight = true;
554        admitted(true)
555    }
556
557    fn record_accepted(&self, module_id: &str) -> bool {
558        self.lock()
559            .remove(module_id)
560            .is_some_and(|state| state.cooldown_until.is_some())
561    }
562
563    fn record_timeout(
564        &self,
565        module_id: &str,
566        threshold: u32,
567        cooldown: Duration,
568    ) -> Option<BreakerOpened> {
569        let mut modules = self.lock();
570        let state = modules.entry(module_id.to_string()).or_default();
571        let was_open = state.cooldown_until.is_some();
572        let was_probe = state.probe_in_flight;
573        state.probe_in_flight = false;
574        state.consecutive_timeouts = state.consecutive_timeouts.saturating_add(1);
575        if state.consecutive_timeouts < threshold {
576            return None;
577        }
578        state.cooldown_until = Some(Instant::now() + cooldown);
579        Some(BreakerOpened {
580            consecutive_timeouts: state.consecutive_timeouts,
581            reopened_after_probe: was_open && was_probe,
582        })
583    }
584
585    fn record_inconclusive(&self, module_id: &str) {
586        if let Some(state) = self.lock().get_mut(module_id) {
587            state.probe_in_flight = false;
588        }
589    }
590
591    /// Discard what was learned about a module, because the process it was
592    /// learned about is gone. Returns the discarded count when it was non-zero.
593    ///
594    /// A BREAKER IS A CACHED VERDICT ABOUT A PROCESS, NOT ABOUT A NAME. A
595    /// `module_id` is a configuration identity that outlives any particular
596    /// child; what the breaker observed was the process behind the module
597    /// connection of the moment. When a new connection registers under that id
598    /// the verdict's subject no longer exists, so the verdict is stale by
599    /// construction rather than merely likely to be wrong. Keeping it would
600    /// apply a dead process's record to a live one, which is the same defect
601    /// class this breaker exists to stop the daemon committing.
602    ///
603    /// A half-open probe in flight is discarded with the rest: it was a
604    /// question about the old process.
605    pub(crate) fn reset_for_new_module_connection(&self, module_id: &str) -> Option<u32> {
606        self.lock()
607            .remove(module_id)
608            .map(|state| state.consecutive_timeouts)
609            .filter(|discarded| *discarded > 0)
610    }
611
612    /// Open breakers, for the `server.describe` counters object. `None` when
613    /// none is open, so the key stays absent rather than present-and-empty.
614    ///
615    /// This is the operator's answer to "is this module refusing instantly or
616    /// is it fine?", which look identical from a client that retries and then
617    /// succeeds.
618    fn open_snapshot(&self) -> Option<serde_json::Value> {
619        let now = Instant::now();
620        let modules = self.lock();
621        let open = modules
622            .iter()
623            .filter_map(|(module_id, state)| {
624                let cooldown_until = state.cooldown_until?;
625                Some((
626                    module_id.clone(),
627                    serde_json::json!({
628                        "consecutive_timeouts": state.consecutive_timeouts,
629                        "cooldown_remaining_ms":
630                            cooldown_until.saturating_duration_since(now).as_millis() as u64,
631                        "probe_in_flight": state.probe_in_flight,
632                    }),
633                ))
634            })
635            .collect::<serde_json::Map<String, serde_json::Value>>();
636        (!open.is_empty()).then_some(serde_json::Value::Object(open))
637    }
638}
639
640impl ControlHandler {
641    pub fn new(registry: Arc<Registry>) -> Self {
642        Self::with_forwarding(registry, Arc::new(ForwardingTable::default()))
643    }
644
645    pub fn with_forwarding(registry: Arc<Registry>, forwarding: Arc<ForwardingTable>) -> Self {
646        let counters = forwarding.counters();
647        // Taken from the forwarding table rather than created here, so that the
648        // breaker a `route.open` consults is the same one a module's
649        // registration resets, however many handlers are built over one table.
650        let route_bind_breakers = forwarding.route_bind_breakers();
651        let route_bind_concurrency = forwarding.route_bind_concurrency();
652        Self {
653            registry,
654            forwarding,
655            process_liveness: None,
656            supervisor: SupervisorHandle::new(),
657            subc_capabilities: Arc::from([
658                CAP_MANIFEST_REGISTRATION.to_string(),
659                CAP_CHANNEL_LIFECYCLE.to_string(),
660                CAP_PING_PONG.to_string(),
661                CAP_SESSION_ATTACH.to_string(),
662                CAP_ADMISSION_FACTS_RELAY.to_string(),
663            ]),
664            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
665            route_bind_relay_timeouts: BTreeMap::new(),
666            route_bind_breakers,
667            route_bind_concurrency,
668            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
669            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
670            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
671            storage_config: None,
672            machine_id: None,
673            admission_facts_carrier_module_id: None,
674            admission_facts_targets: None,
675            rescan: None,
676            connected_clients: ConnectedClients::new(),
677            counters,
678            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
679            daemon_provenance: DaemonProvenanceFacts::default(),
680            #[cfg(test)]
681            control_dispatch_delay: None,
682            #[cfg(test)]
683            provenance_probe_override: None,
684        }
685    }
686
687    /// Set the central storage policy: registering modules then receive their
688    /// resolved storage descriptor in HELLO_ACK.
689    pub fn with_storage_config(
690        mut self,
691        storage_config: Option<crate::daemon_config::StorageConfig>,
692    ) -> Self {
693        self.storage_config = storage_config;
694        self
695    }
696
697    /// Set the machine id served to every registering module (HELLO_ACK) and on
698    /// `server.describe`.
699    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
700        self.machine_id = machine_id;
701        self
702    }
703
704    /// Configure the exact reserved module and target ids permitted to relay
705    /// opaque admission facts. Config-file loading validates this authority;
706    /// this builder keeps the same policy available to embedded test daemons.
707    pub fn with_admission_facts_config(
708        mut self,
709        carrier_module_id: Option<String>,
710        targets: Option<Vec<String>>,
711    ) -> Self {
712        self.admission_facts_carrier_module_id = carrier_module_id;
713        self.admission_facts_targets = targets;
714        self
715    }
716
717    /// Override the route.bind relay timeout. Used by tests that assert the
718    /// timeout path so they don't block on the production-safe default.
719    pub fn with_route_bind_relay_timeout(mut self, timeout: Duration) -> Self {
720        self.route_bind_relay_timeout = timeout;
721        self
722    }
723
724    /// Install per-module route.bind relay budget overrides. A module id
725    /// listed here wins over the daemon-wide default set via
726    /// `with_route_bind_relay_timeout`. Values are pre-resolved at parse time
727    /// from `subc.jsonc` (per-module > daemon-wide > absent), so callers pass
728    /// the same `Duration` the bind path will use.
729    pub fn with_route_bind_relay_timeouts(
730        mut self,
731        timeouts: impl IntoIterator<Item = (String, Duration)>,
732    ) -> Self {
733        self.route_bind_relay_timeouts = timeouts.into_iter().collect();
734        self
735    }
736
737    /// Resolve the route.bind relay budget for a specific target module id.
738    /// Per-module overrides win; the daemon-wide value (set via
739    /// `with_route_bind_relay_timeout` or the built-in default) is the
740    /// fallback. Exposed so config-aware callers (bootstrap, tests) can audit
741    /// the same resolution `handle_route_open` will use.
742    pub fn route_bind_relay_timeout_for(&self, module_id: &str) -> Duration {
743        self.route_bind_relay_timeouts
744            .get(module_id)
745            .copied()
746            .unwrap_or(self.route_bind_relay_timeout)
747    }
748
749    /// Override the per-module bind-relay breaker policy.
750    ///
751    /// Used by tests, which cannot spend three production budgets opening a
752    /// breaker or twenty seconds waiting for its cooldown. The production
753    /// values are `DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD` and
754    /// `DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN`, whose doc comments carry the
755    /// reasoning for the numbers.
756    pub fn with_route_bind_breaker(mut self, threshold: u32, cooldown: Duration) -> Self {
757        self.route_bind_breaker_threshold = threshold.max(1);
758        self.route_bind_breaker_cooldown = cooldown;
759        self
760    }
761
762    #[cfg(test)]
763    pub(crate) fn with_health_probe_timeout(mut self, timeout: Duration) -> Self {
764        self.health_probe_timeout = timeout;
765        self
766    }
767
768    #[cfg(test)]
769    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
770        self.control_dispatch_delay = Some(delay);
771        self
772    }
773
774    pub fn with_process_liveness(
775        mut self,
776        process_liveness: Arc<dyn ModuleProcessLiveness>,
777    ) -> Self {
778        self.process_liveness = Some(process_liveness);
779        self
780    }
781
782    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
783        self.supervisor = supervisor;
784        self
785    }
786
787    pub fn with_daemon_provenance(
788        mut self,
789        pid: u32,
790        started_at_ms: u64,
791        executable_path: Option<PathBuf>,
792        build_git_sha: Option<String>,
793        build_lock_digest: Option<String>,
794    ) -> Self {
795        let executable_identity = executable_path.as_deref().and_then(spawned_file_identity);
796        let process_start_time = process_start_time(pid);
797        self.daemon_provenance = DaemonProvenanceFacts {
798            build: DaemonBuildProvenance {
799                build_git_sha,
800                build_lock_digest,
801            },
802            pid: Some(pid),
803            started_at_ms: Some(started_at_ms),
804            start_clock: None,
805            executable_path,
806            executable_identity,
807            process_start_time,
808            probe: ExecutableIdentityProbe::default(),
809        };
810        self
811    }
812
813    pub(crate) fn with_daemon_start_clock(mut self, clock: crate::clock::StartClock) -> Self {
814        self.daemon_provenance.start_clock = Some(clock);
815        self
816    }
817
818    #[cfg(test)]
819    fn with_provenance_probe_result(mut self, result: subc_control::RunningImageAgreement) -> Self {
820        self.provenance_probe_override = Some(result);
821        self
822    }
823
824    /// Install the configured module set and its reserved capability bindings.
825    /// Bindings are configuration-scoped and may point at a provider that has not
826    /// been installed yet, so this does not require the bound module to exist.
827    pub fn with_capability_config(
828        self,
829        modules: impl IntoIterator<Item = (String, bool)>,
830        reserved_capabilities: BTreeMap<String, String>,
831    ) -> Self {
832        self.capability_evaluator
833            .configure(modules, reserved_capabilities);
834        self
835    }
836
837    pub fn with_supervisor_rescan(
838        mut self,
839        supervisor: Supervisor,
840        config_path: impl Into<PathBuf>,
841        configured_port: Option<u16>,
842    ) -> Self {
843        self.rescan = Some(SupervisorRescanContext {
844            supervisor,
845            config_path: config_path.into(),
846            configured_port,
847            storage_config: self.storage_config.clone(),
848            admission_facts_carrier_module_id: self.admission_facts_carrier_module_id.clone(),
849            admission_facts_targets: self.admission_facts_targets.clone(),
850        });
851        self
852    }
853
854    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
855        self.connected_clients = connected_clients;
856        self
857    }
858
859    pub fn forwarding(&self) -> Arc<ForwardingTable> {
860        Arc::clone(&self.forwarding)
861    }
862
863    pub(crate) fn counters(&self) -> DaemonCounters {
864        self.counters.clone()
865    }
866
867    /// Wake at each candidate's own deadline so a stalled fresh exec emits its
868    /// requirement event without depending on an operator polling a status command.
869    pub fn spawn_capability_deadline_loop(self: Arc<Self>) {
870        tokio::spawn(async move {
871            loop {
872                self.capability_evaluator
873                    .wait_for_change_or_deadline()
874                    .await;
875                self.refresh_capability_requirements();
876            }
877        });
878    }
879
880    fn runtime_capability_snapshot(
881        &self,
882    ) -> Result<(Vec<RuntimeModule>, Vec<RegisteredModule>), RouterError> {
883        let runtime = self
884            .supervisor
885            .list()
886            .into_iter()
887            .map(|module| {
888                let status = module.status().map_err(|err| {
889                    RouterError::backend(0, 0, format!("failed to read capability status: {err}"))
890                })?;
891                Ok(RuntimeModule {
892                    module_id: status.module_id,
893                    state: status.state,
894                    enabled: status.enabled,
895                })
896            })
897            .collect::<Result<Vec<_>, RouterError>>()?;
898        let (_, registrations) = self.registry.list_modules().map_err(|err| {
899            RouterError::backend(
900                0,
901                0,
902                format!("failed to list capability registrations: {err}"),
903            )
904        })?;
905        let registrations = registrations
906            .into_iter()
907            .map(|registration| RegisteredModule {
908                module_id: registration.manifest.module_id,
909                module_version: registration.manifest.module_version,
910                capabilities: registration.manifest.capabilities,
911            })
912            .collect();
913        Ok((runtime, registrations))
914    }
915
916    /// The capability side effects of a module becoming the active registration
917    /// for its id: cache its manifest (warning if its claims drifted), run the
918    /// deny census when its declarations call for one, and recompute the
919    /// requirement statuses. An ordinary HELLO does this as it registers; a swap
920    /// candidate's does not, and the supervisor does it at promotion instead,
921    /// through [`crate::supervise::SwapPromotionObserver`].
922    fn apply_registration_capabilities(&self, registration: &crate::registry::ModuleRegistration) {
923        let cached_registration = RegisteredModule {
924            module_id: registration.manifest.module_id.clone(),
925            module_version: registration.manifest.module_version.clone(),
926            capabilities: registration.manifest.capabilities.clone(),
927        };
928        if self.capability_evaluator.record_hello(&cached_registration) {
929            warn!(
930                module_id = %cached_registration.module_id,
931                "capability claims drifted from the cached manifest"
932            );
933        }
934        if capability_census_trigger(None, registration.manifest.capabilities.as_ref()) {
935            self.enforce_capability_denies();
936        }
937        self.refresh_capability_requirements();
938    }
939
940    /// Point the shared supervisor handle at this handler for swap promotions.
941    /// Called wherever a handler is put behind the `Arc` the router serves, so
942    /// it can be held weakly.
943    pub(crate) fn install_swap_promotion_observer(self: &Arc<Self>) {
944        let observer: std::sync::Weak<dyn crate::supervise::SwapPromotionObserver> =
945            Arc::downgrade(self) as std::sync::Weak<ControlHandler>;
946        self.supervisor.set_swap_promotion_observer(observer);
947    }
948
949    pub fn refresh_capability_requirements(&self) {
950        match self.runtime_capability_snapshot() {
951            Ok((runtime, registrations)) => {
952                log_requirement_events(
953                    self.capability_evaluator
954                        .evaluate_now(&runtime, &registrations),
955                );
956            }
957            Err(err) => warn!(error = %err, "failed to recompute capability requirements"),
958        }
959    }
960
961    /// Reconcile only live, attested route bindings after a capability deny edge
962    /// or target claim was added. This is deliberately a control-plane census:
963    /// the opaque forwarding hot path must not grow a per-frame capability check.
964    fn enforce_capability_denies(&self) {
965        let (_, registrations) = match self.registry.list_modules() {
966            Ok(snapshot) => snapshot,
967            Err(err) => {
968                warn!(error = %err, "failed to read registrations for capability deny census");
969                return;
970            }
971        };
972        let manifests = registrations
973            .into_iter()
974            .map(|registration| {
975                (
976                    registration.manifest.module_id.clone(),
977                    registration.manifest,
978                )
979            })
980            .collect::<BTreeMap<_, _>>();
981        let census = match self.forwarding.route_census(None) {
982            Ok(census) => census,
983            Err(err) => {
984                warn!(error = %err, "failed to read route census for capability deny enforcement");
985                return;
986            }
987        };
988
989        for (target_module_id, routes) in census {
990            let Some(target_manifest) = manifests.get(&target_module_id) else {
991                continue;
992            };
993            let mut closed_routes = Vec::new();
994            let mut module_goodbyes = Vec::new();
995            for route in routes {
996                let Principal::Reserved {
997                    module_id: opening_module_id,
998                } = &route.principal
999                else {
1000                    continue;
1001                };
1002                let Some(opening_manifest) = manifests.get(opening_module_id) else {
1003                    continue;
1004                };
1005                let Some(capability) = denied_capability(opening_manifest, target_manifest) else {
1006                    continue;
1007                };
1008
1009                match self.forwarding.release_client_route(
1010                    route.goodbye_target.connection_id,
1011                    route.goodbye_target.channel,
1012                    route.goodbye_target.epoch,
1013                ) {
1014                    Ok(RouteRelease::Removed(module_goodbye)) => {
1015                        warn!(
1016                            opening_module_id,
1017                            target_module_id,
1018                            capability,
1019                            "force-closing route because an attested capability deny edge now matches"
1020                        );
1021                        closed_routes.push(route);
1022                        module_goodbyes.push(module_goodbye);
1023                    }
1024                    Ok(RouteRelease::Stale | RouteRelease::Absent) => {}
1025                    Err(err) => warn!(
1026                        opening_module_id,
1027                        target_module_id,
1028                        capability,
1029                        error = %err,
1030                        "failed to force-close capability-denied route"
1031                    ),
1032                }
1033            }
1034
1035            if closed_routes.is_empty() {
1036                continue;
1037            }
1038            send_route_control_pushes(
1039                &self.forwarding,
1040                closed_routes,
1041                ClientControlPush::RouteClosed {
1042                    module_id: target_module_id,
1043                    reason: RouteCloseReason::CapabilityDenied,
1044                    drained: false,
1045                    abandoned: 0,
1046                    excluded_subscriptions: 0,
1047                    terminal: Some(false),
1048                },
1049            );
1050            self.emit_route_goodbyes(module_goodbyes);
1051        }
1052    }
1053
1054    /// Why a registered module is not accepting new route binds, or `None` when
1055    /// it is. This is the module's effective readiness: its declared readiness
1056    /// first, then every `need: required` capability it declares evaluating to
1057    /// `provided`. `route.open` and `catalog.list` both read it here so the
1058    /// catalog never reports a module routable that `route.open` would refuse.
1059    fn not_ready_reason(
1060        &self,
1061        registration: &crate::registry::ModuleRegistration,
1062    ) -> Option<NotReadyReason> {
1063        if !registration.ready {
1064            return Some(NotReadyReason {
1065                reason: NotReadyReason::DECLARED_NOT_READY.to_string(),
1066                capability: None,
1067            });
1068        }
1069        self.first_unprovided_required_capability(registration)
1070            .map(|capability| NotReadyReason {
1071                reason: NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED.to_string(),
1072                capability: Some(capability),
1073            })
1074    }
1075
1076    /// The lexicographically first capability this registration declares
1077    /// `need: required` whose evaluator verdict is not `provided`.
1078    ///
1079    /// The verdicts are the capability evaluator's own; nothing here decides
1080    /// what "provided" means. The evaluator counts a capability provided as
1081    /// soon as a module claiming it has REGISTERED, not once that module is
1082    /// ready. That distinction is what keeps two modules that require each
1083    /// other's capabilities from deadlocking: if "provided" meant "the claimant
1084    /// is ready", each would wait for the other to become ready first and
1085    /// neither ever would. Do not tighten it to readiness.
1086    ///
1087    /// A required capability with no verdict at all means this registration's
1088    /// HELLO or catalog.update landed after the last recompute; recompute once
1089    /// rather than let a missing verdict read as either answer. If it is still
1090    /// missing (the recompute itself failed) the capability counts as
1091    /// unprovided: the refusal is retryable, and routing a module whose
1092    /// required provider is unknown is the outcome this check exists to stop.
1093    fn first_unprovided_required_capability(
1094        &self,
1095        registration: &crate::registry::ModuleRegistration,
1096    ) -> Option<String> {
1097        let required = registration
1098            .manifest
1099            .capabilities
1100            .iter()
1101            .flat_map(|declarations| declarations.requires.iter())
1102            .filter(|requirement| requirement.need == CapabilityNeed::Required)
1103            .map(|requirement| requirement.capability.as_str())
1104            .collect::<BTreeSet<_>>();
1105        if required.is_empty() {
1106            return None;
1107        }
1108        let module_id = registration.manifest.module_id.as_str();
1109        let verdict = |capability: &str| self.capability_evaluator.verdict(module_id, capability);
1110        if required
1111            .iter()
1112            .any(|capability| verdict(capability).is_none())
1113        {
1114            self.refresh_capability_requirements();
1115        }
1116        required
1117            .into_iter()
1118            .find(|capability| verdict(capability) != Some(CapabilityVerdict::Provided))
1119            .map(str::to_string)
1120    }
1121
1122    fn capability_requirement_statuses(&self) -> Vec<CapabilityRequirementStatus> {
1123        self.capability_evaluator
1124            .statuses()
1125            .into_iter()
1126            .map(capability_requirement_status)
1127            .collect()
1128    }
1129
1130    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
1131    /// registration-release watch. The signal is what the supervisor waits on
1132    /// before spawning a replacement, so it must only fire once forwarding
1133    /// teardown is also done (see [`Self::cleanup_connection`] /
1134    /// [`Self::handle_goodbye`]). Used directly only where there is no forwarding
1135    /// state to tear down (a HELLO that failed before module registration).
1136    fn deregister_connection(
1137        &self,
1138        connection_id: ConnectionId,
1139    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1140        self.registry.deregister_connection(connection_id)
1141    }
1142
1143    pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
1144        if frame.header.channel != 0 || frame.header.ty != FrameType::Request {
1145            return None;
1146        }
1147        let Ok(ClientControlRequest::RouteOpen { target, .. }) =
1148            parse_client_control_request(&frame.body)
1149        else {
1150            return None;
1151        };
1152        Some(target_module_id(&target).to_string())
1153    }
1154
1155    pub(crate) fn route_open_capacity_refusal(
1156        &self,
1157        ctx: &RouteCtx,
1158        frame: &Frame,
1159        target_module_id: &str,
1160        limit: usize,
1161    ) -> Result<Frame, RouterError> {
1162        self.route_open_admission_refusal_frame(
1163            ctx,
1164            frame,
1165            target_module_id,
1166            format!(
1167                "connection already has {limit} route.open binds in flight; retry after one settles"
1168            ),
1169        )
1170    }
1171
1172    /// Admission pressure clears as existing binds settle, so its refusal must
1173    /// remain in the deployed SDKs' closed retryable set: `unknown_module`,
1174    /// `module_reloading`, `module_warming`, `target_unavailable`, or
1175    /// `module_timeout`. `target_unavailable` is honest for an attempt that
1176    /// cannot currently reach its target; `module_timeout` would falsely claim
1177    /// that a wait expired. A new, cleaner code would be terminal to deployed
1178    /// clients, so it requires a client-tolerance rollout before daemon emission.
1179    fn route_open_admission_refusal_frame(
1180        &self,
1181        ctx: &RouteCtx,
1182        frame: &Frame,
1183        target_module_id: &str,
1184        message: impl Into<String>,
1185    ) -> Result<Frame, RouterError> {
1186        self.route_open_refusal_frame(
1187            ctx,
1188            frame,
1189            target_module_id,
1190            "open_admission_full",
1191            error_codes::TARGET_UNAVAILABLE,
1192            message,
1193        )
1194    }
1195
1196    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
1197    ///
1198    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
1199    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
1200    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
1201    #[cfg(test)]
1202    pub fn handle_control(
1203        &self,
1204        connection_id: ConnectionId,
1205        frame: Frame,
1206    ) -> Result<Vec<Frame>, RouterError> {
1207        match frame.header.ty {
1208            FrameType::Ping => Ok(vec![pong(&frame)?]),
1209            FrameType::Hello => self.handle_hello(connection_id, None, frame),
1210            FrameType::Goodbye => self.handle_goodbye(connection_id),
1211            ty => Ok(vec![control_error_frame(
1212                &frame,
1213                "unsupported_control_frame",
1214                format!("unsupported channel-0 frame {ty:?}"),
1215            )?]),
1216        }
1217    }
1218
1219    pub async fn handle_control_frame(
1220        &self,
1221        ctx: &RouteCtx,
1222        frame: Frame,
1223    ) -> Result<Vec<Frame>, RouterError> {
1224        self.handle_control_frame_timed(ctx, frame, None).await
1225    }
1226
1227    pub(crate) async fn handle_control_frame_timed(
1228        &self,
1229        ctx: &RouteCtx,
1230        frame: Frame,
1231        dispatch_started_at: Option<StdInstant>,
1232    ) -> Result<Vec<Frame>, RouterError> {
1233        match frame.header.ty {
1234            FrameType::Ping => Ok(vec![pong(&frame)?]),
1235            FrameType::Hello => {
1236                self.handle_hello(ctx.connection_id, Some(ctx.egress.clone()), frame)
1237            }
1238            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
1239            FrameType::Cancel => {
1240                if self
1241                    .supervisor
1242                    .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
1243                {
1244                    Ok(Vec::new())
1245                } else {
1246                    Ok(vec![control_error_frame(
1247                        &frame,
1248                        "unknown_subscription",
1249                        "no supervisor spawn subscription has this correlation id",
1250                    )?])
1251                }
1252            }
1253            FrameType::Request => {
1254                if self
1255                    .forwarding
1256                    .module_endpoint_for_connection(ctx.connection_id)
1257                    .map_err(RouterError::Forwarding)?
1258                    .is_some()
1259                {
1260                    if !is_known_module_request_op(&frame.body) {
1261                        return Ok(vec![control_error_frame(
1262                            &frame,
1263                            "unsupported_control_frame",
1264                            "module-originated channel-0 REQUEST is not supported",
1265                        )?]);
1266                    }
1267                    let request = match parse_module_control_request_from_module(&frame.body) {
1268                        Ok(request) => request,
1269                        Err((err, ControlRequestBodyError::UnknownOp)) => {
1270                            return Ok(vec![control_error_frame(
1271                                &frame,
1272                                "unsupported_control_frame",
1273                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
1274                            )?])
1275                        }
1276                        Err((err, ControlRequestBodyError::InvalidBody)) => {
1277                            return Ok(vec![control_error_frame(
1278                                &frame,
1279                                "invalid_control_body",
1280                                format!("malformed module control body: {err}"),
1281                            )?])
1282                        }
1283                    };
1284                    let op = module_control_request_op(&request);
1285                    let corr = frame.header.corr;
1286                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
1287                    let result =
1288                        self.handle_module_control_request(ctx.connection_id, frame, request);
1289                    log_slow_control_dispatch(dispatch_started_at, op, ctx.connection_id, corr);
1290                    return result;
1291                }
1292
1293                if is_known_module_request_op(&frame.body) {
1294                    return Ok(vec![control_error_frame(
1295                        &frame,
1296                        "not_registered",
1297                        "catalog.update requires an active module registration owned by this connection",
1298                    )?]);
1299                }
1300
1301                let request = match parse_client_control_request(&frame.body) {
1302                    Ok(request) => request,
1303                    Err((err, ControlRequestBodyError::UnknownOp)) => {
1304                        return Ok(vec![control_error_frame(
1305                            &frame,
1306                            "unknown_control_op",
1307                            format!("unknown client control op: {err}"),
1308                        )?])
1309                    }
1310                    Err((err, ControlRequestBodyError::InvalidBody)) => {
1311                        return Ok(vec![control_error_frame(
1312                            &frame,
1313                            "invalid_control_body",
1314                            format!("malformed client control body: {err}"),
1315                        )?])
1316                    }
1317                };
1318                let op = client_control_request_op(&request);
1319                let corr = frame.header.corr;
1320                log_control_dispatch_arrival(op, ctx.connection_id, corr);
1321                #[cfg(test)]
1322                if let Some(delay) = self.control_dispatch_delay {
1323                    tokio::time::sleep(delay).await;
1324                }
1325                let result = self
1326                    .handle_client_control_request(ctx, frame, request)
1327                    .await;
1328                log_slow_control_dispatch(dispatch_started_at, op, ctx.connection_id, corr);
1329                result
1330            }
1331            FrameType::Push => {
1332                let Some(endpoint) = self
1333                    .forwarding
1334                    .module_endpoint_for_connection(ctx.connection_id)
1335                    .map_err(RouterError::Forwarding)?
1336                else {
1337                    return Ok(vec![control_error_frame(
1338                        &frame,
1339                        "unsupported_control_frame",
1340                        "client-originated channel-0 PUSH is not supported",
1341                    )?]);
1342                };
1343                self.handle_status_update(endpoint, frame)
1344            }
1345            FrameType::Response | FrameType::Error
1346                if self
1347                    .forwarding
1348                    .module_endpoint_for_connection(ctx.connection_id)
1349                    .map_err(RouterError::Forwarding)?
1350                    .is_some() =>
1351            {
1352                self.handle_module_relay_response(ctx.connection_id, frame)
1353            }
1354            ty => Ok(vec![control_error_frame(
1355                &frame,
1356                "unsupported_control_frame",
1357                format!("unsupported channel-0 frame {ty:?}"),
1358            )?]),
1359        }
1360    }
1361
1362    pub fn cleanup_connection(
1363        &self,
1364        connection_id: ConnectionId,
1365    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1366        let crash_closed = self
1367            .registry
1368            .get_module_by_connection(connection_id)?
1369            .and_then(|registration| {
1370                self.forwarding
1371                    .module_endpoint_for_connection(connection_id)
1372                    .ok()
1373                    .flatten()
1374                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
1375                    .map(|routes| (registration.manifest.module_id, routes))
1376            });
1377        if let Some((module_id, routes)) = crash_closed {
1378            let terminal = match self.supervisor.get(&module_id) {
1379                None => false,
1380                Some(module) => match module.will_recover_after_connection_loss() {
1381                    Ok(will_recover) => !will_recover,
1382                    Err(err) => {
1383                        warn!(
1384                            %module_id,
1385                            error = %err,
1386                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
1387                        );
1388                        false
1389                    }
1390                },
1391            };
1392            send_route_control_pushes(
1393                &self.forwarding,
1394                routes,
1395                ClientControlPush::RouteClosed {
1396                    module_id,
1397                    reason: RouteCloseReason::Crash,
1398                    drained: false,
1399                    abandoned: 0,
1400                    excluded_subscriptions: 0,
1401                    terminal: Some(terminal),
1402                },
1403            );
1404        }
1405        let registrations = self.deregister_connection(connection_id);
1406        if let Ok(released_routes) = self.forwarding.cleanup_connection(connection_id) {
1407            self.emit_route_goodbyes(released_routes);
1408        }
1409        // Signal the registration-release watch only now that BOTH registry and
1410        // forwarding teardown are done, so a supervisor waiting to spawn a
1411        // replacement never observes release while old routes still exist.
1412        if matches!(&registrations, Ok(r) if !r.is_empty()) {
1413            crate::supervise::notify_registration_release();
1414            self.capability_evaluator.wake_deadline_loop();
1415            self.refresh_capability_requirements();
1416        }
1417        self.supervisor.remove_spawn_subscribers(connection_id);
1418        registrations
1419    }
1420
1421    pub(crate) fn handle_route_goodbye(
1422        &self,
1423        connection_id: ConnectionId,
1424        route_channel: u16,
1425        route_epoch: u32,
1426    ) -> Result<bool, RouterError> {
1427        debug!(
1428            connection_id = connection_id.get(),
1429            route_channel, route_epoch, "handling route GOODBYE"
1430        );
1431        let RouteRelease::Removed(released_route) = self
1432            .forwarding
1433            .release_client_route(connection_id, route_channel, route_epoch)
1434            .map_err(RouterError::Forwarding)?
1435        else {
1436            return Ok(false);
1437        };
1438        self.emit_route_goodbyes(vec![released_route]);
1439        Ok(true)
1440    }
1441
1442    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
1443        for released in released_routes {
1444            let frame = match Frame::build_with_version(
1445                released.negotiated_ver,
1446                FrameType::Goodbye,
1447                control_flags(),
1448                released.channel,
1449                released.epoch,
1450                0,
1451                Vec::new(),
1452            ) {
1453                Ok(frame) => frame,
1454                Err(err) => {
1455                    warn!(
1456                        route_channel = released.channel,
1457                        error = %err,
1458                        "failed to build route GOODBYE frame"
1459                    );
1460                    continue;
1461                }
1462            };
1463            if let Err(err) = released.sink.try_send(frame) {
1464                if released.close_on_delivery_failure() {
1465                    warn!(
1466                        target_connection_id = released.connection_id.get(),
1467                        route_channel = released.channel,
1468                        error = %err,
1469                        "route GOODBYE was not delivered to client; closing target connection"
1470                    );
1471                    if self
1472                        .forwarding
1473                        .escalate_client_delivery_failure(
1474                            released.connection_id,
1475                            released.channel,
1476                            released.epoch,
1477                            CloseReason::new(
1478                                "route_goodbye_delivery_failed",
1479                                format!(
1480                                    "failed to enqueue route GOODBYE for channel {}: {err}",
1481                                    released.channel
1482                                ),
1483                            ),
1484                            crate::forwarding::UndeliveredFrame {
1485                                module_id: released.module_id.as_deref(),
1486                                sink: &released.sink,
1487                            },
1488                        )
1489                        .unwrap_or(false)
1490                    {
1491                        self.counters.increment_goodbye_relay_client_failed();
1492                    }
1493                } else {
1494                    self.counters
1495                        .increment_goodbye_relay_module_dropped(released.module_id.as_deref());
1496                    warn!(
1497                        target_connection_id = released.connection_id.get(),
1498                        route_channel = released.channel,
1499                        error = %err,
1500                        "route GOODBYE to module dropped under backpressure; not closing shared module connection"
1501                    );
1502                }
1503            }
1504        }
1505    }
1506
1507    /// Best-effort GOODBYE to a module for a route channel subc reserved but then
1508    /// abandoned (route.bind relay timed out, its waiter was cancelled, or subc's
1509    /// own commit failed after the module had already accepted). Without this, a
1510    /// module that accepts late keeps a binding subc has torn down, so a later
1511    /// frame on that module channel could misdeliver if the channel is reused.
1512    ///
1513    /// Never closes the shared module connection on failure: a dropped notification
1514    /// only wastes a bounded amount of warm module-side state, which the module's
1515    /// own idle reaper reclaims. Only call this once the route.bind relay was
1516    /// actually enqueued to the module — if the relay send itself failed, the
1517    /// module never created a binding and there is nothing to tear down.
1518    fn send_abandoned_route_bind_goodbye(
1519        &self,
1520        module_sink: &crate::FrameSink,
1521        negotiated_ver: u8,
1522        module_channel: u16,
1523        module_epoch: u32,
1524    ) {
1525        let frame = match Frame::build_with_version(
1526            negotiated_ver,
1527            FrameType::Goodbye,
1528            control_flags(),
1529            module_channel,
1530            module_epoch,
1531            0,
1532            Vec::new(),
1533        ) {
1534            Ok(frame) => frame,
1535            Err(err) => {
1536                warn!(
1537                    route_channel = module_channel,
1538                    error = %err,
1539                    "failed to build GOODBYE for abandoned route.bind"
1540                );
1541                return;
1542            }
1543        };
1544        if let Err(err) = module_sink.try_send(frame) {
1545            warn!(
1546                route_channel = module_channel,
1547                error = %err,
1548                "GOODBYE for abandoned route.bind dropped; module idle reaper will reclaim the binding"
1549            );
1550        }
1551    }
1552
1553    fn handle_hello(
1554        &self,
1555        connection_id: ConnectionId,
1556        sink: Option<crate::FrameSink>,
1557        frame: Frame,
1558    ) -> Result<Vec<Frame>, RouterError> {
1559        debug!(
1560            connection_id = connection_id.get(),
1561            corr = frame.header.corr,
1562            "handling HELLO"
1563        );
1564        let hello_value = match serde_json::from_slice::<serde_json::Value>(&frame.body) {
1565            Ok(value) => value,
1566            Err(err) => {
1567                return Ok(vec![control_error_frame(
1568                    &frame,
1569                    "invalid_hello",
1570                    format!("malformed HELLO body: {err}"),
1571                )?])
1572            }
1573        };
1574        if let Err(err) = validate_hello_capability_grammar(&hello_value) {
1575            return Ok(vec![control_error_frame(
1576                &frame,
1577                "invalid_capability_grammar",
1578                err.to_string(),
1579            )?]);
1580        }
1581        if let Err(err) = validate_hello_self_signal_declarations(&hello_value) {
1582            return Ok(vec![control_error_frame(
1583                &frame,
1584                "invalid_manifest",
1585                err.to_string(),
1586            )?]);
1587        }
1588        if let Some(provenance) = hello_value
1589            .get("manifest")
1590            .and_then(|manifest| manifest.get("provenance"))
1591        {
1592            if let Err(err) = serde_json::from_value::<ManifestProvenance>(provenance.clone()) {
1593                return Ok(vec![control_error_frame(
1594                    &frame,
1595                    "invalid_manifest",
1596                    format!("malformed manifest provenance: {err}"),
1597                )?]);
1598            }
1599        }
1600        let hello = match serde_json::from_value::<ModuleHelloBody>(hello_value) {
1601            Ok(hello) => hello,
1602            Err(err) => {
1603                return Ok(vec![control_error_frame(
1604                    &frame,
1605                    "invalid_hello",
1606                    format!("malformed HELLO body: {err}"),
1607                )?])
1608            }
1609        };
1610
1611        if hello.protocol_ver != hello.manifest.protocol_ver {
1612            return Ok(vec![control_error_frame(
1613                &frame,
1614                "invalid_manifest",
1615                format!(
1616                    "HELLO protocol_ver {} does not match manifest protocol_ver {}",
1617                    hello.protocol_ver, hello.manifest.protocol_ver
1618                ),
1619            )?]);
1620        }
1621
1622        if hello.manifest.module_id.trim().is_empty() {
1623            return Ok(vec![control_error_frame(
1624                &frame,
1625                "invalid_manifest",
1626                "manifest module_id must not be empty",
1627            )?]);
1628        }
1629
1630        let negotiated_ver = match negotiate_version(hello.protocol_ver) {
1631            Ok(negotiated_ver) => negotiated_ver,
1632            Err(message) => {
1633                return Ok(vec![control_error_frame(
1634                    &frame,
1635                    "version_unsupported",
1636                    message,
1637                )?])
1638            }
1639        };
1640
1641        // Swap gate, ahead of the reserved gate on purpose. While a blue/green
1642        // swap is open for this id, the only HELLO admitted as a second process
1643        // is the one carrying the candidate's launch nonce (the swap token), and
1644        // it registers into the candidate slot rather than being refused as a
1645        // duplicate. Run after the reserved gate, a reserved module's candidate
1646        // would be refused `reserved_module` for presenting a nonce that gate
1647        // does not know. See `SupervisorHandle::swap_hello_admission`.
1648        let swap_admission = self
1649            .supervisor
1650            .swap_hello_admission(&hello.manifest.module_id, hello.launch_nonce.as_deref());
1651        if swap_admission == SwapHelloAdmission::Refused {
1652            warn!(
1653                module_id = %hello.manifest.module_id,
1654                connection_id = connection_id.get(),
1655                "HELLO refused: a swap is open for this module_id and the launch nonce is not one the supervisor minted for it"
1656            );
1657            return Ok(vec![control_error_frame(
1658                &frame,
1659                "swap_token_invalid",
1660                format!(
1661                    "module_id '{}' is being swapped; HELLO without the swap candidate's launch nonce is rejected",
1662                    hello.manifest.module_id
1663                ),
1664            )?]);
1665        }
1666        let swap_candidate = swap_admission == SwapHelloAdmission::Candidate;
1667
1668        // Reserved-module identity gate: a module_id configured `reserved` may be
1669        // registered ONLY by the process subc spawned for it, proven by echoing the
1670        // one-time launch nonce subc injected. A non-reserved id has no recorded
1671        // nonce and always passes. This blocks a key-holder from impersonating a
1672        // security-boundary module (e.g. the credential vault) while the real one is
1673        // down/restarting and its registration slot is momentarily free. A swap
1674        // candidate has already proven the same thing with its own nonce above.
1675        if let Some(rejection) = (!swap_candidate)
1676            .then(|| {
1677                self.supervisor.reserved_hello_rejection(
1678                    &hello.manifest.module_id,
1679                    hello.launch_nonce.as_deref(),
1680                )
1681            })
1682            .flatten()
1683        {
1684            let message = match rejection {
1685                ReservedHelloRejection::Exact { module_id } => format!(
1686                    "module_id '{module_id}' is reserved; HELLO without a valid launch nonce is rejected"
1687                ),
1688                ReservedHelloRejection::Prefix {
1689                    prefix,
1690                    owner_module_id,
1691                } => format!(
1692                    "module_id '{}' matches reserved prefix '{prefix}' owned by '{owner_module_id}'; HELLO without the owner launch nonce is rejected",
1693                    hello.manifest.module_id
1694                ),
1695            };
1696            return Ok(vec![control_error_frame(
1697                &frame,
1698                "reserved_module",
1699                message,
1700            )?]);
1701        }
1702
1703        let reserved_capability_refusals = self.capability_evaluator.reserved_hello_refusals(
1704            &hello.manifest.module_id,
1705            hello.manifest.capabilities.as_ref(),
1706        );
1707        if let Some(refusal) = reserved_capability_refusals.first() {
1708            let capability = refusal.capability.clone();
1709            let bound_module = refusal.claimants[0].clone();
1710            log_duplicate_claim_events(reserved_capability_refusals);
1711            return Ok(vec![control_error_frame(
1712                &frame,
1713                "reserved_capability",
1714                format!(
1715                    "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
1716                    capability, bound_module, hello.manifest.module_id
1717                ),
1718            )?]);
1719        }
1720
1721        // A connection that already opened client routes must not also register as
1722        // a module: cleanup would then release only one side and leak the other.
1723        if self
1724            .forwarding
1725            .connection_has_client_routes(connection_id)
1726            .map_err(RouterError::Forwarding)?
1727        {
1728            return Ok(vec![control_error_frame(
1729                &frame,
1730                "invalid_hello",
1731                "connection has open client routes and cannot also register as a module",
1732            )?]);
1733        }
1734
1735        let control_ops = effective_module_control_ops(hello.control_ops);
1736        if swap_candidate {
1737            return self.register_swap_candidate(
1738                connection_id,
1739                sink,
1740                &frame,
1741                hello.manifest,
1742                negotiated_ver,
1743                control_ops,
1744            );
1745        }
1746        let registration = match self.registry.register_with_control_ops(
1747            hello.manifest,
1748            negotiated_ver,
1749            connection_id,
1750            control_ops,
1751        ) {
1752            Ok(registration) => registration,
1753            Err(RegistryError::DuplicateModuleId { module_id }) => {
1754                return Ok(vec![control_error_frame(
1755                    &frame,
1756                    "duplicate_module_id",
1757                    format!(
1758                        "module_id '{module_id}' is already registered; duplicate HELLO rejected"
1759                    ),
1760                )?])
1761            }
1762            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
1763                return Ok(vec![control_error_frame(
1764                    &frame,
1765                    "invalid_module_id",
1766                    err.to_string(),
1767                )?])
1768            }
1769            Err(err) => {
1770                return Ok(vec![control_error_frame(
1771                    &frame,
1772                    "registry_error",
1773                    err.to_string(),
1774                )?])
1775            }
1776        };
1777
1778        if let Some(sink) = sink {
1779            // The forwarding table's module store is also the daemon-to-module
1780            // control-RPC lane, so every HELLO gets a live endpoint even when the
1781            // manifest has no routable provider role. Non-routable modules still
1782            // cannot receive route.bind in production: `handle_route_open` checks
1783            // the registry manifest with `target_has_required_role` before the
1784            // only production call to `begin_route_bind_relay_for` below that
1785            // route.open path. The remaining direct relay callers are unit tests
1786            // and benchmark harnesses that construct forwarding state explicitly.
1787            let concurrency = manifest_concurrency(&registration.manifest);
1788            if let Err(err) = self.forwarding.register_module_connection(
1789                connection_id,
1790                registration.manifest.module_id.clone(),
1791                negotiated_ver,
1792                concurrency,
1793                sink,
1794            ) {
1795                // Forwarding registration failed, so there is no forwarding
1796                // state to tear down. Remove the registry entry and signal the
1797                // release watch directly.
1798                if matches!(self.deregister_connection(connection_id), Ok(r) if !r.is_empty()) {
1799                    crate::supervise::notify_registration_release();
1800                }
1801                return Ok(vec![control_error_frame(
1802                    &frame,
1803                    forwarding_error_code(&err),
1804                    err.to_string(),
1805                )?]);
1806            }
1807        }
1808
1809        // Exposure over assumption: Concurrency's serde default is pinned to the
1810        // pre-field behavior (ModuleManaged), so a management surface that is
1811        // genuinely Serial and just never declared it inherits concurrent
1812        // delivery silently. Logging which registrations RESOLVED BY DEFAULT
1813        // turns "no module has been bitten yet" into the checkable claim "no
1814        // module is exposed" -- one read of the boot log instead of a fleet
1815        // audit. Detected from the raw HELLO bytes because the serde default
1816        // deliberately erases the absent/declared distinction from the type.
1817        if manifest_concurrency_was_defaulted(&frame.body, &registration.manifest) {
1818            info!(
1819                module_id = %registration.manifest.module_id,
1820                "management surface registered with DEFAULTED concurrency=module_managed (manifest predates the field; declare the real lane)"
1821            );
1822        }
1823
1824        self.apply_registration_capabilities(&registration);
1825
1826        info!(
1827            module_id = %registration.manifest.module_id,
1828            module_version = %registration.manifest.module_version,
1829            negotiated_ver,
1830            routable_provider = manifest_provides_routable_role(&registration.manifest),
1831            connection_id = connection_id.get(),
1832            "module registered"
1833        );
1834
1835        self.hello_ack(&frame, negotiated_ver, &registration.manifest.module_id)
1836    }
1837
1838    /// Register a HELLO the swap gate admitted into the candidate slot of the
1839    /// registry and of forwarding, where it is reachable over its own
1840    /// connection (its `catalog.update` finds it) but by no by-id lookup, so
1841    /// nothing routes to it until the supervisor cuts over.
1842    ///
1843    /// Registry first, then forwarding, the same order as an ordinary HELLO;
1844    /// a forwarding failure removes the registry entry again. The capability
1845    /// census is not run: it describes routable modules, and this one is not
1846    /// routable until promotion.
1847    fn register_swap_candidate(
1848        &self,
1849        connection_id: ConnectionId,
1850        sink: Option<crate::FrameSink>,
1851        frame: &Frame,
1852        manifest: ModuleManifest,
1853        negotiated_ver: u8,
1854        control_ops: Vec<String>,
1855    ) -> Result<Vec<Frame>, RouterError> {
1856        let module_id = manifest.module_id.clone();
1857        let registration = match self.registry.register_candidate_with_control_ops(
1858            manifest,
1859            negotiated_ver,
1860            connection_id,
1861            control_ops,
1862        ) {
1863            Ok(registration) => registration,
1864            Err(RegistryError::DuplicateModuleId { module_id }) => {
1865                return Ok(vec![control_error_frame(
1866                    frame,
1867                    "duplicate_module_id",
1868                    format!(
1869                        "module_id '{module_id}' already has a swap candidate registered; duplicate HELLO rejected"
1870                    ),
1871                )?])
1872            }
1873            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
1874                return Ok(vec![control_error_frame(
1875                    frame,
1876                    "invalid_module_id",
1877                    err.to_string(),
1878                )?])
1879            }
1880            Err(err) => {
1881                return Ok(vec![control_error_frame(
1882                    frame,
1883                    "registry_error",
1884                    err.to_string(),
1885                )?])
1886            }
1887        };
1888        if let Some(sink) = sink {
1889            let concurrency = manifest_concurrency(&registration.manifest);
1890            if let Err(err) = self.forwarding.register_candidate_module_connection(
1891                connection_id,
1892                module_id.clone(),
1893                negotiated_ver,
1894                concurrency,
1895                sink,
1896            ) {
1897                if matches!(self.deregister_connection(connection_id), Ok(r) if !r.is_empty()) {
1898                    crate::supervise::notify_registration_release();
1899                }
1900                return Ok(vec![control_error_frame(
1901                    frame,
1902                    forwarding_error_code(&err),
1903                    err.to_string(),
1904                )?]);
1905            }
1906        }
1907        self.supervisor.mark_swap_candidate_admitted(&module_id);
1908        info!(
1909            module_id = %module_id,
1910            module_version = %registration.manifest.module_version,
1911            negotiated_ver,
1912            ready = registration.ready,
1913            connection_id = connection_id.get(),
1914            "swap candidate registered; not routable until cutover"
1915        );
1916        self.hello_ack(frame, negotiated_ver, &module_id)
1917    }
1918
1919    fn hello_ack(
1920        &self,
1921        frame: &Frame,
1922        negotiated_ver: u8,
1923        module_id: &str,
1924    ) -> Result<Vec<Frame>, RouterError> {
1925        let ack = ModuleHelloAckBody {
1926            negotiated_ver,
1927            subc_ops: module_subc_ops(),
1928            subc_capabilities: self.subc_capabilities.as_ref().to_vec(),
1929            storage: self
1930                .storage_config
1931                .as_ref()
1932                .map(|cfg| cfg.descriptor_for(module_id)),
1933            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
1934        };
1935        let body = serde_json::to_vec(&ack).map_err(|err| {
1936            RouterError::backend(
1937                0,
1938                frame.header.corr,
1939                format!("failed to encode HELLO_ACK: {err}"),
1940            )
1941        })?;
1942
1943        Ok(vec![Frame::build_with_version(
1944            negotiated_ver,
1945            FrameType::HelloAck,
1946            control_flags(),
1947            0,
1948            0,
1949            frame.header.corr,
1950            body,
1951        )
1952        .map_err(RouterError::FrameBuild)?])
1953    }
1954
1955    async fn handle_client_control_request(
1956        &self,
1957        ctx: &RouteCtx,
1958        frame: Frame,
1959        request: ClientControlRequest,
1960    ) -> Result<Vec<Frame>, RouterError> {
1961        match request {
1962            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
1963            ClientControlRequest::CatalogList { module_id } => {
1964                self.handle_catalog_list(frame, module_id)
1965            }
1966            ClientControlRequest::RouteOpen {
1967                target,
1968                identity,
1969                consumer_identity,
1970                consumer_capabilities,
1971                admission_facts,
1972            } => {
1973                self.handle_route_open(
1974                    ctx,
1975                    frame,
1976                    RouteOpenRequest {
1977                        target,
1978                        identity,
1979                        consumer_identity,
1980                        consumer_capabilities,
1981                        admission_facts,
1982                    },
1983                )
1984                .await
1985            }
1986            ClientControlRequest::RoutePoll {
1987                route_channel,
1988                route_epoch,
1989                kind,
1990            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
1991            ClientControlRequest::SupervisorList {} => self.handle_supervisor_list(frame),
1992            ClientControlRequest::SupervisorSpawnSnapshot {} => {
1993                self.handle_supervisor_spawn_snapshot(frame)
1994            }
1995            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
1996                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
1997            }
1998            ClientControlRequest::SupervisorRestart {
1999                module_id,
2000                drain_timeout_ms,
2001            } => {
2002                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms)
2003                    .await
2004            }
2005            ClientControlRequest::SupervisorSwap {
2006                module_id,
2007                ready_timeout_ms,
2008            } => {
2009                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms)
2010                    .await
2011            }
2012            ClientControlRequest::SupervisorReload { module_id } => {
2013                self.handle_supervisor_reload(frame, module_id).await
2014            }
2015            ClientControlRequest::SupervisorRescan { preview } => {
2016                self.handle_supervisor_rescan(frame, preview).await
2017            }
2018            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
2019                self.handle_supervisor_release_reserved(frame, module_id)
2020                    .await
2021            }
2022            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
2023                self.handle_supervisor_set_enabled(frame, module_id, enabled)
2024                    .await
2025            }
2026            ClientControlRequest::SupervisorHealthProbe { module_id } => {
2027                self.handle_supervisor_health_probe(frame, module_id).await
2028            }
2029            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
2030            ClientControlRequest::SupervisorRoutes { module_id } => {
2031                self.handle_supervisor_routes(frame, module_id)
2032            }
2033            ClientControlRequest::SupervisorProvenance { module_id } => {
2034                self.handle_supervisor_provenance(frame, module_id).await
2035            }
2036            ClientControlRequest::SupervisorStderrTail {
2037                module_id,
2038                max_lines,
2039                max_bytes,
2040            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
2041            ClientControlRequest::SupervisorTerminals { module_id } => {
2042                self.handle_supervisor_terminals(frame, module_id)
2043            }
2044        }
2045    }
2046
2047    fn handle_module_control_request(
2048        &self,
2049        connection_id: ConnectionId,
2050        frame: Frame,
2051        request: ModuleControlRequestFromModule,
2052    ) -> Result<Vec<Frame>, RouterError> {
2053        match request {
2054            ModuleControlRequestFromModule::CatalogUpdate {
2055                provides,
2056                capabilities,
2057                ready,
2058            } => self.handle_catalog_update(connection_id, frame, provides, capabilities, ready),
2059            ModuleControlRequestFromModule::LiveRoots {} => {
2060                let registered = self
2061                    .registry
2062                    .get_module_by_connection(connection_id)
2063                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
2064                let Some(registration) = registered else {
2065                    return Ok(vec![control_error_frame(&frame, "not_registered", "supervisor.live_roots requires an active module registration owned by this connection")?]);
2066                };
2067                let response = self
2068                    .forwarding
2069                    .live_roots(&registration.manifest.module_id)
2070                    .map_err(RouterError::Forwarding)?;
2071                Ok(vec![control_response_body_frame(
2072                    &frame,
2073                    &response,
2074                    "ModuleControlResponseToModule::LiveRoots",
2075                )?])
2076            }
2077        }
2078    }
2079
2080    fn handle_catalog_update(
2081        &self,
2082        connection_id: ConnectionId,
2083        frame: Frame,
2084        provides: Vec<ProviderRole>,
2085        capabilities: Option<CapabilityDeclarations>,
2086        ready: Option<bool>,
2087    ) -> Result<Vec<Frame>, RouterError> {
2088        self.refresh_capability_requirements();
2089        let Some(registration) = self
2090            .registry
2091            .get_module_by_connection(connection_id)
2092            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
2093        else {
2094            return Ok(vec![control_error_frame(
2095                &frame,
2096                "not_registered",
2097                "catalog.update requires an active module registration owned by this connection",
2098            )?]);
2099        };
2100
2101        if let Some(message) =
2102            catalog_update_frozen_field_message(&registration.manifest, &provides)
2103        {
2104            return Ok(vec![control_error_frame(
2105                &frame,
2106                "catalog_update_frozen_field",
2107                message,
2108            )?]);
2109        }
2110
2111        let mut candidate = registration.manifest.clone();
2112        candidate.provides = provides.clone();
2113        candidate.capabilities = capabilities
2114            .clone()
2115            .or_else(|| registration.manifest.capabilities.clone());
2116        if let Err(err) = candidate.validate_capability_grammar() {
2117            return Ok(vec![control_error_frame(
2118                &frame,
2119                "invalid_capability_grammar",
2120                err.to_string(),
2121            )?]);
2122        }
2123
2124        let updated = self
2125            .registry
2126            .replace_catalog_for_connection(connection_id, provides, capabilities, ready)
2127            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
2128        if updated.is_none() {
2129            return Ok(vec![control_error_frame(
2130                &frame,
2131                "not_registered",
2132                "catalog.update requires an active module registration owned by this connection",
2133            )?]);
2134        }
2135        if let Ok((_, registrations)) = self.runtime_capability_snapshot() {
2136            log_duplicate_claim_events(
2137                self.capability_evaluator
2138                    .duplicate_claims(DuplicateClaimSource::CatalogUpdate, &registrations),
2139            );
2140        }
2141        if capability_census_trigger(
2142            registration.manifest.capabilities.as_ref(),
2143            updated
2144                .as_ref()
2145                .and_then(|entry| entry.manifest.capabilities.as_ref()),
2146        ) {
2147            self.enforce_capability_denies();
2148        }
2149        self.refresh_capability_requirements();
2150
2151        let response = ModuleControlResponseToModule::CatalogUpdate {};
2152        control_response_body_frame(
2153            &frame,
2154            &response,
2155            "ModuleControlResponseToModule::CatalogUpdate",
2156        )
2157        .map(|frame| vec![frame])
2158    }
2159
2160    fn handle_server_describe(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
2161        self.refresh_capability_requirements();
2162        // A bare connection count is ambiguous between many clients holding a
2163        // route each and one client accumulating hundreds, so publish the
2164        // concentration alongside it. Route state is best-effort here: a
2165        // diagnostic endpoint must still answer if the forwarding lock is
2166        // contended.
2167        let mut counters = self.counters.snapshot();
2168        if let (Ok((connections_with_routes, max)), Some(obj)) = (
2169            self.forwarding.client_route_concentration(),
2170            counters.as_object_mut(),
2171        ) {
2172            obj.insert(
2173                "client_connections_with_routes".into(),
2174                connections_with_routes.into(),
2175            );
2176            obj.insert("max_routes_on_one_connection".into(), max.into());
2177        }
2178        // A module that is being fast-refused and a module that is fine look
2179        // identical from a client that retries and succeeds, so name the open
2180        // breakers here. This rides the existing free-form counters object
2181        // rather than a new wire field, so no sibling that deserializes
2182        // `ServerDescribe` has to be rebuilt to keep reading it.
2183        if let (Some(open_breakers), Some(obj)) = (
2184            self.route_bind_breakers.open_snapshot(),
2185            counters.as_object_mut(),
2186        ) {
2187            obj.insert("route_bind_breakers_open".into(), open_breakers);
2188        }
2189        let response = ClientControlResponse::ServerDescribe {
2190            protocol_ver: PROTOCOL_VERSION,
2191            subc_ops: subc_ops(),
2192            capabilities: self.subc_capabilities.as_ref().to_vec(),
2193            connected_clients: self.connected_clients.count(),
2194            counters: Some(counters),
2195            build_git_sha: Some(env!("SUBC_BUILD_GIT_SHA").to_string()),
2196            build_lock_digest: Some(env!("SUBC_BUILD_LOCK_DIGEST").to_string()),
2197            capability_requirements: self.capability_requirement_statuses(),
2198            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
2199        };
2200        Ok(vec![control_response_body_frame(
2201            &frame,
2202            &response,
2203            "ClientControlResponse::ServerDescribe",
2204        )?])
2205    }
2206
2207    fn handle_catalog_list(
2208        &self,
2209        frame: Frame,
2210        module_id: Option<String>,
2211    ) -> Result<Vec<Frame>, RouterError> {
2212        let (generation, modules) = self.registry.list_modules().map_err(|err| {
2213            RouterError::backend(0, frame.header.corr, format!("registry error: {err}"))
2214        })?;
2215        let entries = modules
2216            .into_iter()
2217            .filter(|registration| {
2218                module_id
2219                    .as_deref()
2220                    .map(|wanted| registration.manifest.module_id == wanted)
2221                    .unwrap_or(true)
2222            })
2223            .map(|registration| {
2224                let not_ready = self.not_ready_reason(&registration);
2225                let roles = registration.manifest.provides;
2226                CatalogEntry {
2227                    module_id: registration.manifest.module_id,
2228                    ready: not_ready.is_none(),
2229                    not_ready,
2230                    module_version: Some(registration.manifest.module_version),
2231                    roles,
2232                    control_ops: registration.control_ops,
2233                    capabilities: registration.manifest.capabilities,
2234                    self_signals: registration.manifest.self_signals,
2235                }
2236            })
2237            .collect();
2238        let response = ClientControlResponse::CatalogList {
2239            generation,
2240            modules: entries,
2241            subc_ops: subc_ops(),
2242        };
2243        Ok(vec![control_response_body_frame(
2244            &frame,
2245            &response,
2246            "ClientControlResponse::CatalogList",
2247        )?])
2248    }
2249
2250    fn route_open_principal(
2251        &self,
2252        frame: &Frame,
2253        consumer_identity: Option<ConsumerIdentity>,
2254    ) -> Result<Result<Principal, Frame>, RouterError> {
2255        let Some(consumer_identity) = consumer_identity else {
2256            return Ok(Ok(Principal::Direct));
2257        };
2258
2259        if self.supervisor.spawned_consumer_authorized(
2260            &consumer_identity.module_id,
2261            &consumer_identity.launch_nonce,
2262        ) {
2263            return Ok(Ok(Principal::Reserved {
2264                module_id: consumer_identity.module_id,
2265            }));
2266        }
2267
2268        Ok(Err(control_error_frame(
2269            frame,
2270            "bad_consumer_identity",
2271            format!(
2272                "consumer_identity for module_id '{}' did not match a supervised launch nonce",
2273                consumer_identity.module_id
2274            ),
2275        )?))
2276    }
2277
2278    /// Every refusal of a `route.open` goes through here so the daemon can
2279    /// attest which code it sent: without the event, a client's "the daemon
2280    /// refused me" and the daemon's own view could only be reconciled by
2281    /// argument. Malformed input (`invalid_project_root`) does not come here;
2282    /// rejecting a request that was never a valid open is not a refusal of one.
2283    fn route_open_refusal_frame(
2284        &self,
2285        ctx: &RouteCtx,
2286        frame: &Frame,
2287        module_id: &str,
2288        reason: &'static str,
2289        code: &'static str,
2290        message: impl Into<String>,
2291    ) -> Result<Frame, RouterError> {
2292        self.observe_route_open_refusal(ctx, module_id, reason, code);
2293        control_error_frame(frame, code, message.into())
2294    }
2295
2296    /// Refuse a `route.open` because the target module's bind-relay breaker is
2297    /// open, without attempting the relay.
2298    ///
2299    /// The wire code is `module_timeout`, which is the truth (the module has
2300    /// not been answering binds) and which both SDKs already classify as
2301    /// retryable with capped backoff. Reusing it is what keeps this change out
2302    /// of both SDKs; the daemon-side distinction lives in the counter key
2303    /// instead.
2304    ///
2305    /// DELIBERATELY NOT LOGGED PER OCCURRENCE, unlike every other refusal.
2306    /// While a breaker is open this fires on every open to that module, and the
2307    /// stall written up in `docs/designs/route-open-head-of-line.md` already
2308    /// produced 261 lines about a single module inside 3000 lines of daemon
2309    /// log. The rare transitions are logged at warn/info instead and the volume
2310    /// is carried by the counter, so the evidence survives without the flood.
2311    /// The debug line keeps a per-refusal record reachable for whoever turns
2312    /// the level up.
2313    fn route_open_breaker_refusal_frame(
2314        &self,
2315        ctx: &RouteCtx,
2316        frame: &Frame,
2317        module_id: &str,
2318        consecutive_timeouts: u32,
2319        retry_in: Duration,
2320        probe_in_flight: bool,
2321    ) -> Result<Frame, RouterError> {
2322        self.counters
2323            .increment_route_open_refused(crate::observability::ROUTE_OPEN_REFUSED_BREAKER_OPEN);
2324        debug!(
2325            target: "control",
2326            code = "module_timeout",
2327            module_id = ?module_id,
2328            connection_id = ctx.connection_id.get(),
2329            consecutive_timeouts,
2330            retry_in_ms = retry_in.as_millis() as u64,
2331            probe_in_flight,
2332            "route.open refused by open bind-relay breaker"
2333        );
2334        let detail = if probe_in_flight {
2335            "one probe bind is already in flight; retry once it settles".to_string()
2336        } else {
2337            format!("not relaying for another {retry_in:?}")
2338        };
2339        control_error_frame(
2340            frame,
2341            "module_timeout",
2342            format!(
2343                "module_id '{module_id}' failed {consecutive_timeouts} consecutive route.bind \
2344                 relays; {detail}"
2345            ),
2346        )
2347    }
2348
2349    /// `code` is daemon vocabulary and prints plainly; `module_id` is the
2350    /// requester's bytes (an unknown target is whatever the client sent) and
2351    /// is Debug-formatted so control characters land in the log escaped
2352    /// rather than as terminal sequences for whoever tails it.
2353    ///
2354    /// `reason` names the check that refused, because one wire code has
2355    /// several senders: after a module registers, `target_unavailable` can
2356    /// come from a missing role, an inactive registration, a supervisor that
2357    /// has not marked the process live, a missing forwarding connection, or a
2358    /// failed relay, and a log that records only the code cannot say which of
2359    /// them fired. It is a static, daemon-chosen label per branch, so it is
2360    /// safe to print plainly and stays a closed set.
2361    fn observe_route_open_refusal(
2362        &self,
2363        ctx: &RouteCtx,
2364        module_id: &str,
2365        reason: &'static str,
2366        code: &'static str,
2367    ) {
2368        self.counters.increment_route_open_refused(code);
2369        info!(
2370            target: "control",
2371            code,
2372            reason,
2373            module_id = ?module_id,
2374            connection_id = ctx.connection_id.get(),
2375            "route.open refused"
2376        );
2377    }
2378
2379    /// Record an ACCEPTED route.open.
2380    ///
2381    /// Refusals have been logged and counted since the attestation work; accepts
2382    /// were invisible, so the daemon knew every principal it stamped and wrote
2383    /// none of them down. The party that attests the identity was the only party
2384    /// not recording it, which left a credential vault unable to name the sender
2385    /// of a call that reached it (claustrum #43) and left the launch-nonce
2386    /// concurrency question unanswerable from the outside.
2387    ///
2388    /// FIELD NAMES MATCH `route.open refused` DELIBERATELY, so one grep over
2389    /// `code`/`module_id`/`connection_id` returns both directions of the same
2390    /// decision rather than two shapes a reader has to join by hand.
2391    ///
2392    /// `module_id` IS RENDERED BARE HERE AND DEBUG-ESCAPED ON THE REFUSAL PATH,
2393    /// and the difference carries information rather than being an
2394    /// inconsistency. This line is only reachable after a successful bind to a
2395    /// REGISTERED module, so the value has already passed HELLO validation
2396    /// including the path-hazard refusal and cannot contain control bytes. A
2397    /// refused id may be arbitrary attacker-chosen bytes and must stay escaped.
2398    /// So A QUOTED `module_id` IN THE LOG MEANS THE VALUE WAS NEVER VALIDATED.
2399    ///
2400    /// Bare is also what every other daemon line already emits (`module
2401    /// registered`, `configured module supervised`). Shipping `?module_id` here
2402    /// made this instrument the only one in the file whose ids did not answer
2403    /// `grep module_id=broca` -- 3 hits against 342 for the escaped form, in a
2404    /// line whose whole purpose is being grepped beside its sibling.
2405    ///
2406    /// THIS RENDERING IS UNFENCED AND THE REASON IS WORTH KNOWING: the in-crate
2407    /// `EventCapture` test layer implements only `record_debug`, so `Visit`
2408    /// forwards every field type through it and a bare `&str` and a `?`-escaped
2409    /// one are recorded identically. A test written against that harness passes
2410    /// either way -- I wrote one, measured it, and deleted it rather than ship a
2411    /// green assertion that cannot fail. The same limit applies to the escaping
2412    /// assertion in `route_open_supervised_absence_emits_refusal_fields_and_counts_code`:
2413    /// it reads as a guard on the Debug escaping and cannot detect its removal.
2414    /// Fencing either needs the real formatter, not the capture layer.
2415    ///
2416    /// `peer_addr` is NOT here and cannot be: `SO_PEERCRED`/`LOCAL_PEERPID` are
2417    /// unix-socket options and subc is loopback TCP, so there is no peer identity
2418    /// to record. The ephemeral port would decay within minutes and answer only a
2419    /// live question. The identity question is instead answered by counting
2420    /// distinct live connections presenting one module's `consumer_identity` --
2421    /// "is anyone else holding this secret" rather than "is this the right
2422    /// process".
2423    fn observe_route_open_accept(&self, ctx: &RouteCtx, module_id: &str, principal: &str) {
2424        self.counters.increment_route_open_accepted(principal);
2425        info!(
2426            target: "control",
2427            principal,
2428            module_id,
2429            connection_id = ctx.connection_id.get(),
2430            "route.open accepted"
2431        );
2432    }
2433
2434    fn supervised_absent_route_open_refusal_frame(
2435        &self,
2436        ctx: &RouteCtx,
2437        frame: &Frame,
2438        module_id: &str,
2439        code: &'static str,
2440        status: &crate::supervise::ModuleStatus,
2441    ) -> Result<Frame, RouterError> {
2442        self.counters.increment_route_open_refused(code);
2443        info!(
2444            target: "control",
2445            code,
2446            reason = "supervised_not_registered",
2447            module_id = ?module_id,
2448            connection_id = ctx.connection_id.get(),
2449            state = %status.state,
2450            enabled = status.enabled,
2451            live = status.live,
2452            "route.open refused"
2453        );
2454        control_error_frame(
2455            frame,
2456            code,
2457            format!(
2458                "module_id '{module_id}' is supervised but not available (state={}, enabled={}, live={})",
2459                status.state, status.enabled, status.live
2460            ),
2461        )
2462    }
2463
2464    async fn handle_route_open(
2465        &self,
2466        ctx: &RouteCtx,
2467        frame: Frame,
2468        request: RouteOpenRequest,
2469    ) -> Result<Vec<Frame>, RouterError> {
2470        let RouteOpenRequest {
2471            target,
2472            mut identity,
2473            consumer_identity,
2474            consumer_capabilities,
2475            admission_facts,
2476        } = request;
2477        let target_module_id = target_module_id(&target).to_string();
2478        debug!(
2479            connection_id = ctx.connection_id.get(),
2480            corr = frame.header.corr,
2481            module_id = %target_module_id,
2482            "handling route.open"
2483        );
2484
2485        // WHY THESE REPLIES DISCRIMINATE FREELY, since the usual rule is the
2486        // opposite. Below, a caller learns whether a module is unregistered,
2487        // supervised-but-down (with state/enabled/live), or registered without the
2488        // requested role. Elsewhere that is an enumeration leak: a probe learning
2489        // the shape of a fleet it cannot otherwise see.
2490        //
2491        // It is not one here, and the reason is the ACCESS MODEL rather than
2492        // anything about these errors. Reaching route.open requires the
2493        // pre-envelope HMAC handshake, whose key lives in a 0600 user-owned
2494        // connection file, so any caller who completes it already runs as this
2495        // user -- and can read subc.jsonc for the module list and `ck module
2496        // status` for live state. The reply discloses nothing the caller cannot
2497        // read more easily from disk, while the precision is load-bearing:
2498        // `unknown_module` is retryable and a missing role is not.
2499        //
2500        // IF THE HANDSHAKE EVER ADMITS A PRINCIPAL THAT IS NOT THIS USER -- a
2501        // remote transport, a sandboxed caller, a shared-host mode -- THAT
2502        // PREMISE DIES AND THESE THREE REPLIES MUST COLLAPSE INTO ONE.
2503        let Some(registration) = self
2504            .registry
2505            .get_module(&target_module_id)
2506            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
2507        else {
2508            if let Some((status, warming)) =
2509                self.supervisor_status(&target_module_id, frame.header.corr)?
2510            {
2511                // BEFORE the two availability codes below, because for a module
2512                // that speaks no subc wire both of them are false comfort: they
2513                // say "not right now" and are retried, and this module will
2514                // never register no matter how long the caller waits. The
2515                // absence here is the declaration being honoured, not a module
2516                // that is late.
2517                if status.protocol == ModuleProtocol::None {
2518                    return Ok(vec![self.route_open_refusal_frame(
2519                        ctx,
2520                        &frame,
2521                        &target_module_id,
2522                        "protocol_none",
2523                        error_codes::MODULE_NO_PROTOCOL,
2524                        format!(
2525                            "module_id '{target_module_id}' is declared protocol: none; \
2526                             it speaks no subc wire and serves no routes"
2527                        ),
2528                    )?]);
2529                }
2530                let code = if warming {
2531                    "module_warming"
2532                } else {
2533                    "target_unavailable"
2534                };
2535                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
2536                    ctx,
2537                    &frame,
2538                    &target_module_id,
2539                    code,
2540                    &status,
2541                )?]);
2542            }
2543            if let Some(removed_ago_ms) =
2544                self.supervisor.removal_tombstone_age_ms(&target_module_id)
2545            {
2546                return Ok(vec![self.route_open_refusal_frame(
2547                    ctx,
2548                    &frame,
2549                    &target_module_id,
2550                    "removed",
2551                    error_codes::MODULE_REMOVED,
2552                    format!("module_id '{target_module_id}' was removed {removed_ago_ms} ms ago"),
2553                )?]);
2554            }
2555            return Ok(vec![self.route_open_refusal_frame(
2556                ctx,
2557                &frame,
2558                &target_module_id,
2559                "not_registered",
2560                error_codes::UNKNOWN_MODULE,
2561                format!("module_id '{target_module_id}' is not registered"),
2562            )?]);
2563        };
2564
2565        // Best-effort only: registry readiness and forwarding reservation use
2566        // different locks, so a module can flip readiness between this read and
2567        // the relay. Modules must still tolerate an `on_bind` while not ready.
2568        if !registration.ready {
2569            self.counters
2570                .increment_route_open_refused(ROUTE_OPEN_REFUSED_DECLARED_NOT_READY);
2571            info!(
2572                target: "control",
2573                code = error_codes::MODULE_WARMING,
2574                module_id = ?target_module_id,
2575                connection_id = ctx.connection_id.get(),
2576                reason = "declared_not_ready",
2577                "route.open refused"
2578            );
2579            return Ok(vec![control_error_body_frame(
2580                &frame,
2581                ErrorBody {
2582                    code: error_codes::MODULE_WARMING.to_string(),
2583                    message: format!(
2584                        "module_id '{target_module_id}' is registered and has declared itself not ready; retry"
2585                    ),
2586                    detail: Some(serde_json::json!({
2587                        "reason": "declared_not_ready"
2588                    })),
2589                },
2590            )?]);
2591        }
2592
2593        // Effective readiness, second half: a module that declares a capability
2594        // `need: required` is not routable while that capability has no
2595        // registered provider. It is enforced HERE, as a retryable routing
2596        // refusal, and deliberately not as spawn ordering or a boot block. The
2597        // module is still started and registered and can make its own calls;
2598        // spawn ordering is a promise that cannot be kept once a provider
2599        // crashes at runtime, and refusing to boot would stop the whole
2600        // machine, including the tools needed to fix its configuration.
2601        //
2602        // "Provided" is the evaluator's verdict, which counts a provider as
2603        // soon as it has REGISTERED, not once it is ready. Two modules that
2604        // require each other's capabilities are therefore both routable once
2605        // both register; counting readiness instead would deadlock them.
2606        //
2607        // Only new opens are refused. Routes already bound when a provider
2608        // goes away stay bound: nothing here tears them down, and the module
2609        // answers them as it can. Like the readiness read above this is
2610        // best-effort against a provider registering or leaving concurrently.
2611        if let Some(capability) = self.first_unprovided_required_capability(&registration) {
2612            self.counters
2613                .increment_route_open_refused(ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED);
2614            info!(
2615                target: "control",
2616                code = error_codes::MODULE_WARMING,
2617                module_id = ?target_module_id,
2618                connection_id = ctx.connection_id.get(),
2619                reason = NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
2620                capability = %capability,
2621                "route.open refused"
2622            );
2623            return Ok(vec![control_error_body_frame(
2624                &frame,
2625                ErrorBody {
2626                    code: error_codes::MODULE_WARMING.to_string(),
2627                    message: format!(
2628                        "module_id '{target_module_id}' requires capability '{capability}', \
2629                         which no registered module provides; retry"
2630                    ),
2631                    detail: Some(serde_json::json!({
2632                        "reason": NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
2633                        "capability": capability,
2634                    })),
2635                },
2636            )?]);
2637        }
2638
2639        if !target_has_required_role(&target, &registration.manifest.provides) {
2640            return Ok(vec![self.route_open_refusal_frame(
2641                ctx,
2642                &frame,
2643                &target_module_id,
2644                "role_not_provided",
2645                "target_unavailable",
2646                format!("module_id '{target_module_id}' does not provide the requested target"),
2647            )?]);
2648        }
2649
2650        if registration.state != ChannelState::Active {
2651            return Ok(vec![self.route_open_refusal_frame(
2652                ctx,
2653                &frame,
2654                &target_module_id,
2655                "registration_not_active",
2656                "target_unavailable",
2657                format!("module_id '{target_module_id}' is not active"),
2658            )?]);
2659        }
2660
2661        if self
2662            .forwarding
2663            .module_is_draining(&target_module_id)
2664            .map_err(RouterError::Forwarding)?
2665        {
2666            return Ok(vec![self.route_open_refusal_frame(
2667                ctx,
2668                &frame,
2669                &target_module_id,
2670                "reloading",
2671                "module_reloading",
2672                format!("module_id '{target_module_id}' is reloading"),
2673            )?]);
2674        }
2675
2676        if self
2677            .process_liveness
2678            .as_ref()
2679            .and_then(|process_liveness| process_liveness.process_live(&target_module_id))
2680            == Some(false)
2681        {
2682            return Ok(vec![self.route_open_refusal_frame(
2683                ctx,
2684                &frame,
2685                &target_module_id,
2686                "supervisor_not_live",
2687                "target_unavailable",
2688                format!("module_id '{target_module_id}' is not live"),
2689            )?]);
2690        }
2691
2692        if !self
2693            .forwarding
2694            .has_live_module_connection(&target_module_id)
2695            .map_err(RouterError::Forwarding)?
2696        {
2697            return Ok(vec![self.route_open_refusal_frame(
2698                ctx,
2699                &frame,
2700                &target_module_id,
2701                "no_forwarding_connection",
2702                "target_unavailable",
2703                format!("module_id '{target_module_id}' has no live forwarding connection"),
2704            )?]);
2705        }
2706
2707        if let Some(error) =
2708            self.guard_module_control_op(&frame, &target_module_id, "route.bind")?
2709        {
2710            self.observe_route_open_refusal(
2711                ctx,
2712                &target_module_id,
2713                "op_not_allowed",
2714                "op_not_allowed",
2715            );
2716            return Ok(vec![error]);
2717        }
2718
2719        let principal = match self.route_open_principal(&frame, consumer_identity)? {
2720            Ok(principal) => principal,
2721            Err(error) => {
2722                self.observe_route_open_refusal(
2723                    ctx,
2724                    &target_module_id,
2725                    "bad_consumer_identity",
2726                    "bad_consumer_identity",
2727                );
2728                return Ok(vec![error]);
2729            }
2730        };
2731
2732        // This is attested, control-plane policy for supervised module origins.
2733        // Keep it before route reservation and out of the opaque forwarding hot
2734        // path: data frames must never acquire a per-frame capability check.
2735        if let Principal::Reserved {
2736            module_id: opening_module_id,
2737        } = &principal
2738        {
2739            if let Some(opening_registration) = self
2740                .registry
2741                .get_module(opening_module_id)
2742                .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
2743            {
2744                if let Some(capability) =
2745                    denied_capability(&opening_registration.manifest, &registration.manifest)
2746                {
2747                    warn!(
2748                        opening_module_id,
2749                        target_module_id,
2750                        capability,
2751                        "refusing route.open because an attested capability deny edge matches"
2752                    );
2753                    return Ok(vec![self.route_open_refusal_frame(
2754                        ctx,
2755                        &frame,
2756                        &target_module_id,
2757                        "capability_deny_edge",
2758                        "capability_forbidden",
2759                        format!(
2760                            "module_id '{opening_module_id}' must never reach capability '{capability}' provided by '{target_module_id}'"
2761                        ),
2762                    )?]);
2763                }
2764            }
2765        }
2766
2767        if admission_facts.is_some() {
2768            let carrier_matches = matches!(
2769                &principal,
2770                Principal::Reserved { module_id }
2771                    if self.admission_facts_carrier_module_id.as_deref() == Some(module_id)
2772            );
2773            if !carrier_matches {
2774                return Ok(vec![self.route_open_refusal_frame(
2775                    ctx,
2776                    &frame,
2777                    &target_module_id,
2778                    "admission_facts_carrier_not_permitted",
2779                    "admission_facts_not_permitted",
2780                    "admission facts may only be carried by the configured reserved module",
2781                )?]);
2782            }
2783
2784            let target_allowed = self
2785                .admission_facts_targets
2786                .as_ref()
2787                .is_some_and(|targets| targets.iter().any(|id| id == &target_module_id));
2788            if !target_allowed {
2789                return Ok(vec![self.route_open_refusal_frame(
2790                    ctx,
2791                    &frame,
2792                    &target_module_id,
2793                    "admission_facts_target_not_listed",
2794                    "admission_facts_target_not_allowed",
2795                    format!(
2796                        "admission facts are not permitted for target module_id '{target_module_id}'"
2797                    ),
2798                )?]);
2799            }
2800
2801            // Keep the value opaque to subc. The downstream admission validator owns
2802            // schema and semantic checks; this daemon only enforces carrier authority
2803            // and the configured destination allowlist.
2804        }
2805
2806        // Bind admits a root that no longer exists on disk, because refusing here
2807        // closes the only exit from a paused run: cancel needs a bound route, and a
2808        // renamed or reclaimed directory makes that route unopenable forever. The
2809        // run itself is intact and still addressable by its recorded identity.
2810        //
2811        // This does NOT relax the rule the strict constructor protects. That rule is
2812        // that no root is ever aliased into NEW durable state -- a missing component
2813        // can reappear as a symlink elsewhere, which would move the identity and
2814        // split a session's history across two of them. The engine now refuses the
2815        // two operations that create such state (send and import) at admission,
2816        // which is a narrower way to hold the same invariant: reads and terminations
2817        // are admitted, writes are not. That refusal had to ship before this line
2818        // changed, or there is an interval where a send commits under a provisional
2819        // identity -- the exact failure the original policy existed to prevent.
2820        //
2821        // Resolution follows realpath rather than lexical cleanup: the longest
2822        // existing ancestor is canonicalized and the missing tail re-appended, so a
2823        // live root is unchanged and a vanished leaf keeps the identity it was
2824        // admitted under. Lexical cleanup would mint a DIFFERENT identity for the
2825        // same caller the moment the directory vanished, which strands the run more
2826        // quietly than refusing it.
2827        let project_root = match ProjectRootId::from_path_allowing_missing(&identity.project_root) {
2828            Ok(project_root) => project_root,
2829            Err(err) => {
2830                return Ok(vec![control_error_frame(
2831                    &frame,
2832                    "invalid_project_root",
2833                    err.to_string(),
2834                )?])
2835            }
2836        };
2837        identity.project_root = project_root.as_path().to_path_buf();
2838
2839        // Last gate before any relay work, and deliberately after the cheap
2840        // registry and availability checks above: those name a more precise
2841        // condition (unknown, removed, reloading) and a caller is better served
2842        // by the precise code than by this one.
2843        //
2844        // Everything below this point costs an egress permit, a reserved handle
2845        // pair and, if the module does not answer, the whole relay budget. The
2846        // reader no longer waits for that budget, so cap each target explicitly;
2847        // serial dispatch used to provide the accidental cap of one relay per
2848        // connection. Admission is a mutex-protected count and never waits.
2849        let _concurrency_guard = match self
2850            .route_bind_concurrency
2851            .try_admit(&target_module_id, MAX_PENDING_ROUTE_BINDS_PER_TARGET)
2852        {
2853            Ok(guard) => guard,
2854            Err(in_flight) => {
2855                return Ok(vec![self.route_open_admission_refusal_frame(
2856                    ctx,
2857                    &frame,
2858                    &target_module_id,
2859                    format!(
2860                        "module_id '{target_module_id}' already has {in_flight} route.bind relays in flight; retry after one settles"
2861                    ),
2862                )?]);
2863            }
2864        };
2865
2866        // A module that has already burned the whole budget `threshold` times
2867        // in a row does not get to charge it again until a probe says it recovered.
2868        let mut breaker = match self.route_bind_breakers.admit(&target_module_id) {
2869            RouteBindAdmission::Admitted { guard, probe } => {
2870                if probe {
2871                    info!(
2872                        module_id = %target_module_id,
2873                        connection_id = ctx.connection_id.get(),
2874                        "route.bind breaker half-open: admitting one probe"
2875                    );
2876                }
2877                guard
2878            }
2879            RouteBindAdmission::Refused {
2880                consecutive_timeouts,
2881                retry_in,
2882                probe_in_flight,
2883            } => {
2884                return Ok(vec![self.route_open_breaker_refusal_frame(
2885                    ctx,
2886                    &frame,
2887                    &target_module_id,
2888                    consecutive_timeouts,
2889                    retry_in,
2890                    probe_in_flight,
2891                )?]);
2892            }
2893        };
2894
2895        // Resolve the per-module budget here so the wait matches the operator's
2896        // intent for this specific target. A per-module override in
2897        // `subc.jsonc` (or `with_route_bind_relay_timeouts` for embedded
2898        // daemons) wins over the daemon-wide default.
2899        let route_bind_relay_timeout = self.route_bind_relay_timeout_for(&target_module_id);
2900        let relay_deadline = Instant::now() + route_bind_relay_timeout;
2901        let pending = match self
2902            .forwarding
2903            .begin_route_bind_relay_for(
2904                ctx.connection_id,
2905                ctx.egress.clone(),
2906                response_version(&frame),
2907                frame.header.corr,
2908                &target_module_id,
2909                principal.clone(),
2910                Some(project_root),
2911                relay_deadline,
2912            )
2913            .await
2914        {
2915            Ok(pending) => pending,
2916            Err(err) => {
2917                return Ok(vec![self.route_open_refusal_frame(
2918                    ctx,
2919                    &frame,
2920                    &target_module_id,
2921                    "relay_reservation_failed",
2922                    forwarding_error_code(&err),
2923                    err.to_string(),
2924                )?])
2925            }
2926        };
2927        let crate::forwarding::PendingRouteBindRelay {
2928            endpoint,
2929            module_sink,
2930            negotiated_ver,
2931            client_channel,
2932            client_epoch,
2933            module_channel,
2934            module_epoch,
2935            corr: relay_corr,
2936            receiver,
2937        } = pending;
2938        let mut reservation =
2939            RouteBindReservationGuard::new(Arc::clone(&self.forwarding), endpoint, relay_corr);
2940
2941        debug!(
2942            connection_id = ctx.connection_id.get(),
2943            client_channel,
2944            client_epoch,
2945            module_channel,
2946            module_epoch,
2947            "reserved route handle pair"
2948        );
2949        // Rendered BEFORE the move into the relay, because the accept arm below
2950        // is where it is logged and the principal is gone by then.
2951        let principal_label = match &principal {
2952            Principal::Reserved { module_id } => format!("reserved:{module_id}"),
2953            Principal::Direct => "direct".to_string(),
2954            other => format!("{other:?}"),
2955        };
2956        let relay = ModuleControlRequest::RouteBind {
2957            route_channel: module_channel,
2958            epoch: module_epoch,
2959            target,
2960            identity,
2961            principal: Some(principal),
2962            consumer_capabilities,
2963            admission_facts,
2964        };
2965        let relay_body = serde_json::to_vec(&relay).map_err(|err| {
2966            RouterError::backend(
2967                0,
2968                frame.header.corr,
2969                format!("failed to encode route.bind request: {err}"),
2970            )
2971        })?;
2972        let relay_frame = Frame::build_with_version(
2973            negotiated_ver,
2974            FrameType::Request,
2975            control_flags(),
2976            0,
2977            0,
2978            relay_corr,
2979            relay_body,
2980        )
2981        .map_err(RouterError::FrameBuild)?;
2982
2983        if let Err(err) = module_sink.send(relay_frame).await {
2984            reservation.release_and_disarm();
2985            return Ok(vec![self.route_open_refusal_frame(
2986                ctx,
2987                &frame,
2988                &target_module_id,
2989                "relay_send_failed",
2990                "target_unavailable",
2991                err.to_string(),
2992            )?]);
2993        }
2994
2995        if !self
2996            .forwarding
2997            .mark_route_bind_relay_enqueued(endpoint, relay_corr)
2998            .map_err(RouterError::Forwarding)?
2999        {
3000            self.send_abandoned_route_bind_goodbye(
3001                &module_sink,
3002                negotiated_ver,
3003                module_channel,
3004                module_epoch,
3005            );
3006        }
3007
3008        match timeout_at(relay_deadline, receiver).await {
3009            Ok(Ok(RouteBindRelayOutcome::Accepted)) => {
3010                reservation.disarm();
3011                if breaker.record_accepted() {
3012                    info!(
3013                        module_id = %target_module_id,
3014                        "route.bind breaker closed: the probe was accepted"
3015                    );
3016                }
3017                self.observe_route_open_accept(ctx, &target_module_id, &principal_label);
3018                Ok(Vec::new())
3019            }
3020            Ok(Ok(RouteBindRelayOutcome::Rejected(body))) => {
3021                reservation.release_and_disarm();
3022                // A module that says no in microseconds is healthy. Rejection
3023                // is a different condition with its own refusal and must not
3024                // move the breaker.
3025                breaker.record_inconclusive();
3026                self.counters
3027                    .increment_route_open_refused("module_rejected");
3028                info!(
3029                    target: "control",
3030                    code = "module_rejected",
3031                    module_code = ?body.code,
3032                    module_id = ?target_module_id,
3033                    connection_id = ctx.connection_id.get(),
3034                    "route.open refused"
3035                );
3036                Ok(vec![control_error_body_frame(&frame, body)?])
3037            }
3038            Ok(Ok(RouteBindRelayOutcome::ModuleGone(message))) => {
3039                reservation.release_and_disarm();
3040                breaker.record_inconclusive();
3041                // Fires when the module's connection closes while a relayed
3042                // bind is pending -- typically a caller racing a module restart
3043                // whose bind was relayed BEFORE the drain mark went up. Logged
3044                // because the caller sees only its own error and the fleet has
3045                // already spent one diagnosis round unable to tell this arm
3046                // from a relay timeout without daemon-side evidence.
3047                tracing::warn!(
3048                    module_id = %target_module_id,
3049                    "route.bind relay abandoned: {message}"
3050                );
3051                Ok(vec![self.route_open_refusal_frame(
3052                    ctx,
3053                    &frame,
3054                    &target_module_id,
3055                    "relay_abandoned",
3056                    "target_unavailable",
3057                    message,
3058                )?])
3059            }
3060            Ok(Err(_)) => {
3061                reservation.release_and_disarm();
3062                breaker.record_inconclusive();
3063                Ok(vec![self.route_open_refusal_frame(
3064                    ctx,
3065                    &frame,
3066                    &target_module_id,
3067                    "relay_waiter_canceled",
3068                    "target_unavailable",
3069                    "route.bind relay waiter was canceled before the module responded",
3070                )?])
3071            }
3072            Err(_) => {
3073                reservation.release_and_disarm();
3074                // THE ONLY ARM THAT MOVES THE BREAKER. Budget exhausted with no
3075                // answer at all is the one condition a fast refusal can
3076                // usefully stand in for; every other arm already answered.
3077                if let Some(opened) = breaker.record_timeout(
3078                    self.route_bind_breaker_threshold,
3079                    self.route_bind_breaker_cooldown,
3080                ) {
3081                    warn!(
3082                        module_id = %target_module_id,
3083                        consecutive_timeouts = opened.consecutive_timeouts,
3084                        cooldown_ms = self.route_bind_breaker_cooldown.as_millis() as u64,
3085                        reopened_after_probe = opened.reopened_after_probe,
3086                        "route.bind breaker open: refusing route.open for this module without relaying until one probe says it recovered"
3087                    );
3088                }
3089                // The generous budget just burned to no answer: the module is
3090                // registered and its connection is up, but its bind handler sat
3091                // on the ack for the full budget (warm-on-bind, cold configure,
3092                // or a wedged handler). Every earlier unavailability shape
3093                // fast-refuses BEFORE the relay, so this arm firing means the
3094                // slowness is module-side -- log it so the per-module timeline
3095                // is reconstructable without client audit rows.
3096                tracing::warn!(
3097                    module_id = %target_module_id,
3098                    timeout_ms = route_bind_relay_timeout.as_millis() as u64,
3099                    "route.bind relay timed out: module did not ack within budget"
3100                );
3101                Ok(vec![self.route_open_refusal_frame(
3102                    ctx,
3103                    &frame,
3104                    &target_module_id,
3105                    "relay_timed_out",
3106                    "module_timeout",
3107                    format!(
3108                        "module_id '{target_module_id}' did not answer route.bind within {:?}",
3109                        route_bind_relay_timeout
3110                    ),
3111                )?])
3112            }
3113        }
3114    }
3115
3116    fn handle_supervisor_spawn_snapshot(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
3117        let response = ClientControlResponse::SupervisorSpawnSnapshot {
3118            snapshot: self.supervisor.spawn_snapshot(),
3119        };
3120        Ok(vec![control_response_body_frame(
3121            &frame,
3122            &response,
3123            "ClientControlResponse::SupervisorSpawnSnapshot",
3124        )?])
3125    }
3126
3127    fn handle_supervisor_spawn_subscribe(
3128        &self,
3129        ctx: &RouteCtx,
3130        frame: Frame,
3131        since: Option<SpawnCursor>,
3132    ) -> Result<Vec<Frame>, RouterError> {
3133        match self.supervisor.subscribe_spawns(
3134            ctx.connection_id,
3135            frame.header.corr,
3136            response_version(&frame),
3137            since,
3138            ctx.egress.clone(),
3139        ) {
3140            Ok(()) => Ok(Vec::new()),
3141            Err(SpawnSubscribeRefusal::ForeignIncarnation { current }) => {
3142                Ok(vec![control_error_body_frame(
3143                    &frame,
3144                    ErrorBody {
3145                        code: "spawn_cursor_incarnation_mismatch".to_string(),
3146                        message: "spawn cursor belongs to a different daemon incarnation"
3147                            .to_string(),
3148                        detail: Some(serde_json::json!({
3149                            "current_daemon_incarnation": current
3150                        })),
3151                    },
3152                )?])
3153            }
3154            Err(SpawnSubscribeRefusal::TooOld { oldest }) => Ok(vec![control_error_body_frame(
3155                &frame,
3156                ErrorBody {
3157                    code: "spawn_cursor_too_old".to_string(),
3158                    message: "spawn cursor predates the retained event ring".to_string(),
3159                    detail: Some(serde_json::json!({
3160                        "oldest_retained_cursor": oldest
3161                    })),
3162                },
3163            )?]),
3164            Err(SpawnSubscribeRefusal::Frame(error)) => Err(RouterError::backend(
3165                0,
3166                frame.header.corr,
3167                format!("failed to open supervisor spawn subscription: {error}"),
3168            )),
3169        }
3170    }
3171
3172    fn handle_supervisor_list(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
3173        let generation = self
3174            .registry
3175            .generation()
3176            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
3177        let modules = self
3178            .supervisor
3179            .list()
3180            .into_iter()
3181            .map(|module| {
3182                let status = module.status_for_control("list").map_err(|err| {
3183                    RouterError::backend(
3184                        0,
3185                        frame.header.corr,
3186                        format!("failed to read supervisor status: {err}"),
3187                    )
3188                })?;
3189                Ok(SupervisorEntry {
3190                    module_id: status.module_id,
3191                    state: status.state.to_string(),
3192                    enabled: status.enabled,
3193                    live: status.live,
3194                    protocol: status.protocol,
3195                    health: status.health.status,
3196                    last_probe_ms: status.health.last_probe_ms,
3197                    last_exit_code: status.last_exit.as_ref().and_then(|e| e.code),
3198                    last_exit_signal: status.last_exit.as_ref().and_then(|e| e.signal),
3199                    last_exit_ms: status.last_exit.as_ref().map(|e| e.at_ms),
3200                    last_exit_kind: status.last_exit.as_ref().map(|e| e.kind.into()),
3201                    restart_count: Some(status.restart_count),
3202                    max_restarts: Some(status.max_restarts),
3203                    lifetime_restarts: Some(status.lifetime_restarts),
3204                    spawn_generation: Some(status.spawn_generation),
3205                    restart_window_secs: Some(status.restart_window.as_secs()),
3206                    drain_timeout_ms: Some(status.drain_timeout.as_millis() as u64),
3207                    restart_backoff_ms: Some(status.restart_backoff.as_millis() as u64),
3208                    restart_max_backoff_ms: Some(status.restart_max_backoff.as_millis() as u64),
3209                })
3210            })
3211            .collect::<Result<Vec<_>, RouterError>>()?;
3212        let response = ClientControlResponse::SupervisorList {
3213            generation,
3214            modules,
3215        };
3216        Ok(vec![control_response_body_frame(
3217            &frame,
3218            &response,
3219            "ClientControlResponse::SupervisorList",
3220        )?])
3221    }
3222
3223    fn handle_supervisor_stderr_tail(
3224        &self,
3225        frame: Frame,
3226        module_id: String,
3227        max_lines: Option<u32>,
3228        max_bytes: Option<u32>,
3229    ) -> Result<Vec<Frame>, RouterError> {
3230        let Some(module) = self.supervisor.get(&module_id) else {
3231            return Ok(vec![control_error_frame(
3232                &frame,
3233                "unknown_module",
3234                format!("module_id '{module_id}' is not supervised"),
3235            )?]);
3236        };
3237
3238        let snapshot = module.stderr_tail(
3239            max_lines.map(|value| value as usize),
3240            max_bytes.map(|value| value as usize),
3241        );
3242
3243        let response = ClientControlResponse::SupervisorStderrTail {
3244            module_id,
3245            tail: StderrTail {
3246                capture: match snapshot.capture {
3247                    CaptureState::Captured => StderrCaptureState::Captured,
3248                    CaptureState::Incomplete { reason } => {
3249                        StderrCaptureState::Incomplete { reason }
3250                    }
3251                    CaptureState::NotCaptured { reason } => {
3252                        StderrCaptureState::NotCaptured { reason }
3253                    }
3254                },
3255                entries: snapshot
3256                    .entries
3257                    .into_iter()
3258                    .map(|entry| match entry {
3259                        TailEntry::Line { text, truncated } => {
3260                            StderrTailEntry::Line { text, truncated }
3261                        }
3262                        TailEntry::ProcessStart => StderrTailEntry::ProcessStart,
3263                    })
3264                    .collect(),
3265                dropped_lines: snapshot.dropped_lines,
3266            },
3267        };
3268        Ok(vec![control_response_body_frame(
3269            &frame,
3270            &response,
3271            "ClientControlResponse::SupervisorStderrTail",
3272        )?])
3273    }
3274
3275    fn handle_supervisor_terminals(
3276        &self,
3277        frame: Frame,
3278        module_id: String,
3279    ) -> Result<Vec<Frame>, RouterError> {
3280        let Some(module) = self.supervisor.get(&module_id) else {
3281            return Ok(vec![control_error_frame(
3282                &frame,
3283                "unknown_module",
3284                format!("module_id '{module_id}' is not supervised"),
3285            )?]);
3286        };
3287
3288        let response = ClientControlResponse::SupervisorTerminals {
3289            module_id,
3290            terminals: module.durable_terminal_history(),
3291        };
3292        Ok(vec![control_response_body_frame(
3293            &frame,
3294            &response,
3295            "ClientControlResponse::SupervisorTerminals",
3296        )?])
3297    }
3298
3299    fn handle_supervisor_routes(
3300        &self,
3301        frame: Frame,
3302        module_id: Option<String>,
3303    ) -> Result<Vec<Frame>, RouterError> {
3304        let modules = self
3305            .forwarding
3306            .route_census(module_id.as_deref())
3307            .map_err(RouterError::Forwarding)?
3308            .into_iter()
3309            .map(|(module_id, routes)| SupervisorRouteModule {
3310                module_id,
3311                routes: routes
3312                    .into_iter()
3313                    .map(|route| SupervisorRoute {
3314                        consumer: match route.principal {
3315                            Principal::Reserved { module_id } => {
3316                                SupervisorRouteConsumer::Reserved { module_id }
3317                            }
3318                            Principal::Direct | Principal::Unverified => {
3319                                SupervisorRouteConsumer::Direct {
3320                                    connection_id: route.goodbye_target.connection_id.get(),
3321                                }
3322                            }
3323                        },
3324                        age_ms: Instant::now()
3325                            .saturating_duration_since(route.bound_at)
3326                            .as_millis()
3327                            .try_into()
3328                            .unwrap_or(u64::MAX),
3329                        draining: route.draining,
3330                        drain_reason: route.drain_reason,
3331                    })
3332                    .collect(),
3333            })
3334            .collect();
3335        let response = ClientControlResponse::SupervisorRoutes { modules };
3336        Ok(vec![control_response_body_frame(
3337            &frame,
3338            &response,
3339            "ClientControlResponse::SupervisorRoutes",
3340        )?])
3341    }
3342
3343    async fn handle_supervisor_provenance(
3344        &self,
3345        frame: Frame,
3346        module_id: Option<String>,
3347    ) -> Result<Vec<Frame>, RouterError> {
3348        let mut selected = if let Some(module_id) = module_id {
3349            let Some(module) = self.supervisor.get(&module_id) else {
3350                return Ok(vec![control_error_frame(
3351                    &frame,
3352                    "unknown_module",
3353                    format!("module_id '{module_id}' is not supervised"),
3354                )?]);
3355            };
3356            vec![module]
3357        } else {
3358            self.supervisor.list()
3359        };
3360
3361        let mut modules = Vec::with_capacity(selected.len());
3362        for module in selected.drain(..) {
3363            let status = module.status().map_err(|err| {
3364                RouterError::backend(
3365                    0,
3366                    frame.header.corr,
3367                    format!("failed to read supervisor status: {err}"),
3368                )
3369            })?;
3370            let module_declared = self
3371                .registry
3372                .get_module(&status.module_id)
3373                .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
3374                .and_then(|registration| registration.manifest.provenance)
3375                .map(|build| ModuleDeclaredProvenance::Reported { build })
3376                .unwrap_or(ModuleDeclaredProvenance::Unverifiable);
3377            #[cfg(test)]
3378            let running_image = match &self.provenance_probe_override {
3379                Some(result) => result.clone(),
3380                None => module.running_image_agreement().await,
3381            };
3382            #[cfg(not(test))]
3383            let running_image = module.running_image_agreement().await;
3384            modules.push(SupervisorModuleProvenance {
3385                module_id: status.module_id,
3386                module_declared,
3387                daemon_observed: SupervisorObservedProcess {
3388                    pid: status.pid,
3389                    spawned_at_ms: status.spawned_at_ms,
3390                    spawned_from: status.spawned_from,
3391                    running_image,
3392                },
3393            });
3394        }
3395        let daemon = SupervisorDaemonProvenance {
3396            daemon_build: self.daemon_provenance.build.clone(),
3397            daemon_observed: DaemonObservedProcess {
3398                pid: self.daemon_provenance.pid,
3399                started_at_ms: self
3400                    .daemon_provenance
3401                    .start_clock
3402                    .map(|clock| clock.started_at_ms())
3403                    .or(self.daemon_provenance.started_at_ms),
3404                running_image: self
3405                    .daemon_provenance
3406                    .probe
3407                    .observe(
3408                        self.daemon_provenance.pid,
3409                        self.daemon_provenance.executable_path.as_deref(),
3410                        self.daemon_provenance.executable_identity,
3411                        self.daemon_provenance.process_start_time,
3412                    )
3413                    .await,
3414            },
3415        };
3416        let response = ClientControlResponse::SupervisorProvenance { daemon, modules };
3417        Ok(vec![control_response_body_frame(
3418            &frame,
3419            &response,
3420            "ClientControlResponse::SupervisorProvenance",
3421        )?])
3422    }
3423
3424    fn handle_supervisor_health(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
3425        self.refresh_capability_requirements();
3426        let generation = self
3427            .registry
3428            .generation()
3429            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
3430        let modules = self
3431            .supervisor
3432            .list()
3433            .into_iter()
3434            .map(|module| {
3435                let status = module.status_for_control("health").map_err(|err| {
3436                    RouterError::backend(
3437                        0,
3438                        frame.header.corr,
3439                        format!("failed to read supervisor health: {err}"),
3440                    )
3441                })?;
3442                let module_id = status.module_id;
3443                let capability_detail = self
3444                    .capability_evaluator
3445                    .required_problem_detail(&module_id);
3446                Ok(SupervisorHealthEntry {
3447                    module_id,
3448                    status: status.health.status,
3449                    detail: append_capability_problem_detail(
3450                        status.health.detail,
3451                        capability_detail,
3452                    ),
3453                    metrics: status.health.metrics,
3454                    consecutive_failures: status.health.consecutive_failures,
3455                    late_answer_count: status.health.late_answer_count,
3456                    last_late_answer_latency_ms: status.health.last_late_answer_latency_ms,
3457                    last_action: status.health.last_action,
3458                    last_action_ms: status.health.last_action_ms,
3459                    last_probe_ms: status.health.last_probe_ms,
3460                })
3461            })
3462            .collect::<Result<Vec<_>, RouterError>>()?;
3463        let response = ClientControlResponse::SupervisorHealth {
3464            generation,
3465            modules,
3466        };
3467        Ok(vec![control_response_body_frame(
3468            &frame,
3469            &response,
3470            "ClientControlResponse::SupervisorHealth",
3471        )?])
3472    }
3473
3474    async fn handle_supervisor_restart(
3475        &self,
3476        frame: Frame,
3477        module_id: String,
3478        drain_timeout_ms: Option<u64>,
3479    ) -> Result<Vec<Frame>, RouterError> {
3480        let operation_lock = self.supervisor.operation_lock();
3481        let _operation_guard = operation_lock.lock().await;
3482        let Some(module) = self.supervisor.get(&module_id) else {
3483            return Ok(vec![control_error_frame(
3484                &frame,
3485                "unknown_module",
3486                format!("module_id '{module_id}' is not supervised"),
3487            )?]);
3488        };
3489
3490        if let Err(err) = module.restart(drain_timeout_ms).await {
3491            let (code, message) = match err {
3492                crate::supervise::SuperviseError::Disabled { .. } => {
3493                    ("module_disabled", err.to_string())
3494                }
3495                crate::supervise::SuperviseError::SwapInProgress { .. } => {
3496                    ("swap_in_progress", err.to_string())
3497                }
3498                _ => (
3499                    "target_unavailable",
3500                    format!("failed to restart module_id '{module_id}': {err}"),
3501                ),
3502            };
3503            return Ok(vec![control_error_frame(&frame, code, message)?]);
3504        }
3505
3506        let response = ClientControlResponse::SupervisorAck {
3507            module_id,
3508            applied: true,
3509        };
3510        Ok(vec![control_response_body_frame(
3511            &frame,
3512            &response,
3513            "ClientControlResponse::SupervisorAck",
3514        )?])
3515    }
3516
3517    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
3518    /// when the old process has finished draining: a caller whose own lane
3519    /// rides the old process must get its reply before that drain waits on it.
3520    async fn handle_supervisor_swap(
3521        &self,
3522        frame: Frame,
3523        module_id: String,
3524        ready_timeout_ms: Option<u64>,
3525    ) -> Result<Vec<Frame>, RouterError> {
3526        // The daemon-wide operation lock is held only to resolve the handle,
3527        // not across the swap. The swap can take its whole readiness budget,
3528        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
3529        // holding it here would park an operator's stop behind the swap it is
3530        // meant to abort. A rescan or stop that reaches the module during the
3531        // swap is served by the swap itself (see `supervise_swap`).
3532        let module = {
3533            let operation_lock = self.supervisor.operation_lock();
3534            let _operation_guard = operation_lock.lock().await;
3535            self.supervisor.get(&module_id)
3536        };
3537        let Some(module) = module else {
3538            return Ok(vec![control_error_frame(
3539                &frame,
3540                "unknown_module",
3541                format!("module_id '{module_id}' is not supervised"),
3542            )?]);
3543        };
3544
3545        if let Err(err) = module
3546            .swap(ready_timeout_ms.map(Duration::from_millis))
3547            .await
3548        {
3549            use crate::supervise::SuperviseError;
3550            let message = err.to_string();
3551            let error = match err {
3552                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
3553                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
3554                    code: "swap_refused".to_string(),
3555                    message,
3556                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
3557                },
3558                SuperviseError::SwapFailed {
3559                    arm,
3560                    candidate_exit,
3561                    ..
3562                } => ErrorBody {
3563                    code: "swap_failed".to_string(),
3564                    message,
3565                    detail: Some(serde_json::json!({
3566                        "arm": arm.as_str(),
3567                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
3568                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
3569                    })),
3570                },
3571                _ => ErrorBody::new(
3572                    "target_unavailable",
3573                    format!("failed to swap module_id '{module_id}': {message}"),
3574                ),
3575            };
3576            return Ok(vec![control_error_body_frame(&frame, error)?]);
3577        }
3578
3579        let response = ClientControlResponse::SupervisorAck {
3580            module_id,
3581            applied: true,
3582        };
3583        Ok(vec![control_response_body_frame(
3584            &frame,
3585            &response,
3586            "ClientControlResponse::SupervisorAck",
3587        )?])
3588    }
3589
3590    async fn handle_supervisor_reload(
3591        &self,
3592        frame: Frame,
3593        module_id: String,
3594    ) -> Result<Vec<Frame>, RouterError> {
3595        let operation_lock = self.supervisor.operation_lock();
3596        let _operation_guard = operation_lock.lock().await;
3597        let Some(module) = self.supervisor.get(&module_id) else {
3598            return Ok(vec![control_error_frame(
3599                &frame,
3600                "unknown_module",
3601                format!("module_id '{module_id}' is not supervised"),
3602            )?]);
3603        };
3604
3605        if let Err(err) = module.reload().await {
3606            let (code, message) = match err {
3607                crate::supervise::SuperviseError::Disabled { .. } => {
3608                    ("module_disabled", err.to_string())
3609                }
3610                crate::supervise::SuperviseError::SwapInProgress { .. } => {
3611                    ("swap_in_progress", err.to_string())
3612                }
3613                _ => (
3614                    "reload_failed",
3615                    format!("failed to reload module_id '{module_id}': {err}"),
3616                ),
3617            };
3618            return Ok(vec![control_error_frame(&frame, code, message)?]);
3619        }
3620
3621        let response = ClientControlResponse::SupervisorAck {
3622            module_id,
3623            applied: true,
3624        };
3625        Ok(vec![control_response_body_frame(
3626            &frame,
3627            &response,
3628            "ClientControlResponse::SupervisorAck",
3629        )?])
3630    }
3631
3632    async fn handle_supervisor_rescan(
3633        &self,
3634        frame: Frame,
3635        preview: bool,
3636    ) -> Result<Vec<Frame>, RouterError> {
3637        let Some(context) = self.rescan.clone() else {
3638            return Ok(vec![control_error_frame(
3639                &frame,
3640                "rescan_unavailable",
3641                "the daemon was not started with a reloadable config path".to_string(),
3642            )?]);
3643        };
3644
3645        let operation_lock = self.supervisor.operation_lock();
3646        let _operation_guard = operation_lock.lock().await;
3647        let loaded = match crate::daemon_config::load(&context.config_path) {
3648            Ok(config) => config,
3649            Err(err) => {
3650                return Ok(vec![control_error_frame(
3651                    &frame,
3652                    "invalid_daemon_config",
3653                    format!("supervisor rescan rejected daemon config: {err}"),
3654                )?])
3655            }
3656        };
3657        // `load` reports a missing file as Ok(None), which is correct at boot
3658        // (no config, nothing to supervise) and catastrophic here: rescan treats
3659        // "not in the config" as "remove it", so an absent file would read as an
3660        // empty module list and retire the entire running fleet. An editor
3661        // writing via write-new-then-rename, or a half-finished edit, is enough
3662        // to open that window. Refuse instead: a config that cannot be read
3663        // carries no instruction to remove anything.
3664        let Some(config) = loaded else {
3665            return Ok(vec![control_error_frame(
3666                &frame,
3667                "invalid_daemon_config",
3668                format!(
3669                    "daemon config not found at {}; refusing to rescan (an absent config would \
3670                     retire every supervised module)",
3671                    context.config_path.display()
3672                ),
3673            )?]);
3674        };
3675        let (
3676            configured_port,
3677            storage_config,
3678            admission_facts_carrier_module_id,
3679            admission_facts_targets,
3680            modules,
3681            reserved_capabilities,
3682        ) = (
3683            config.port,
3684            config.storage,
3685            config.admission_facts_carrier_module_id,
3686            config.admission_facts_targets,
3687            config.modules,
3688            config.reserved_capabilities,
3689        );
3690
3691        // Collect the sections rescan cannot apply, so the REPLY carries them.
3692        //
3693        // The warning below has always been correct and has always gone only to
3694        // the journal -- addressed to whoever reads logs, while the person who
3695        // just edited the config is looking at the CLI. Naming each section
3696        // individually rather than setting a flag: "something outside modules
3697        // changed" sends the operator back to diffing their own file, which is
3698        // the work this is meant to save.
3699        let mut restart_required = Vec::new();
3700        for section in RestartRequiredSection::ALL {
3701            let changed = match section {
3702                RestartRequiredSection::Port => configured_port != context.configured_port,
3703                RestartRequiredSection::Storage => storage_config != context.storage_config,
3704                RestartRequiredSection::AdmissionFactsCarrierModuleId => {
3705                    admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
3706                }
3707                RestartRequiredSection::AdmissionFactsTargets => {
3708                    admission_facts_targets != context.admission_facts_targets
3709                }
3710            };
3711            if changed {
3712                restart_required.push(section.label().to_string());
3713            }
3714        }
3715        if !restart_required.is_empty() {
3716            warn!(
3717                config_path = %context.config_path.display(),
3718                sections = %restart_required.join(", "),
3719                "daemon config changed outside the modules section; restart the daemon to apply those changes"
3720            );
3721        }
3722
3723        for configured in &modules {
3724            if let Err(err) = validate_spec(&configured.module_spec()) {
3725                return Ok(vec![control_error_frame(
3726                    &frame,
3727                    "invalid_daemon_config",
3728                    format!("supervisor rescan rejected daemon config: {err}"),
3729                )?]);
3730            }
3731        }
3732
3733        let configured_capabilities = modules
3734            .iter()
3735            .map(|module| (module.module_id.clone(), module.enabled))
3736            .collect::<Vec<_>>();
3737        let preview_capability_warnings = if preview {
3738            let (_, registrations) = self.runtime_capability_snapshot()?;
3739            let current_modules = self
3740                .supervisor
3741                .list()
3742                .into_iter()
3743                .map(|module| module.module_id().to_string())
3744                .collect::<BTreeSet<_>>();
3745            let resulting_modules = configured_capabilities.clone();
3746            let removed = current_modules
3747                .into_iter()
3748                .filter(|module_id| {
3749                    !resulting_modules
3750                        .iter()
3751                        .any(|(configured_id, _)| configured_id == module_id)
3752                })
3753                .collect::<Vec<_>>();
3754            self.capability_evaluator.preview_removal_warnings(
3755                resulting_modules,
3756                &removed,
3757                &registrations,
3758            )
3759        } else {
3760            Vec::new()
3761        };
3762        let result = match self
3763            .reconcile_supervised_modules(&context.supervisor, modules, preview)
3764            .await
3765        {
3766            Ok(result) => result,
3767            Err(message) => {
3768                return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
3769            }
3770        };
3771        if !preview {
3772            self.capability_evaluator
3773                .configure(configured_capabilities, reserved_capabilities);
3774            self.capability_evaluator.wake_deadline_loop();
3775            self.refresh_capability_requirements();
3776        }
3777        let mut result = result;
3778        result.restart_required = restart_required;
3779        result.capability_warnings = preview_capability_warnings;
3780        let response = ClientControlResponse::SupervisorRescan { result };
3781        Ok(vec![control_response_body_frame(
3782            &frame,
3783            &response,
3784            "ClientControlResponse::SupervisorRescan",
3785        )?])
3786    }
3787
3788    async fn handle_supervisor_release_reserved(
3789        &self,
3790        frame: Frame,
3791        module_id: String,
3792    ) -> Result<Vec<Frame>, RouterError> {
3793        let Some(context) = self.rescan.clone() else {
3794            return Ok(vec![control_error_frame(
3795                &frame,
3796                "release_unavailable",
3797                "reserved-id release requires a daemon started with a reloadable config path",
3798            )?]);
3799        };
3800        let operation_lock = self.supervisor.operation_lock();
3801        let _operation_guard = operation_lock.lock().await;
3802        let loaded = match crate::daemon_config::load(&context.config_path) {
3803            Ok(Some(config)) => config,
3804            Ok(None) => {
3805                return Ok(vec![control_error_frame(
3806                    &frame,
3807                    "invalid_daemon_config",
3808                    format!(
3809                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
3810                        context.config_path.display()
3811                    ),
3812                )?])
3813            }
3814            Err(err) => {
3815                return Ok(vec![control_error_frame(
3816                    &frame,
3817                    "invalid_daemon_config",
3818                    format!("unable to verify reserved-id release against daemon config: {err}"),
3819                )?])
3820            }
3821        };
3822        if loaded
3823            .modules
3824            .iter()
3825            .any(|configured| configured.module_id == module_id)
3826        {
3827            return Ok(vec![control_error_frame(
3828                &frame,
3829                "reserved_module_configured",
3830                format!(
3831                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
3832                ),
3833            )?]);
3834        }
3835        if !self.supervisor.release_retained_reserved_gate(&module_id) {
3836            return Ok(vec![control_error_frame(
3837                &frame,
3838                "reserved_gate_not_retained",
3839                format!(
3840                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
3841                ),
3842            )?]);
3843        }
3844
3845        let response = ClientControlResponse::SupervisorAck {
3846            module_id,
3847            applied: true,
3848        };
3849        Ok(vec![control_response_body_frame(
3850            &frame,
3851            &response,
3852            "ClientControlResponse::SupervisorAck",
3853        )?])
3854    }
3855
3856    /// Reconcile the running module set against the configured one.
3857    ///
3858    /// With `preview` set, the diff is computed and returned WITHOUT applying any
3859    /// of it: nothing is retired, reconfigured, enabled or spawned. The preview
3860    /// deliberately shares this function with the executing path rather than
3861    /// computing the same diff somewhere else -- two implementations of one
3862    /// decision agree until they do not, and the whole value of a preview is that
3863    /// it describes the operation that will actually run.
3864    async fn reconcile_supervised_modules(
3865        &self,
3866        supervisor: &Supervisor,
3867        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
3868        preview: bool,
3869    ) -> Result<SupervisorRescanResult, String> {
3870        let mut current = BTreeMap::new();
3871        for module in self.supervisor.list() {
3872            let (spec, health) = module.configuration().map_err(|err| {
3873                format!(
3874                    "failed to read configuration for module_id '{}': {err}",
3875                    module.module_id()
3876                )
3877            })?;
3878            let enabled = module
3879                .status()
3880                .map_err(|err| {
3881                    format!(
3882                        "failed to read status for module_id '{}': {err}",
3883                        module.module_id()
3884                    )
3885                })?
3886                .enabled;
3887            current.insert(
3888                module.module_id().to_string(),
3889                (module, spec, health, enabled),
3890            );
3891        }
3892        let configured = configured_modules
3893            .into_iter()
3894            .map(|module| (module.module_id.clone(), module))
3895            .collect::<BTreeMap<_, _>>();
3896
3897        let added = configured
3898            .keys()
3899            .filter(|module_id| !current.contains_key(*module_id))
3900            .cloned()
3901            .collect::<Vec<_>>();
3902        let removed = current
3903            .keys()
3904            .filter(|module_id| !configured.contains_key(*module_id))
3905            .cloned()
3906            .collect::<Vec<_>>();
3907        let mut changed_pending_reload = Vec::new();
3908        let mut configuration_changes = BTreeSet::new();
3909        let mut enabled_changes = BTreeSet::new();
3910        let mut unchanged = 0_u32;
3911
3912        for (module_id, configured_module) in &configured {
3913            let Some((_, current_spec, current_health, current_enabled)) = current.get(module_id)
3914            else {
3915                continue;
3916            };
3917            let configuration_changed = *current_spec != configured_module.module_spec()
3918                || *current_health != configured_module.health;
3919            let enabled_changed = *current_enabled != configured_module.enabled;
3920            if configuration_changed {
3921                configuration_changes.insert(module_id.clone());
3922                changed_pending_reload.push(module_id.clone());
3923            }
3924            if enabled_changed {
3925                enabled_changes.insert(module_id.clone());
3926            }
3927            if !configuration_changed && !enabled_changed {
3928                unchanged = unchanged.saturating_add(1);
3929            }
3930        }
3931
3932        // Everything above this point is pure computation over two snapshots.
3933        // Everything below MUTATES. The preview returns here so the boundary is a
3934        // single early return rather than a condition repeated at each mutation
3935        // site, where one missed guard would apply part of a change the caller was
3936        // told would not happen.
3937        if preview {
3938            return Ok(SupervisorRescanResult {
3939                added,
3940                removed,
3941                changed_pending_reload,
3942                enabled_changes: enabled_changes.iter().cloned().collect(),
3943                unchanged,
3944                preview: true,
3945                // Filled by the caller on both paths, so the preview reports
3946                // restart-required sections identically to an executed rescan --
3947                // the preview is where an operator is most likely to be looking.
3948                restart_required: Vec::new(),
3949                capability_warnings: Vec::new(),
3950            });
3951        }
3952
3953        for module_id in &removed {
3954            let module = &current
3955                .get(module_id)
3956                .expect("removed module came from current supervisor state")
3957                .0;
3958            module.retire().await.map_err(|err| {
3959                format!("failed to retire module_id '{module_id}' during rescan: {err}")
3960            })?;
3961            // TOMBSTONE BEFORE RETIRE, and the order is the whole fix.
3962            //
3963            // `handle_route_open` resolves an absent module in three steps:
3964            // registry, then supervisor status, then tombstone. Retiring first
3965            // opens a window where ALL THREE ARE ABSENT -- the registry entry
3966            // went with the teardown above, the supervisor entry went with
3967            // `retire`, and the tombstone does not exist yet -- so a route.open
3968            // landing in it gets `unknown_module` (RETRYABLE, "never heard of
3969            // it") for a module that was deliberately removed and whose caller
3970            // should get `module_removed` (TERMINAL, carrying a removal age).
3971            //
3972            // Writing the tombstone first closes it: during the window the
3973            // supervisor entry still answers, so the caller gets
3974            // `target_unavailable` -- retryable, and TRUE, because the module
3975            // is mid-teardown. After both statements it is `module_removed`.
3976            // No instant remains where a removed module reads as one that
3977            // never existed.
3978            //
3979            // NOT DETERMINISTICALLY TESTABLE FROM HERE, said plainly because
3980            // the absence of a test beside a fix invites deletion: these are
3981            // two sync statements with no await between them, so reaching the
3982            // window needs a second worker thread to land exactly between them
3983            // and there is no hook to force it. MEASURED: the 25 daemon_config
3984            // tests pass identically with the old order and the new one, so
3985            // the existing suite cannot see this and a green run is not
3986            // evidence either way. What the suite does hold is the
3987            // post-condition -- a removed module answers `module_removed` --
3988            // which this preserves.
3989            //
3990            // Found by an Athena panel reading the shipped tree against a
3991            // design note (2026-09-19), as the one concrete instance of that
3992            // note's class that survived contact with source. Direction is
3993            // benign: retryable where terminal was intended, never the reverse.
3994            self.supervisor.record_rescan_removal(module_id);
3995            self.supervisor.retire(module_id);
3996        }
3997
3998        for module_id in configured.keys() {
3999            let Some((module, _, _, _)) = current.get(module_id) else {
4000                continue;
4001            };
4002            let configured_module = configured
4003                .get(module_id)
4004                .expect("configured module id came from configured map");
4005            if configuration_changes.contains(module_id) {
4006                module
4007                    .update_configuration(
4008                        configured_module.module_spec(),
4009                        configured_module.health,
4010                        configured_module.drain_timeout_ms,
4011                    )
4012                    .await
4013                    .map_err(|err| {
4014                        format!(
4015                            "failed to update module_id '{module_id}' configuration during rescan: {err}"
4016                        )
4017                    })?;
4018            }
4019            if enabled_changes.contains(module_id) {
4020                module
4021                    .set_enabled(configured_module.enabled)
4022                    .await
4023                    .map_err(|err| {
4024                        format!(
4025                            "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
4026                            configured_module.enabled
4027                        )
4028                    })?;
4029            }
4030        }
4031
4032        for module_id in &added {
4033            let configured_module = configured
4034                .get(module_id)
4035                .expect("added module id came from configured map");
4036            supervisor
4037                .supervise_configured_with_health(
4038                    configured_module.module_spec(),
4039                    configured_module.enabled,
4040                    configured_module.health,
4041                    configured_module.drain_timeout_ms,
4042                    configured_module.restart,
4043                )
4044                .map_err(|err| {
4045                    format!("failed to add module_id '{module_id}' during rescan: {err}")
4046                })?;
4047        }
4048
4049        Ok(SupervisorRescanResult {
4050            added,
4051            removed,
4052            changed_pending_reload,
4053            enabled_changes: enabled_changes.iter().cloned().collect(),
4054            unchanged,
4055            preview: false,
4056            // Filled by the caller, which is the only layer that can see the
4057            // previous config to diff against.
4058            restart_required: Vec::new(),
4059            capability_warnings: Vec::new(),
4060        })
4061    }
4062
4063    async fn handle_supervisor_set_enabled(
4064        &self,
4065        frame: Frame,
4066        module_id: String,
4067        enabled: bool,
4068    ) -> Result<Vec<Frame>, RouterError> {
4069        let operation_lock = self.supervisor.operation_lock();
4070        let _operation_guard = operation_lock.lock().await;
4071        let Some(module) = self.supervisor.get(&module_id) else {
4072            return Ok(vec![control_error_frame(
4073                &frame,
4074                "unknown_module",
4075                format!("module_id '{module_id}' is not supervised"),
4076            )?]);
4077        };
4078
4079        let applied = match module.set_enabled(enabled).await {
4080            Ok(applied) => applied,
4081            Err(err) => {
4082                return Ok(vec![control_error_frame(
4083                    &frame,
4084                    "target_unavailable",
4085                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
4086                )?])
4087            }
4088        };
4089
4090        self.capability_evaluator.wake_deadline_loop();
4091        self.refresh_capability_requirements();
4092        let response = ClientControlResponse::SupervisorAck { module_id, applied };
4093        Ok(vec![control_response_body_frame(
4094            &frame,
4095            &response,
4096            "ClientControlResponse::SupervisorAck",
4097        )?])
4098    }
4099
4100    async fn handle_supervisor_health_probe(
4101        &self,
4102        frame: Frame,
4103        module_id: String,
4104    ) -> Result<Vec<Frame>, RouterError> {
4105        self.refresh_capability_requirements();
4106        let Some(registration) = self
4107            .registry
4108            .get_module(&module_id)
4109            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
4110        else {
4111            return Ok(vec![control_error_frame(
4112                &frame,
4113                "unknown_module",
4114                format!("module_id '{module_id}' is not registered"),
4115            )?]);
4116        };
4117
4118        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
4119        // named for it. Making `module_registration_grants_op` return false
4120        // unconditionally reddens five tests, and every one is named for something
4121        // else -- capability relay, probe/bind demultiplexing, supervision-only
4122        // probing. They exercise a successful advertisement check on the way to their
4123        // own subject.
4124        //
4125        // Real protection, fragile in a specific way: narrowing any of those tests to
4126        // focus on its stated subject would silently remove coverage nobody knows
4127        // they are carrying. Recorded here rather than as a sixth test, because the
4128        // useful fact is WHICH tests hold the guard up -- a new test would add
4129        // coverage without telling the next person what the existing ones quietly do.
4130        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
4131        {
4132            return Ok(vec![control_error_frame(
4133                &frame,
4134                "health_not_advertised",
4135                format!("module_id '{module_id}' did not advertise health.check"),
4136            )?]);
4137        }
4138
4139        let deadline = Instant::now() + self.health_probe_timeout;
4140        let pending = match self.forwarding.begin_module_control_rpc_for(
4141            &module_id,
4142            MODULE_CONTROL_OP_HEALTH_CHECK,
4143            deadline,
4144        ) {
4145            Ok(pending) => pending,
4146            Err(err) => {
4147                return Ok(vec![control_error_frame(
4148                    &frame,
4149                    forwarding_error_code(&err),
4150                    err.to_string(),
4151                )?])
4152            }
4153        };
4154
4155        let PendingModuleControlRpc {
4156            endpoint,
4157            module_sink,
4158            negotiated_ver,
4159            corr: probe_corr,
4160            receiver,
4161        } = pending;
4162        let mut guard =
4163            ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
4164        let probe_body =
4165            serde_json::to_vec(&ModuleControlRequest::HealthCheck {}).map_err(|err| {
4166                RouterError::backend(
4167                    0,
4168                    frame.header.corr,
4169                    format!("failed to encode health.check request: {err}"),
4170                )
4171            })?;
4172        let probe_frame = Frame::build_with_version(
4173            negotiated_ver,
4174            FrameType::Request,
4175            control_flags(),
4176            0,
4177            0,
4178            probe_corr,
4179            probe_body,
4180        )
4181        .map_err(RouterError::FrameBuild)?;
4182
4183        if let Err(err) = module_sink.send(probe_frame).await {
4184            return Ok(vec![control_error_frame(
4185                &frame,
4186                "target_unavailable",
4187                err.to_string(),
4188            )?]);
4189        }
4190
4191        match timeout_at(deadline, receiver).await {
4192            Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
4193                guard.disarm();
4194                let Some(report) = response.health_report() else {
4195                    return Ok(vec![control_error_frame(
4196                        &frame,
4197                        "invalid_control_body",
4198                        "health.check RPC returned a non-health response",
4199                    )?]);
4200                };
4201                // Metrics go out whole here. The supervisor's cached snapshot
4202                // caps this blob (see truncate_health_metrics), and this path
4203                // exists precisely to answer without that cap -- so applying it
4204                // here would leave no way to see what the cached view drops.
4205                let HealthReport {
4206                    status,
4207                    detail,
4208                    metrics,
4209                } = report;
4210                let capability_detail = self
4211                    .capability_evaluator
4212                    .required_problem_detail(&module_id);
4213                let response = ClientControlResponse::SupervisorHealthProbe {
4214                    module_id,
4215                    status,
4216                    detail: append_capability_problem_detail(detail, capability_detail),
4217                    metrics,
4218                };
4219                Ok(vec![control_response_body_frame(
4220                    &frame,
4221                    &response,
4222                    "ClientControlResponse::SupervisorHealthProbe",
4223                )?])
4224            }
4225            Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
4226                guard.disarm();
4227                Ok(vec![control_error_body_frame(&frame, body)?])
4228            }
4229            Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
4230                guard.disarm();
4231                Ok(vec![control_error_frame(
4232                    &frame,
4233                    "target_unavailable",
4234                    message,
4235                )?])
4236            }
4237            Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
4238                guard.disarm();
4239                Ok(vec![control_error_frame(
4240                    &frame,
4241                    "invalid_control_body",
4242                    message,
4243                )?])
4244            }
4245            Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
4246                guard.disarm();
4247                Ok(vec![control_error_frame(
4248                    &frame,
4249                    "invalid_control_body",
4250                    format!("expected module-control op '{expected}', got '{actual}'"),
4251                )?])
4252            }
4253            Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
4254                guard.disarm();
4255                Ok(vec![control_error_frame(
4256                    &frame,
4257                    "module_timeout",
4258                    format!(
4259                        "module_id '{module_id}' answered health.check after {:?}",
4260                        self.health_probe_timeout
4261                    ),
4262                )?])
4263            }
4264            Ok(Err(_)) => Ok(vec![control_error_frame(
4265                &frame,
4266                "target_unavailable",
4267                "health.check waiter was canceled before the module responded",
4268            )?]),
4269            Err(_) => Ok(vec![control_error_frame(
4270                &frame,
4271                "module_timeout",
4272                format!(
4273                    "module_id '{module_id}' did not answer health.check within {:?}",
4274                    self.health_probe_timeout
4275                ),
4276            )?]),
4277        }
4278    }
4279
4280    fn supervisor_status(
4281        &self,
4282        module_id: &str,
4283        corr: u64,
4284    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
4285        self.supervisor
4286            .get(module_id)
4287            .map(|module| {
4288                let warming = module.is_warming_for_control("status").map_err(|err| {
4289                    RouterError::backend(
4290                        0,
4291                        corr,
4292                        format!(
4293                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
4294                        ),
4295                    )
4296                })?;
4297                module.status_for_control("status").map_err(|err| {
4298                    RouterError::backend(
4299                        0,
4300                        corr,
4301                        format!(
4302                            "failed to read supervisor status for module_id '{module_id}': {err}"
4303                        ),
4304                    )
4305                }).map(|status| (status, warming))
4306            })
4307            .transpose()
4308    }
4309
4310    fn guard_module_control_op(
4311        &self,
4312        frame: &Frame,
4313        module_id: &str,
4314        op: &str,
4315    ) -> Result<Option<Frame>, RouterError> {
4316        if self.module_grants_op(module_id, op, frame.header.corr)? {
4317            return Ok(None);
4318        }
4319
4320        Ok(Some(control_error_frame(
4321            frame,
4322            "op_not_allowed",
4323            format!("module_id '{module_id}' did not grant control op '{op}'"),
4324        )?))
4325    }
4326
4327    fn module_grants_op(&self, module_id: &str, op: &str, corr: u64) -> Result<bool, RouterError> {
4328        let Some(registration) = self
4329            .registry
4330            .get_module(module_id)
4331            .map_err(|err| RouterError::backend(0, corr, err.to_string()))?
4332        else {
4333            return Ok(false);
4334        };
4335        Ok(module_registration_grants_op(&registration.control_ops, op))
4336    }
4337
4338    fn handle_status_update(
4339        &self,
4340        endpoint: ModuleEndpointId,
4341        frame: Frame,
4342    ) -> Result<Vec<Frame>, RouterError> {
4343        let update = match serde_json::from_slice::<ModuleControlPush>(&frame.body) {
4344            Ok(update) => update,
4345            Err(err) => {
4346                // Forward-compat: a newer module may push a channel-0 op this subc
4347                // version doesn't know. The control contract says unknown push ops
4348                // are IGNORED, never answered with an error. Only a malformed body
4349                // for an op we DO know is a real error worth surfacing.
4350                if is_known_module_push_op(&frame.body) {
4351                    return Ok(vec![control_error_frame(
4352                        &frame,
4353                        "invalid_control_body",
4354                        format!("malformed module control push body: {err}"),
4355                    )?]);
4356                }
4357                return Ok(Vec::new());
4358            }
4359        };
4360
4361        match update {
4362            ModuleControlPush::RouteStatus {
4363                route_channel,
4364                route_epoch,
4365                status,
4366            } => {
4367                self.forwarding
4368                    .cache_status(endpoint, route_channel, route_epoch, status)
4369                    .map_err(RouterError::Forwarding)?;
4370            }
4371        }
4372        Ok(Vec::new())
4373    }
4374
4375    fn handle_route_poll(
4376        &self,
4377        ctx: &RouteCtx,
4378        frame: Frame,
4379        route_channel: u16,
4380        route_epoch: u32,
4381        kind: PollKind,
4382    ) -> Result<Vec<Frame>, RouterError> {
4383        let snapshot = self
4384            .forwarding
4385            .route_poll_snapshot(ctx.connection_id, route_channel, route_epoch)
4386            .map_err(RouterError::Forwarding)?;
4387        let response = match (kind, snapshot) {
4388            (PollKind::Status, RoutePollSnapshot::Bound { status, .. }) => {
4389                ClientControlResponse::RoutePoll {
4390                    route_channel,
4391                    route_epoch,
4392                    status,
4393                    live: None,
4394                }
4395            }
4396            (PollKind::Status, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
4397                route_channel,
4398                route_epoch,
4399                status: None,
4400                live: None,
4401            },
4402            (PollKind::Liveness, RoutePollSnapshot::Bound { module_id, .. }) => {
4403                // ABSENCE HERE MEANS "NOT SUPERVISED", NOT "UNKNOWN", and that
4404                // is what makes reporting `true` correct rather than a
4405                // confident guess. `process_live` returns None only when the
4406                // module id has no supervisor snapshot at all -- an
4407                // externally-started module the daemon did not spawn -- and
4408                // for those the supervisor has no opinion to offer, ever. It
4409                // is never None for a supervised module in an unknown state:
4410                // a supervised module always has a snapshot, and the answer
4411                // comes from `state == Running && process_alive`.
4412                //
4413                // The route is Bound, so the module completed a HELLO on a
4414                // live connection; "the process this route points at is
4415                // running" is therefore attested by the binding rather than
4416                // assumed. Reporting `false` for an unsupervised module would
4417                // be the actual lie -- it would tell a client its healthy
4418                // route is dead because the daemon does not manage the
4419                // process.
4420                //
4421                // IF `process_live` EVER GAINS A THIRD CASE -- a supervised
4422                // module whose liveness is genuinely unknown, e.g. a snapshot
4423                // that has not been populated yet -- THIS DEFAULT BECOMES
4424                // WRONG and must split: unsupervised stays true, unknown
4425                // becomes null so the client can tell the two apart. The
4426                // response field is already `Option<bool>`, so the wire can
4427                // carry that distinction today.
4428                let live = self
4429                    .process_liveness
4430                    .as_ref()
4431                    .and_then(|source| source.process_live(&module_id))
4432                    .unwrap_or(true);
4433                ClientControlResponse::RoutePoll {
4434                    route_channel,
4435                    route_epoch,
4436                    status: None,
4437                    live: Some(live),
4438                }
4439            }
4440            (PollKind::Liveness, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
4441                route_channel,
4442                route_epoch,
4443                status: None,
4444                live: Some(false),
4445            },
4446        };
4447
4448        Ok(vec![control_response_body_frame(
4449            &frame,
4450            &response,
4451            "ClientControlResponse::RoutePoll",
4452        )?])
4453    }
4454
4455    pub(crate) fn observe_module_control_completion(
4456        &self,
4457        completion: ModuleControlRpcCompletion,
4458    ) -> bool {
4459        match completion {
4460            ModuleControlRpcCompletion::Unknown => false,
4461            ModuleControlRpcCompletion::Settled => true,
4462            ModuleControlRpcCompletion::LateHealthAnswer { module_id, latency } => {
4463                let latency_ms = latency.as_millis().min(u128::from(u64::MAX)) as u64;
4464                info!(
4465                    module_id = %module_id,
4466                    latency_ms,
4467                    "late health.check answer proves the module is alive"
4468                );
4469                match self
4470                    .supervisor
4471                    .record_late_health_answer(&module_id, latency_ms)
4472                {
4473                    Ok(true) => {}
4474                    Ok(false) => debug!(
4475                        module_id = %module_id,
4476                        latency_ms,
4477                        "late health.check answer has no active supervisor snapshot"
4478                    ),
4479                    Err(err) => warn!(
4480                        module_id = %module_id,
4481                        latency_ms,
4482                        error = %err,
4483                        "failed to record late health.check answer"
4484                    ),
4485                }
4486                true
4487            }
4488        }
4489    }
4490
4491    /// Decide whether a failure while settling a relayed `route.bind` belongs to
4492    /// the module connection whose frame is being handled, or to the client that
4493    /// relay was opened for.
4494    ///
4495    /// This runs on the MODULE connection's frame handler, where returning `Err`
4496    /// ends that connection -- and a module connection carries every client's
4497    /// routes to that module, so ending it costs the whole fleet its tools.
4498    /// `ConnectionClosing` carries the id of the connection that is closing, and
4499    /// when that id is a CLIENT's, the condition is entirely about that one
4500    /// client's route.open. A client-scoped condition has no authority over a
4501    /// shared module connection, so it is logged and the single relay is dropped:
4502    /// the client is going away, and `complete_pending_relay` already removed the
4503    /// relay before failing, so there is nothing left to settle. Anything that
4504    /// relay still reserved is released by that client's own connection teardown,
4505    /// which is already under way -- that is what "closing" means.
4506    ///
4507    /// Every other failure is a statement about THIS connection and stays fatal:
4508    /// a poisoned forwarding lock, a stale module endpoint, and the module's own
4509    /// id in `ConnectionClosing` all mean this connection cannot keep serving
4510    /// frames correctly.
4511    fn refuse_to_end_module_connection_for_a_client(
4512        &self,
4513        module_connection_id: ConnectionId,
4514        corr: u64,
4515        err: ForwardingError,
4516    ) -> Result<(), RouterError> {
4517        if let ForwardingError::ConnectionClosing { connection_id } = err {
4518            if connection_id != module_connection_id {
4519                warn!(
4520                    module_connection_id = module_connection_id.get(),
4521                    client_connection_id = connection_id.get(),
4522                    corr,
4523                    "dropping a route.bind response for a closing client; the module connection keeps serving"
4524                );
4525                return Ok(());
4526            }
4527        }
4528        Err(RouterError::Forwarding(err))
4529    }
4530
4531    fn handle_module_relay_response(
4532        &self,
4533        connection_id: ConnectionId,
4534        frame: Frame,
4535    ) -> Result<Vec<Frame>, RouterError> {
4536        let mut secondary_error = None;
4537        let outcome = match frame.header.ty {
4538            FrameType::Response => match serde_json::from_slice::<ControlOpProbe>(&frame.body) {
4539                Ok(probe) if probe.op == "route.bind" => {
4540                    match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
4541                        Ok(ModuleControlResponse::RouteBindAck {}) => {
4542                            RouteBindRelayOutcome::Accepted
4543                        }
4544                        Ok(other) => {
4545                            let message =
4546                                format!("route.bind response carried unexpected body: {other:?}");
4547                            secondary_error = Some(control_error_frame(
4548                                &frame,
4549                                "invalid_control_body",
4550                                message.clone(),
4551                            )?);
4552                            RouteBindRelayOutcome::ModuleGone(message)
4553                        }
4554                        Err(err) => {
4555                            let message = format!("malformed route.bind response body: {err}");
4556                            secondary_error = Some(control_error_frame(
4557                                &frame,
4558                                "invalid_control_body",
4559                                message.clone(),
4560                            )?);
4561                            RouteBindRelayOutcome::ModuleGone(message)
4562                        }
4563                    }
4564                }
4565                Ok(probe) => {
4566                    let outcome = match serde_json::from_slice::<ModuleControlResponse>(&frame.body)
4567                    {
4568                        Ok(response) => ModuleControlRpcOutcome::Response(response),
4569                        Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
4570                            "malformed {} response body: {err}",
4571                            probe.op
4572                        )),
4573                    };
4574                    let completion = self
4575                        .forwarding
4576                        .complete_module_control_rpc(
4577                            connection_id,
4578                            frame.header.corr,
4579                            Some(&probe.op),
4580                            outcome,
4581                        )
4582                        .map_err(RouterError::Forwarding)?;
4583                    if !self.observe_module_control_completion(completion) {
4584                        debug!(
4585                            connection_id = connection_id.get(),
4586                            corr = frame.header.corr,
4587                            op = %probe.op,
4588                            "dropping late or unknown module-control RPC response"
4589                        );
4590                    }
4591                    return Ok(Vec::new());
4592                }
4593                Err(err) => {
4594                    if let Some(expected_op) = self
4595                        .forwarding
4596                        .pending_module_control_op(connection_id, frame.header.corr)
4597                        .map_err(RouterError::Forwarding)?
4598                    {
4599                        let completion = self
4600                            .forwarding
4601                            .complete_module_control_rpc(
4602                                connection_id,
4603                                frame.header.corr,
4604                                None,
4605                                ModuleControlRpcOutcome::MalformedResponse(format!(
4606                                    "malformed {expected_op} response body: {err}"
4607                                )),
4608                            )
4609                            .map_err(RouterError::Forwarding)?;
4610                        if !self.observe_module_control_completion(completion) {
4611                            debug!(
4612                                connection_id = connection_id.get(),
4613                                corr = frame.header.corr,
4614                                "dropping late malformed module-control RPC response"
4615                            );
4616                        }
4617                        return Ok(Vec::new());
4618                    }
4619                    let message = format!("malformed route.bind response body: {err}");
4620                    secondary_error = Some(control_error_frame(
4621                        &frame,
4622                        "invalid_control_body",
4623                        message.clone(),
4624                    )?);
4625                    RouteBindRelayOutcome::ModuleGone(message)
4626                }
4627            },
4628            FrameType::Error => {
4629                if self
4630                    .forwarding
4631                    .pending_module_control_op(connection_id, frame.header.corr)
4632                    .map_err(RouterError::Forwarding)?
4633                    .is_some()
4634                {
4635                    let outcome = match serde_json::from_slice::<ErrorBody>(&frame.body) {
4636                        Ok(body) => ModuleControlRpcOutcome::Rejected(body),
4637                        Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
4638                            "malformed module-control ERROR body: {err}"
4639                        )),
4640                    };
4641                    let completion = self
4642                        .forwarding
4643                        .complete_module_control_rpc(
4644                            connection_id,
4645                            frame.header.corr,
4646                            None,
4647                            outcome,
4648                        )
4649                        .map_err(RouterError::Forwarding)?;
4650                    if !self.observe_module_control_completion(completion) {
4651                        debug!(
4652                            connection_id = connection_id.get(),
4653                            corr = frame.header.corr,
4654                            "dropping late or unknown module-control RPC error"
4655                        );
4656                    }
4657                    return Ok(Vec::new());
4658                }
4659                match serde_json::from_slice::<ErrorBody>(&frame.body) {
4660                    Ok(body) => RouteBindRelayOutcome::Rejected(body),
4661                    Err(err) => {
4662                        let message = format!("malformed route.bind ERROR body: {err}");
4663                        secondary_error = Some(control_error_frame(
4664                            &frame,
4665                            "invalid_control_body",
4666                            message.clone(),
4667                        )?);
4668                        RouteBindRelayOutcome::ModuleGone(message)
4669                    }
4670                }
4671            }
4672            ty => {
4673                return Ok(vec![control_error_frame(
4674                    &frame,
4675                    "unsupported_control_frame",
4676                    format!("unsupported module channel-0 frame {ty:?}"),
4677                )?])
4678            }
4679        };
4680
4681        let settled =
4682            self.forwarding
4683                .complete_pending_relay(connection_id, frame.header.corr, outcome);
4684        let completion = match settled {
4685            Ok(completion) => completion,
4686            Err(err) => {
4687                self.refuse_to_end_module_connection_for_a_client(
4688                    connection_id,
4689                    frame.header.corr,
4690                    err,
4691                )?;
4692                return Ok(secondary_error.into_iter().collect());
4693            }
4694        };
4695        if let Some(target) = completion.abandoned.as_ref() {
4696            send_goodbye_target_best_effort(target, "late accepted route.bind");
4697        }
4698        if !completion.settled {
4699            debug!(
4700                connection_id = connection_id.get(),
4701                corr = frame.header.corr,
4702                frame_type = ?frame.header.ty,
4703                "dropping late or unknown route.bind relay response"
4704            );
4705        }
4706        Ok(secondary_error.into_iter().collect())
4707    }
4708
4709    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
4710        debug!(connection_id = connection_id.get(), "handling GOODBYE");
4711        let registrations = self
4712            .deregister_connection(connection_id)
4713            .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
4714        let released_routes = self
4715            .forwarding
4716            .cleanup_connection(connection_id)
4717            .map_err(RouterError::Forwarding)?;
4718        self.emit_route_goodbyes(released_routes);
4719        // Notify only after forwarding teardown completes (see cleanup_connection).
4720        if !registrations.is_empty() {
4721            crate::supervise::notify_registration_release();
4722        }
4723        Ok(Vec::new())
4724    }
4725}
4726
4727impl Default for ControlHandler {
4728    fn default() -> Self {
4729        Self::new(Arc::new(Registry::default()))
4730    }
4731}
4732
4733impl crate::supervise::SwapPromotionObserver for ControlHandler {
4734    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
4735        self.apply_registration_capabilities(registration);
4736    }
4737}
4738
4739fn capability_requirement_status(status: RequirementStatus) -> CapabilityRequirementStatus {
4740    CapabilityRequirementStatus {
4741        consumer: status.consumer,
4742        capability: status.capability,
4743        need: match status.need {
4744            subc_protocol::manifest::CapabilityNeed::Required => "required".to_string(),
4745            subc_protocol::manifest::CapabilityNeed::Optional => "optional".to_string(),
4746        },
4747        verdict: status.verdict.as_str().to_string(),
4748        episode_seq: status.episode_seq,
4749        config_satisfiable: status.config_satisfiable,
4750        runtime_available: status.runtime_available,
4751        detail: status.detail,
4752    }
4753}
4754
4755fn append_capability_problem_detail(
4756    detail: Option<String>,
4757    capability_detail: Option<String>,
4758) -> Option<String> {
4759    match (detail, capability_detail) {
4760        (Some(detail), Some(capability_detail)) => Some(format!("{detail}; {capability_detail}")),
4761        (Some(detail), None) => Some(detail),
4762        (None, Some(capability_detail)) => Some(capability_detail),
4763        (None, None) => None,
4764    }
4765}
4766
4767fn subc_ops() -> Vec<String> {
4768    SUBC_CONTROL_OPS
4769        .iter()
4770        .map(|op| (*op).to_string())
4771        .collect()
4772}
4773
4774fn module_subc_ops() -> Vec<String> {
4775    SUBC_CONTROL_OPS
4776        .iter()
4777        .chain(MODULE_TO_SUBC_CONTROL_OPS.iter())
4778        .map(|op| (*op).to_string())
4779        .collect()
4780}
4781
4782#[cfg(test)]
4783fn module_baseline_control_ops() -> Vec<String> {
4784    MODULE_BASELINE_CONTROL_OPS
4785        .iter()
4786        .map(|op| (*op).to_string())
4787        .collect()
4788}
4789
4790fn effective_module_control_ops(declared: Option<Vec<String>>) -> Vec<String> {
4791    let mut seen = HashSet::new();
4792    let mut effective = Vec::new();
4793    for op in MODULE_BASELINE_CONTROL_OPS {
4794        if seen.insert((*op).to_string()) {
4795            effective.push((*op).to_string());
4796        }
4797    }
4798    for op in declared.unwrap_or_default() {
4799        if seen.insert(op.clone()) {
4800            effective.push(op);
4801        }
4802    }
4803    effective
4804}
4805
4806fn module_registration_grants_op(control_ops: &[String], op: &str) -> bool {
4807    MODULE_BASELINE_CONTROL_OPS.contains(&op) || control_ops.iter().any(|granted| granted == op)
4808}
4809
4810fn target_module_id(target: &RouteTarget) -> &str {
4811    match target {
4812        RouteTarget::ToolProvider { module_id }
4813        | RouteTarget::ManagementSurface { module_id }
4814        | RouteTarget::InternalService { module_id, .. } => module_id,
4815    }
4816}
4817
4818fn target_has_required_role(target: &RouteTarget, roles: &[ProviderRole]) -> bool {
4819    roles.iter().any(|role| match (target, role) {
4820        (RouteTarget::ToolProvider { .. }, ProviderRole::ToolProvider { .. }) => true,
4821        (RouteTarget::ManagementSurface { .. }, ProviderRole::ManagementSurface { .. }) => true,
4822        (
4823            RouteTarget::InternalService { service_id, .. },
4824            ProviderRole::InternalService {
4825                service_id: provided,
4826                ..
4827            },
4828        ) => service_id == provided,
4829        _ => false,
4830    })
4831}
4832
4833fn is_routable_role(role: &ProviderRole) -> bool {
4834    matches!(
4835        role,
4836        ProviderRole::ToolProvider { .. }
4837            | ProviderRole::ManagementSurface { .. }
4838            | ProviderRole::InternalService { .. }
4839    )
4840}
4841
4842#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4843enum ControlRequestBodyError {
4844    UnknownOp,
4845    InvalidBody,
4846}
4847
4848#[derive(Debug, Deserialize)]
4849struct ControlOpProbe {
4850    op: String,
4851}
4852
4853/// Channel-0 push ops this subc version understands. A push whose `op` is not in
4854/// this set is treated as a forward-compat unknown and ignored rather than errored.
4855const MODULE_PUSH_OPS: &[&str] = &["route.status"];
4856
4857fn is_known_module_push_op(body: &[u8]) -> bool {
4858    serde_json::from_slice::<ControlOpProbe>(body)
4859        .map(|probe| MODULE_PUSH_OPS.contains(&probe.op.as_str()))
4860        .unwrap_or(false)
4861}
4862
4863fn is_known_module_request_op(body: &[u8]) -> bool {
4864    serde_json::from_slice::<ControlOpProbe>(body)
4865        .map(|probe| MODULE_TO_SUBC_CONTROL_OPS.contains(&probe.op.as_str()))
4866        .unwrap_or(false)
4867}
4868
4869fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
4870    debug!(
4871        op = %op,
4872        connection_id = connection_id.get(),
4873        corr,
4874        "control dispatch"
4875    );
4876}
4877
4878fn log_slow_control_dispatch(
4879    dispatch_started_at: Option<StdInstant>,
4880    op: &'static str,
4881    connection_id: ConnectionId,
4882    corr: u64,
4883) {
4884    let Some(dispatch_started_at) = dispatch_started_at else {
4885        return;
4886    };
4887    let elapsed = dispatch_started_at.elapsed();
4888    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
4889        warn!(
4890            op = %op,
4891            connection_id = connection_id.get(),
4892            corr,
4893            elapsed_ms = elapsed.as_millis() as u64,
4894            "slow control dispatch"
4895        );
4896    }
4897}
4898
4899fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
4900    match request {
4901        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
4902        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
4903        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
4904        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
4905        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
4906        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
4907        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
4908        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
4909        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
4910        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
4911        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
4912        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
4913        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
4914        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
4915        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
4916        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
4917        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
4918        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
4919        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
4920    }
4921}
4922
4923fn module_control_request_op(request: &ModuleControlRequestFromModule) -> &'static str {
4924    match request {
4925        ModuleControlRequestFromModule::CatalogUpdate { .. } => MODULE_TO_SUBC_OP_CATALOG_UPDATE,
4926        ModuleControlRequestFromModule::LiveRoots {} => "supervisor.live_roots",
4927    }
4928}
4929
4930fn parse_client_control_request(
4931    body: &[u8],
4932) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
4933    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
4934        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
4935            Ok(probe) if SUBC_CONTROL_OPS.contains(&probe.op.as_str()) => {
4936                ControlRequestBodyError::InvalidBody
4937            }
4938            Ok(_) => ControlRequestBodyError::UnknownOp,
4939            Err(_) => ControlRequestBodyError::InvalidBody,
4940        };
4941        (err, classification)
4942    })
4943}
4944
4945fn parse_module_control_request_from_module(
4946    body: &[u8],
4947) -> Result<ModuleControlRequestFromModule, (serde_json::Error, ControlRequestBodyError)> {
4948    serde_json::from_slice::<ModuleControlRequestFromModule>(body).map_err(|err| {
4949        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
4950            Ok(probe) if MODULE_TO_SUBC_CONTROL_OPS.contains(&probe.op.as_str()) => {
4951                ControlRequestBodyError::InvalidBody
4952            }
4953            Ok(_) => ControlRequestBodyError::UnknownOp,
4954            Err(_) => ControlRequestBodyError::InvalidBody,
4955        };
4956        (err, classification)
4957    })
4958}
4959
4960#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
4961enum ProviderRoleKind {
4962    ToolProvider,
4963    PipelineStage,
4964    ManagementSurface,
4965    InternalService,
4966}
4967
4968fn provider_role_kind(role: &ProviderRole) -> ProviderRoleKind {
4969    match role {
4970        ProviderRole::ToolProvider { .. } => ProviderRoleKind::ToolProvider,
4971        ProviderRole::PipelineStage { .. } => ProviderRoleKind::PipelineStage,
4972        ProviderRole::ManagementSurface { .. } => ProviderRoleKind::ManagementSurface,
4973        ProviderRole::InternalService { .. } => ProviderRoleKind::InternalService,
4974    }
4975}
4976
4977fn provider_role_kind_set(roles: &[ProviderRole]) -> BTreeSet<ProviderRoleKind> {
4978    roles.iter().map(provider_role_kind).collect()
4979}
4980
4981/// Return whether a catalog change can create a newly violating live route.
4982/// Removing an attested claim is intentionally excluded: it makes fewer routes
4983/// forbidden and therefore must leave the existing route census untouched.
4984fn capability_census_trigger(
4985    old: Option<&CapabilityDeclarations>,
4986    new: Option<&CapabilityDeclarations>,
4987) -> bool {
4988    let old_provides = old
4989        .map(|capabilities| capabilities.provides.iter().collect::<HashSet<_>>())
4990        .unwrap_or_default();
4991    let old_denies = old
4992        .map(|capabilities| capabilities.must_never_reach.iter().collect::<HashSet<_>>())
4993        .unwrap_or_default();
4994    let new = new.cloned().unwrap_or(CapabilityDeclarations {
4995        provides: Vec::new(),
4996        requires: Vec::new(),
4997        must_never_reach: Vec::new(),
4998    });
4999
5000    new.provides
5001        .iter()
5002        .any(|capability| !old_provides.contains(capability))
5003        || new
5004            .must_never_reach
5005            .iter()
5006            .any(|capability| !old_denies.contains(capability))
5007}
5008
5009/// Find the first capability an attested opener denies that an attested target
5010/// claims. Both manifests are live registry records, never cached or client data.
5011fn denied_capability<'a>(
5012    opening_manifest: &'a ModuleManifest,
5013    target_manifest: &ModuleManifest,
5014) -> Option<&'a str> {
5015    let opening_capabilities = opening_manifest.capabilities.as_ref()?;
5016    let target_capabilities = target_manifest.capabilities.as_ref()?;
5017    opening_capabilities
5018        .must_never_reach
5019        .iter()
5020        .find(|denied| {
5021            target_capabilities
5022                .provides
5023                .iter()
5024                .any(|provided| provided == *denied)
5025        })
5026        .map(String::as_str)
5027}
5028
5029fn catalog_update_frozen_field_message(
5030    registered: &ModuleManifest,
5031    provides: &[ProviderRole],
5032) -> Option<String> {
5033    let old_has_provides = !registered.provides.is_empty();
5034    let new_has_provides = !provides.is_empty();
5035    if old_has_provides != new_has_provides {
5036        return Some(format!(
5037            "catalog.update cannot change module '{}' between supervision-only and routable; routability is fixed at HELLO",
5038            registered.module_id
5039        ));
5040    }
5041
5042    if provider_role_kind_set(&registered.provides) != provider_role_kind_set(provides) {
5043        return Some(format!(
5044            "catalog.update cannot change provider role kinds for module '{}'; role kinds are fixed at HELLO",
5045            registered.module_id
5046        ));
5047    }
5048
5049    let registered_concurrency = manifest_concurrency(registered);
5050    let mut candidate = registered.clone();
5051    candidate.provides = provides.to_vec();
5052    let candidate_concurrency = manifest_concurrency(&candidate);
5053    if candidate_concurrency != registered_concurrency {
5054        return Some(format!(
5055            "catalog.update cannot change module '{}' concurrency from {:?} to {:?}; concurrency is fixed at HELLO",
5056            registered.module_id, registered_concurrency, candidate_concurrency
5057        ));
5058    }
5059
5060    // control_ops live beside the manifest in the HELLO body, not inside
5061    // ModuleManifest, so a provides-only catalog.update cannot change them.
5062    None
5063}
5064
5065fn manifest_provides_routable_role(manifest: &ModuleManifest) -> bool {
5066    manifest.provides.iter().any(is_routable_role)
5067}
5068
5069/// Returns the routable-provider concurrency subc should enforce for this manifest.
5070///
5071/// ToolProvider and ManagementSurface store their delivery concurrency directly.
5072/// InternalService has no role-specific concurrency field, so it retains the
5073/// existing ModuleManaged default for backward compatibility.
5074fn manifest_concurrency(manifest: &ModuleManifest) -> Concurrency {
5075    manifest
5076        .provides
5077        .iter()
5078        .find_map(|provider| match provider {
5079            ProviderRole::ToolProvider { concurrency, .. }
5080            | ProviderRole::ManagementSurface { concurrency, .. } => Some(concurrency.clone()),
5081            ProviderRole::PipelineStage { .. } | ProviderRole::InternalService { .. } => None,
5082        })
5083        .unwrap_or(Concurrency::ModuleManaged)
5084}
5085
5086/// True when the manifest carries a ManagementSurface role whose concurrency
5087/// was RESOLVED BY SERDE DEFAULT rather than declared. Reads the raw HELLO
5088/// bytes because the typed manifest deliberately erases that distinction: the
5089/// default exists for wire compatibility, and this probe exists so the default
5090/// stays observable. Any parse irregularity returns false -- the caller only
5091/// logs, and a malformed body already failed registration upstream.
5092fn manifest_concurrency_was_defaulted(raw_hello: &[u8], manifest: &ModuleManifest) -> bool {
5093    let has_management_surface = manifest
5094        .provides
5095        .iter()
5096        .any(|provider| matches!(provider, ProviderRole::ManagementSurface { .. }));
5097    if !has_management_surface {
5098        return false;
5099    }
5100    let Ok(raw) = serde_json::from_slice::<serde_json::Value>(raw_hello) else {
5101        return false;
5102    };
5103    let Some(provides) = raw
5104        .get("manifest")
5105        .and_then(|manifest| manifest.get("provides"))
5106        .and_then(serde_json::Value::as_array)
5107    else {
5108        return false;
5109    };
5110    // ProviderRole is internally tagged (`tag = "role"`), so the wire shape is
5111    // flat: {"role": "management_surface", ..., "concurrency": ...} -- verified
5112    // against the management_surface_manifest_without_concurrency golden, not
5113    // recalled (the externally-tagged guess was this function's first bug).
5114    provides.iter().any(|role| {
5115        role.get("role").and_then(serde_json::Value::as_str) == Some("management_surface")
5116            && role.get("concurrency").is_none()
5117    })
5118}
5119
5120fn negotiate_version(peer_version: u8) -> Result<u8, String> {
5121    if peer_version != PROTOCOL_VERSION {
5122        return Err(format!(
5123            "protocol_ver {peer_version} is unsupported; this daemon requires exactly {PROTOCOL_VERSION}"
5124        ));
5125    }
5126    Ok(PROTOCOL_VERSION)
5127}
5128
5129fn pong(frame: &Frame) -> Result<Frame, RouterError> {
5130    Frame::build_with_version(
5131        response_version(frame),
5132        FrameType::Pong,
5133        frame.header.flags,
5134        0,
5135        0,
5136        frame.header.corr,
5137        Vec::new(),
5138    )
5139    .map_err(RouterError::FrameBuild)
5140}
5141
5142fn control_error_frame(
5143    frame: &Frame,
5144    code: &'static str,
5145    message: impl Into<String>,
5146) -> Result<Frame, RouterError> {
5147    control_error_body_frame(
5148        frame,
5149        ErrorBody {
5150            code: code.to_string(),
5151            message: message.into(),
5152            detail: None,
5153        },
5154    )
5155}
5156
5157fn control_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
5158    let body = serde_json::to_vec(&error).map_err(|err| {
5159        RouterError::backend(
5160            0,
5161            frame.header.corr,
5162            format!("failed to encode control ERROR: {err}"),
5163        )
5164    })?;
5165
5166    Frame::build_with_version(
5167        response_version(frame),
5168        FrameType::Error,
5169        control_flags(),
5170        0,
5171        0,
5172        frame.header.corr,
5173        body,
5174    )
5175    .map_err(RouterError::FrameBuild)
5176}
5177
5178fn control_response_body_frame<T: Serialize>(
5179    frame: &Frame,
5180    reply: &T,
5181    label: &'static str,
5182) -> Result<Frame, RouterError> {
5183    let body = serde_json::to_vec(reply).map_err(|err| {
5184        RouterError::backend(
5185            0,
5186            frame.header.corr,
5187            format!("failed to encode {label}: {err}"),
5188        )
5189    })?;
5190
5191    Frame::build_with_version(
5192        response_version(frame),
5193        FrameType::Response,
5194        control_flags(),
5195        0,
5196        0,
5197        frame.header.corr,
5198        body,
5199    )
5200    .map_err(RouterError::FrameBuild)
5201}
5202
5203/// Map a forwarding failure to the wire code a client sees.
5204///
5205/// The code is not a label: clients BRANCH on it. Both SDKs decide "retry in
5206/// place" with `subc_protocol::error_codes::is_retryable_route_open`, so a code
5207/// chosen here decides whether a caller retries or gives up.
5208///
5209/// That makes attribution the load-bearing property, not merely having a code. A
5210/// permanent fault published as a retryable one produces a fleet-wide retry storm
5211/// against something that can never recover; a transient fault published as
5212/// permanent gives up on work that would have succeeded. Both look correct in a
5213/// log, which is why `retryability_of_forwarding_codes_matches_the_failure` pins
5214/// the mapping per variant rather than merely asserting that some code exists.
5215///
5216/// That fence partitions by RETRYABILITY, which is coarser than identity: swapping
5217/// two codes on the same side of the boundary passes it. Measured rather than
5218/// assumed — `NoModuleConnection` re-pointed at `module_reloading` is caught only
5219/// by `supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up`,
5220/// a test named for something else that happens to assert the string.
5221///
5222/// That accidental coverage is deliberately left alone rather than promoted to a
5223/// named test, because it guards a property this function does not promise.
5224/// Checked at source: every consumer branches on the RETRYABLE SET and none on a
5225/// specific code within a class, so identity is free to change and only the
5226/// partition is a contract. Splitting it out would assert a guarantee nothing
5227/// depends on — and a suite that promises more than the code does is the harder
5228/// thing to correct later, because the next reader cannot tell which assertions
5229/// are load-bearing.
5230///
5231/// Pin identity here the moment a consumer branches on a specific code.
5232fn forwarding_error_code(err: &ForwardingError) -> &'static str {
5233    match err {
5234        ForwardingError::NoModuleConnection => "target_unavailable",
5235        ForwardingError::ModuleReloading { .. } => "module_reloading",
5236        ForwardingError::ClientRouteChannelExhausted { .. }
5237        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
5238        ForwardingError::StaleModuleEndpoint
5239        | ForwardingError::UnknownReservation { .. }
5240        | ForwardingError::ConnectionClosing { .. }
5241        | ForwardingError::ClientEgressClosed { .. } => "target_unavailable",
5242        // Only a swap candidate's registration can produce this, and it means
5243        // exactly what a second active HELLO for a live id means.
5244        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
5245        ForwardingError::RelayCorrelationExhausted
5246        | ForwardingError::RouteOpenBuild(_)
5247        | ForwardingError::Poisoned => "forwarding_error",
5248    }
5249}
5250
5251fn response_version(frame: &Frame) -> u8 {
5252    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
5253        frame.header.ver
5254    } else {
5255        PROTOCOL_VERSION
5256    }
5257}
5258
5259fn control_flags() -> Flags {
5260    Flags::new(false, Priority::Passive, false)
5261}
5262
5263fn send_goodbye_target_best_effort(target: &GoodbyeTarget, context: &str) {
5264    let Ok(frame) = Frame::build_with_version(
5265        target.negotiated_ver,
5266        FrameType::Goodbye,
5267        control_flags(),
5268        target.channel,
5269        target.epoch,
5270        0,
5271        Vec::new(),
5272    ) else {
5273        return;
5274    };
5275    if let Err(err) = target.sink.try_send(frame) {
5276        warn!(
5277            route_channel = target.channel,
5278            route_epoch = target.epoch,
5279            error = %err,
5280            %context,
5281            "route GOODBYE dropped under backpressure"
5282        );
5283    }
5284}
5285
5286pub(crate) fn send_route_control_pushes(
5287    forwarding: &ForwardingTable,
5288    routes: Vec<EndpointRoute>,
5289    push: ClientControlPush,
5290) {
5291    let body = match serde_json::to_vec(&push) {
5292        Ok(body) => body,
5293        Err(err) => {
5294            warn!(error = %err, "failed to serialize route lifecycle control PUSH");
5295            return;
5296        }
5297    };
5298    let mut targets = Vec::new();
5299    for route in routes {
5300        let target = route.goodbye_target;
5301        if let Some(existing) = targets
5302            .iter()
5303            .find(|existing: &&GoodbyeTarget| existing.connection_id == target.connection_id)
5304        {
5305            debug_assert_eq!(
5306                existing.negotiated_ver, target.negotiated_ver,
5307                "one connection cannot negotiate multiple frame versions"
5308            );
5309            continue;
5310        }
5311        targets.push(target);
5312    }
5313    for target in targets {
5314        let frame = match Frame::build_with_version(
5315            target.negotiated_ver,
5316            FrameType::Push,
5317            control_flags(),
5318            0,
5319            0,
5320            0,
5321            body.clone(),
5322        ) {
5323            Ok(frame) => frame,
5324            Err(err) => {
5325                warn!(
5326                    route_channel = target.channel,
5327                    error = %err,
5328                    "failed to build route lifecycle control PUSH frame"
5329                );
5330                continue;
5331            }
5332        };
5333        if let Err(err) = target.sink.try_send(frame) {
5334            if target.close_on_delivery_failure() {
5335                warn!(
5336                    target_connection_id = target.connection_id.get(),
5337                    route_channel = target.channel,
5338                    error = %err,
5339                    "route lifecycle control PUSH was not delivered to client; closing target connection"
5340                );
5341                let _ = forwarding.escalate_client_delivery_failure(
5342                    target.connection_id,
5343                    target.channel,
5344                    target.epoch,
5345                    CloseReason::new(
5346                        "route_lifecycle_push_delivery_failed",
5347                        format!(
5348                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
5349                            target.channel
5350                        ),
5351                    ),
5352                    crate::forwarding::UndeliveredFrame {
5353                        module_id: target.module_id.as_deref(),
5354                        sink: &target.sink,
5355                    },
5356                );
5357            }
5358        }
5359    }
5360}
5361
5362#[cfg(test)]
5363mod tests {
5364    use std::{
5365        collections::BTreeMap,
5366        fmt,
5367        path::PathBuf,
5368        sync::{Arc, Mutex},
5369        time::Duration,
5370    };
5371
5372    use serde_json::{json, Value};
5373    use subc_protocol::{
5374        manifest::{
5375            Concurrency, ExecutionMode, IdentityScope, ManagementOperation,
5376            ManagementOperationKind, ObservabilityKind, ObservabilitySurface, ProviderRole, Tool,
5377        },
5378        session::HealthStatus,
5379        FrameType,
5380    };
5381
5382    use super::*;
5383    use crate::{
5384        forwarding::{DataRoute, DataRouteState},
5385        registry::ChannelState,
5386        router::FrameSink,
5387        stderr_tail::DEFAULT_MAX_LINE_BYTES,
5388        supervise::{ModuleSpec, ModuleState, RestartPolicy, Supervisor, SupervisorHandle},
5389        test_support::TestTempDir,
5390        RouteCtx, Router,
5391    };
5392    use tokio::{
5393        sync::mpsc,
5394        time::{sleep, Instant},
5395    };
5396    use tracing::{
5397        field::{Field, Visit},
5398        Event, Subscriber,
5399    };
5400    use tracing_subscriber::{layer::Context, prelude::*, Layer};
5401
5402    /// Locates the `fake-aft-stub` binary from a `src/lib.rs` unit test.
5403    ///
5404    /// `CARGO_BIN_EXE_*` (compile-time `env!` and runtime `std::env::var` alike)
5405    /// is only populated for `tests/*.rs` integration test binaries -- this file
5406    /// compiles as part of the library target, which gets neither. This test's
5407    /// own executable path is `<target-dir>/<profile>/deps/subc_core-<hash>`,
5408    /// and the sibling binary lives two directories up at
5409    /// `<target-dir>/<profile>/fake-aft-stub`.
5410    ///
5411    /// THE BINARY IS NOT ALWAYS THERE, and the existence check below is why.
5412    /// `cargo test -p subc-core` builds every target including `[[bin]]`, so the
5413    /// stub is on disk; `cargo test -p subc-core --lib` builds ONLY the library
5414    /// test and leaves the stub unbuilt. A bare spawn then fails with a raw
5415    /// `NotFound`, which reads as a broken test rather than an unbuilt
5416    /// dependency -- so state the cause and the remedy instead. Deliberately a
5417    /// panic and not a silent skip: a test that quietly passes when it could not
5418    /// run is worse than one that fails, because it reports health it never
5419    /// verified.
5420    fn fake_aft_stub_path() -> PathBuf {
5421        let mut path = std::env::current_exe().expect("current_exe available in tests");
5422        path.pop(); // .../deps/
5423        path.pop(); // .../<profile>/
5424        path.push(if cfg!(windows) {
5425            "fake-aft-stub.exe"
5426        } else {
5427            "fake-aft-stub"
5428        });
5429        assert!(
5430            path.exists(),
5431            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
5432             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
5433            path.display()
5434        );
5435        path
5436    }
5437
5438    /// Whether clients retry `code` in place: the predicate itself, never a copy
5439    /// of its set. A copied list breaks silently when a code is added to or
5440    /// removed from the real one, and a stale copy here would let exactly the
5441    /// failure this test exists to catch pass.
5442    fn client_retries(code: &str) -> bool {
5443        subc_protocol::error_codes::is_retryable_route_open(code)
5444    }
5445
5446    /// A code is not a label — clients branch on it, so publishing the wrong KIND
5447    /// of failure is worse than publishing none. A permanent fault dressed as
5448    /// retryable makes every client in the fleet retry forever against something
5449    /// that cannot recover; a transient fault dressed as permanent abandons work
5450    /// that would have succeeded.
5451    ///
5452    /// Asserting "a code exists" cannot catch either, because the string is free
5453    /// to say anything. This enumerates every variant and pins which side of the
5454    /// retry boundary it lands on, so a new variant must be classified here
5455    /// deliberately rather than inheriting whichever arm it was appended to.
5456    #[test]
5457    fn retryability_of_forwarding_codes_matches_the_failure() {
5458        // Transient by nature: the target is booting, reloading, or its endpoint
5459        // was swapped mid-flight. Retrying is how these resolve.
5460        let transient = [
5461            ForwardingError::NoModuleConnection,
5462            ForwardingError::ModuleReloading {
5463                module_id: "m".into(),
5464            },
5465            ForwardingError::StaleModuleEndpoint,
5466            ForwardingError::UnknownReservation {
5467                client_channel: 1,
5468                module_channel: 1,
5469            },
5470            ForwardingError::ConnectionClosing {
5471                connection_id: ConnectionId::new(1),
5472            },
5473            ForwardingError::ClientEgressClosed {
5474                connection_id: ConnectionId::new(1),
5475            },
5476        ];
5477        for err in transient {
5478            let code = forwarding_error_code(&err);
5479            assert!(
5480                client_retries(code),
5481                "{err:?} is transient but publishes {code:?}, which clients treat as permanent"
5482            );
5483        }
5484
5485        // Not fixed by retrying. Channel and correlation exhaustion need the
5486        // caller to close routes, and a poisoned lock is a daemon that cannot
5487        // recover at all — the worst thing to advertise as retryable, since every
5488        // client would storm a daemon that will never answer.
5489        let permanent = [
5490            ForwardingError::ClientRouteChannelExhausted {
5491                connection_id: ConnectionId::new(1),
5492            },
5493            ForwardingError::ModuleRouteChannelExhausted {
5494                endpoint: ModuleEndpointId {
5495                    connection_id: ConnectionId::new(1),
5496                    generation: 1,
5497                },
5498            },
5499            ForwardingError::RelayCorrelationExhausted,
5500            ForwardingError::RouteOpenBuild("x".into()),
5501            ForwardingError::Poisoned,
5502        ];
5503        for err in permanent {
5504            let code = forwarding_error_code(&err);
5505            assert!(
5506                !client_retries(code),
5507                "{err:?} cannot be fixed by retrying but publishes {code:?}, which clients retry"
5508            );
5509        }
5510    }
5511
5512    /// The principal is the daemon's answer to "who is calling", and modules
5513    /// branch on it: aft gates bash on it, cerebellum gates browser control,
5514    /// plexus gates connector invocation. So a stamp is an authorization input in
5515    /// another process, not a label — and both possible answers SUCCEED, which is
5516    /// what makes a wrong one quiet. An unattested caller stamped `Reserved` hands
5517    /// first-party capability to something that never proved it; a supervised one
5518    /// stamped `Direct` silently strips a module of capability it is entitled to.
5519    ///
5520    /// Neither shows up in a test that only checks the bind succeeded. Before this
5521    /// test the only coverage was accidental —
5522    /// `route_open_round_trip_via_tagged_shape_forwards_through_stub` asserts the
5523    /// stamped principal on its way past, so narrowing that wire-shape test to its
5524    /// stated subject would have deleted the last assertion on this value. It
5525    /// still asserts the stamp, which is now redundancy rather than the only
5526    /// guard: both fail under the same mutation, and this one names the reason.
5527    /// SCOPE: this handler's supervisor has spawned nothing, so
5528    /// `spawned_consumer_authorized` can only ever return false and the GRANT arm
5529    /// is unreachable here. Both assertions below are refusals, and a mutant that
5530    /// refuses everything would satisfy them.
5531    ///
5532    /// The grant side is covered where a real nonce exists: `tests/forwarding.rs`
5533    /// spawns a supervised consumer, reads its live nonce, and asserts the module
5534    /// observed `principal.kind == "reserved"` carrying that module_id — verified
5535    /// at source rather than assumed, since a citation is a claim about another
5536    /// file and ages like one. Recorded because a harness that structurally
5537    /// cannot reach an arm reports "none" for that arm identically to one that
5538    /// covers it and found nothing.
5539    #[tokio::test]
5540    async fn an_unattested_caller_is_never_stamped_as_a_supervised_module() {
5541        let handler = ControlHandler::default();
5542        let frame =
5543            Frame::build(FrameType::Request, control_flags(), 0, 0, 900, Vec::new()).unwrap();
5544
5545        // Absent consumer_identity is the ordinary case: a human at a terminal, or
5546        // any process holding the connection file. Nothing was proved, so nothing
5547        // may be granted beyond the unattested floor.
5548        let stamped = handler.route_open_principal(&frame, None).unwrap().unwrap();
5549        assert_eq!(
5550            stamped,
5551            Principal::Direct,
5552            "a caller that proved nothing must not be stamped as a supervised module"
5553        );
5554
5555        // A claimed module_id with a nonce no supervised child was given is a
5556        // forgery attempt, not a weaker caller: it must be REFUSED rather than
5557        // quietly demoted to Direct, or an impersonation attempt looks identical
5558        // to an ordinary unattested connection.
5559        let forged = handler
5560            .route_open_principal(
5561                &frame,
5562                Some(ConsumerIdentity {
5563                    module_id: "aft".to_string(),
5564                    launch_nonce: "not-a-real-nonce".to_string(),
5565                }),
5566            )
5567            .unwrap();
5568        let refusal = forged.expect_err("an unmatched launch nonce must not yield a principal");
5569        assert_eq!(parse_error(&refusal)["code"], "bad_consumer_identity");
5570    }
5571
5572    /// The test above hands `route_open_principal` an identity it built itself,
5573    /// which proves the stamping rule and nothing about where the identity comes
5574    /// from. The real producer is a wire body, and the two are joined by a serde
5575    /// field name that nothing else asserts.
5576    ///
5577    /// That join fails quietly in one specific way: an unrecognised key is simply
5578    /// absent after parsing, so a renamed or misspelled `consumer_identity`
5579    /// yields `None` and every supervised module silently drops to `Direct`.
5580    /// Capability-wise that is the safe direction, but it surfaces far from its
5581    /// cause — as a module mysteriously refused bash — and it would pass every
5582    /// test that builds its own input.
5583    ///
5584    /// Deliberately NOT closed with `deny_unknown_fields`: refusing unknown keys
5585    /// would break every client the moment the daemon gains a field, trading a
5586    /// quiet demotion for a hard refusal on additive change. Asserting the join
5587    /// instead means a rename breaks a test here rather than the fleet.
5588    #[test]
5589    fn a_wire_body_actually_yields_the_consumer_identity_the_daemon_stamps_from() {
5590        let body = br#"{"op":"route.open","target":{"kind":"tool_provider","module_id":"m"},"identity":{"session":"s","project_root":"/p","harness":"h"},"consumer_identity":{"module_id":"aft","launch_nonce":"n"}}"#;
5591        let parsed: ClientControlRequest = serde_json::from_slice(body).unwrap();
5592        let ClientControlRequest::RouteOpen {
5593            consumer_identity, ..
5594        } = parsed
5595        else {
5596            panic!("route.open body must parse as RouteOpen");
5597        };
5598        assert_eq!(
5599            consumer_identity,
5600            Some(ConsumerIdentity {
5601                module_id: "aft".to_string(),
5602                launch_nonce: "n".to_string(),
5603            }),
5604            "the wire field name must reach the value route_open_principal reads"
5605        );
5606    }
5607
5608    fn manifest(module_id: &str, protocol_ver: u8) -> ModuleManifest {
5609        ModuleManifest::builder(module_id, "0.1.0")
5610            .protocol_ver(protocol_ver)
5611            .provides(vec![ProviderRole::ToolProvider {
5612                tools: vec![Tool {
5613                    name: "read".to_string(),
5614                    description: None,
5615                    execution_mode: ExecutionMode::Pure,
5616                    schema: json!({"type": "object"}),
5617                }],
5618                identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
5619                concurrency: Concurrency::ModuleManaged,
5620                emits_push: true,
5621                sub_supervises: true,
5622            }])
5623            .build()
5624    }
5625
5626    fn hello_frame(module_id: &str, protocol_ver: u8, corr: u64) -> Frame {
5627        hello_frame_with_control_ops(module_id, protocol_ver, corr, None)
5628    }
5629
5630    fn hello_frame_with_control_ops(
5631        module_id: &str,
5632        protocol_ver: u8,
5633        corr: u64,
5634        control_ops: Option<Vec<String>>,
5635    ) -> Frame {
5636        hello_frame_full(module_id, protocol_ver, corr, control_ops, None)
5637    }
5638
5639    fn hello_frame_with_nonce(
5640        module_id: &str,
5641        protocol_ver: u8,
5642        corr: u64,
5643        launch_nonce: Option<&str>,
5644    ) -> Frame {
5645        hello_frame_full(
5646            module_id,
5647            protocol_ver,
5648            corr,
5649            None,
5650            launch_nonce.map(ToOwned::to_owned),
5651        )
5652    }
5653
5654    fn hello_frame_full(
5655        module_id: &str,
5656        protocol_ver: u8,
5657        corr: u64,
5658        control_ops: Option<Vec<String>>,
5659        launch_nonce: Option<String>,
5660    ) -> Frame {
5661        let body = serde_json::to_vec(&ModuleHelloBody {
5662            manifest: manifest(module_id, protocol_ver),
5663            protocol_ver,
5664            control_ops,
5665            launch_nonce,
5666        })
5667        .unwrap();
5668        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
5669    }
5670
5671    fn non_routable_hello_frame_with_control_ops(
5672        module_id: &str,
5673        corr: u64,
5674        control_ops: Option<Vec<String>>,
5675    ) -> Frame {
5676        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
5677        manifest.provides.clear();
5678        let body = serde_json::to_vec(&ModuleHelloBody {
5679            manifest,
5680            protocol_ver: PROTOCOL_VERSION,
5681            control_ops,
5682            launch_nonce: None,
5683        })
5684        .unwrap();
5685        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
5686    }
5687
5688    fn capability_grammar_hello_frame(
5689        capabilities: Value,
5690        runtime_computed: Option<Value>,
5691        corr: u64,
5692    ) -> Frame {
5693        let mut body = serde_json::to_value(ModuleHelloBody {
5694            manifest: manifest("capability-grammar-test", PROTOCOL_VERSION),
5695            protocol_ver: PROTOCOL_VERSION,
5696            control_ops: None,
5697            launch_nonce: None,
5698        })
5699        .expect("HELLO body serializes");
5700        body["manifest"]["capabilities"] = capabilities;
5701        if let Some(runtime_computed) = runtime_computed {
5702            body["runtime_computed"] = runtime_computed;
5703        }
5704        Frame::build(
5705            FrameType::Hello,
5706            control_flags(),
5707            0,
5708            0,
5709            corr,
5710            serde_json::to_vec(&body).expect("HELLO body reserializes"),
5711        )
5712        .expect("HELLO frame builds")
5713    }
5714
5715    fn channel_request(channel: u16, corr: u64) -> Frame {
5716        Frame::build(
5717            FrameType::Request,
5718            Flags::new(true, Priority::Interactive, false),
5719            channel,
5720            0,
5721            corr,
5722            b"opaque".to_vec(),
5723        )
5724        .unwrap()
5725    }
5726
5727    fn route_ctx(
5728        connection_id: ConnectionId,
5729    ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
5730        let (tx, rx) = mpsc::channel(8);
5731        (
5732            RouteCtx {
5733                connection_id,
5734                egress: FrameSink::new(tx),
5735            },
5736            rx,
5737        )
5738    }
5739
5740    fn parse_ack(frame: &Frame) -> ModuleHelloAckBody {
5741        serde_json::from_slice(&frame.body).unwrap()
5742    }
5743
5744    fn parse_error(frame: &Frame) -> Value {
5745        serde_json::from_slice(&frame.body).unwrap()
5746    }
5747
5748    fn parse_route_poll(frame: &Frame) -> ClientControlResponse {
5749        serde_json::from_slice(&frame.body).unwrap()
5750    }
5751
5752    fn route_poll_frame(corr: u64, kind: PollKind, route_channel: u16) -> Frame {
5753        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
5754            route_channel,
5755            route_epoch: 0,
5756            kind,
5757        })
5758        .unwrap();
5759        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
5760    }
5761
5762    fn supervisor_health_probe_frame(corr: u64, module_id: &str) -> Frame {
5763        let body = serde_json::to_vec(&ClientControlRequest::SupervisorHealthProbe {
5764            module_id: module_id.to_string(),
5765        })
5766        .unwrap();
5767        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
5768    }
5769
5770    fn route_open_frame(corr: u64, module_id: &str, project_root: TestTempDir) -> Frame {
5771        route_open_frame_with_consumer_capabilities(corr, module_id, project_root, None)
5772    }
5773
5774    fn route_open_frame_with_consumer_capabilities(
5775        corr: u64,
5776        module_id: &str,
5777        project_root: TestTempDir,
5778        consumer_capabilities: Option<Vec<String>>,
5779    ) -> Frame {
5780        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
5781            target: RouteTarget::ToolProvider {
5782                module_id: module_id.to_string(),
5783            },
5784            identity: BindIdentity::new(
5785                project_root.path().to_path_buf(),
5786                "unit".to_string(),
5787                "session".to_string(),
5788            ),
5789            consumer_identity: None,
5790            consumer_capabilities,
5791            admission_facts: None,
5792        })
5793        .unwrap();
5794        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
5795    }
5796
5797    fn route_open_frame_with_admission_facts(
5798        corr: u64,
5799        module_id: &str,
5800        project_root: TestTempDir,
5801        consumer_identity: Option<subc_control::ConsumerIdentity>,
5802        facts: Option<Value>,
5803    ) -> Frame {
5804        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
5805            target: RouteTarget::ToolProvider {
5806                module_id: module_id.to_string(),
5807            },
5808            identity: BindIdentity::new(
5809                project_root.path().to_path_buf(),
5810                "unit".to_string(),
5811                format!("session-{corr}"),
5812            ),
5813            consumer_identity,
5814            consumer_capabilities: None,
5815            admission_facts: facts,
5816        })
5817        .unwrap();
5818        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
5819    }
5820
5821    #[derive(Clone, Default)]
5822    struct EventCapture {
5823        events: Arc<Mutex<Vec<CapturedEvent>>>,
5824    }
5825
5826    #[derive(Clone, Debug)]
5827    struct CapturedEvent {
5828        target: String,
5829        fields: BTreeMap<String, String>,
5830    }
5831
5832    impl EventCapture {
5833        fn events(&self) -> Vec<CapturedEvent> {
5834            self.events.lock().unwrap().clone()
5835        }
5836    }
5837
5838    impl<S> Layer<S> for EventCapture
5839    where
5840        S: Subscriber,
5841    {
5842        fn on_event(&self, event: &Event<'_>, _context: Context<'_, S>) {
5843            let mut visitor = EventFieldVisitor::default();
5844            event.record(&mut visitor);
5845            self.events.lock().unwrap().push(CapturedEvent {
5846                target: event.metadata().target().to_string(),
5847                fields: visitor.fields,
5848            });
5849        }
5850    }
5851
5852    #[derive(Default)]
5853    struct EventFieldVisitor {
5854        fields: BTreeMap<String, String>,
5855    }
5856
5857    impl Visit for EventFieldVisitor {
5858        fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
5859            self.fields
5860                .insert(field.name().to_string(), format!("{value:?}"));
5861        }
5862    }
5863
5864    fn health_response(corr: u64, status: HealthStatus) -> Frame {
5865        let body = serde_json::to_vec(&ModuleControlResponse::HealthCheck {
5866            status,
5867            detail: Some("warming".to_string()),
5868            metrics: Some(json!({"queue_depth": 3})),
5869        })
5870        .unwrap();
5871        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
5872    }
5873
5874    fn route_bind_ack(corr: u64) -> Frame {
5875        let body = serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap();
5876        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
5877    }
5878
5879    fn unique_project_root(label: &str) -> TestTempDir {
5880        TestTempDir::new(label)
5881    }
5882
5883    fn assert_route_poll_liveness(frame: &Frame, expected_live: bool) {
5884        match parse_route_poll(frame) {
5885            ClientControlResponse::RoutePoll {
5886                status: None,
5887                live: Some(live),
5888                ..
5889            } => assert_eq!(live, expected_live),
5890            other => panic!("unexpected route.poll response: {other:?}"),
5891        }
5892    }
5893
5894    fn bind_liveness_route(
5895        registry: &Registry,
5896        forwarding: &ForwardingTable,
5897        module_id: &str,
5898    ) -> (RouteCtx, u16, u32) {
5899        let module_connection = ConnectionId::new(101);
5900        let client_connection = ConnectionId::new(202);
5901        let registration = registry
5902            .register_with_control_ops(
5903                manifest(module_id, PROTOCOL_VERSION),
5904                PROTOCOL_VERSION,
5905                module_connection,
5906                module_baseline_control_ops(),
5907            )
5908            .unwrap();
5909        let (module_tx, _module_rx) = mpsc::channel(8);
5910        let endpoint = forwarding
5911            .register_module_connection(
5912                module_connection,
5913                module_id.to_string(),
5914                PROTOCOL_VERSION,
5915                manifest_concurrency(&registration.manifest),
5916                FrameSink::new(module_tx),
5917            )
5918            .unwrap();
5919        let (client_ctx, _client_rx) = route_ctx(client_connection);
5920        let pending = forwarding
5921            .begin_route_bind_relay_for_test(
5922                client_connection,
5923                client_ctx.egress.clone(),
5924                1,
5925                module_id,
5926            )
5927            .unwrap();
5928        assert_eq!(pending.endpoint, endpoint);
5929        let route_channel = pending.client_channel;
5930        let route_epoch = pending.client_epoch;
5931        forwarding
5932            .complete_pending_relay(
5933                module_connection,
5934                pending.corr,
5935                RouteBindRelayOutcome::Accepted,
5936            )
5937            .unwrap();
5938        (client_ctx, route_channel, route_epoch)
5939    }
5940
5941    struct FakeProcessLiveness {
5942        live: Option<bool>,
5943    }
5944
5945    impl ModuleProcessLiveness for FakeProcessLiveness {
5946        fn process_live(&self, _module_id: &str) -> Option<bool> {
5947            self.live
5948        }
5949    }
5950
5951    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
5952    async fn supervisor_stderr_tail_converts_a_real_truncated_ring_entry_to_prefix_only_wire_data()
5953    {
5954        let registry = Arc::new(Registry::default());
5955        let supervisor_handle = SupervisorHandle::new();
5956        let supervisor = Supervisor::new(
5957            Arc::clone(&registry),
5958            RestartPolicy::new(1, Duration::from_millis(10)),
5959        )
5960        .with_handle(supervisor_handle.clone());
5961        let source_line = format!("config error: {}", "x".repeat(DEFAULT_MAX_LINE_BYTES));
5962        let module = supervisor
5963            .spawn(ModuleSpec {
5964                module_id: "stderr-tail-wire".to_string(),
5965                program: fake_aft_stub_path(),
5966                args: Vec::new(),
5967                env: vec![
5968                    ("FAKE_AFT_STDERR_LINE".to_string(), source_line.clone()),
5969                    ("FAKE_AFT_EXIT_CODE".to_string(), "1".to_string()),
5970                ],
5971                reserved: false,
5972                reserved_prefixes: Vec::new(),
5973                protocol: ModuleProtocol::Subc,
5974                overlap: Default::default(),
5975            })
5976            .unwrap();
5977
5978        let deadline = Instant::now() + Duration::from_secs(5);
5979        loop {
5980            let tail = module.stderr_tail(None, None);
5981            if tail
5982                .entries
5983                .iter()
5984                .any(|entry| matches!(entry, TailEntry::ProcessStart))
5985                && tail.entries.iter().any(|entry| {
5986                    matches!(
5987                        entry,
5988                        TailEntry::Line {
5989                            truncated: true,
5990                            ..
5991                        }
5992                    )
5993                })
5994            {
5995                break;
5996            }
5997            assert!(
5998                Instant::now() < deadline,
5999                "module did not produce a truncated line and restart boundary: {tail:?}"
6000            );
6001            sleep(Duration::from_millis(10)).await;
6002        }
6003
6004        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
6005        let request = ClientControlRequest::SupervisorStderrTail {
6006            module_id: "stderr-tail-wire".to_string(),
6007            max_lines: None,
6008            max_bytes: None,
6009        };
6010        let frame = Frame::build(
6011            FrameType::Request,
6012            control_flags(),
6013            0,
6014            0,
6015            1,
6016            serde_json::to_vec(&request).unwrap(),
6017        )
6018        .unwrap();
6019        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
6020        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
6021        let ClientControlResponse::SupervisorStderrTail { tail, .. } =
6022            serde_json::from_slice(&responses[0].body).unwrap()
6023        else {
6024            panic!("expected supervisor.stderr_tail response");
6025        };
6026
6027        assert!(
6028            tail.entries
6029                .iter()
6030                .any(|entry| matches!(entry, StderrTailEntry::ProcessStart)),
6031            "the control response lost the restart boundary"
6032        );
6033        let Some(StderrTailEntry::Line { text, truncated }) = tail.entries.iter().find(|entry| {
6034            matches!(
6035                entry,
6036                StderrTailEntry::Line {
6037                    truncated: true,
6038                    ..
6039                }
6040            )
6041        }) else {
6042            panic!("the control response lost the truncated line");
6043        };
6044        assert_eq!(text, &source_line[..DEFAULT_MAX_LINE_BYTES]);
6045        assert!(*truncated);
6046    }
6047
6048    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
6049    async fn supervisor_terminals_golden_is_generated_through_the_real_handler() {
6050        let registry = Arc::new(Registry::default());
6051        let supervisor_handle = SupervisorHandle::new();
6052        let supervisor =
6053            Supervisor::new(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
6054                .with_handle(supervisor_handle.clone());
6055        let module = supervisor
6056            .spawn(ModuleSpec {
6057                module_id: "terminal-golden".to_string(),
6058                program: fake_aft_stub_path(),
6059                args: Vec::new(),
6060                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
6061                reserved: false,
6062                reserved_prefixes: Vec::new(),
6063                protocol: ModuleProtocol::Subc,
6064                overlap: Default::default(),
6065            })
6066            .unwrap();
6067
6068        let deadline = Instant::now() + Duration::from_secs(5);
6069        while module.terminal_history().entries.len() != 2 {
6070            assert!(
6071                Instant::now() < deadline,
6072                "module did not retain two terminal exits: {:?}",
6073                module.terminal_history()
6074            );
6075            sleep(Duration::from_millis(10)).await;
6076        }
6077
6078        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
6079        let request = ClientControlRequest::SupervisorTerminals {
6080            module_id: "terminal-golden".to_string(),
6081        };
6082        let frame = Frame::build(
6083            FrameType::Request,
6084            control_flags(),
6085            0,
6086            0,
6087            1,
6088            serde_json::to_vec(&request).unwrap(),
6089        )
6090        .unwrap();
6091        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
6092        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
6093        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
6094        let ClientControlResponse::SupervisorTerminals { terminals, .. } = &response else {
6095            panic!("expected supervisor.terminals response");
6096        };
6097        assert_eq!(terminals.entries.len(), 2);
6098        assert_eq!(terminals.dropped, 0);
6099
6100        let mut rendered = serde_json::to_value(response).unwrap();
6101        // Wall-clock fields are the observation contract, but not stable fixture
6102        // bytes; normalize only them after the real handler has shaped the response.
6103        rendered["daemon_started_at_ms"] = json!(1_700_000_000_000u64);
6104        for (index, entry) in rendered["entries"]
6105            .as_array_mut()
6106            .expect("terminal response entries array")
6107            .iter_mut()
6108            .enumerate()
6109        {
6110            entry["at_ms"] = json!(1_700_000_000_001u64 + index as u64);
6111        }
6112
6113        let golden_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
6114            .join("../subc-control/tests/golden/client_control_response_supervisor_terminals.json");
6115        let serialized = serde_json::to_string_pretty(&rendered).unwrap() + "\n";
6116        if std::env::var_os("UPDATE_GOLDEN").is_some() {
6117            std::fs::write(&golden_path, &serialized).unwrap();
6118        }
6119        let expected: Value =
6120            serde_json::from_str(&std::fs::read_to_string(&golden_path).unwrap()).unwrap();
6121        assert_eq!(rendered, expected);
6122    }
6123
6124    #[test]
6125    fn hello_registers_manifest_and_returns_ack() {
6126        let registry = Arc::new(Registry::default());
6127        let handler = ControlHandler::new(Arc::clone(&registry));
6128        let conn = ConnectionId::new(1);
6129
6130        let responses = handler
6131            .handle_control(conn, hello_frame("aft", PROTOCOL_VERSION, 7))
6132            .unwrap();
6133
6134        assert_eq!(responses.len(), 1);
6135        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
6136        assert_eq!(responses[0].header.channel, 0);
6137        assert_eq!(responses[0].header.corr, 7);
6138        let ack = parse_ack(&responses[0]);
6139        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
6140        assert!(ack
6141            .subc_capabilities
6142            .contains(&CAP_MANIFEST_REGISTRATION.to_string()));
6143        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_LIST.to_string()));
6144        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_RESTART.to_string()));
6145        assert!(ack
6146            .subc_ops
6147            .contains(&ops::SUPERVISOR_SET_ENABLED.to_string()));
6148        assert!(ack
6149            .subc_ops
6150            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE.to_string()));
6151
6152        let registration = registry.get_module("aft").unwrap().unwrap();
6153        assert_eq!(registration.negotiated_ver, PROTOCOL_VERSION);
6154        assert_eq!(registration.state, ChannelState::Active);
6155        assert_eq!(registration.connection_id, conn);
6156        assert_eq!(registration.control_ops, module_baseline_control_ops());
6157    }
6158
6159    #[test]
6160    fn capability_grammar_refusals_name_the_field_and_leave_no_catalog_entry() {
6161        let invalid_identifiers = [
6162            ("case_change", "credentials-Provider/v1"),
6163            ("leading_zero", "credentials-provider/v01"),
6164            ("trailing_hyphen", "credentials-provider-/v1"),
6165            ("consecutive_hyphens", "credentials--provider/v1"),
6166            ("uppercase", "Credentials-provider/v1"),
6167            ("missing_v", "credentials-provider/1"),
6168            ("whitespace", "credentials provider/v1"),
6169            ("zero_version", "credentials-provider/v0"),
6170            ("out_of_range_version", "credentials-provider/v4294967296"),
6171            (
6172                "overlength_name",
6173                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
6174            ),
6175        ];
6176        let mut cases = invalid_identifiers
6177            .into_iter()
6178            .map(|(name, identifier)| {
6179                (
6180                    format!("identifier_{name}"),
6181                    "capabilities.provides[0]".to_string(),
6182                    identifier.to_string(),
6183                    json!({ "provides": [identifier] }),
6184                    None,
6185                )
6186            })
6187            .collect::<Vec<_>>();
6188        cases.extend([
6189            (
6190                "unknown_need".to_string(),
6191                "capabilities.requires[0].need".to_string(),
6192                "deferred".to_string(),
6193                json!({ "requires": [{ "capability": "credentials-provider/v1", "need": "deferred" }] }),
6194                None,
6195            ),
6196            (
6197                "duplicate_provides".to_string(),
6198                "capabilities.provides[1]".to_string(),
6199                "credentials-provider/v1".to_string(),
6200                json!({ "provides": ["credentials-provider/v1", "credentials-provider/v1"] }),
6201                None,
6202            ),
6203            (
6204                "duplicate_must_never_reach".to_string(),
6205                "capabilities.must_never_reach[1]".to_string(),
6206                "credentials-provider/v1".to_string(),
6207                json!({ "must_never_reach": ["credentials-provider/v1", "credentials-provider/v1"] }),
6208                None,
6209            ),
6210            (
6211                "duplicate_requires_same_need".to_string(),
6212                "capabilities.requires[1]".to_string(),
6213                "credentials-provider/v1".to_string(),
6214                json!({ "requires": [
6215                    { "capability": "credentials-provider/v1", "need": "required" },
6216                    { "capability": "credentials-provider/v1", "need": "required" }
6217                ] }),
6218                None,
6219            ),
6220            (
6221                "duplicate_requires_conflicting_need".to_string(),
6222                "capabilities.requires[1]".to_string(),
6223                "credentials-provider/v1".to_string(),
6224                json!({ "requires": [
6225                    { "capability": "credentials-provider/v1", "need": "required" },
6226                    { "capability": "credentials-provider/v1", "need": "optional" }
6227                ] }),
6228                None,
6229            ),
6230            (
6231                "capabilities_root_pointer".to_string(),
6232                "runtime_computed[0]".to_string(),
6233                "/capabilities".to_string(),
6234                json!({}),
6235                Some(json!(["/capabilities"])),
6236            ),
6237            (
6238                "capabilities_descendant_pointer".to_string(),
6239                "runtime_computed[0]".to_string(),
6240                "/capabilities/provides".to_string(),
6241                json!({}),
6242                Some(json!(["/capabilities/provides"])),
6243            ),
6244            (
6245                "malformed_pointer_without_leading_slash".to_string(),
6246                "runtime_computed[0]".to_string(),
6247                "capabilities".to_string(),
6248                json!({}),
6249                Some(json!(["capabilities"])),
6250            ),
6251            (
6252                "malformed_pointer_escape".to_string(),
6253                "runtime_computed[0]".to_string(),
6254                "/roles/~2/tools".to_string(),
6255                json!({}),
6256                Some(json!(["/roles/~2/tools"])),
6257            ),
6258            (
6259                "unknown_capabilities_field".to_string(),
6260                "capabilities.future".to_string(),
6261                "<array>".to_string(),
6262                json!({ "future": [] }),
6263                None,
6264            ),
6265        ]);
6266
6267        for (index, (name, field, value, capabilities, runtime_computed)) in
6268            cases.into_iter().enumerate()
6269        {
6270            let registry = Arc::new(Registry::default());
6271            let handler = ControlHandler::new(Arc::clone(&registry));
6272            let response = handler
6273                .handle_control(
6274                    ConnectionId::new((index + 1) as u64),
6275                    capability_grammar_hello_frame(
6276                        capabilities,
6277                        runtime_computed,
6278                        index as u64 + 1,
6279                    ),
6280                )
6281                .expect("invalid HELLO returns a refusal");
6282
6283            assert_eq!(response.len(), 1, "{name} must emit one refusal");
6284            let error = parse_error(&response[0]);
6285            assert_eq!(error["code"], "invalid_capability_grammar", "{name}");
6286            let message = error["message"]
6287                .as_str()
6288                .expect("error message is a string");
6289            assert!(
6290                message.contains(&field),
6291                "{name}: field missing from {message}"
6292            );
6293            assert!(
6294                message.contains(&value),
6295                "{name}: value missing from {message}"
6296            );
6297            assert_eq!(
6298                registry
6299                    .active_registration_count()
6300                    .expect("registry reads"),
6301                0,
6302                "{name}: refused HELLO must not create a catalog entry"
6303            );
6304        }
6305    }
6306
6307    #[test]
6308    fn legal_runtime_pointer_and_capabilities_are_mirrored_in_catalog_list() {
6309        let registry = Arc::new(Registry::default());
6310        let handler = ControlHandler::new(Arc::clone(&registry));
6311        let capabilities = json!({
6312            "provides": ["credentials-provider/v1"],
6313            "requires": [{ "capability": "context-transform/v1", "need": "optional" }],
6314            "must_never_reach": ["federation-transport/v1"]
6315        });
6316        let response = handler
6317            .handle_control(
6318                ConnectionId::new(99),
6319                capability_grammar_hello_frame(
6320                    capabilities.clone(),
6321                    Some(json!(["/roles/0/tools"])),
6322                    99,
6323                ),
6324            )
6325            .expect("valid HELLO registers");
6326        assert_eq!(response[0].header.ty, FrameType::HelloAck);
6327
6328        let request = Frame::build(
6329            FrameType::Request,
6330            control_flags(),
6331            0,
6332            0,
6333            100,
6334            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
6335                .expect("catalog request serializes"),
6336        )
6337        .expect("catalog request frame builds");
6338        let response = handler
6339            .handle_catalog_list(request, None)
6340            .expect("catalog list succeeds");
6341        let ClientControlResponse::CatalogList { modules, .. } =
6342            serde_json::from_slice(&response[0].body).expect("catalog response decodes")
6343        else {
6344            panic!("catalog request must return catalog.list");
6345        };
6346        assert_eq!(modules.len(), 1);
6347        assert_eq!(
6348            serde_json::to_value(&modules[0].capabilities).expect("catalog capabilities serialize"),
6349            capabilities
6350        );
6351    }
6352
6353    #[test]
6354    fn catalog_list_mirrors_management_operation_description() {
6355        let registry = Arc::new(Registry::default());
6356        let handler = ControlHandler::new(Arc::clone(&registry));
6357        let description = "List managed records and return their identifiers and metadata.";
6358        let mut manifest = manifest("described-management", PROTOCOL_VERSION);
6359        manifest.provides = vec![ProviderRole::ManagementSurface {
6360            operations: vec![ManagementOperation {
6361                name: "records.list".to_string(),
6362                kind: ManagementOperationKind::Query,
6363                description: Some(description.to_string()),
6364            }],
6365            config_schema: json!({"type": "object"}),
6366            observability: vec![ObservabilitySurface {
6367                name: "records.stats".to_string(),
6368                kind: ObservabilityKind::Snapshot,
6369            }],
6370            identity_scope: vec![IdentityScope::Project],
6371            concurrency: Concurrency::ModuleManaged,
6372        }];
6373        registry
6374            .register_with_control_ops(
6375                manifest,
6376                PROTOCOL_VERSION,
6377                ConnectionId::new(99),
6378                Vec::new(),
6379            )
6380            .expect("described management manifest registers");
6381
6382        let request = Frame::build(
6383            FrameType::Request,
6384            control_flags(),
6385            0,
6386            0,
6387            100,
6388            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
6389                .expect("catalog request serializes"),
6390        )
6391        .expect("catalog request frame builds");
6392        let response = handler
6393            .handle_catalog_list(request, None)
6394            .expect("catalog list succeeds");
6395        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
6396        assert_eq!(
6397            body["modules"][0]["roles"][0]["operations"][0]["description"], description,
6398            "catalog.list must preserve the declared operation description verbatim"
6399        );
6400    }
6401
6402    #[test]
6403    fn reserved_capability_refusal_mutation_proof_leaves_no_catalog_entry() {
6404        let registry = Arc::new(Registry::default());
6405        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
6406            [("vault".to_string(), true), ("squatter".to_string(), true)],
6407            BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
6408        );
6409        let mut squatter = manifest("squatter", PROTOCOL_VERSION);
6410        squatter.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
6411            provides: vec!["credentials-provider/v1".to_string()],
6412            requires: Vec::new(),
6413            must_never_reach: Vec::new(),
6414        });
6415        let frame = Frame::build(
6416            FrameType::Hello,
6417            control_flags(),
6418            0,
6419            0,
6420            77,
6421            serde_json::to_vec(&ModuleHelloBody {
6422                manifest: squatter,
6423                protocol_ver: PROTOCOL_VERSION,
6424                control_ops: None,
6425                launch_nonce: None,
6426            })
6427            .expect("HELLO serializes"),
6428        )
6429        .expect("HELLO frame builds");
6430        let response = handler
6431            .handle_control(ConnectionId::new(77), frame)
6432            .expect("reserved claim receives a typed refusal");
6433        assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
6434        assert_eq!(
6435            registry
6436                .active_registration_count()
6437                .expect("registry reads"),
6438            0,
6439            "a reserved capability refusal must not leave a catalog entry"
6440        );
6441    }
6442
6443    #[test]
6444    fn server_describe_surfaces_required_capability_verdict_fields() {
6445        let registry = Arc::new(Registry::default());
6446        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
6447            [
6448                ("consumer".to_string(), true),
6449                ("provider".to_string(), false),
6450            ],
6451            BTreeMap::new(),
6452        );
6453        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
6454        consumer.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
6455            provides: Vec::new(),
6456            requires: vec![subc_protocol::manifest::CapabilityRequirement {
6457                capability: "credentials-provider/v1".to_string(),
6458                need: subc_protocol::manifest::CapabilityNeed::Required,
6459            }],
6460            must_never_reach: Vec::new(),
6461        });
6462        let hello = Frame::build(
6463            FrameType::Hello,
6464            control_flags(),
6465            0,
6466            0,
6467            78,
6468            serde_json::to_vec(&ModuleHelloBody {
6469                manifest: consumer,
6470                protocol_ver: PROTOCOL_VERSION,
6471                control_ops: None,
6472                launch_nonce: None,
6473            })
6474            .expect("HELLO serializes"),
6475        )
6476        .expect("HELLO frame builds");
6477        handler
6478            .handle_control(ConnectionId::new(78), hello)
6479            .expect("consumer registers");
6480        let describe = Frame::build(
6481            FrameType::Request,
6482            control_flags(),
6483            0,
6484            0,
6485            79,
6486            serde_json::to_vec(&ClientControlRequest::ServerDescribe {})
6487                .expect("request serializes"),
6488        )
6489        .expect("describe frame builds");
6490        let response = handler
6491            .handle_server_describe(describe)
6492            .expect("server.describe succeeds");
6493        let rendered: Value = serde_json::from_slice(&response[0].body).expect("response JSON");
6494        let requirement = &rendered["capability_requirements"][0];
6495        assert_eq!(requirement["consumer"], "consumer");
6496        assert_eq!(requirement["verdict"], "never_provided");
6497        assert_eq!(requirement["episode_seq"], 1);
6498        assert_eq!(requirement["config_satisfiable"], false);
6499        assert_eq!(requirement["runtime_available"], false);
6500        assert!(requirement["detail"]
6501            .as_str()
6502            .expect("detail string")
6503            .contains("credentials-provider/v1"));
6504    }
6505
6506    #[test]
6507    fn catalog_list_omits_capabilities_for_legacy_manifest() {
6508        let registry = Arc::new(Registry::default());
6509        let handler = ControlHandler::new(Arc::clone(&registry));
6510        let hello = handler
6511            .handle_control(
6512                ConnectionId::new(101),
6513                hello_frame("legacy-capability-manifest", PROTOCOL_VERSION, 101),
6514            )
6515            .expect("legacy HELLO registers");
6516        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
6517
6518        let request = Frame::build(
6519            FrameType::Request,
6520            control_flags(),
6521            0,
6522            0,
6523            102,
6524            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
6525                .expect("catalog request serializes"),
6526        )
6527        .expect("catalog request frame builds");
6528        let response = handler
6529            .handle_catalog_list(request, None)
6530            .expect("catalog list succeeds");
6531        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
6532        assert!(
6533            body["modules"][0].get("capabilities").is_none(),
6534            "legacy manifest must retain an absent capabilities field on catalog.list"
6535        );
6536    }
6537
6538    #[test]
6539    fn hello_ack_omits_storage_when_no_storage_config() {
6540        let registry = Arc::new(Registry::default());
6541        let handler = ControlHandler::new(Arc::clone(&registry));
6542        let responses = handler
6543            .handle_control(
6544                ConnectionId::new(1),
6545                hello_frame("aft", PROTOCOL_VERSION, 7),
6546            )
6547            .unwrap();
6548        let ack = parse_ack(&responses[0]);
6549        assert_eq!(ack.storage, None, "no storage config -> no descriptor");
6550        assert_eq!(ack.machine_id, None, "no machine id configured -> no field");
6551    }
6552
6553    #[tokio::test]
6554    async fn hello_ack_and_server_describe_carry_the_configured_machine_id() {
6555        let id = crate::machine_id::MachineId::parse("0123456789abcdef0123456789abcdef").unwrap();
6556        let registry = Arc::new(Registry::default());
6557        let handler = ControlHandler::new(Arc::clone(&registry)).with_machine_id(Some(id.clone()));
6558        let responses = handler
6559            .handle_control(
6560                ConnectionId::new(1),
6561                hello_frame("aft", PROTOCOL_VERSION, 7),
6562            )
6563            .unwrap();
6564        let ack = parse_ack(&responses[0]);
6565        assert_eq!(ack.machine_id.as_deref(), Some(id.as_str()));
6566
6567        let described = handler
6568            .handle_control_frame(
6569                &route_ctx(ConnectionId::new(2)).0,
6570                Frame::build(
6571                    FrameType::Request,
6572                    control_flags(),
6573                    0,
6574                    0,
6575                    9,
6576                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
6577                )
6578                .unwrap(),
6579            )
6580            .await
6581            .unwrap();
6582        let ClientControlResponse::ServerDescribe { machine_id, .. } =
6583            serde_json::from_slice(&described[0].body).unwrap()
6584        else {
6585            panic!("server.describe answered with another shape");
6586        };
6587        assert_eq!(machine_id.as_deref(), Some(id.as_str()));
6588    }
6589
6590    #[test]
6591    fn hello_ack_delivers_resolved_storage_descriptor_per_module() {
6592        // With a central sqlite storage policy, each registering module gets its
6593        // own resolved descriptor in HELLO_ACK, keyed by its module id.
6594        let registry = Arc::new(Registry::default());
6595        let handler = ControlHandler::new(Arc::clone(&registry)).with_storage_config(Some(
6596            crate::daemon_config::StorageConfig::Sqlite {
6597                data_home: std::path::PathBuf::from("/data"),
6598            },
6599        ));
6600
6601        let responses = handler
6602            .handle_control(
6603                ConnectionId::new(1),
6604                hello_frame("alfonso-routing", PROTOCOL_VERSION, 7),
6605            )
6606            .unwrap();
6607        let ack = parse_ack(&responses[0]);
6608        assert_eq!(
6609            ack.storage,
6610            Some(serde_json::json!({
6611                "module_id": "alfonso-routing",
6612                "storage_namespace": "default",
6613                "isolation": { "kind": "module" },
6614                "backend": {
6615                    "backend": "sqlite",
6616                    "path": "/data/cortexkit/alfonso-routing/store.db"
6617                }
6618            })),
6619            "the delivered descriptor is the module's own sqlite store path"
6620        );
6621    }
6622
6623    #[test]
6624    fn hello_control_ops_none_is_baseline_and_guard_rejects_synthetic_gated_op() {
6625        let registry = Arc::new(Registry::default());
6626        let handler = ControlHandler::new(Arc::clone(&registry));
6627        let conn = ConnectionId::new(1);
6628        let responses = handler
6629            .handle_control(
6630                conn,
6631                hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
6632            )
6633            .unwrap();
6634        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
6635        let registration = registry.get_module("aft").unwrap().unwrap();
6636        assert_eq!(registration.control_ops, module_baseline_control_ops());
6637
6638        let frame =
6639            Frame::build(FrameType::Request, control_flags(), 0, 0, 77, Vec::new()).unwrap();
6640        assert!(handler
6641            .guard_module_control_op(&frame, "aft", "route.bind")
6642            .unwrap()
6643            .is_none());
6644        let error = handler
6645            .guard_module_control_op(&frame, "aft", "test.synthetic")
6646            .unwrap()
6647            .expect("synthetic ungranted op should be rejected");
6648        assert_eq!(error.header.ty, FrameType::Error);
6649        assert_eq!(parse_error(&error)["code"], "op_not_allowed");
6650    }
6651
6652    #[test]
6653    fn hello_control_ops_some_adds_optional_grants() {
6654        let registry = Arc::new(Registry::default());
6655        let handler = ControlHandler::new(Arc::clone(&registry));
6656        handler
6657            .handle_control(
6658                ConnectionId::new(1),
6659                hello_frame_with_control_ops(
6660                    "aft",
6661                    PROTOCOL_VERSION,
6662                    7,
6663                    Some(vec![
6664                        "future.synthetic".to_string(),
6665                        "route.bind".to_string(),
6666                    ]),
6667                ),
6668            )
6669            .unwrap();
6670        let registration = registry.get_module("aft").unwrap().unwrap();
6671        assert_eq!(
6672            registration.control_ops,
6673            vec![
6674                "route.bind".to_string(),
6675                "route.status".to_string(),
6676                "future.synthetic".to_string(),
6677            ]
6678        );
6679        let frame =
6680            Frame::build(FrameType::Request, control_flags(), 0, 0, 78, Vec::new()).unwrap();
6681        assert!(handler
6682            .guard_module_control_op(&frame, "aft", "future.synthetic")
6683            .unwrap()
6684            .is_none());
6685    }
6686
6687    #[tokio::test]
6688    async fn health_probe_refuses_unadvertised_module_without_sending_frame() {
6689        let registry = Arc::new(Registry::default());
6690        let forwarding = Arc::new(ForwardingTable::default());
6691        let handler =
6692            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
6693        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(10));
6694        let responses = handler
6695            .handle_control_frame(
6696                &module_ctx,
6697                hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
6698            )
6699            .await
6700            .unwrap();
6701        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
6702
6703        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(20));
6704        let responses = handler
6705            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(77, "aft"))
6706            .await
6707            .unwrap();
6708        assert_eq!(responses.len(), 1);
6709        assert_eq!(responses[0].header.ty, FrameType::Error);
6710        assert_eq!(parse_error(&responses[0])["code"], "health_not_advertised");
6711        assert!(module_rx.try_recv().is_err());
6712    }
6713
6714    #[tokio::test]
6715    async fn health_probe_demuxes_while_route_bind_relay_is_in_flight() {
6716        let registry = Arc::new(Registry::default());
6717        let forwarding = Arc::new(ForwardingTable::default());
6718        let handler =
6719            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
6720        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(30));
6721        handler
6722            .handle_control_frame(
6723                &module_ctx,
6724                hello_frame_with_control_ops(
6725                    "aft",
6726                    PROTOCOL_VERSION,
6727                    7,
6728                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
6729                ),
6730            )
6731            .await
6732            .unwrap();
6733
6734        let project_root = unique_project_root("demux");
6735        let (route_client_ctx, mut route_client_rx) = route_ctx(ConnectionId::new(31));
6736        let route_handler = handler.clone();
6737        let route_task = tokio::spawn(async move {
6738            route_handler
6739                .handle_control_frame(
6740                    &route_client_ctx,
6741                    route_open_frame(100, "aft", project_root),
6742                )
6743                .await
6744                .unwrap()
6745        });
6746        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
6747            .await
6748            .unwrap()
6749            .unwrap();
6750        assert!(matches!(
6751            serde_json::from_slice::<ModuleControlRequest>(&bind_frame.body).unwrap(),
6752            ModuleControlRequest::RouteBind { .. }
6753        ));
6754
6755        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(32));
6756        let health_handler = handler.clone();
6757        let health_task = tokio::spawn(async move {
6758            health_handler
6759                .handle_control_frame(
6760                    &health_client_ctx,
6761                    supervisor_health_probe_frame(101, "aft"),
6762                )
6763                .await
6764                .unwrap()
6765        });
6766        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
6767            .await
6768            .unwrap()
6769            .unwrap();
6770        assert_eq!(
6771            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
6772            ModuleControlRequest::HealthCheck {}
6773        );
6774
6775        handler
6776            .handle_control_frame(
6777                &module_ctx,
6778                health_response(health_frame.header.corr, HealthStatus::Degraded),
6779            )
6780            .await
6781            .unwrap();
6782        let health_response = health_task.await.unwrap();
6783        assert_eq!(health_response.len(), 1);
6784        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
6785            ClientControlResponse::SupervisorHealthProbe {
6786                module_id,
6787                status,
6788                detail,
6789                metrics,
6790            } => {
6791                assert_eq!(module_id, "aft");
6792                assert_eq!(status, HealthStatus::Degraded);
6793                assert_eq!(detail.as_deref(), Some("warming"));
6794                assert_eq!(metrics, Some(json!({"queue_depth": 3})));
6795            }
6796            other => panic!("unexpected health response: {other:?}"),
6797        }
6798
6799        handler
6800            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
6801            .await
6802            .unwrap();
6803        let route_response = route_task.await.unwrap();
6804        assert!(route_response.is_empty());
6805        let published = route_client_rx.recv().await.unwrap();
6806        assert!(matches!(
6807            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
6808            ClientControlResponse::RouteOpen { .. }
6809        ));
6810    }
6811
6812    /// Start one `route.open` on `client_connection` and return its still-running
6813    /// handler task together with the `route.bind` the module received for it.
6814    /// The handler blocks until the module answers, so it has to run as a task
6815    /// while the test drives the module side.
6816    async fn relay_route_open(
6817        handler: &ControlHandler,
6818        client_connection: ConnectionId,
6819        client_egress: &FrameSink,
6820        module_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
6821        corr: u64,
6822        module_id: &str,
6823        project_root_label: &str,
6824    ) -> (tokio::task::JoinHandle<Vec<Frame>>, Frame) {
6825        let ctx = RouteCtx {
6826            connection_id: client_connection,
6827            egress: client_egress.clone(),
6828        };
6829        let handler = handler.clone();
6830        let project_root = unique_project_root(project_root_label);
6831        let module_id = module_id.to_string();
6832        let dispatch = tracing::dispatcher::get_default(|dispatch| dispatch.clone());
6833        let task = tokio::spawn(async move {
6834            let _guard = tracing::dispatcher::set_default(&dispatch);
6835            handler
6836                .handle_control_frame(&ctx, route_open_frame(corr, &module_id, project_root))
6837                .await
6838                .unwrap()
6839        });
6840        let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
6841            .await
6842            .expect("module receives the relayed route.bind")
6843            .expect("module egress is open");
6844        (task, bind.frame)
6845    }
6846
6847    fn route_bind_channel(frame: &Frame) -> (u16, u32) {
6848        match serde_json::from_slice::<ModuleControlRequest>(&frame.body).unwrap() {
6849            ModuleControlRequest::RouteBind {
6850                route_channel,
6851                epoch,
6852                ..
6853            } => (route_channel, epoch),
6854            other => panic!("expected a route.bind request, got {other:?}"),
6855        }
6856    }
6857
6858    fn published_route(frame: &Frame) -> (u16, u32) {
6859        match serde_json::from_slice::<ClientControlResponse>(&frame.body).unwrap() {
6860            ClientControlResponse::RouteOpen {
6861                route_channel,
6862                route_epoch,
6863            } => (route_channel, route_epoch),
6864            other => panic!("expected a route.open response, got {other:?}"),
6865        }
6866    }
6867
6868    /// Reproduction of a production outage. A client had `route.open`s in
6869    /// flight to a module and was already marked closing -- its egress had refused a
6870    /// module frame, so the daemon asked its connection to end -- while its sink
6871    /// was still open. When the module acked those binds, the daemon refused to
6872    /// commit a route for a closing client, and that refusal was returned from
6873    /// the MODULE connection's frame handler, where a router error that has no
6874    /// ERROR-frame translation ends the connection. The module saw EOF, exited 0,
6875    /// the supervisor correctly did not respawn a clean exit, and every seat lost
6876    /// its tools for hours -- one client's teardown took down a connection
6877    /// carrying ~170 other routes.
6878    ///
6879    /// The window is opened here by calling the production path that opens it
6880    /// (`escalate_client_delivery_failure`) rather than by closing a socket. The
6881    /// state that matters is "in `closing_connections`, sink still open, relay
6882    /// still pending", and it lasts only from the close request until the
6883    /// connection loop reacts to it; a socket-level test can flood a client into
6884    /// that escalation but cannot pin the module's ack inside the window. Closing
6885    /// the socket instead takes the other path entirely -- connection teardown
6886    /// removes the pending relay under the same lock, so the ack finds nothing.
6887    #[tokio::test]
6888    async fn late_bind_ack_for_a_closing_client_keeps_the_module_connection_serving() {
6889        let registry = Arc::new(Registry::default());
6890        let forwarding = Arc::new(ForwardingTable::default());
6891        let handler =
6892            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
6893
6894        let module_connection = ConnectionId::new(30);
6895        let (module_ctx, mut module_rx) = route_ctx(module_connection);
6896        handler
6897            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
6898            .await
6899            .unwrap();
6900
6901        let dying_client = ConnectionId::new(31);
6902        let (dying_ctx, mut dying_rx) = route_ctx(dying_client);
6903
6904        // A published route on the dying client. The escalation below only marks
6905        // a connection closing for a route it has already published.
6906        let (first_task, first_bind) = relay_route_open(
6907            &handler,
6908            dying_client,
6909            &dying_ctx.egress,
6910            &mut module_rx,
6911            100,
6912            "aft",
6913            "closing-first",
6914        )
6915        .await;
6916        handler
6917            .handle_control_frame(&module_ctx, route_bind_ack(first_bind.header.corr))
6918            .await
6919            .unwrap();
6920        assert!(first_task.await.unwrap().is_empty());
6921        let (first_channel, first_epoch) = published_route(&dying_rx.recv().await.unwrap());
6922
6923        // A second route.open from the same client, relayed and awaiting its ack.
6924        let (second_task, second_bind) = relay_route_open(
6925            &handler,
6926            dying_client,
6927            &dying_ctx.egress,
6928            &mut module_rx,
6929            101,
6930            "aft",
6931            "closing-second",
6932        )
6933        .await;
6934        let (abandoned_channel, abandoned_epoch) = route_bind_channel(&second_bind);
6935
6936        // The window: the client is closing, its sink is still open, and its
6937        // second bind is still pending.
6938        assert!(forwarding
6939            .escalate_client_delivery_failure(
6940                dying_client,
6941                first_channel,
6942                first_epoch,
6943                CloseReason::new(
6944                    "module_to_client_delivery_failed",
6945                    "client egress refused a module frame",
6946                ),
6947                crate::forwarding::UndeliveredFrame {
6948                    module_id: None,
6949                    sink: &dying_ctx.egress,
6950                },
6951            )
6952            .unwrap());
6953        assert!(!dying_ctx.egress.is_closed());
6954
6955        // The frame that used to end the module connection.
6956        let ack = handler
6957            .handle_control_frame(&module_ctx, route_bind_ack(second_bind.header.corr))
6958            .await;
6959        let module_loop_error = ack.as_ref().err().map(ToString::to_string);
6960        if module_loop_error.is_some() {
6961            // What the server's connection loop does with a router error that has
6962            // no ERROR-frame translation: end the connection, which releases the
6963            // module's registration and every route on it.
6964            handler.cleanup_connection(module_connection).unwrap();
6965        }
6966        // Read the module's next frame before opening the co-tenant's route, so
6967        // the GOODBYE assertion below is about THIS ack and not about later
6968        // traffic. `None` means the module was told nothing.
6969        let post_ack_module_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
6970            .await
6971            .ok()
6972            .flatten();
6973
6974        // 1. The module connection is still registered.
6975        assert!(
6976            registry
6977                .get_module_by_connection(module_connection)
6978                .unwrap()
6979                .is_some(),
6980            "one client's closing connection ended the shared module connection: \
6981             {module_loop_error:?}"
6982        );
6983        // ...and still serving: another client can open and use a route on it.
6984        let cotenant = ConnectionId::new(32);
6985        let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
6986        let (cotenant_task, cotenant_bind) = relay_route_open(
6987            &handler,
6988            cotenant,
6989            &cotenant_ctx.egress,
6990            &mut module_rx,
6991            102,
6992            "aft",
6993            "closing-cotenant",
6994        )
6995        .await;
6996        handler
6997            .handle_control_frame(&module_ctx, route_bind_ack(cotenant_bind.header.corr))
6998            .await
6999            .unwrap();
7000        assert!(cotenant_task.await.unwrap().is_empty());
7001        let (cotenant_channel, cotenant_epoch) =
7002            published_route(&cotenant_rx.recv().await.unwrap());
7003        assert!(matches!(
7004            forwarding
7005                .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
7006                .unwrap(),
7007            DataRoute::Client(DataRouteState::Bound(_))
7008        ));
7009
7010        // 2. The module was told to drop the binding it created for the route
7011        //    that will never be published.
7012        let goodbye = post_ack_module_frame
7013            .expect("module receives a GOODBYE for the abandoned route channel");
7014        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
7015        assert_eq!(goodbye.header.channel, abandoned_channel);
7016        assert_eq!(goodbye.header.epoch, abandoned_epoch);
7017
7018        // 3. The dying client received nothing: no route was ever published to
7019        //    it. Its route.open is answered as unavailable, which the connection
7020        //    loop would write to a socket that is already going away.
7021        assert!(dying_rx.try_recv().is_err());
7022        let second_response = second_task.await.unwrap();
7023        assert_eq!(second_response.len(), 1);
7024        assert_eq!(
7025            parse_error(&second_response[0])["code"],
7026            "target_unavailable"
7027        );
7028    }
7029
7030    /// The fence at the module-loop boundary, stated as its own contract: which
7031    /// forwarding failures are allowed to end the module connection that is being
7032    /// served. A `ConnectionClosing` naming some client is about that client, and
7033    /// a module connection is shared; the same error naming the module's own
7034    /// connection is about this connection and must stay fatal, as must failures
7035    /// that are about the forwarding table itself.
7036    #[test]
7037    fn only_the_modules_own_closing_connection_ends_the_module_loop() {
7038        let handler = ControlHandler::default();
7039        let module_connection = ConnectionId::new(30);
7040        let client_connection = ConnectionId::new(31);
7041
7042        handler
7043            .refuse_to_end_module_connection_for_a_client(
7044                module_connection,
7045                77,
7046                ForwardingError::ConnectionClosing {
7047                    connection_id: client_connection,
7048                },
7049            )
7050            .expect("a closing client must never end the module connection");
7051
7052        assert!(matches!(
7053            handler.refuse_to_end_module_connection_for_a_client(
7054                module_connection,
7055                78,
7056                ForwardingError::ConnectionClosing {
7057                    connection_id: module_connection,
7058                },
7059            ),
7060            Err(RouterError::Forwarding(ForwardingError::ConnectionClosing {
7061                connection_id
7062            })) if connection_id == module_connection
7063        ));
7064        assert!(matches!(
7065            handler.refuse_to_end_module_connection_for_a_client(
7066                module_connection,
7067                79,
7068                ForwardingError::Poisoned,
7069            ),
7070            Err(RouterError::Forwarding(ForwardingError::Poisoned))
7071        ));
7072        assert!(matches!(
7073            handler.refuse_to_end_module_connection_for_a_client(
7074                module_connection,
7075                80,
7076                ForwardingError::StaleModuleEndpoint,
7077            ),
7078            Err(RouterError::Forwarding(
7079                ForwardingError::StaleModuleEndpoint
7080            ))
7081        ));
7082    }
7083
7084    /// The spawn-attestation guard is what stops a connected module from claiming
7085    /// another module's identity and being stamped `Reserved` for it. Every other
7086    /// test that supplies a consumer_identity supplies a CORRECT one, because a
7087    /// correct one is what the rest of the flow needs -- so the guard's rejection
7088    /// branch was never the subject of an assertion, only its acceptance branch.
7089    ///
7090    /// Deleting the guard's EFFECT (granting Reserved unconditionally) leaves the
7091    /// whole subc-core library suite green; only the forwarding integration tests
7092    /// notice, and they notice for unrelated reasons. This test exists so the
7093    /// refusal itself is asserted where the guard lives: it fails if the identity
7094    /// check stops refusing, which is the direction that matters, since a guard
7095    /// that wrongly ACCEPTS is silent while one that wrongly REJECTS is loud.
7096    #[tokio::test]
7097    async fn route_open_refuses_consumer_identity_that_fails_spawn_attestation() {
7098        let registry = Arc::new(Registry::default());
7099        let forwarding = Arc::new(ForwardingTable::default());
7100        let supervisor = SupervisorHandle::new();
7101        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
7102        let handler =
7103            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
7104                .with_supervisor(supervisor);
7105
7106        let (target_ctx, _target_rx) = route_ctx(ConnectionId::new(90));
7107        handler
7108            .handle_control_frame(&target_ctx, hello_frame("target", PROTOCOL_VERSION, 1))
7109            .await
7110            .unwrap();
7111
7112        // A real supervised module id presenting the wrong nonce. This is the
7113        // impersonation case: the attacker knows a privileged module_id, which is
7114        // public, and guesses at the nonce, which is not.
7115        let wrong_nonce = handler
7116            .handle_control_frame(
7117                &route_ctx(ConnectionId::new(91)).0,
7118                route_open_frame_with_admission_facts(
7119                    20,
7120                    "target",
7121                    unique_project_root("admission-facts"),
7122                    Some(subc_control::ConsumerIdentity {
7123                        module_id: "fed".to_string(),
7124                        launch_nonce: "not-the-real-nonce".to_string(),
7125                    }),
7126                    None,
7127                ),
7128            )
7129            .await
7130            .unwrap();
7131        assert_eq!(
7132            parse_error(&wrong_nonce[0])["code"],
7133            "bad_consumer_identity",
7134            "a mismatched launch nonce must be refused, not stamped Reserved"
7135        );
7136
7137        // A module id the supervisor never spawned at all, so no nonce exists to
7138        // compare against. An implementation that treats "no record" as "nothing
7139        // to check" fails open here while passing the case above.
7140        let never_spawned = handler
7141            .handle_control_frame(
7142                &route_ctx(ConnectionId::new(92)).0,
7143                route_open_frame_with_admission_facts(
7144                    21,
7145                    "target",
7146                    unique_project_root("admission-facts"),
7147                    Some(subc_control::ConsumerIdentity {
7148                        module_id: "never-spawned".to_string(),
7149                        launch_nonce: "any-nonce".to_string(),
7150                    }),
7151                    None,
7152                ),
7153            )
7154            .await
7155            .unwrap();
7156        assert_eq!(
7157            parse_error(&never_spawned[0])["code"],
7158            "bad_consumer_identity",
7159            "an unspawned module_id must be refused rather than accepted for lack of a record"
7160        );
7161    }
7162
7163    /// The refusal test above proves the guard says NO. Nothing proved it can say
7164    /// YES, and the difference is not academic: replacing the whole authorization
7165    /// with `false` -- admitting no consumer identity at all, revoking Reserved
7166    /// standing for every supervised module in the fleet -- leaves 110 of the 111
7167    /// library tests GREEN. The one that notices does so by HANGING, because it
7168    /// waits for a bind that can no longer happen.
7169    ///
7170    /// A hang is the weakest signal a suite can produce. In CI it reads as a slow
7171    /// or flaky test, invites a RETRY rather than an investigation, and the retry
7172    /// hangs too and gets blamed on the runner. So a total revocation of the
7173    /// daemon's trust grant would have shipped behind a symptom nobody attributes
7174    /// to code.
7175    ///
7176    /// The bias is structural rather than accidental. A REFUSAL looks like a
7177    /// failure someone writes a test for; a GRANT looks like the happy path. Every
7178    /// binary-outcome guard whose STRICTNESS is the point acquires a refusal-heavy
7179    /// suite for that reason, and this one is the purest case in the daemon.
7180    ///
7181    /// This test asserts the EFFECT rather than the absence of an error: the module
7182    /// receives a RouteBind and it carries `Reserved` naming the attested module.
7183    /// A guard that admitted nobody would produce no bind at all; one that admitted
7184    /// everybody would stamp the wrong principal, which the refusal test catches.
7185    #[tokio::test]
7186    async fn route_open_stamps_reserved_for_a_correctly_attested_consumer() {
7187        let registry = Arc::new(Registry::default());
7188        let forwarding = Arc::new(ForwardingTable::default());
7189        let supervisor = SupervisorHandle::new();
7190        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
7191        let handler =
7192            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
7193                .with_supervisor(supervisor);
7194
7195        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(95));
7196        handler
7197            .handle_control_frame(&target_ctx, hello_frame("target", PROTOCOL_VERSION, 1))
7198            .await
7199            .unwrap();
7200
7201        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(96));
7202        let route_handler = handler.clone();
7203        let route_task = tokio::spawn(async move {
7204            route_handler
7205                .handle_control_frame(
7206                    &client_ctx,
7207                    route_open_frame_with_admission_facts(
7208                        30,
7209                        "target",
7210                        unique_project_root("admission-facts"),
7211                        Some(subc_control::ConsumerIdentity {
7212                            module_id: "fed".to_string(),
7213                            launch_nonce: "fed-nonce".to_string(),
7214                        }),
7215                        None,
7216                    ),
7217                )
7218                .await
7219                .unwrap()
7220        });
7221
7222        // BOUND THE WAIT. The first version of this test recv'd unbounded, and under
7223        // the very mutation it exists to catch -- a guard that admits nobody -- no
7224        // bind is ever sent, so it HUNG rather than failing. That reproduces the
7225        // exact defect being fixed: a total revocation detected only as a stalled
7226        // suite, which reads as flakiness and invites a retry. An acceptance test
7227        // that waits for an effect must bound the wait, or a red becomes a hang.
7228        let bind_frame = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
7229            .await
7230            .expect("no route.bind within 5s: the consumer-identity guard refused a correctly attested consumer")
7231            .expect("module control channel closed before route.bind");
7232        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
7233        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
7234            panic!("expected route.bind")
7235        };
7236        assert_eq!(
7237            principal,
7238            Some(Principal::Reserved {
7239                module_id: "fed".to_string()
7240            }),
7241            "a correctly attested consumer must be stamped Reserved for its own id"
7242        );
7243
7244        handler
7245            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
7246            .await
7247            .unwrap();
7248        assert!(route_task.await.unwrap().is_empty());
7249        assert!(
7250            matches!(
7251                serde_json::from_slice::<ClientControlResponse>(
7252                    &client_rx.recv().await.unwrap().body
7253                )
7254                .unwrap(),
7255                ClientControlResponse::RouteOpen { .. }
7256            ),
7257            "the route must actually open, not merely avoid an error"
7258        );
7259    }
7260
7261    #[tokio::test(start_paused = true)]
7262    async fn supervisor_routes_serializes_live_draining_bindings_from_the_real_handler() {
7263        let registry = Arc::new(Registry::default());
7264        let forwarding = Arc::new(ForwardingTable::default());
7265        let supervisor = SupervisorHandle::new();
7266        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
7267        let handler =
7268            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
7269                .with_supervisor(supervisor);
7270
7271        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(101));
7272        handler
7273            .handle_control_frame(&target_ctx, hello_frame("target", PROTOCOL_VERSION, 1))
7274            .await
7275            .unwrap();
7276
7277        let (direct_ctx, mut direct_rx) = route_ctx(ConnectionId::new(102));
7278        let direct_handler = handler.clone();
7279        let direct_open = tokio::spawn(async move {
7280            direct_handler
7281                .handle_control_frame(
7282                    &direct_ctx,
7283                    route_open_frame(2, "target", unique_project_root("route-census-direct")),
7284                )
7285                .await
7286                .unwrap()
7287        });
7288        let direct_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
7289            .await
7290            .expect("no direct route.bind within 5s")
7291            .expect("target control channel closed before direct route.bind");
7292        handler
7293            .handle_control_frame(&target_ctx, route_bind_ack(direct_bind.header.corr))
7294            .await
7295            .unwrap();
7296        assert!(direct_open.await.unwrap().is_empty());
7297        let _ = direct_rx.recv().await.unwrap();
7298
7299        let (reserved_ctx, mut reserved_rx) = route_ctx(ConnectionId::new(103));
7300        let reserved_handler = handler.clone();
7301        let reserved_open = tokio::spawn(async move {
7302            reserved_handler
7303                .handle_control_frame(
7304                    &reserved_ctx,
7305                    route_open_frame_with_admission_facts(
7306                        3,
7307                        "target",
7308                        unique_project_root("admission-facts"),
7309                        Some(ConsumerIdentity {
7310                            module_id: "fed".to_string(),
7311                            launch_nonce: "fed-nonce".to_string(),
7312                        }),
7313                        None,
7314                    ),
7315                )
7316                .await
7317                .unwrap()
7318        });
7319        let reserved_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
7320            .await
7321            .expect("no reserved route.bind within 5s")
7322            .expect("target control channel closed before reserved route.bind");
7323        handler
7324            .handle_control_frame(&target_ctx, route_bind_ack(reserved_bind.header.corr))
7325            .await
7326            .unwrap();
7327        assert!(reserved_open.await.unwrap().is_empty());
7328        let _ = reserved_rx.recv().await.unwrap();
7329
7330        forwarding
7331            .begin_module_drain("target", subc_control::RouteCloseReason::Reload)
7332            .unwrap();
7333        let (census_ctx, _census_rx) = route_ctx(ConnectionId::new(104));
7334        let census_body = serde_json::to_vec(&ClientControlRequest::SupervisorRoutes {
7335            module_id: Some("target".to_string()),
7336        })
7337        .unwrap();
7338        let census_frame =
7339            Frame::build(FrameType::Request, control_flags(), 0, 0, 4, census_body).unwrap();
7340        let response = handler
7341            .handle_control_frame(&census_ctx, census_frame)
7342            .await
7343            .unwrap()
7344            .pop()
7345            .unwrap();
7346        let actual: Value = serde_json::from_slice(&response.body).unwrap();
7347        let decoded: ClientControlResponse = serde_json::from_value(actual.clone()).unwrap();
7348        assert!(matches!(
7349            decoded,
7350            ClientControlResponse::SupervisorRoutes { .. }
7351        ));
7352        let routes = actual["modules"][0]["routes"].as_array().unwrap();
7353        assert_eq!(routes.len(), 2);
7354        assert!(routes.iter().all(|route| route["draining"] == true));
7355        // The census carries WHY: the reason the drain was begun with, in the
7356        // route.closing vocabulary, on every draining route this drain marked.
7357        assert!(
7358            routes.iter().all(|route| route["drain_reason"] == "reload"),
7359            "draining routes must name the drain's reason: {routes:?}"
7360        );
7361        assert!(routes.iter().any(|route| {
7362            route["consumer"] == serde_json::json!({"kind": "direct", "connection_id": 102})
7363        }));
7364        assert!(routes.iter().any(|route| {
7365            route["consumer"] == serde_json::json!({"kind": "reserved", "module_id": "fed"})
7366        }));
7367
7368        let golden_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7369            .join("../subc-control/tests/golden/client_control_response_supervisor_routes.json");
7370        if std::env::var_os("UPDATE_GOLDEN").is_some() {
7371            std::fs::write(
7372                &golden_path,
7373                format!("{}\n", serde_json::to_string_pretty(&actual).unwrap()),
7374            )
7375            .unwrap();
7376        }
7377        let expected: Value =
7378            serde_json::from_str(&std::fs::read_to_string(golden_path).unwrap()).unwrap();
7379        assert_eq!(actual, expected);
7380    }
7381
7382    async fn query_live_roots(
7383        handler: &ControlHandler,
7384        module_ctx: &RouteCtx,
7385    ) -> ModuleControlResponseToModule {
7386        let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {}).unwrap();
7387        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 900, body).unwrap();
7388        let response = handler
7389            .handle_control_frame(module_ctx, frame)
7390            .await
7391            .unwrap()
7392            .pop()
7393            .unwrap();
7394        serde_json::from_slice(&response.body).unwrap()
7395    }
7396
7397    #[tokio::test(start_paused = true)]
7398    async fn supervisor_live_roots_root_known_arm_counts_bound_and_pending_from_real_handler() {
7399        let registry = Arc::new(Registry::default());
7400        let forwarding = Arc::new(ForwardingTable::default());
7401        let handler = ControlHandler::with_forwarding(registry, forwarding);
7402        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(301));
7403        handler
7404            .handle_control_frame(&target_ctx, hello_frame("target", PROTOCOL_VERSION, 1))
7405            .await
7406            .unwrap();
7407        let root = unique_project_root("live-roots-known");
7408        let path = ProjectRootId::from_path_allowing_missing(root.path())
7409            .unwrap()
7410            .as_path()
7411            .to_path_buf();
7412        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(302));
7413        let open_handler = handler.clone();
7414        let opened = tokio::spawn(async move {
7415            open_handler
7416                .handle_control_frame(&client_ctx, route_open_frame(2, "target", root))
7417                .await
7418                .unwrap()
7419        });
7420        let bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
7421            .await
7422            .unwrap()
7423            .unwrap();
7424        handler
7425            .handle_control_frame(&target_ctx, route_bind_ack(bind.header.corr))
7426            .await
7427            .unwrap();
7428        assert!(opened.await.unwrap().is_empty());
7429        let _ = client_rx.recv().await.unwrap();
7430
7431        let root = unique_project_root("live-roots-pending");
7432        let pending_path = ProjectRootId::from_path_allowing_missing(root.path())
7433            .unwrap()
7434            .as_path()
7435            .to_path_buf();
7436        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(303));
7437        let open_handler = handler.clone();
7438        let pending = tokio::spawn(async move {
7439            open_handler
7440                .handle_control_frame(&client_ctx, route_open_frame(3, "target", root))
7441                .await
7442                .unwrap()
7443        });
7444        let pending_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
7445            .await
7446            .unwrap()
7447            .unwrap();
7448        let actual = query_live_roots(&handler, &target_ctx).await;
7449        let ModuleControlResponseToModule::LiveRoots {
7450            roots,
7451            unknown_root_bindings,
7452            total_bindings,
7453        } = actual
7454        else {
7455            panic!("expected live roots")
7456        };
7457        assert_eq!(total_bindings, 2, "root-known arm must count live routes");
7458        assert_eq!(unknown_root_bindings, 0);
7459        assert_eq!(
7460            roots.len(),
7461            2,
7462            "root-known arm must retain each canonical root"
7463        );
7464        assert_eq!(
7465            total_bindings,
7466            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
7467        );
7468        let counts = roots
7469            .iter()
7470            .map(|root| (root.project_root.clone(), root.bound, root.pending))
7471            .collect::<Vec<_>>();
7472        let mut expected = vec![(path, 1, 0), (pending_path, 0, 1)];
7473        expected.sort_by(|a, b| a.0.cmp(&b.0));
7474        assert_eq!(
7475            counts, expected,
7476            "roots must sort by path and count pending separately"
7477        );
7478        handler
7479            .handle_control_frame(&target_ctx, route_bind_ack(pending_bind.header.corr))
7480            .await
7481            .unwrap();
7482        assert!(pending.await.unwrap().is_empty());
7483    }
7484
7485    #[tokio::test(start_paused = true)]
7486    async fn supervisor_live_roots_unknown_root_arm_is_not_no_bindings() {
7487        let forwarding = Arc::new(ForwardingTable::default());
7488        let handler =
7489            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
7490        let (target_ctx, _target_rx) = route_ctx(ConnectionId::new(311));
7491        handler
7492            .handle_control_frame(&target_ctx, hello_frame("target", PROTOCOL_VERSION, 1))
7493            .await
7494            .unwrap();
7495        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(312));
7496        let pending = forwarding
7497            .begin_route_bind_relay_for_test(
7498                client_ctx.connection_id,
7499                client_ctx.egress.clone(),
7500                2,
7501                "target",
7502            )
7503            .unwrap();
7504        forwarding
7505            .complete_pending_relay(
7506                target_ctx.connection_id,
7507                pending.corr,
7508                RouteBindRelayOutcome::Accepted,
7509            )
7510            .unwrap();
7511        let actual = query_live_roots(&handler, &target_ctx).await;
7512        let ModuleControlResponseToModule::LiveRoots {
7513            roots,
7514            unknown_root_bindings,
7515            total_bindings,
7516        } = actual
7517        else {
7518            panic!("expected live roots")
7519        };
7520        assert!(roots.is_empty(), "unknown-root arm must not invent a root");
7521        assert_eq!(
7522            unknown_root_bindings, 1,
7523            "unknown-root arm must not read as no bindings"
7524        );
7525        assert_eq!(total_bindings, 1, "unknown-root arm has a live binding");
7526        assert_eq!(
7527            total_bindings,
7528            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
7529        );
7530    }
7531
7532    #[tokio::test(start_paused = true)]
7533    async fn supervisor_live_roots_cross_module_scope_uses_requesting_connection() {
7534        let handler = ControlHandler::with_forwarding(
7535            Arc::new(Registry::default()),
7536            Arc::new(ForwardingTable::default()),
7537        );
7538        let (first_ctx, _first_rx) = route_ctx(ConnectionId::new(315));
7539        let (second_ctx, mut second_rx) = route_ctx(ConnectionId::new(316));
7540        handler
7541            .handle_control_frame(&first_ctx, hello_frame("first", PROTOCOL_VERSION, 1))
7542            .await
7543            .unwrap();
7544        handler
7545            .handle_control_frame(&second_ctx, hello_frame("second", PROTOCOL_VERSION, 2))
7546            .await
7547            .unwrap();
7548        let root = unique_project_root("second-only");
7549        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(317));
7550        let cloned = handler.clone();
7551        let open = tokio::spawn(async move {
7552            cloned
7553                .handle_control_frame(&client_ctx, route_open_frame(3, "second", root))
7554                .await
7555                .unwrap()
7556        });
7557        let bind = tokio::time::timeout(Duration::from_secs(5), second_rx.recv())
7558            .await
7559            .unwrap()
7560            .unwrap();
7561        let first = query_live_roots(&handler, &first_ctx).await;
7562        let second = query_live_roots(&handler, &second_ctx).await;
7563        assert!(
7564            matches!(
7565                first,
7566                ModuleControlResponseToModule::LiveRoots {
7567                    total_bindings: 0,
7568                    ..
7569                }
7570            ),
7571            "cross-module scope must not expose another module's roots"
7572        );
7573        assert!(
7574            matches!(
7575                second,
7576                ModuleControlResponseToModule::LiveRoots {
7577                    total_bindings: 1,
7578                    ..
7579                }
7580            ),
7581            "second module must see its pending route"
7582        );
7583        handler
7584            .handle_control_frame(&second_ctx, route_bind_ack(bind.header.corr))
7585            .await
7586            .unwrap();
7587        assert!(open.await.unwrap().is_empty());
7588    }
7589
7590    #[tokio::test(start_paused = true)]
7591    async fn supervisor_live_roots_no_bindings_arm_is_empty() {
7592        let handler = ControlHandler::with_forwarding(
7593            Arc::new(Registry::default()),
7594            Arc::new(ForwardingTable::default()),
7595        );
7596        let (target_ctx, _target_rx) = route_ctx(ConnectionId::new(321));
7597        handler
7598            .handle_control_frame(&target_ctx, hello_frame("target", PROTOCOL_VERSION, 1))
7599            .await
7600            .unwrap();
7601        let actual = query_live_roots(&handler, &target_ctx).await;
7602        let ModuleControlResponseToModule::LiveRoots {
7603            roots,
7604            unknown_root_bindings,
7605            total_bindings,
7606        } = actual
7607        else {
7608            panic!("expected live roots")
7609        };
7610        assert!(roots.is_empty());
7611        assert_eq!(unknown_root_bindings, 0);
7612        assert_eq!(total_bindings, 0);
7613        assert_eq!(
7614            total_bindings,
7615            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
7616        );
7617    }
7618
7619    /// Read the vendored fed corpus rather than hand-building a package.
7620    ///
7621    /// A hand-built object encodes what the test author believed the carrier
7622    /// emits. These vectors are what it actually emits, and one of them exists
7623    /// specifically to pin OUR side of the seam: its note reads "SUBC relay
7624    /// ignores additive unknown fields at the traversal emit terminus."
7625    fn fed_admission_facts_vectors() -> Vec<(String, Value)> {
7626        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
7627            .join("tests/fixtures/fed/admission-facts-emit.jsonl");
7628        let text = std::fs::read_to_string(&path)
7629            .unwrap_or_else(|err| panic!("vendored fed corpus unreadable at {path:?}: {err}"));
7630        let vectors: Vec<(String, Value)> = text
7631            .lines()
7632            .filter(|line| !line.trim().is_empty())
7633            .map(|line| {
7634                let entry: Value = serde_json::from_str(line).expect("corpus line must be JSON");
7635                let id = entry["corpus_id"]
7636                    .as_str()
7637                    .expect("every vector carries a corpus_id")
7638                    .to_string();
7639                (id, entry["package"].clone())
7640            })
7641            .collect();
7642        // Pin the count: a corpus that silently shrinks would take its coverage
7643        // with it, and a suite reading N-1 vectors reports the same clean pass
7644        // as one reading N.
7645        assert_eq!(
7646            vectors.len(),
7647            3,
7648            "vendored fed corpus changed size; re-sync from subc-federation"
7649        );
7650
7651        // Pin what makes the corpus DISCRIMINATING, not just present.
7652        //
7653        // The relay test below takes its expected value from the corpus, so the
7654        // corpus supplies the test's power to detect a lossy relay rather than
7655        // its correctness. A relay that dropped unrecognised fields would still
7656        // be caught -- but only by a package carrying fields it does not know.
7657        // Shrink every package to the handful of keys any implementation would
7658        // recognise and the test keeps passing over an input that can no longer
7659        // fail, which is the same clean green as a corpus that shrank away.
7660        //
7661        // So assert the precondition rather than duplicating the packages here:
7662        // at least one vector must carry a field beyond the small common set.
7663        // That is one claim to maintain instead of nine, and it fails loudly if
7664        // a re-sync ever flattens the corpus.
7665        const COMMONLY_MODELLED: [&str; 3] = ["schema", "verified_class", "org"];
7666        let richest = vectors
7667            .iter()
7668            .filter_map(|(_, package)| package.as_object())
7669            .map(|object| {
7670                object
7671                    .keys()
7672                    .filter(|key| !COMMONLY_MODELLED.contains(&key.as_str()))
7673                    .count()
7674            })
7675            .max()
7676            .unwrap_or(0);
7677        assert!(
7678            richest >= 2,
7679            "vendored corpus no longer carries a package with unmodelled fields, \
7680             so the relay test can no longer distinguish a verbatim relay from a lossy one"
7681        );
7682
7683        vectors
7684    }
7685
7686    /// The relay must carry the carrier's package through BYTE-FOR-BYTE.
7687    ///
7688    /// The gate test below proves the ACCESS RULE (who may send facts, to whom).
7689    /// This proves the PAYLOAD RULE, which the gate cannot: it hand-builds a
7690    /// three-key object, so a relay that quietly dropped fields it did not
7691    /// recognise would satisfy it. These vectors carry nine keys including ones
7692    /// this crate has no type for, so a typed relay fails here and only here.
7693    #[tokio::test]
7694    async fn admission_facts_relay_carries_vendored_packages_verbatim() {
7695        for (corpus_id, package) in fed_admission_facts_vectors() {
7696            let registry = Arc::new(Registry::default());
7697            let forwarding = Arc::new(ForwardingTable::default());
7698            let supervisor = SupervisorHandle::new();
7699            supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
7700            let handler =
7701                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
7702                    .with_supervisor(supervisor)
7703                    .with_admission_facts_config(
7704                        Some("fed".to_string()),
7705                        Some(vec!["target".to_string()]),
7706                    );
7707
7708            let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
7709            handler
7710                .handle_control_frame(&target_ctx, hello_frame("target", PROTOCOL_VERSION, 1))
7711                .await
7712                .unwrap();
7713
7714            let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(91));
7715            let route_handler = handler.clone();
7716            let expected = package.clone();
7717            let route_task = tokio::spawn(async move {
7718                route_handler
7719                    .handle_control_frame(
7720                        &client_ctx,
7721                        route_open_frame_with_admission_facts(
7722                            20,
7723                            "target",
7724                            unique_project_root("admission-facts"),
7725                            Some(subc_control::ConsumerIdentity {
7726                                module_id: "fed".to_string(),
7727                                launch_nonce: "fed-nonce".to_string(),
7728                            }),
7729                            Some(package),
7730                        ),
7731                    )
7732                    .await
7733                    .unwrap()
7734            });
7735
7736            let bind_frame = target_rx.recv().await.unwrap();
7737            let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
7738            let ModuleControlRequest::RouteBind {
7739                admission_facts, ..
7740            } = bind
7741            else {
7742                panic!("{corpus_id}: expected route.bind")
7743            };
7744            assert_eq!(
7745                admission_facts,
7746                Some(expected),
7747                "{corpus_id}: relay must not add, drop or reshape any field"
7748            );
7749
7750            handler
7751                .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
7752                .await
7753                .unwrap();
7754            route_task.await.unwrap();
7755        }
7756    }
7757
7758    #[tokio::test]
7759    async fn admission_facts_gate_checks_carrier_target_and_precedence() {
7760        let registry = Arc::new(Registry::default());
7761        let forwarding = Arc::new(ForwardingTable::default());
7762        let supervisor = SupervisorHandle::new();
7763        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
7764        supervisor.set_spawn_nonce("other", "other-nonce".to_string());
7765        let handler =
7766            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
7767                .with_supervisor(supervisor)
7768                .with_admission_facts_config(
7769                    Some("fed".to_string()),
7770                    Some(vec!["target".to_string()]),
7771                );
7772
7773        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(70));
7774        handler
7775            .handle_control_frame(&target_ctx, hello_frame("target", PROTOCOL_VERSION, 1))
7776            .await
7777            .unwrap();
7778        let (other_ctx, _other_rx) = route_ctx(ConnectionId::new(71));
7779        handler
7780            .handle_control_frame(&other_ctx, hello_frame("other", PROTOCOL_VERSION, 2))
7781            .await
7782            .unwrap();
7783
7784        let facts = json!({"schema": 1, "verified_class": "member", "org": "01H"});
7785        let expected_facts = facts.clone();
7786        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(72));
7787        let route_handler = handler.clone();
7788        let route_task = tokio::spawn(async move {
7789            route_handler
7790                .handle_control_frame(
7791                    &client_ctx,
7792                    route_open_frame_with_admission_facts(
7793                        10,
7794                        "target",
7795                        unique_project_root("admission-facts"),
7796                        Some(subc_control::ConsumerIdentity {
7797                            module_id: "fed".to_string(),
7798                            launch_nonce: "fed-nonce".to_string(),
7799                        }),
7800                        Some(facts.clone()),
7801                    ),
7802                )
7803                .await
7804                .unwrap()
7805        });
7806        let bind_frame = target_rx.recv().await.unwrap();
7807        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
7808        let ModuleControlRequest::RouteBind {
7809            admission_facts, ..
7810        } = bind
7811        else {
7812            panic!("expected route.bind")
7813        };
7814        assert_eq!(admission_facts, Some(expected_facts));
7815        handler
7816            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
7817            .await
7818            .unwrap();
7819        assert!(route_task.await.unwrap().is_empty());
7820        assert!(matches!(
7821            serde_json::from_slice::<ClientControlResponse>(&client_rx.recv().await.unwrap().body)
7822                .unwrap(),
7823            ClientControlResponse::RouteOpen { .. }
7824        ));
7825
7826        let direct = handler
7827            .handle_control_frame(
7828                &route_ctx(ConnectionId::new(73)).0,
7829                route_open_frame_with_admission_facts(
7830                    11,
7831                    "target",
7832                    unique_project_root("admission-facts"),
7833                    None,
7834                    Some(json!({"x": 1})),
7835                ),
7836            )
7837            .await
7838            .unwrap();
7839        assert_eq!(
7840            parse_error(&direct[0])["code"],
7841            "admission_facts_not_permitted"
7842        );
7843
7844        let different_reserved = handler
7845            .handle_control_frame(
7846                &route_ctx(ConnectionId::new(77)).0,
7847                route_open_frame_with_admission_facts(
7848                    15,
7849                    "target",
7850                    unique_project_root("admission-facts"),
7851                    Some(subc_control::ConsumerIdentity {
7852                        module_id: "other".to_string(),
7853                        launch_nonce: "other-nonce".to_string(),
7854                    }),
7855                    Some(json!({"x": 1})),
7856                ),
7857            )
7858            .await
7859            .unwrap();
7860        assert_eq!(
7861            parse_error(&different_reserved[0])["code"],
7862            "admission_facts_not_permitted"
7863        );
7864
7865        let other_target = handler
7866            .handle_control_frame(
7867                &route_ctx(ConnectionId::new(74)).0,
7868                route_open_frame_with_admission_facts(
7869                    12,
7870                    "other",
7871                    unique_project_root("admission-facts"),
7872                    Some(subc_control::ConsumerIdentity {
7873                        module_id: "fed".to_string(),
7874                        launch_nonce: "fed-nonce".to_string(),
7875                    }),
7876                    Some(json!({"x": 1})),
7877                ),
7878            )
7879            .await
7880            .unwrap();
7881        assert_eq!(
7882            parse_error(&other_target[0])["code"],
7883            "admission_facts_target_not_allowed"
7884        );
7885
7886        let nonexistent = handler
7887            .handle_control_frame(
7888                &route_ctx(ConnectionId::new(75)).0,
7889                route_open_frame_with_admission_facts(
7890                    13,
7891                    "missing",
7892                    unique_project_root("admission-facts"),
7893                    None,
7894                    Some(json!({"x": 1})),
7895                ),
7896            )
7897            .await
7898            .unwrap();
7899        assert_eq!(parse_error(&nonexistent[0])["code"], "unknown_module");
7900
7901        let described = handler
7902            .handle_control_frame(
7903                &route_ctx(ConnectionId::new(76)).0,
7904                Frame::build(
7905                    FrameType::Request,
7906                    control_flags(),
7907                    0,
7908                    0,
7909                    14,
7910                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
7911                )
7912                .unwrap(),
7913            )
7914            .await
7915            .unwrap();
7916        let ClientControlResponse::ServerDescribe { capabilities, .. } =
7917            serde_json::from_slice(&described[0].body).unwrap()
7918        else {
7919            panic!("expected server.describe response")
7920        };
7921        assert!(capabilities
7922            .iter()
7923            .any(|cap| cap == "admission_facts_relay_v1"));
7924    }
7925
7926    #[tokio::test]
7927    async fn admission_facts_without_configured_carrier_are_rejected() {
7928        let registry = Arc::new(Registry::default());
7929        let forwarding = Arc::new(ForwardingTable::default());
7930        let handler = ControlHandler::with_forwarding(registry, forwarding);
7931        let (target_ctx, _) = route_ctx(ConnectionId::new(78));
7932        handler
7933            .handle_control_frame(&target_ctx, hello_frame("target", PROTOCOL_VERSION, 1))
7934            .await
7935            .unwrap();
7936
7937        let responses = handler
7938            .handle_control_frame(
7939                &route_ctx(ConnectionId::new(79)).0,
7940                route_open_frame_with_admission_facts(
7941                    16,
7942                    "target",
7943                    unique_project_root("admission-facts"),
7944                    None,
7945                    Some(json!({"x": 1})),
7946                ),
7947            )
7948            .await
7949            .unwrap();
7950        assert_eq!(
7951            parse_error(&responses[0])["code"],
7952            "admission_facts_not_permitted"
7953        );
7954    }
7955
7956    #[tokio::test]
7957    async fn route_open_relays_consumer_capabilities_verbatim() {
7958        let registry = Arc::new(Registry::default());
7959        let forwarding = Arc::new(ForwardingTable::default());
7960        let handler =
7961            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
7962        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(37));
7963        handler
7964            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
7965            .await
7966            .unwrap();
7967
7968        let expected = vec!["elicitation".to_string(), "roots".to_string()];
7969        let expected_for_request = expected.clone();
7970        let project_root = unique_project_root("consumer-capabilities-present");
7971        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(38));
7972        let route_handler = handler.clone();
7973        let route_task = tokio::spawn(async move {
7974            route_handler
7975                .handle_control_frame(
7976                    &client_ctx,
7977                    route_open_frame_with_consumer_capabilities(
7978                        401,
7979                        "aft",
7980                        project_root,
7981                        Some(expected_for_request),
7982                    ),
7983                )
7984                .await
7985                .unwrap()
7986        });
7987        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
7988            .await
7989            .unwrap()
7990            .unwrap();
7991        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
7992        let ModuleControlRequest::RouteBind {
7993            consumer_capabilities,
7994            ..
7995        } = bind
7996        else {
7997            panic!("expected route.bind request, got {bind:?}");
7998        };
7999        assert_eq!(consumer_capabilities, Some(expected.clone()));
8000
8001        handler
8002            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
8003            .await
8004            .unwrap();
8005        let route_response = route_task.await.unwrap();
8006        assert!(route_response.is_empty());
8007        let published = client_rx.recv().await.unwrap();
8008        assert!(matches!(
8009            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
8010            ClientControlResponse::RouteOpen { .. }
8011        ));
8012    }
8013
8014    #[tokio::test]
8015    async fn route_open_without_consumer_capabilities_relays_none() {
8016        let registry = Arc::new(Registry::default());
8017        let forwarding = Arc::new(ForwardingTable::default());
8018        let handler =
8019            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
8020        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(39));
8021        handler
8022            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
8023            .await
8024            .unwrap();
8025
8026        let project_root = unique_project_root("consumer-capabilities-absent");
8027        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(40));
8028        let route_handler = handler.clone();
8029        let route_task = tokio::spawn(async move {
8030            route_handler
8031                .handle_control_frame(&client_ctx, route_open_frame(402, "aft", project_root))
8032                .await
8033                .unwrap()
8034        });
8035        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
8036            .await
8037            .unwrap()
8038            .unwrap();
8039        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
8040        let ModuleControlRequest::RouteBind {
8041            consumer_capabilities,
8042            ..
8043        } = bind
8044        else {
8045            panic!("expected route.bind request, got {bind:?}");
8046        };
8047        assert_eq!(consumer_capabilities, None);
8048
8049        handler
8050            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
8051            .await
8052            .unwrap();
8053        let route_response = route_task.await.unwrap();
8054        assert!(route_response.is_empty());
8055        let published = client_rx.recv().await.unwrap();
8056        assert!(matches!(
8057            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
8058            ClientControlResponse::RouteOpen { .. }
8059        ));
8060    }
8061
8062    #[tokio::test]
8063    async fn supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up() {
8064        let registry = Arc::new(Registry::default());
8065        let forwarding = Arc::new(ForwardingTable::default());
8066        let handler =
8067            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
8068                .with_health_probe_timeout(Duration::from_secs(5));
8069        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(35));
8070        let responses = handler
8071            .handle_control_frame(
8072                &module_ctx,
8073                non_routable_hello_frame_with_control_ops(
8074                    "mcp",
8075                    300,
8076                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
8077                ),
8078            )
8079            .await
8080            .unwrap();
8081        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
8082        assert!(registry
8083            .get_module("mcp")
8084            .unwrap()
8085            .unwrap()
8086            .manifest
8087            .provides
8088            .is_empty());
8089
8090        let (route_client_ctx, _route_client_rx) = route_ctx(ConnectionId::new(36));
8091        let route_response = handler
8092            .handle_control_frame(
8093                &route_client_ctx,
8094                route_open_frame(301, "mcp", unique_project_root("non-routable-mcp")),
8095            )
8096            .await
8097            .unwrap();
8098        assert_eq!(route_response[0].header.ty, FrameType::Error);
8099        assert_eq!(
8100            parse_error(&route_response[0])["code"],
8101            "target_unavailable"
8102        );
8103        assert!(parse_error(&route_response[0])["message"]
8104            .as_str()
8105            .unwrap()
8106            .contains("does not provide the requested target"));
8107        assert!(module_rx.try_recv().is_err());
8108
8109        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(37));
8110        let health_handler = handler.clone();
8111        let health_task = tokio::spawn(async move {
8112            health_handler
8113                .handle_control_frame(
8114                    &health_client_ctx,
8115                    supervisor_health_probe_frame(302, "mcp"),
8116                )
8117                .await
8118                .unwrap()
8119        });
8120        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
8121            .await
8122            .unwrap()
8123            .unwrap();
8124        assert_eq!(
8125            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
8126            ModuleControlRequest::HealthCheck {}
8127        );
8128        handler
8129            .handle_control_frame(
8130                &module_ctx,
8131                health_response(health_frame.header.corr, HealthStatus::Ok),
8132            )
8133            .await
8134            .unwrap();
8135        let health_response = health_task.await.unwrap();
8136        assert_eq!(health_response[0].header.ty, FrameType::Response);
8137        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
8138            ClientControlResponse::SupervisorHealthProbe {
8139                module_id, status, ..
8140            } => {
8141                assert_eq!(module_id, "mcp");
8142                assert_eq!(status, HealthStatus::Ok);
8143            }
8144            other => panic!("unexpected health response: {other:?}"),
8145        }
8146
8147        // Exercise the forwarding cleanup path directly while leaving the registry
8148        // advertisement in place. If cleanup leaves a stale control sink behind,
8149        // the next probe will enqueue onto it and wait for the long probe timeout
8150        // instead of returning an immediate no-connection error.
8151        forwarding
8152            .cleanup_connection(module_ctx.connection_id)
8153            .unwrap();
8154        let (cleanup_probe_ctx, _cleanup_probe_rx) = route_ctx(ConnectionId::new(38));
8155        let cleanup_response = tokio::time::timeout(
8156            Duration::from_millis(200),
8157            handler.handle_control_frame(
8158                &cleanup_probe_ctx,
8159                supervisor_health_probe_frame(303, "mcp"),
8160            ),
8161        )
8162        .await
8163        .expect("probe should fail immediately when the control lane is gone")
8164        .unwrap();
8165        assert_eq!(cleanup_response[0].header.ty, FrameType::Error);
8166        assert_eq!(
8167            parse_error(&cleanup_response[0])["code"],
8168            "target_unavailable"
8169        );
8170        assert!(parse_error(&cleanup_response[0])["message"]
8171            .as_str()
8172            .unwrap()
8173            .contains("no module connection"));
8174
8175        handler
8176            .cleanup_connection(module_ctx.connection_id)
8177            .unwrap();
8178    }
8179
8180    #[tokio::test]
8181    async fn route_open_classifies_unregistered_running_supervised_module_as_warming() {
8182        let registry = Arc::new(Registry::default());
8183        let supervisor_handle = SupervisorHandle::new();
8184        let supervisor =
8185            Supervisor::new(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
8186                .with_handle(supervisor_handle.clone())
8187                .with_connection_file_path(
8188                    std::env::temp_dir()
8189                        .join(format!("subc-route-open-warming-{}", std::process::id())),
8190                );
8191        let module = supervisor
8192            .supervise_configured(
8193                ModuleSpec {
8194                    module_id: "warming".to_string(),
8195                    program: fake_aft_stub_path(),
8196                    args: Vec::new(),
8197                    env: Vec::new(),
8198                    reserved: false,
8199                    reserved_prefixes: Vec::new(),
8200                    protocol: ModuleProtocol::Subc,
8201                    overlap: Default::default(),
8202                },
8203                true,
8204            )
8205            .unwrap();
8206        assert_eq!(module.state().unwrap(), ModuleState::Running);
8207
8208        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
8209        let (ctx, _rx) = route_ctx(ConnectionId::new(39));
8210        let response = handler
8211            .handle_control_frame(
8212                &ctx,
8213                route_open_frame(304, "warming", unique_project_root("warming")),
8214            )
8215            .await
8216            .unwrap();
8217        module.stop().await.unwrap();
8218
8219        assert_eq!(response[0].header.ty, FrameType::Error);
8220        let error = parse_error(&response[0]);
8221        assert_eq!(error["code"], "module_warming");
8222        assert!(error["message"]
8223            .as_str()
8224            .unwrap()
8225            .contains("state=running, enabled=true, live=false"));
8226    }
8227
8228    /// One wire code has several senders, so the refusal line names the check
8229    /// that refused. This drives the shared refusal path (every non-supervised
8230    /// refusal goes through `route_open_refusal_frame`) with an unregistered
8231    /// target and requires the branch label on the event.
8232    #[tokio::test]
8233    async fn route_open_refusal_names_the_check_that_refused() {
8234        let handler = ControlHandler::new(Arc::new(Registry::default()));
8235        let capture = EventCapture::default();
8236        let _subscriber =
8237            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
8238        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
8239        let response = handler
8240            .handle_control_frame(
8241                &ctx,
8242                route_open_frame(395, "nobody", unique_project_root("refusal-reason")),
8243            )
8244            .await
8245            .unwrap();
8246
8247        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
8248        let event = capture
8249            .events()
8250            .into_iter()
8251            .find(|event| {
8252                event.target == "control"
8253                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
8254            })
8255            .expect("route.open refusal event");
8256        assert_eq!(
8257            event.fields.get("reason"),
8258            Some(&"\"not_registered\"".to_string())
8259        );
8260    }
8261
8262    #[tokio::test]
8263    async fn route_open_supervised_absence_emits_refusal_fields_and_counts_code() {
8264        let registry = Arc::new(Registry::default());
8265        let supervisor_handle = SupervisorHandle::new();
8266        let supervisor =
8267            Supervisor::new(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
8268                .with_handle(supervisor_handle.clone())
8269                .with_connection_file_path(std::env::temp_dir().join(format!(
8270                    "subc-route-open-refusal-info-{}",
8271                    std::process::id()
8272                )));
8273        let module = supervisor
8274            .supervise_configured(
8275                ModuleSpec {
8276                    module_id: "warming".to_string(),
8277                    program: fake_aft_stub_path(),
8278                    args: Vec::new(),
8279                    env: Vec::new(),
8280                    reserved: false,
8281                    reserved_prefixes: Vec::new(),
8282                    protocol: ModuleProtocol::Subc,
8283                    overlap: Default::default(),
8284                },
8285                true,
8286            )
8287            .unwrap();
8288        assert_eq!(module.state().unwrap(), ModuleState::Running);
8289
8290        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
8291        assert!(handler
8292            .counters()
8293            .snapshot()
8294            .get("route_open_refused_by_code")
8295            .is_none());
8296        let capture = EventCapture::default();
8297        let _subscriber =
8298            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
8299        let (ctx, _rx) = route_ctx(ConnectionId::new(94));
8300        let response = handler
8301            .handle_control_frame(
8302                &ctx,
8303                route_open_frame(394, "warming", unique_project_root("refusal-info")),
8304            )
8305            .await
8306            .unwrap();
8307        module.stop().await.unwrap();
8308
8309        assert_eq!(parse_error(&response[0])["code"], "module_warming");
8310        let event = capture
8311            .events()
8312            .into_iter()
8313            .find(|event| {
8314                event.target == "control"
8315                    && event.fields.get("code") == Some(&"\"module_warming\"".to_string())
8316            })
8317            .expect("route.open refusal event");
8318        assert_eq!(
8319            event.fields.get("module_id"),
8320            Some(&"\"warming\"".to_string())
8321        );
8322        assert_eq!(event.fields.get("connection_id"), Some(&"94".to_string()));
8323        assert_eq!(
8324            event.fields.get("reason"),
8325            Some(&"\"supervised_not_registered\"".to_string())
8326        );
8327        assert_eq!(event.fields.get("state"), Some(&"running".to_string()));
8328        assert_eq!(event.fields.get("enabled"), Some(&"true".to_string()));
8329        assert_eq!(event.fields.get("live"), Some(&"false".to_string()));
8330        assert_eq!(
8331            handler.counters().snapshot()["route_open_refused_by_code"],
8332            json!({ "module_warming": 1 })
8333        );
8334    }
8335
8336    #[tokio::test(flavor = "current_thread")]
8337    async fn route_open_unknown_module_escapes_target_module_id() {
8338        let handler = ControlHandler::new(Arc::new(Registry::default()));
8339        let capture = EventCapture::default();
8340        let _subscriber =
8341            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
8342        let hostile_module_id = "\u{1b}]52;c;AAAA\u{07}";
8343        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
8344        let response = handler
8345            .handle_control_frame(
8346                &ctx,
8347                route_open_frame(
8348                    395,
8349                    hostile_module_id,
8350                    unique_project_root("hostile-target-module-id"),
8351                ),
8352            )
8353            .await
8354            .unwrap();
8355
8356        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
8357        let event = capture
8358            .events()
8359            .into_iter()
8360            .find(|event| {
8361                event.target == "control"
8362                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
8363            })
8364            .expect("route.open unknown-module refusal event");
8365        let logged = event.fields.get("module_id").expect("module_id field");
8366        assert!(!logged.bytes().any(|byte| byte < 0x20));
8367        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
8368    }
8369
8370    #[tokio::test(flavor = "current_thread")]
8371    async fn route_open_module_rejection_uses_daemon_counter_key() {
8372        let registry = Arc::new(Registry::default());
8373        let forwarding = Arc::new(ForwardingTable::default());
8374        let handler =
8375            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
8376        let module_connection = ConnectionId::new(95);
8377        let (module_ctx, mut module_rx) = route_ctx(module_connection);
8378        handler
8379            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 395))
8380            .await
8381            .unwrap();
8382
8383        let client_connection = ConnectionId::new(96);
8384        let (client_ctx, _client_rx) = route_ctx(client_connection);
8385        let capture = EventCapture::default();
8386        let _subscriber =
8387            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
8388        let (route_task, bind) = relay_route_open(
8389            &handler,
8390            client_connection,
8391            &client_ctx.egress,
8392            &mut module_rx,
8393            396,
8394            "aft",
8395            "hostile-module-code",
8396        )
8397        .await;
8398        let hostile_code = "\u{1b}]52;c;AAAA\u{07}";
8399        let rejection = Frame::build(
8400            FrameType::Error,
8401            control_flags(),
8402            0,
8403            0,
8404            bind.header.corr,
8405            serde_json::to_vec(&ErrorBody::new(hostile_code, "module refused route.bind")).unwrap(),
8406        )
8407        .unwrap();
8408        handler
8409            .handle_control_frame(&module_ctx, rejection)
8410            .await
8411            .unwrap();
8412
8413        let response = route_task.await.unwrap();
8414        assert_eq!(parse_error(&response[0])["code"], hostile_code);
8415        let counters = handler.counters().snapshot();
8416        assert_eq!(
8417            counters["route_open_refused_by_code"],
8418            json!({ "module_rejected": 1 })
8419        );
8420        assert!(counters["route_open_refused_by_code"]
8421            .get(hostile_code)
8422            .is_none());
8423
8424        let event = capture
8425            .events()
8426            .into_iter()
8427            .find(|event| {
8428                event.target == "control"
8429                    && event.fields.get("code") == Some(&"\"module_rejected\"".to_string())
8430            })
8431            .expect("route.open module-rejection refusal event");
8432        let logged = event.fields.get("module_code").expect("module_code field");
8433        assert!(!logged.bytes().any(|byte| byte < 0x20));
8434        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
8435    }
8436
8437    #[tokio::test]
8438    async fn route_open_keeps_failed_unregistered_supervised_module_unavailable() {
8439        let registry = Arc::new(Registry::default());
8440        let supervisor_handle = SupervisorHandle::new();
8441        let missing_program = std::env::temp_dir().join(format!(
8442            "subc-route-open-missing-program-{}",
8443            std::process::id()
8444        ));
8445        let supervisor =
8446            Supervisor::new(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
8447                .with_handle(supervisor_handle.clone());
8448        let module = supervisor
8449            .supervise_configured(
8450                ModuleSpec {
8451                    module_id: "failed".to_string(),
8452                    program: missing_program,
8453                    args: Vec::new(),
8454                    env: Vec::new(),
8455                    reserved: false,
8456                    reserved_prefixes: Vec::new(),
8457                    protocol: ModuleProtocol::Subc,
8458                    overlap: Default::default(),
8459                },
8460                true,
8461            )
8462            .unwrap();
8463        assert_eq!(module.state().unwrap(), ModuleState::Failed);
8464
8465        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
8466        let (ctx, _rx) = route_ctx(ConnectionId::new(40));
8467        let response = handler
8468            .handle_control_frame(
8469                &ctx,
8470                route_open_frame(305, "failed", unique_project_root("failed")),
8471            )
8472            .await
8473            .unwrap();
8474
8475        assert_eq!(response[0].header.ty, FrameType::Error);
8476        let error = parse_error(&response[0]);
8477        assert_eq!(error["code"], "target_unavailable");
8478        assert!(error["message"]
8479            .as_str()
8480            .unwrap()
8481            .contains("state=failed, enabled=true, live=false"));
8482    }
8483
8484    #[tokio::test]
8485    async fn route_open_role_mismatch_remains_target_unavailable() {
8486        let registry = Arc::new(Registry::default());
8487        let handler = ControlHandler::new(Arc::clone(&registry));
8488        handler
8489            .handle_control(
8490                ConnectionId::new(41),
8491                non_routable_hello_frame_with_control_ops("health-only", 306, None),
8492            )
8493            .unwrap();
8494
8495        let (ctx, _rx) = route_ctx(ConnectionId::new(42));
8496        let response = handler
8497            .handle_control_frame(
8498                &ctx,
8499                route_open_frame(307, "health-only", unique_project_root("role-mismatch")),
8500            )
8501            .await
8502            .unwrap();
8503
8504        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
8505        assert!(parse_error(&response[0])["message"]
8506            .as_str()
8507            .unwrap()
8508            .contains("does not provide the requested target"));
8509    }
8510
8511    #[tokio::test]
8512    async fn route_open_inactive_registration_remains_target_unavailable() {
8513        let registry = Arc::new(Registry::default());
8514        let handler = ControlHandler::new(Arc::clone(&registry));
8515        handler
8516            .handle_control(
8517                ConnectionId::new(43),
8518                hello_frame("inactive", PROTOCOL_VERSION, 308),
8519            )
8520            .unwrap();
8521        assert!(registry
8522            .set_module_state_for_test("inactive", ChannelState::Closed)
8523            .unwrap());
8524
8525        let (ctx, _rx) = route_ctx(ConnectionId::new(44));
8526        let response = handler
8527            .handle_control_frame(
8528                &ctx,
8529                route_open_frame(309, "inactive", unique_project_root("inactive")),
8530            )
8531            .await
8532            .unwrap();
8533
8534        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
8535        assert!(parse_error(&response[0])["message"]
8536            .as_str()
8537            .unwrap()
8538            .contains("is not active"));
8539    }
8540
8541    #[tokio::test]
8542    async fn late_health_reply_is_recorded_through_the_module_response_path() {
8543        let registry = Arc::new(Registry::default());
8544        let forwarding = Arc::new(ForwardingTable::default());
8545        let supervisor_handle = SupervisorHandle::new();
8546        let supervisor = Supervisor::new(Arc::clone(&registry), crate::RestartPolicy::default())
8547            .with_forwarding(Arc::clone(&forwarding))
8548            .with_handle(supervisor_handle.clone());
8549        let module = supervisor
8550            .supervise_configured(
8551                crate::ModuleSpec {
8552                    module_id: "late-health-response".to_string(),
8553                    program: PathBuf::from("disabled-module"),
8554                    args: Vec::new(),
8555                    env: Vec::new(),
8556                    reserved: false,
8557                    reserved_prefixes: Vec::new(),
8558                    protocol: ModuleProtocol::Subc,
8559                    overlap: Default::default(),
8560                },
8561                false,
8562            )
8563            .unwrap();
8564        let handler =
8565            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
8566                .with_supervisor(supervisor_handle);
8567        let (module_ctx, _module_rx) = route_ctx(ConnectionId::new(39));
8568        handler
8569            .handle_control_frame(
8570                &module_ctx,
8571                hello_frame_with_control_ops(
8572                    "late-health-response",
8573                    PROTOCOL_VERSION,
8574                    7,
8575                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
8576                ),
8577            )
8578            .await
8579            .unwrap();
8580        let probe_started_at = Instant::now() - Duration::from_millis(80);
8581        let pending = forwarding
8582            .begin_health_probe_rpc_for(
8583                "late-health-response",
8584                MODULE_CONTROL_OP_HEALTH_CHECK,
8585                probe_started_at,
8586                Instant::now() - Duration::from_millis(1),
8587            )
8588            .unwrap();
8589        assert!(forwarding
8590            .tombstone_health_probe_rpc(pending.endpoint, pending.corr)
8591            .unwrap());
8592
8593        let responses = handler
8594            .handle_control_frame(&module_ctx, health_response(pending.corr, HealthStatus::Ok))
8595            .await
8596            .unwrap();
8597
8598        assert!(responses.is_empty());
8599        let health = module.status().unwrap().health;
8600        assert_eq!(health.late_answer_count, 1);
8601        assert!(health.last_late_answer_latency_ms.unwrap() >= 80);
8602    }
8603
8604    #[tokio::test]
8605    async fn health_probe_timeout_and_module_death_are_typed() {
8606        let registry = Arc::new(Registry::default());
8607        let forwarding = Arc::new(ForwardingTable::default());
8608        let handler =
8609            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
8610                .with_health_probe_timeout(Duration::from_millis(50));
8611        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
8612        handler
8613            .handle_control_frame(
8614                &module_ctx,
8615                hello_frame_with_control_ops(
8616                    "aft",
8617                    PROTOCOL_VERSION,
8618                    7,
8619                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
8620                ),
8621            )
8622            .await
8623            .unwrap();
8624
8625        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
8626        let responses = handler
8627            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(201, "aft"))
8628            .await
8629            .unwrap();
8630        assert_eq!(responses[0].header.ty, FrameType::Error);
8631        assert_eq!(parse_error(&responses[0])["code"], "module_timeout");
8632        let _ = module_rx.try_recv();
8633
8634        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(42));
8635        let health_handler = handler.clone();
8636        let death_task = tokio::spawn(async move {
8637            health_handler
8638                .handle_control_frame(&client_ctx, supervisor_health_probe_frame(202, "aft"))
8639                .await
8640                .unwrap()
8641        });
8642        tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
8643            .await
8644            .unwrap()
8645            .unwrap();
8646        handler
8647            .cleanup_connection(module_ctx.connection_id)
8648            .unwrap();
8649        let responses = death_task.await.unwrap();
8650        assert_eq!(responses[0].header.ty, FrameType::Error);
8651        assert_eq!(parse_error(&responses[0])["code"], "target_unavailable");
8652    }
8653
8654    #[test]
8655    fn hello_requires_exact_protocol_version() {
8656        for (connection, offered) in [(1, PROTOCOL_VERSION - 1), (2, PROTOCOL_VERSION + 1)] {
8657            let registry = Arc::new(Registry::default());
8658            let handler = ControlHandler::new(Arc::clone(&registry));
8659            let responses = handler
8660                .handle_control(
8661                    ConnectionId::new(connection),
8662                    hello_frame("aft", offered, 9),
8663                )
8664                .unwrap();
8665
8666            assert_eq!(responses.len(), 1);
8667            assert_eq!(responses[0].header.ty, FrameType::Error);
8668            let error = parse_error(&responses[0]);
8669            assert_eq!(error["code"], "version_unsupported");
8670            assert!(registry.get_module("aft").unwrap().is_none());
8671            assert_eq!(registry.active_registration_count().unwrap(), 0);
8672        }
8673    }
8674
8675    #[test]
8676    fn unknown_module_push_op_is_ignored_but_malformed_known_op_errors() {
8677        let registry = Arc::new(Registry::default());
8678        let forwarding = Arc::new(ForwardingTable::default());
8679        let handler =
8680            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
8681        let module_connection = ConnectionId::new(301);
8682        let registration = registry
8683            .register_with_control_ops(
8684                manifest("aft-push", PROTOCOL_VERSION),
8685                PROTOCOL_VERSION,
8686                module_connection,
8687                module_baseline_control_ops(),
8688            )
8689            .unwrap();
8690        let (module_tx, _module_rx) = mpsc::channel(8);
8691        let endpoint = forwarding
8692            .register_module_connection(
8693                module_connection,
8694                "aft-push".to_string(),
8695                PROTOCOL_VERSION,
8696                manifest_concurrency(&registration.manifest),
8697                FrameSink::new(module_tx),
8698            )
8699            .unwrap();
8700
8701        // A push op this version does not know is ignored (forward-compat), not errored.
8702        let unknown = Frame::build(
8703            FrameType::Push,
8704            control_flags(),
8705            0,
8706            0,
8707            5,
8708            serde_json::to_vec(&json!({"op": "route.future.v2", "extra": 1})).unwrap(),
8709        )
8710        .unwrap();
8711        let out = handler.handle_status_update(endpoint, unknown).unwrap();
8712        assert!(
8713            out.is_empty(),
8714            "unknown push op must be ignored, got {out:?}"
8715        );
8716
8717        // A malformed body for a KNOWN op is a real error worth surfacing.
8718        let malformed = Frame::build(
8719            FrameType::Push,
8720            control_flags(),
8721            0,
8722            0,
8723            6,
8724            serde_json::to_vec(&json!({"op": "route.status"})).unwrap(),
8725        )
8726        .unwrap();
8727        let out = handler.handle_status_update(endpoint, malformed).unwrap();
8728        assert_eq!(out.len(), 1);
8729        assert_eq!(out[0].header.ty, FrameType::Error);
8730        assert_eq!(parse_error(&out[0])["code"], "invalid_control_body");
8731    }
8732
8733    #[test]
8734    fn hello_rejected_when_connection_already_owns_client_routes() {
8735        let registry = Arc::new(Registry::default());
8736        let forwarding = Arc::new(ForwardingTable::default());
8737        let handler =
8738            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
8739        // Commits a client route on connection 202 (bound to a module on conn 101).
8740        let _ = bind_liveness_route(&registry, &forwarding, "aft-module");
8741        let client_connection = ConnectionId::new(202);
8742
8743        // That same connection now tries to register as a module: rejected, so one
8744        // connection never holds both client-route and module-endpoint state.
8745        let responses = handler
8746            .handle_control(
8747                client_connection,
8748                hello_frame("aft-second", PROTOCOL_VERSION, 9),
8749            )
8750            .unwrap();
8751        assert_eq!(responses[0].header.ty, FrameType::Error);
8752        assert_eq!(parse_error(&responses[0])["code"], "invalid_hello");
8753        assert!(registry.get_module("aft-second").unwrap().is_none());
8754    }
8755
8756    #[test]
8757    fn reserved_module_hello_requires_matching_launch_nonce() {
8758        let registry = Arc::new(Registry::default());
8759        let supervisor = SupervisorHandle::new();
8760        // The supervisor recorded the nonce it injected when it spawned the reserved
8761        // module; the HELLO verifier checks against the same shared handle.
8762        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
8763        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
8764
8765        // A HELLO with NO nonce is rejected.
8766        let no_nonce = handler
8767            .handle_control(
8768                ConnectionId::new(1),
8769                hello_frame("vault", PROTOCOL_VERSION, 1),
8770            )
8771            .unwrap();
8772        assert_eq!(no_nonce[0].header.ty, FrameType::Error);
8773        assert_eq!(parse_error(&no_nonce[0])["code"], "reserved_module");
8774        assert!(registry.get_module("vault").unwrap().is_none());
8775
8776        // A HELLO with the WRONG nonce is rejected.
8777        let wrong = handler
8778            .handle_control(
8779                ConnectionId::new(2),
8780                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some("forged")),
8781            )
8782            .unwrap();
8783        assert_eq!(wrong[0].header.ty, FrameType::Error);
8784        assert_eq!(parse_error(&wrong[0])["code"], "reserved_module");
8785        assert!(registry.get_module("vault").unwrap().is_none());
8786
8787        // A HELLO with the CORRECT nonce registers.
8788        let ok = handler
8789            .handle_control(
8790                ConnectionId::new(3),
8791                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some("the-real-nonce")),
8792            )
8793            .unwrap();
8794        assert_eq!(ok[0].header.ty, FrameType::HelloAck);
8795        assert!(registry.get_module("vault").unwrap().is_some());
8796    }
8797
8798    #[test]
8799    fn reserved_prefix_hello_uses_delimiter_sensitive_owner_nonce() {
8800        let registry = Arc::new(Registry::default());
8801        let supervisor = SupervisorHandle::new();
8802        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
8803        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
8804        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
8805
8806        let squat = handler
8807            .handle_control(
8808                ConnectionId::new(1),
8809                hello_frame("fed:peerA:tool", PROTOCOL_VERSION, 1),
8810            )
8811            .unwrap();
8812        assert_eq!(squat[0].header.ty, FrameType::Error);
8813        assert_eq!(parse_error(&squat[0])["code"], "reserved_module");
8814        assert!(parse_error(&squat[0])["message"]
8815            .as_str()
8816            .unwrap()
8817            .contains("fed:"));
8818
8819        let accepted_peer = handler
8820            .handle_control(
8821                ConnectionId::new(2),
8822                hello_frame_with_nonce("fed:peerA:tool", PROTOCOL_VERSION, 2, Some("owner-nonce")),
8823            )
8824            .unwrap();
8825        assert_eq!(accepted_peer[0].header.ty, FrameType::HelloAck);
8826
8827        let accepted_short = handler
8828            .handle_control(
8829                ConnectionId::new(3),
8830                hello_frame_with_nonce("fed:x", PROTOCOL_VERSION, 3, Some("owner-nonce")),
8831            )
8832            .unwrap();
8833        assert_eq!(accepted_short[0].header.ty, FrameType::HelloAck);
8834
8835        for (conn, module_id) in [(4, "fedx:tool"), (5, "fed"), (6, "FED:x")] {
8836            let response = handler
8837                .handle_control(
8838                    ConnectionId::new(conn),
8839                    hello_frame(module_id, PROTOCOL_VERSION, conn),
8840                )
8841                .unwrap();
8842            assert_eq!(response[0].header.ty, FrameType::HelloAck, "{module_id}");
8843        }
8844    }
8845
8846    #[test]
8847    fn exact_reserved_module_takes_precedence_over_reserved_prefix() {
8848        let registry = Arc::new(Registry::default());
8849        let supervisor = SupervisorHandle::new();
8850        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
8851        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
8852        supervisor.set_reserved_nonce("fed:special", "exact-nonce".to_string());
8853        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
8854
8855        let owner_nonce = handler
8856            .handle_control(
8857                ConnectionId::new(1),
8858                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 1, Some("owner-nonce")),
8859            )
8860            .unwrap();
8861        assert_eq!(owner_nonce[0].header.ty, FrameType::Error);
8862        assert_eq!(parse_error(&owner_nonce[0])["code"], "reserved_module");
8863        assert!(registry.get_module("fed:special").unwrap().is_none());
8864
8865        let exact_nonce = handler
8866            .handle_control(
8867                ConnectionId::new(2),
8868                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 2, Some("exact-nonce")),
8869            )
8870            .unwrap();
8871        assert_eq!(exact_nonce[0].header.ty, FrameType::HelloAck);
8872        assert!(registry.get_module("fed:special").unwrap().is_some());
8873    }
8874
8875    #[test]
8876    fn non_reserved_module_ignores_launch_nonce() {
8877        let registry = Arc::new(Registry::default());
8878        // No reserved nonce recorded for these ids: they are not reserved, so HELLO
8879        // registration succeeds whether a spawned process echoes a nonce or not.
8880        let handler = ControlHandler::new(Arc::clone(&registry));
8881        let no_nonce = handler
8882            .handle_control(
8883                ConnectionId::new(1),
8884                hello_frame("aft-no-nonce", PROTOCOL_VERSION, 1),
8885            )
8886            .unwrap();
8887        assert_eq!(no_nonce[0].header.ty, FrameType::HelloAck);
8888        assert!(registry.get_module("aft-no-nonce").unwrap().is_some());
8889
8890        let echoed_nonce = handler
8891            .handle_control(
8892                ConnectionId::new(2),
8893                hello_frame_with_nonce("aft-with-nonce", PROTOCOL_VERSION, 2, Some("spawn-nonce")),
8894            )
8895            .unwrap();
8896        assert_eq!(echoed_nonce[0].header.ty, FrameType::HelloAck);
8897        assert!(registry.get_module("aft-with-nonce").unwrap().is_some());
8898    }
8899
8900    #[test]
8901    fn malformed_hello_returns_error_and_handler_still_answers_ping() {
8902        let handler = ControlHandler::default();
8903        let conn = ConnectionId::new(1);
8904        let malformed = Frame::build(
8905            FrameType::Hello,
8906            control_flags(),
8907            0,
8908            0,
8909            3,
8910            b"{not json".to_vec(),
8911        )
8912        .unwrap();
8913
8914        let error = handler.handle_control(conn, malformed).unwrap();
8915        assert_eq!(error[0].header.ty, FrameType::Error);
8916        assert_eq!(parse_error(&error[0])["code"], "invalid_hello");
8917
8918        let ping = Frame::build(FrameType::Ping, control_flags(), 0, 0, 4, Vec::new()).unwrap();
8919        let pong = handler.handle_control(conn, ping).unwrap();
8920        assert_eq!(pong[0].header.ty, FrameType::Pong);
8921        assert_eq!(pong[0].header.corr, 4);
8922    }
8923
8924    #[test]
8925    fn duplicate_module_id_is_rejected_without_replacing_active_registration() {
8926        let registry = Arc::new(Registry::default());
8927        let handler = ControlHandler::new(Arc::clone(&registry));
8928
8929        handler
8930            .handle_control(
8931                ConnectionId::new(1),
8932                hello_frame("aft", PROTOCOL_VERSION, 1),
8933            )
8934            .unwrap();
8935        let duplicate = handler
8936            .handle_control(
8937                ConnectionId::new(2),
8938                hello_frame("aft", PROTOCOL_VERSION, 2),
8939            )
8940            .unwrap();
8941
8942        assert_eq!(duplicate[0].header.ty, FrameType::Error);
8943        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
8944        let registration = registry.get_module("aft").unwrap().unwrap();
8945        assert_eq!(registration.connection_id, ConnectionId::new(1));
8946    }
8947
8948    #[test]
8949    fn liveness_poll_reports_false_when_process_liveness_reports_dead() {
8950        let registry = Arc::new(Registry::default());
8951        let forwarding = Arc::new(ForwardingTable::default());
8952        let process_liveness = Arc::new(FakeProcessLiveness { live: Some(false) });
8953        let handler =
8954            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
8955                .with_process_liveness(process_liveness);
8956        let (ctx, route_channel, route_epoch) =
8957            bind_liveness_route(&registry, &forwarding, "aft-dead");
8958        let responses = handler
8959            .handle_route_poll(
8960                &ctx,
8961                route_poll_frame(41, PollKind::Liveness, route_channel),
8962                route_channel,
8963                route_epoch,
8964                PollKind::Liveness,
8965            )
8966            .unwrap();
8967
8968        assert_eq!(responses.len(), 1);
8969        assert_eq!(responses[0].header.ty, FrameType::Response);
8970        assert_route_poll_liveness(&responses[0], false);
8971    }
8972
8973    #[test]
8974    fn liveness_poll_without_process_source_uses_bound_route() {
8975        let registry = Arc::new(Registry::default());
8976        let forwarding = Arc::new(ForwardingTable::default());
8977        let handler =
8978            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
8979        let (ctx, route_channel, route_epoch) =
8980            bind_liveness_route(&registry, &forwarding, "aft-bound-only");
8981        let responses = handler
8982            .handle_route_poll(
8983                &ctx,
8984                route_poll_frame(42, PollKind::Liveness, route_channel),
8985                route_channel,
8986                route_epoch,
8987                PollKind::Liveness,
8988            )
8989            .unwrap();
8990
8991        assert_route_poll_liveness(&responses[0], true);
8992    }
8993
8994    #[test]
8995    fn liveness_poll_untracked_process_source_uses_bound_route() {
8996        let registry = Arc::new(Registry::default());
8997        let forwarding = Arc::new(ForwardingTable::default());
8998        let process_liveness = Arc::new(FakeProcessLiveness { live: None });
8999        let handler =
9000            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
9001                .with_process_liveness(process_liveness);
9002        let (ctx, route_channel, route_epoch) =
9003            bind_liveness_route(&registry, &forwarding, "aft-untracked");
9004        let responses = handler
9005            .handle_route_poll(
9006                &ctx,
9007                route_poll_frame(43, PollKind::Liveness, route_channel),
9008                route_channel,
9009                route_epoch,
9010                PollKind::Liveness,
9011            )
9012            .unwrap();
9013
9014        assert_route_poll_liveness(&responses[0], true);
9015    }
9016
9017    #[tokio::test]
9018    async fn unknown_op_returns_unknown_control_op() {
9019        let handler = ControlHandler::default();
9020        let (ctx, _rx) = route_ctx(ConnectionId::new(77));
9021        let request = Frame::build(
9022            FrameType::Request,
9023            control_flags(),
9024            0,
9025            0,
9026            55,
9027            br#"{"op":"route.nope","route_channel":1}"#.to_vec(),
9028        )
9029        .unwrap();
9030
9031        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
9032
9033        assert_eq!(response.len(), 1);
9034        assert_eq!(response[0].header.ty, FrameType::Error);
9035        assert_eq!(response[0].header.corr, 55);
9036        assert_eq!(parse_error(&response[0])["code"], "unknown_control_op");
9037    }
9038
9039    #[tokio::test]
9040    async fn supervisor_provenance_rejects_unknown_exact_module() {
9041        let handler = ControlHandler::default();
9042        let (ctx, _rx) = route_ctx(ConnectionId::new(79));
9043        let request = Frame::build(
9044            FrameType::Request,
9045            control_flags(),
9046            0,
9047            0,
9048            57,
9049            br#"{"op":"supervisor.provenance","module_id":"missing"}"#.to_vec(),
9050        )
9051        .unwrap();
9052
9053        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
9054
9055        assert_eq!(response.len(), 1);
9056        assert_eq!(response[0].header.ty, FrameType::Error);
9057        assert_eq!(response[0].header.corr, 57);
9058        let error = parse_error(&response[0]);
9059        assert_eq!(error["code"], "unknown_module");
9060        assert_eq!(error["message"], "module_id 'missing' is not supervised");
9061    }
9062
9063    #[test]
9064    fn provenance_probe_override_keeps_handler_tests_deterministic() {
9065        let expected = subc_control::RunningImageAgreement::Unavailable {
9066            reason: subc_control::RunningImageUnavailableReason::HashFailed,
9067        };
9068        let handler = ControlHandler::default().with_provenance_probe_result(expected.clone());
9069        assert_eq!(handler.provenance_probe_override, Some(expected));
9070    }
9071
9072    #[tokio::test]
9073    async fn malformed_control_bodies_return_invalid_control_body() {
9074        let handler = ControlHandler::default();
9075        let (ctx, _rx) = route_ctx(ConnectionId::new(78));
9076
9077        for (corr, body) in [
9078            (56, br#"{"route_channel":1}"#.as_slice()),
9079            (57, br#"{"op":17,"route_channel":1}"#.as_slice()),
9080            (
9081                58,
9082                br#"{"op":"route.poll","route_channel":"bad","kind":"status"}"#.as_slice(),
9083            ),
9084        ] {
9085            let request = Frame::build(
9086                FrameType::Request,
9087                control_flags(),
9088                0,
9089                0,
9090                corr,
9091                body.to_vec(),
9092            )
9093            .unwrap();
9094            let response = handler.handle_control_frame(&ctx, request).await.unwrap();
9095
9096            assert_eq!(response.len(), 1);
9097            assert_eq!(response[0].header.ty, FrameType::Error);
9098            assert_eq!(response[0].header.corr, corr);
9099            assert_eq!(parse_error(&response[0])["code"], "invalid_control_body");
9100        }
9101    }
9102
9103    #[tokio::test]
9104    async fn goodbye_tears_down_registration_and_later_channel_is_unknown() {
9105        let registry = Arc::new(Registry::default());
9106        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
9107        let router = Router::with_control_handler(Arc::clone(&control));
9108        let connection = router.begin_connection();
9109        let (ctx, mut rx) = route_ctx(connection.id());
9110
9111        router
9112            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 11))
9113            .await
9114            .unwrap();
9115        let response = rx.recv().await.unwrap();
9116        let ack = parse_ack(&response);
9117        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
9118        let channel = 1;
9119
9120        let goodbye =
9121            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 12, Vec::new()).unwrap();
9122        router.route_for_connection(&ctx, goodbye).await.unwrap();
9123        assert!(rx.try_recv().is_err());
9124        assert!(registry.get_module("aft").unwrap().is_none());
9125
9126        router
9127            .route_for_connection(&ctx, channel_request(channel, 13))
9128            .await
9129            .unwrap();
9130        let error_frame = rx.recv().await.unwrap();
9131        assert_eq!(error_frame.header.ty, FrameType::Error);
9132        assert_eq!(error_frame.header.channel, channel);
9133    }
9134
9135    #[tokio::test]
9136    async fn dropping_router_connection_releases_registration() {
9137        let registry = Arc::new(Registry::default());
9138        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
9139        let router = Router::with_control_handler(control);
9140        let connection = router.begin_connection();
9141        let (ctx, mut rx) = route_ctx(connection.id());
9142
9143        router
9144            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 31))
9145            .await
9146            .unwrap();
9147        let response = rx.recv().await.unwrap();
9148        let ack = parse_ack(&response);
9149        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
9150        assert!(registry.get_module("aft").unwrap().is_some());
9151
9152        drop(connection);
9153
9154        assert!(registry.get_module("aft").unwrap().is_none());
9155        assert_eq!(registry.active_registration_count().unwrap(), 0);
9156    }
9157
9158    fn capability_manifest(
9159        module_id: &str,
9160        provides: &[&str],
9161        must_never_reach: &[&str],
9162    ) -> ModuleManifest {
9163        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
9164        manifest.capabilities = Some(CapabilityDeclarations {
9165            provides: provides
9166                .iter()
9167                .map(|capability| (*capability).to_string())
9168                .collect(),
9169            requires: Vec::new(),
9170            must_never_reach: must_never_reach
9171                .iter()
9172                .map(|capability| (*capability).to_string())
9173                .collect(),
9174        });
9175        manifest
9176    }
9177
9178    fn hello_frame_with_manifest(manifest: ModuleManifest, corr: u64) -> Frame {
9179        Frame::build(
9180            FrameType::Hello,
9181            control_flags(),
9182            0,
9183            0,
9184            corr,
9185            serde_json::to_vec(&ModuleHelloBody {
9186                protocol_ver: manifest.protocol_ver,
9187                manifest,
9188                control_ops: None,
9189                launch_nonce: None,
9190            })
9191            .expect("capability test HELLO serializes"),
9192        )
9193        .expect("capability test HELLO frame builds")
9194    }
9195
9196    fn catalog_update_with_capabilities_frame(
9197        corr: u64,
9198        capabilities: CapabilityDeclarations,
9199    ) -> Frame {
9200        Frame::build(
9201            FrameType::Request,
9202            control_flags(),
9203            0,
9204            0,
9205            corr,
9206            serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
9207                provides: manifest("catalog-update-placeholder", PROTOCOL_VERSION).provides,
9208                capabilities: Some(capabilities),
9209                ready: None,
9210            })
9211            .expect("capability catalog.update serializes"),
9212        )
9213        .expect("capability catalog.update frame builds")
9214    }
9215
9216    async fn register_capability_manifest(
9217        handler: &ControlHandler,
9218        ctx: &RouteCtx,
9219        manifest: ModuleManifest,
9220        corr: u64,
9221    ) {
9222        let replies = handler
9223            .handle_control_frame(ctx, hello_frame_with_manifest(manifest, corr))
9224            .await
9225            .expect("capability test HELLO succeeds");
9226        assert!(
9227            matches!(replies.as_slice(), [Frame { header, .. }] if header.ty == FrameType::HelloAck),
9228            "capability test HELLO must register"
9229        );
9230    }
9231
9232    async fn open_route_for_capability_test(
9233        handler: &ControlHandler,
9234        target_ctx: &RouteCtx,
9235        target_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
9236        client_connection_id: u64,
9237        corr: u64,
9238        target_module_id: &str,
9239        consumer_identity: Option<ConsumerIdentity>,
9240    ) -> (
9241        mpsc::Receiver<crate::router::OutboundFrame>,
9242        ModuleControlRequest,
9243    ) {
9244        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(client_connection_id));
9245        let route_handler = handler.clone();
9246        let target_module_id = target_module_id.to_string();
9247        let route_task = tokio::spawn(async move {
9248            route_handler
9249                .handle_control_frame(
9250                    &client_ctx,
9251                    route_open_frame_with_admission_facts(
9252                        corr,
9253                        &target_module_id,
9254                        unique_project_root("admission-facts"),
9255                        consumer_identity,
9256                        None,
9257                    ),
9258                )
9259                .await
9260                .expect("capability test route.open succeeds")
9261        });
9262        let bind = tokio::time::timeout(Duration::from_secs(1), target_rx.recv())
9263            .await
9264            .expect("capability test route.open must reach route.bind")
9265            .expect("target control receiver stays open");
9266        let bind_request: ModuleControlRequest =
9267            serde_json::from_slice(&bind.body).expect("route.bind decodes");
9268        handler
9269            .handle_control_frame(target_ctx, route_bind_ack(bind.header.corr))
9270            .await
9271            .expect("capability test route.bind ACK succeeds");
9272        assert!(route_task.await.expect("route.open task joins").is_empty());
9273        let opened = client_rx
9274            .recv()
9275            .await
9276            .expect("successful route.open publishes a response");
9277        assert!(matches!(
9278            serde_json::from_slice::<ClientControlResponse>(&opened.body),
9279            Ok(ClientControlResponse::RouteOpen { .. })
9280        ));
9281        (client_rx, bind_request)
9282    }
9283
9284    fn assert_capability_denied_push(frame: Frame, target_module_id: &str) {
9285        assert_eq!(frame.header.ty, FrameType::Push);
9286        assert_eq!(frame.header.channel, 0);
9287        assert_eq!(
9288            serde_json::from_slice::<ClientControlPush>(&frame.body)
9289                .expect("route.closed control push decodes"),
9290            ClientControlPush::RouteClosed {
9291                module_id: target_module_id.to_string(),
9292                reason: RouteCloseReason::CapabilityDenied,
9293                drained: false,
9294                abandoned: 0,
9295                excluded_subscriptions: 0,
9296                terminal: Some(false),
9297            }
9298        );
9299    }
9300
9301    #[tokio::test]
9302    async fn route_open_capability_forbidden_mutation_proof_creates_no_route() {
9303        let registry = Arc::new(Registry::default());
9304        let forwarding = Arc::new(ForwardingTable::default());
9305        let supervisor = SupervisorHandle::new();
9306        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
9307        let handler =
9308            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
9309                .with_supervisor(supervisor);
9310        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(700));
9311        let (opener_ctx, _opener_rx) = route_ctx(ConnectionId::new(701));
9312        register_capability_manifest(
9313            &handler,
9314            &target_ctx,
9315            capability_manifest("target", &["credentials-provider/v1"], &[]),
9316            1,
9317        )
9318        .await;
9319        register_capability_manifest(
9320            &handler,
9321            &opener_ctx,
9322            capability_manifest("opener", &[], &["credentials-provider/v1"]),
9323            2,
9324        )
9325        .await;
9326
9327        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(702));
9328        let replies = handler
9329            .handle_control_frame(
9330                &client_ctx,
9331                route_open_frame_with_admission_facts(
9332                    3,
9333                    "target",
9334                    unique_project_root("admission-facts"),
9335                    Some(ConsumerIdentity {
9336                        module_id: "opener".to_string(),
9337                        launch_nonce: "opener-nonce".to_string(),
9338                    }),
9339                    None,
9340                ),
9341            )
9342            .await
9343            .expect("denied route.open returns a typed frame");
9344        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
9345        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
9346        assert!(
9347            target_rx.try_recv().is_err(),
9348            "forbidden route.open must not relay route.bind"
9349        );
9350    }
9351
9352    #[tokio::test]
9353    async fn capability_deny_edge_hello_mutation_proof_force_closes_existing_route() {
9354        let registry = Arc::new(Registry::default());
9355        let forwarding = Arc::new(ForwardingTable::default());
9356        let supervisor = SupervisorHandle::new();
9357        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
9358        let handler =
9359            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
9360                .with_supervisor(supervisor);
9361        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(710));
9362        let (old_opener_ctx, _old_opener_rx) = route_ctx(ConnectionId::new(711));
9363        register_capability_manifest(
9364            &handler,
9365            &target_ctx,
9366            capability_manifest("target", &["credentials-provider/v1"], &[]),
9367            1,
9368        )
9369        .await;
9370        register_capability_manifest(
9371            &handler,
9372            &old_opener_ctx,
9373            capability_manifest("opener", &[], &[]),
9374            2,
9375        )
9376        .await;
9377        let (mut client_rx, _) = open_route_for_capability_test(
9378            &handler,
9379            &target_ctx,
9380            &mut target_rx,
9381            712,
9382            3,
9383            "target",
9384            Some(ConsumerIdentity {
9385                module_id: "opener".to_string(),
9386                launch_nonce: "opener-nonce".to_string(),
9387            }),
9388        )
9389        .await;
9390        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
9391
9392        handler
9393            .cleanup_connection(old_opener_ctx.connection_id)
9394            .expect("old opener registration cleans up");
9395        let (new_opener_ctx, _new_opener_rx) = route_ctx(ConnectionId::new(713));
9396        register_capability_manifest(
9397            &handler,
9398            &new_opener_ctx,
9399            capability_manifest("opener", &[], &["credentials-provider/v1"]),
9400            4,
9401        )
9402        .await;
9403
9404        assert_capability_denied_push(
9405            client_rx
9406                .try_recv()
9407                .expect("HELLO deny addition must emit route.closed")
9408                .frame,
9409            "target",
9410        );
9411        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
9412        assert!(matches!(
9413            target_rx.try_recv(),
9414            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
9415        ));
9416    }
9417
9418    #[tokio::test]
9419    async fn capability_claim_catalog_update_mutation_proof_force_closes_existing_route() {
9420        let registry = Arc::new(Registry::default());
9421        let forwarding = Arc::new(ForwardingTable::default());
9422        let supervisor = SupervisorHandle::new();
9423        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
9424        let handler =
9425            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
9426                .with_supervisor(supervisor);
9427        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(720));
9428        let (opener_ctx, _opener_rx) = route_ctx(ConnectionId::new(721));
9429        register_capability_manifest(
9430            &handler,
9431            &target_ctx,
9432            capability_manifest("target", &[], &[]),
9433            1,
9434        )
9435        .await;
9436        register_capability_manifest(
9437            &handler,
9438            &opener_ctx,
9439            capability_manifest("opener", &[], &["credentials-provider/v1"]),
9440            2,
9441        )
9442        .await;
9443        let (mut client_rx, _) = open_route_for_capability_test(
9444            &handler,
9445            &target_ctx,
9446            &mut target_rx,
9447            722,
9448            3,
9449            "target",
9450            Some(ConsumerIdentity {
9451                module_id: "opener".to_string(),
9452                launch_nonce: "opener-nonce".to_string(),
9453            }),
9454        )
9455        .await;
9456        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
9457
9458        let replies = handler
9459            .handle_control_frame(
9460                &target_ctx,
9461                catalog_update_with_capabilities_frame(
9462                    4,
9463                    CapabilityDeclarations {
9464                        provides: vec!["credentials-provider/v1".to_string()],
9465                        requires: Vec::new(),
9466                        must_never_reach: Vec::new(),
9467                    },
9468                ),
9469            )
9470            .await
9471            .expect("claim catalog.update succeeds");
9472        assert!(matches!(
9473            serde_json::from_slice::<ModuleControlResponseToModule>(&replies[0].body),
9474            Ok(ModuleControlResponseToModule::CatalogUpdate {})
9475        ));
9476        assert_capability_denied_push(
9477            client_rx
9478                .try_recv()
9479                .expect("claim addition must emit route.closed")
9480                .frame,
9481            "target",
9482        );
9483        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
9484        assert!(matches!(
9485            target_rx.try_recv(),
9486            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
9487        ));
9488    }
9489
9490    #[tokio::test]
9491    async fn capability_claim_removal_mutation_proof_keeps_route_open_without_close_frame() {
9492        let registry = Arc::new(Registry::default());
9493        let forwarding = Arc::new(ForwardingTable::default());
9494        let supervisor = SupervisorHandle::new();
9495        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
9496        let handler =
9497            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
9498                .with_supervisor(supervisor);
9499        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(730));
9500        let (opener_ctx, _opener_rx) = route_ctx(ConnectionId::new(731));
9501        register_capability_manifest(
9502            &handler,
9503            &target_ctx,
9504            capability_manifest("target", &["credentials-provider/v1"], &[]),
9505            1,
9506        )
9507        .await;
9508        register_capability_manifest(
9509            &handler,
9510            &opener_ctx,
9511            capability_manifest("opener", &[], &[]),
9512            2,
9513        )
9514        .await;
9515        let (mut client_rx, _) = open_route_for_capability_test(
9516            &handler,
9517            &target_ctx,
9518            &mut target_rx,
9519            732,
9520            3,
9521            "target",
9522            Some(ConsumerIdentity {
9523                module_id: "opener".to_string(),
9524                launch_nonce: "opener-nonce".to_string(),
9525            }),
9526        )
9527        .await;
9528        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
9529
9530        handler
9531            .handle_control_frame(
9532                &target_ctx,
9533                catalog_update_with_capabilities_frame(
9534                    4,
9535                    CapabilityDeclarations {
9536                        provides: Vec::new(),
9537                        requires: Vec::new(),
9538                        must_never_reach: Vec::new(),
9539                    },
9540                ),
9541            )
9542            .await
9543            .expect("claim removal catalog.update succeeds");
9544        assert_eq!(
9545            forwarding.active_binding_count().unwrap(),
9546            1,
9547            "removing an attested target claim must leave the route census unchanged"
9548        );
9549        assert!(
9550            client_rx.try_recv().is_err(),
9551            "claim removal must not emit route.closed capability_denied"
9552        );
9553        assert!(
9554            target_rx.try_recv().is_err(),
9555            "claim removal must not send the target a route GOODBYE"
9556        );
9557    }
9558
9559    /// A direct client may open a route to a denied capability provider; this
9560    /// policy applies only to attested supervised module origins, not to direct clients.
9561    #[tokio::test]
9562    async fn direct_client_scope_honesty_mutation_proof_opens_denied_capability_provider() {
9563        let registry = Arc::new(Registry::default());
9564        let forwarding = Arc::new(ForwardingTable::default());
9565        let supervisor = SupervisorHandle::new();
9566        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
9567        let handler =
9568            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
9569                .with_supervisor(supervisor);
9570        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(740));
9571        let (opener_ctx, _opener_rx) = route_ctx(ConnectionId::new(741));
9572        register_capability_manifest(
9573            &handler,
9574            &target_ctx,
9575            capability_manifest("target", &["credentials-provider/v1"], &[]),
9576            1,
9577        )
9578        .await;
9579        register_capability_manifest(
9580            &handler,
9581            &opener_ctx,
9582            capability_manifest("opener", &[], &["credentials-provider/v1"]),
9583            2,
9584        )
9585        .await;
9586
9587        let (_client_rx, bind) = open_route_for_capability_test(
9588            &handler,
9589            &target_ctx,
9590            &mut target_rx,
9591            742,
9592            3,
9593            "target",
9594            None,
9595        )
9596        .await;
9597        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
9598            panic!("direct scope-honesty route must bind");
9599        };
9600        assert_eq!(principal, Some(Principal::Direct));
9601        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
9602    }
9603
9604    /// A module that denies a capability receives no self-route exemption when it
9605    /// also attestedly provides that capability.
9606    #[tokio::test]
9607    async fn must_never_reach_self_route_is_capability_forbidden() {
9608        let registry = Arc::new(Registry::default());
9609        let forwarding = Arc::new(ForwardingTable::default());
9610        let supervisor = SupervisorHandle::new();
9611        supervisor.set_spawn_nonce("self-provider", "self-nonce".to_string());
9612        let handler =
9613            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
9614                .with_supervisor(supervisor);
9615        let (self_ctx, mut self_rx) = route_ctx(ConnectionId::new(750));
9616        register_capability_manifest(
9617            &handler,
9618            &self_ctx,
9619            capability_manifest(
9620                "self-provider",
9621                &["credentials-provider/v1"],
9622                &["credentials-provider/v1"],
9623            ),
9624            1,
9625        )
9626        .await;
9627
9628        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(751));
9629        let replies = handler
9630            .handle_control_frame(
9631                &client_ctx,
9632                route_open_frame_with_admission_facts(
9633                    2,
9634                    "self-provider",
9635                    unique_project_root("admission-facts"),
9636                    Some(ConsumerIdentity {
9637                        module_id: "self-provider".to_string(),
9638                        launch_nonce: "self-nonce".to_string(),
9639                    }),
9640                    None,
9641                ),
9642            )
9643            .await
9644            .expect("self-route refusal returns a typed frame");
9645        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
9646        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
9647        assert!(
9648            self_rx.try_recv().is_err(),
9649            "self denial must not relay route.bind"
9650        );
9651    }
9652
9653    #[test]
9654    fn unsupported_channel_zero_frame_returns_error() {
9655        let handler = ControlHandler::default();
9656        let request = Frame::build(
9657            FrameType::Request,
9658            control_flags(),
9659            0,
9660            0,
9661            21,
9662            b"opaque".to_vec(),
9663        )
9664        .unwrap();
9665
9666        let response = handler
9667            .handle_control(ConnectionId::new(1), request)
9668            .unwrap();
9669
9670        assert_eq!(response[0].header.ty, FrameType::Error);
9671        assert_eq!(
9672            parse_error(&response[0])["code"],
9673            "unsupported_control_frame"
9674        );
9675    }
9676
9677    /// Blue/green swap at the control-plane boundary. The supervisor that opens
9678    /// a swap is not wired yet, so the candidate is registered here directly
9679    /// into the registry and forwarding candidate slots, the way the swap's
9680    /// HELLO admission will.
9681    mod swap {
9682        use super::*;
9683
9684        const INCUMBENT: ConnectionId = ConnectionId::new(30);
9685        const CANDIDATE: ConnectionId = ConnectionId::new(40);
9686
9687        struct Swap {
9688            registry: Arc<Registry>,
9689            forwarding: Arc<ForwardingTable>,
9690            handler: ControlHandler,
9691            incumbent_ctx: RouteCtx,
9692            incumbent_rx: mpsc::Receiver<crate::router::OutboundFrame>,
9693            candidate_ctx: RouteCtx,
9694            candidate_rx: mpsc::Receiver<crate::router::OutboundFrame>,
9695        }
9696
9697        async fn swap_with_incumbent() -> Swap {
9698            let registry = Arc::new(Registry::default());
9699            let forwarding = Arc::new(ForwardingTable::default());
9700            let handler =
9701                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
9702            let (incumbent_ctx, incumbent_rx) = route_ctx(INCUMBENT);
9703            handler
9704                .handle_control_frame(&incumbent_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
9705                .await
9706                .unwrap();
9707            let (candidate_ctx, candidate_rx) = route_ctx(CANDIDATE);
9708            Swap {
9709                registry,
9710                forwarding,
9711                handler,
9712                incumbent_ctx,
9713                incumbent_rx,
9714                candidate_ctx,
9715                candidate_rx,
9716            }
9717        }
9718
9719        fn register_candidate(swap: &Swap, ready: Option<bool>) {
9720            let mut candidate_manifest = manifest("aft", PROTOCOL_VERSION);
9721            candidate_manifest.ready = ready;
9722            let registration = swap
9723                .registry
9724                .register_candidate_with_control_ops(
9725                    candidate_manifest,
9726                    PROTOCOL_VERSION,
9727                    CANDIDATE,
9728                    module_baseline_control_ops(),
9729                )
9730                .unwrap();
9731            swap.forwarding
9732                .register_candidate_module_connection(
9733                    CANDIDATE,
9734                    "aft".to_string(),
9735                    PROTOCOL_VERSION,
9736                    manifest_concurrency(&registration.manifest),
9737                    swap.candidate_ctx.egress.clone(),
9738                )
9739                .unwrap();
9740        }
9741
9742        fn cutover(swap: &Swap) -> crate::forwarding::ModuleEndpointId {
9743            let cutover = swap.forwarding.cutover_candidate("aft").unwrap().unwrap();
9744            swap.registry.promote_candidate("aft").unwrap().unwrap();
9745            cutover.incumbent.unwrap()
9746        }
9747
9748        fn keyed_total(counters: &Value, key: &str) -> u64 {
9749            counters[key]
9750                .as_object()
9751                .map(|counts| counts.values().filter_map(Value::as_u64).sum())
9752                .unwrap_or(0)
9753        }
9754
9755        /// An ack from the incumbent for a bind it was sent before cutover,
9756        /// arriving before the incumbent is drained. The incumbent is the live
9757        /// connection carrying every other client's routes, so the ack must
9758        /// not end it: the waiting client is told to retry, the reservation is
9759        /// given back, and the incumbent is told to drop just that binding.
9760        #[tokio::test]
9761        async fn incumbent_ack_between_promotion_and_drain_keeps_the_incumbent_serving() {
9762            let mut swap = swap_with_incumbent().await;
9763            let handler = swap.handler.clone();
9764
9765            // A co-tenant route, bound on the incumbent before the swap.
9766            let cotenant = ConnectionId::new(31);
9767            let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
9768            let (cotenant_task, cotenant_bind) = relay_route_open(
9769                &handler,
9770                cotenant,
9771                &cotenant_ctx.egress,
9772                &mut swap.incumbent_rx,
9773                100,
9774                "aft",
9775                "swap-cotenant",
9776            )
9777            .await;
9778            handler
9779                .handle_control_frame(
9780                    &swap.incumbent_ctx,
9781                    route_bind_ack(cotenant_bind.header.corr),
9782                )
9783                .await
9784                .unwrap();
9785            assert!(cotenant_task.await.unwrap().is_empty());
9786            let (cotenant_channel, cotenant_epoch) =
9787                published_route(&cotenant_rx.recv().await.unwrap());
9788
9789            // A second route.open, relayed to the incumbent and not yet acked.
9790            let caller = ConnectionId::new(32);
9791            let (caller_ctx, mut caller_rx) = route_ctx(caller);
9792            let (caller_task, caller_bind) = relay_route_open(
9793                &handler,
9794                caller,
9795                &caller_ctx.egress,
9796                &mut swap.incumbent_rx,
9797                101,
9798                "aft",
9799                "swap-caller",
9800            )
9801            .await;
9802            let (abandoned_channel, abandoned_epoch) = route_bind_channel(&caller_bind);
9803
9804            register_candidate(&swap, None);
9805            cutover(&swap);
9806
9807            // The incumbent acks after promotion and before any drain.
9808            let ack = handler
9809                .handle_control_frame(&swap.incumbent_ctx, route_bind_ack(caller_bind.header.corr))
9810                .await;
9811            let module_loop_error = ack.as_ref().err().map(ToString::to_string);
9812            if module_loop_error.is_some() {
9813                // What the connection loop does with an untranslated router
9814                // error: end the connection, releasing every route on it.
9815                handler.cleanup_connection(INCUMBENT).unwrap();
9816            }
9817
9818            // 1. The incumbent's other routes survive.
9819            assert!(
9820                cotenant_rx.try_recv().is_err(),
9821                "the co-tenant route on the incumbent was torn down by one late ack: \
9822                 {module_loop_error:?}"
9823            );
9824            assert!(matches!(
9825                swap.forwarding
9826                    .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
9827                    .unwrap(),
9828                DataRoute::Client(DataRouteState::Bound(_))
9829            ));
9830            assert_eq!(module_loop_error, None);
9831            assert!(swap
9832                .registry
9833                .get_module_by_connection(INCUMBENT)
9834                .unwrap()
9835                .is_some());
9836
9837            // 2. Exactly one channel-scoped GOODBYE to the incumbent.
9838            let goodbye = tokio::time::timeout(Duration::from_secs(1), swap.incumbent_rx.recv())
9839                .await
9840                .expect("the incumbent is told to drop the abandoned binding")
9841                .unwrap()
9842                .frame;
9843            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
9844            assert_eq!(goodbye.header.channel, abandoned_channel);
9845            assert_eq!(goodbye.header.epoch, abandoned_epoch);
9846            assert!(swap.incumbent_rx.try_recv().is_err());
9847
9848            // 3. The waiting client gets a retryable refusal and no route.
9849            let response = caller_task.await.unwrap();
9850            assert_eq!(response.len(), 1);
9851            assert_eq!(parse_error(&response[0])["code"], "module_reloading");
9852            assert!(caller_rx.try_recv().is_err());
9853
9854            // 4. The reservation pair is given back, and the pending bind
9855            //    settled exactly once: one accepted open (the co-tenant) and one
9856            //    refused open (the caller), nothing counted twice.
9857            assert_eq!(swap.forwarding.reserved_route_count().unwrap(), (0, 0));
9858            let counters = handler.counters().snapshot();
9859            assert_eq!(
9860                keyed_total(&counters, "route_open_accepted_by_principal"),
9861                1
9862            );
9863            assert_eq!(keyed_total(&counters, "route_open_refused_by_code"), 1);
9864            assert_eq!(counters["route_open_refused_by_code"]["module_rejected"], 1);
9865        }
9866
9867        /// After cutover the incumbent is drained BY ENDPOINT. Draining by module
9868        /// id would resolve to the promoted candidate and every new route.open
9869        /// would be refused as reloading, leaving neither process routable.
9870        #[tokio::test]
9871        async fn route_open_after_cutover_and_incumbent_drain_is_relayed_to_the_candidate() {
9872            let mut swap = swap_with_incumbent().await;
9873            register_candidate(&swap, None);
9874            let incumbent = cutover(&swap);
9875            swap.forwarding
9876                .begin_endpoint_drain(incumbent, RouteCloseReason::Restart)
9877                .unwrap()
9878                .expect("the incumbent is still registered");
9879
9880            let client = ConnectionId::new(33);
9881            let (client_ctx, mut client_rx) = route_ctx(client);
9882            let route_handler = swap.handler.clone();
9883            let open_ctx = RouteCtx {
9884                connection_id: client,
9885                egress: client_ctx.egress.clone(),
9886            };
9887            let mut route_task = tokio::spawn(async move {
9888                route_handler
9889                    .handle_control_frame(
9890                        &open_ctx,
9891                        route_open_frame(90, "aft", unique_project_root("swap-after-drain")),
9892                    )
9893                    .await
9894                    .unwrap()
9895            });
9896            let bind = tokio::select! {
9897                bind = swap.candidate_rx.recv() => bind.expect("candidate egress is open").frame,
9898                response = &mut route_task => {
9899                    let response = response.unwrap();
9900                    panic!(
9901                        "post-cutover route.open was refused instead of relayed to the candidate: {}",
9902                        parse_error(&response[0])["code"]
9903                    );
9904                }
9905            };
9906            swap.handler
9907                .handle_control_frame(&swap.candidate_ctx, route_bind_ack(bind.header.corr))
9908                .await
9909                .unwrap();
9910            assert!(route_task.await.unwrap().is_empty());
9911            let (channel, epoch) = published_route(&client_rx.recv().await.unwrap());
9912            match swap
9913                .forwarding
9914                .lookup_data_route(client, channel, epoch)
9915                .unwrap()
9916            {
9917                DataRoute::Client(DataRouteState::Bound(route)) => {
9918                    assert_eq!(route.module_endpoint.connection_id, CANDIDATE)
9919                }
9920                other => panic!("expected a bound route on the candidate, got {other:?}"),
9921            }
9922            assert!(swap.incumbent_rx.try_recv().is_err());
9923        }
9924
9925        /// A candidate declares itself ready with `catalog.update` on its own
9926        /// connection. If the connection-keyed registry lookups searched only the
9927        /// active slot, this would answer `not_registered` and the candidate
9928        /// would never become ready.
9929        #[tokio::test]
9930        async fn candidate_catalog_update_ready_reaches_the_candidate_registration() {
9931            let swap = swap_with_incumbent().await;
9932            register_candidate(&swap, Some(false));
9933            let update = Frame::build(
9934                FrameType::Request,
9935                control_flags(),
9936                0,
9937                0,
9938                55,
9939                serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
9940                    provides: manifest("aft", PROTOCOL_VERSION).provides,
9941                    capabilities: None,
9942                    ready: Some(true),
9943                })
9944                .unwrap(),
9945            )
9946            .unwrap();
9947
9948            let replies = swap
9949                .handler
9950                .handle_control_frame(&swap.candidate_ctx, update)
9951                .await
9952                .unwrap();
9953
9954            assert_eq!(replies.len(), 1);
9955            assert_eq!(
9956                replies[0].header.ty,
9957                FrameType::Response,
9958                "candidate catalog.update was refused: {:?}",
9959                serde_json::from_slice::<Value>(&replies[0].body).ok()
9960            );
9961            assert!(swap.registry.get_candidate("aft").unwrap().unwrap().ready);
9962            assert_eq!(
9963                swap.registry
9964                    .get_module("aft")
9965                    .unwrap()
9966                    .unwrap()
9967                    .connection_id,
9968                INCUMBENT
9969            );
9970        }
9971    }
9972
9973    /// The HELLO gate while the supervisor has a swap open: only the nonce it
9974    /// minted for the candidate admits a second process, into the candidate
9975    /// slot, and that check runs ahead of the reserved-module gate.
9976    mod swap_admission {
9977        use super::*;
9978
9979        const INCUMBENT_NONCE: &str = "incumbent-nonce";
9980        const CANDIDATE_NONCE: &str = "candidate-nonce";
9981
9982        fn handler_with_incumbent(
9983            module_id: &str,
9984            reserved: bool,
9985        ) -> (Arc<Registry>, SupervisorHandle, ControlHandler) {
9986            let registry = Arc::new(Registry::default());
9987            let supervisor = SupervisorHandle::new();
9988            supervisor.set_spawn_nonce(module_id, INCUMBENT_NONCE.to_string());
9989            if reserved {
9990                supervisor.set_reserved_nonce(module_id, INCUMBENT_NONCE.to_string());
9991            }
9992            let handler =
9993                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor.clone());
9994            let incumbent = handler
9995                .handle_control(
9996                    ConnectionId::new(1),
9997                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 1, Some(INCUMBENT_NONCE)),
9998                )
9999                .unwrap();
10000            assert_eq!(incumbent[0].header.ty, FrameType::HelloAck);
10001            supervisor.open_swap(module_id, CANDIDATE_NONCE.to_string());
10002            (registry, supervisor, handler)
10003        }
10004
10005        /// Design mutation arm (ii). On an UNRESERVED id the reserved gate
10006        /// admits every nonce, so while a swap is open the swap gate is the only
10007        /// thing between a key-holder and the candidate slot. A nonce the
10008        /// supervisor did not mint, or none at all, is refused, and neither the
10009        /// incumbent's registration nor the candidate slot moves.
10010        #[test]
10011        fn unminted_nonce_on_an_unreserved_id_with_an_open_swap_is_refused() {
10012            let (registry, _supervisor, handler) = handler_with_incumbent("aft", false);
10013
10014            for (connection, nonce) in [(2, Some("forged")), (3, None)] {
10015                let replies = handler
10016                    .handle_control(
10017                        ConnectionId::new(connection),
10018                        hello_frame_with_nonce("aft", PROTOCOL_VERSION, connection, nonce),
10019                    )
10020                    .unwrap();
10021                assert_eq!(replies[0].header.ty, FrameType::Error);
10022                assert_eq!(
10023                    parse_error(&replies[0])["code"],
10024                    "swap_token_invalid",
10025                    "nonce {nonce:?}"
10026                );
10027            }
10028            assert!(registry.get_candidate("aft").unwrap().is_none());
10029            assert_eq!(
10030                registry.get_module("aft").unwrap().unwrap().connection_id,
10031                ConnectionId::new(1)
10032            );
10033
10034            // Control: the minted token is admitted, into the candidate slot,
10035            // and only once.
10036            let admitted = handler
10037                .handle_control(
10038                    ConnectionId::new(4),
10039                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 4, Some(CANDIDATE_NONCE)),
10040                )
10041                .unwrap();
10042            assert_eq!(admitted[0].header.ty, FrameType::HelloAck);
10043            assert_eq!(
10044                registry
10045                    .get_candidate("aft")
10046                    .unwrap()
10047                    .unwrap()
10048                    .connection_id,
10049                ConnectionId::new(4)
10050            );
10051            assert_eq!(
10052                registry.get_module("aft").unwrap().unwrap().connection_id,
10053                ConnectionId::new(1),
10054                "the candidate must not take the active slot"
10055            );
10056            let replayed = handler
10057                .handle_control(
10058                    ConnectionId::new(5),
10059                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 5, Some(CANDIDATE_NONCE)),
10060                )
10061                .unwrap();
10062            assert_eq!(parse_error(&replayed[0])["code"], "swap_token_invalid");
10063
10064            // The case only this gate covers: the incumbent has died mid-swap,
10065            // so its duplicate refusal is gone too, and without the gate a
10066            // key-holder would take the id's ACTIVE slot.
10067            handler.cleanup_connection(ConnectionId::new(1)).unwrap();
10068            let squatter = handler
10069                .handle_control(
10070                    ConnectionId::new(6),
10071                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 6, Some("forged")),
10072                )
10073                .unwrap();
10074            assert_eq!(parse_error(&squatter[0])["code"], "swap_token_invalid");
10075            assert!(
10076                registry.get_module("aft").unwrap().is_none(),
10077                "a squatter took the active slot of an id being swapped"
10078            );
10079        }
10080
10081        /// Design mutation arm (iii). A reserved module's candidate presents a
10082        /// nonce the reserved gate has never seen (that gate holds the
10083        /// incumbent's), so the swap gate must run first or the candidate is
10084        /// refused `reserved_module` and a reserved module can never be swapped.
10085        #[test]
10086        fn reserved_module_candidate_is_admitted_ahead_of_the_reserved_gate() {
10087            let (registry, _supervisor, handler) = handler_with_incumbent("vault", true);
10088
10089            let replies = handler
10090                .handle_control(
10091                    ConnectionId::new(2),
10092                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
10093                )
10094                .unwrap();
10095
10096            assert_eq!(
10097                replies[0].header.ty,
10098                FrameType::HelloAck,
10099                "reserved candidate refused: {:?}",
10100                serde_json::from_slice::<Value>(&replies[0].body).ok()
10101            );
10102            assert_eq!(
10103                registry
10104                    .get_candidate("vault")
10105                    .unwrap()
10106                    .unwrap()
10107                    .connection_id,
10108                ConnectionId::new(2)
10109            );
10110        }
10111
10112        /// With no swap open the gate is inert: the incumbent's reserved gate
10113        /// and duplicate refusal behave exactly as before.
10114        #[test]
10115        fn without_an_open_swap_the_ordinary_gates_decide() {
10116            let (registry, supervisor, handler) = handler_with_incumbent("vault", true);
10117            supervisor.close_swap("vault");
10118
10119            let candidate = handler
10120                .handle_control(
10121                    ConnectionId::new(2),
10122                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
10123                )
10124                .unwrap();
10125            assert_eq!(parse_error(&candidate[0])["code"], "reserved_module");
10126            let duplicate = handler
10127                .handle_control(
10128                    ConnectionId::new(3),
10129                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some(INCUMBENT_NONCE)),
10130                )
10131                .unwrap();
10132            assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
10133            assert!(registry.get_candidate("vault").unwrap().is_none());
10134        }
10135    }
10136}
10137
10138#[cfg(test)]
10139mod concurrency_default_exposure_tests {
10140    use super::*;
10141
10142    fn hello_body(role_json: &str) -> Vec<u8> {
10143        format!(
10144            r#"{{"protocol_ver":2,"module_id":"m","manifest":{{"module_id":"m","module_version":"1.0.0","protocol_ver":2,"trust_tier":"first_party","provides":[{role_json}],"consumes":[],"bindings":{{"storage":{{"kind":"sqlite","scope":"project","owns_schema":false}},"vault_grants":[],"identity":{{"requires":[],"optional":[]}}}}}}}}"#
10145        )
10146        .into_bytes()
10147    }
10148
10149    fn manifest_from(body: &[u8]) -> ModuleManifest {
10150        let value: serde_json::Value = serde_json::from_slice(body).expect("hello parses");
10151        serde_json::from_value(value.get("manifest").expect("manifest key").clone())
10152            .expect("manifest parses")
10153    }
10154
10155    const SURFACE_TAIL: &str = r#""operations":[],"config_schema":{"type":"object"},"observability":[],"identity_scope":[]"#;
10156
10157    #[test]
10158    fn absent_concurrency_on_management_surface_is_reported_as_defaulted() {
10159        let body = hello_body(&format!(
10160            r#"{{"role":"management_surface",{SURFACE_TAIL}}}"#
10161        ));
10162        let manifest = manifest_from(&body);
10163        // Precondition: serde really resolved it to the default, so the typed
10164        // manifest alone cannot answer the question this probe exists for.
10165        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
10166        assert!(manifest_concurrency_was_defaulted(&body, &manifest));
10167    }
10168
10169    #[test]
10170    fn declared_concurrency_is_not_reported_even_when_it_equals_the_default() {
10171        let body = hello_body(&format!(
10172            r#"{{"role":"management_surface",{SURFACE_TAIL},"concurrency":"module_managed"}}"#
10173        ));
10174        let manifest = manifest_from(&body);
10175        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
10176        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
10177    }
10178
10179    #[test]
10180    fn non_management_roles_are_never_reported() {
10181        let body = hello_body(
10182            r#"{"role":"internal_service","service_id":"s","transport":"bulk","agent_facing":false,"operations":[]}"#,
10183        );
10184        let manifest = manifest_from(&body);
10185        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
10186    }
10187}