Skip to main content

subc_daemon/
control.rs

1#[path = "control/list_diagnostics.rs"]
2pub(crate) mod list_diagnostics;
3mod route_open_refusal_log;
4
5use std::{
6    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
7    fmt,
8    net::SocketAddr,
9    path::{Path, PathBuf},
10    sync::{Arc, Mutex, RwLock},
11    time::{Duration, Instant as StdInstant},
12};
13
14use crate::scopes::admission::denied_capability;
15use serde::{Deserialize, Serialize};
16use subc_control::{
17    ops, CapabilityRequirementStatus, CatalogEntry, ClientControlPush, ClientControlRequest,
18    ClientControlResponse, ConsumerIdentity, DaemonBuildProvenance, DaemonObservedProcess,
19    ModuleDeclaredProvenance, ModuleProtocol, NotReadyReason, PendingReloadVerdict, PollKind,
20    ReloadPathAgreement, ReloadPathUnavailableReason, RouteCloseReason, SpawnCursor,
21    StderrCaptureState, StderrTail, StderrTailEntry, SupervisorDaemonProvenance, SupervisorEntry,
22    SupervisorHealthEntry, SupervisorModuleProvenance, SupervisorObservedProcess,
23    SupervisorRescanResult, SupervisorRoute, SupervisorRouteConsumer, SupervisorRouteModule,
24};
25use subc_protocol::{
26    call_mode::{derive_call_mode, CALL_MODES_CAPABILITY},
27    error_codes,
28    manifest::{
29        validate_hello_capability_grammar, validate_hello_confirm_operations,
30        validate_hello_display_name, validate_hello_event_declarations,
31        validate_hello_flow_operations, validate_hello_operation_deferral,
32        validate_hello_rich_ui_descriptor, validate_hello_role_declarations,
33        validate_hello_self_signal_declarations, validate_role_declarations_value,
34        CapabilityDeclarations, CapabilityNeed, Concurrency, ManifestProvenance, ModuleManifest,
35        ProviderRole,
36    },
37    peer::{
38        ObservedPeer, RouteBindPeer, OBSERVED_PEER_CAPABILITY, OPERATOR_APP_CAPABILITY,
39        PEER_BUILD_CAPABILITY,
40    },
41    provider_declarations::ProviderDeclarations,
42    scope::{
43        ScopeEnd, ScopeRecord, ScopeRecordOutcome, ScopeRecordResult, ScopeSelector,
44        CAP_ROUTE_ROLE_VERSIONS_V1, CAP_SCOPES_V1, SCOPE_APPLY_OP, SCOPE_DESCRIBE_OP,
45        SCOPE_SYNC_OP,
46    },
47    session::{
48        validate_role_versions, HealthReport, ModuleControlPush, ModuleControlRequest,
49        ModuleControlRequestFromModule, ModuleControlResponse, ModuleControlResponseToModule,
50        OperatorConfirmRequest, MODULE_CONTROL_OP_HEALTH_CHECK, MODULE_TO_SUBC_OP_CATALOG_UPDATE,
51        MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS, ROLE_VERSIONS_FIELD,
52    },
53    BindIdentity, ErrorBody, Flags, FrameType, ModuleHelloAckBody, ModuleHelloBody, Principal,
54    Priority, RouteTarget, PROTOCOL_VERSION,
55};
56use tokio::time::{timeout_at, Instant};
57use tracing::{debug, info, instrument::WithSubscriber, warn};
58
59use crate::{
60    caller_identity::CallerIdentity,
61    capability_requirements::{
62        log_duplicate_claim_events, log_manifest_change, log_requirement_events,
63        CapabilityRequirementEvaluator, CapabilityVerdict, DuplicateClaimSource, RegisteredModule,
64        RequirementStatus, RuntimeModule,
65    },
66    child_roster::DaemonShutdownFlag,
67    daemon_config::{PrivilegedOperatorPrompt, RestartRequiredSection},
68    forwarding::{
69        CloseReason, EndpointRoute, ForwardingError, ForwardingTable, GoodbyeTarget,
70        ModuleControlRpcCompletion, ModuleControlRpcOutcome, ModuleEndpointId,
71        PendingModuleControlRpc, RouteBindRelayOutcome, RoutePollSnapshot, RouteRelease,
72    },
73    observability::{
74        ROUTE_OPEN_REFUSED_DECLARED_NOT_READY, ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED,
75    },
76    privileged_prompt::{prompt_text, PrivilegedOperation},
77    provenance::{
78        process_start_time, spawned_file_identity, ExecutableIdentityProbe, SpawnedFileIdentity,
79    },
80    registry::{ChannelState, ConnectionId, RegistrationEndReason, Registry, RegistryError},
81    router::{daemon_error_flags, RouteCtx, RouterError},
82    scopes::{HelloLaunchNonces, ScopeRecords, ScopeTable},
83    server::MAX_PENDING_ROUTE_BINDS_PER_TARGET,
84    stderr_tail::{CaptureState, TailEntry},
85    supervise::{
86        validate_spec, ModuleProcessLiveness, ReservedHelloRejection, ReservedHelloVerification,
87        SpawnSubscribeRefusal, SupervisorHandle, SwapHelloAdmission,
88    },
89    ConnectedClients, DaemonCounters, Frame, ProjectRootId, Supervisor,
90};
91
92/// Lowest envelope version this subc build will negotiate.
93///
94/// Module HELLO negotiation is exact: peers must use the daemon's locked
95/// protocol version. Older and newer peers receive `version_unsupported` and
96/// are not registered.
97pub const MIN_SUPPORTED_VERSION: u8 = PROTOCOL_VERSION;
98
99mod route_open;
100use route_open::is_routable_role;
101use route_open::principal_label;
102#[cfg(test)]
103use route_open::RouteBindAdmission;
104pub(crate) use route_open::RouteBindBreakers;
105pub(crate) use route_open::RouteBindConcurrency;
106use route_open::RouteOpenCaller;
107use route_open::RouteOpenRequest;
108use route_open::RouteOpenTimings;
109pub use route_open::DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN;
110pub use route_open::DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD;
111pub use route_open::DEFAULT_ROUTE_BIND_RELAY_TIMEOUT;
112
113mod server_describe;
114use server_describe::subc_ops;
115use server_describe::CAP_ADMISSION_FACTS_RELAY;
116use server_describe::CAP_CHANNEL_LIFECYCLE;
117use server_describe::CAP_MANIFEST_REGISTRATION;
118use server_describe::CAP_PING_PONG;
119use server_describe::CAP_SESSION_ATTACH;
120
121mod supervisor_operations;
122use supervisor_operations::launch_spec_agreement;
123#[cfg(test)]
124use supervisor_operations::reload_verdict;
125use supervisor_operations::DaemonProvenanceFacts;
126use supervisor_operations::ModuleControlRpcGuard;
127use supervisor_operations::DEFAULT_HEALTH_PROBE_TIMEOUT;
128
129mod activity;
130#[cfg(test)]
131use activity::ActivityRequestPause;
132
133mod scopes;
134#[cfg(test)]
135use scopes::ScopeOutcomeCounts;
136
137mod module_operations;
138use module_operations::is_known_module_request_op;
139use module_operations::manifest_concurrency;
140#[cfg(test)]
141use module_operations::manifest_concurrency_was_defaulted;
142#[cfg(test)]
143use module_operations::module_baseline_control_ops;
144use module_operations::module_control_request_op;
145use module_operations::module_registration_grants_op;
146use module_operations::parse_module_control_request_from_module;
147#[cfg(all(test, unix, feature = "test-support"))]
148use module_operations::MODULE_TO_SUBC_UNADVERTISED_OPS;
149mod advertised_ops;
150use advertised_ops::*;
151mod caller_attestation;
152mod channel_operations;
153#[cfg(all(test, unix, feature = "test-support"))]
154#[path = "control/channel_operations_tests.rs"]
155mod channel_operations_tests;
156pub(crate) mod claims;
157#[cfg(test)]
158#[path = "control/config_advertisement_tests.rs"]
159mod config_advertisement_tests;
160mod config_gate;
161#[path = "operator_apps/connection.rs"]
162mod peer_identity;
163use caller_attestation::scope_acts_for_another;
164mod activity_reservations;
165#[cfg(all(test, unix, feature = "test-support"))]
166#[path = "control/caller_attestation_tests.rs"]
167mod caller_attestation_tests;
168mod capability_census;
169use capability_census::append_capability_problem_detail;
170use capability_census::capability_census_trigger;
171mod route_bind_settlement;
172mod scope_expiry;
173mod scope_watch;
174mod usage;
175
176mod agent_commands;
177pub(crate) mod catalog;
178mod policy_root;
179mod rescan_checked;
180pub(crate) mod upgrade_in_place;
181use rescan_checked::RescanMode;
182use rescan_checked::SupervisorRescanContext;
183
184const SLOW_CONTROL_DISPATCH_THRESHOLD: Duration = Duration::from_secs(1);
185
186/// A test hold: signal arrival, then wait for release on the holding thread.
187#[cfg(test)]
188type TestPause = (
189    tokio::sync::oneshot::Sender<()>,
190    std::sync::mpsc::Receiver<()>,
191);
192
193/// A test hook run once at a fixed point in a handler.
194#[cfg(test)]
195type TestHook = Box<dyn FnOnce() + Send>;
196
197/// A test hold for async code: signal arrival, then await release.
198#[cfg(test)]
199type AsyncTestPause = (
200    tokio::sync::oneshot::Sender<()>,
201    tokio::sync::oneshot::Receiver<()>,
202);
203
204/// Accept-time diagnostics, kept apart from peer observations used for trust.
205#[derive(Clone)]
206pub(crate) enum RouteOpenerConnection {
207    Local(Option<subc_os::local_peer::DiagnosticProcess>),
208    Tcp,
209}
210
211/// Real channel-0 control handler for subc itself.
212#[derive(Clone)]
213pub struct ControlHandler {
214    #[cfg(test)]
215    activity_request_pause: Arc<Mutex<Option<Arc<ActivityRequestPause>>>>,
216    /// Holds connection cleanup at a numbered point: 0 is just after the agent
217    /// declaration queue closes, 1 just after the registration channel is
218    /// forgotten.
219    #[cfg(test)]
220    cleanup_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
221    /// Runs once in `route.open`'s launch-nonce attestation, right after the
222    /// nonce is resolved, to interleave a nonce withdrawal there.
223    #[cfg(test)]
224    after_nonce_attestation: Arc<Mutex<Option<TestHook>>>,
225    /// Holds a registration channel's HELLO after its reader resolved the
226    /// channel and before the blocking HELLO handler starts.
227    #[cfg(test)]
228    hello_ingress_pause: Arc<Mutex<Option<AsyncTestPause>>>,
229    /// Holds an agent command declaration at a numbered point in its handler.
230    #[cfg(test)]
231    agent_commands_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
232    claims: Arc<claims::Claims>,
233    registry: Arc<Registry>,
234    control_usage: Arc<Mutex<usage::ControlUsage>>,
235    catalog_cache: Arc<Mutex<catalog::CatalogCache>>,
236    catalog_readiness_revision: Arc<std::sync::atomic::AtomicU64>,
237    config_runtime: Option<Arc<crate::config_gate::runtime::RuntimeOwner>>,
238    config_review_admission: Arc<dyn crate::config_gate::ReviewAdmission>,
239    config_review_admission_is_default: bool,
240    activity: Option<crate::activity::ActivityLedger>,
241    activity_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
242    activity_reservations: activity_reservations::ActivityReservations,
243    catalog_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
244    config_settings_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
245    scope_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
246    forwarding: Arc<ForwardingTable>,
247    process_liveness: Option<Arc<dyn ModuleProcessLiveness>>,
248    supervisor: SupervisorHandle,
249    pub(crate) resource_tracker: Arc<crate::resource_totals::Tracker>,
250    agent_declarations: agent_commands::Queues,
251    list_admission: Arc<tokio::sync::Semaphore>,
252    subc_capabilities: Arc<[String]>,
253    /// Daemon-wide route.bind relay budget. Used as the fallback when the
254    /// target module has no per-module override in
255    /// `route_bind_relay_timeouts`.
256    route_bind_relay_timeout: Duration,
257    /// Per-module route.bind relay budget overrides, keyed by module id. When
258    /// `handle_route_open` resolves the deadline for a target module, a
259    /// per-module entry wins over the daemon-wide value above.
260    route_bind_relay_timeouts: BTreeMap<String, Duration>,
261    /// Per-target-module bind-relay breaker state. Shared with the forwarding
262    /// table, which is where a new module connection resets it.
263    route_bind_breakers: RouteBindBreakers,
264    /// Live relay admissions keyed by target module. Shared through the
265    /// forwarding table so cloned or separately built handlers enforce one cap.
266    route_bind_concurrency: RouteBindConcurrency,
267    /// Start and end of each module's not-serving period as seen by
268    /// `route.open`, so an outage gets one line at each edge instead of only
269    /// the per-refusal INFO lines. Taken from the forwarding table, so every
270    /// handler built over one table shares it.
271    route_outages: Arc<crate::route_outage::RouteOutageTracker>,
272    route_refusal_log: route_open_refusal_log::RefusalLog,
273    /// Consecutive relay timeouts that open a module's breaker.
274    route_bind_breaker_threshold: u32,
275    /// How long a breaker stays open before one probe is admitted.
276    route_bind_breaker_cooldown: Duration,
277    health_probe_timeout: Duration,
278    /// Central storage policy. When set, each registering module receives its
279    /// resolved storage descriptor in HELLO_ACK; `None` leaves the field absent.
280    storage_config: Option<crate::daemon_config::StorageConfig>,
281    /// The machine id established at boot, served on every HELLO_ACK and on
282    /// `server.describe`. Fixed for the daemon's lifetime: `ck machine adopt`
283    /// changes the file, never this value. `None` serves no id.
284    machine_id: Option<crate::machine_id::MachineId>,
285    admission_facts_carrier_module_id: Option<String>,
286    admission_facts_targets: Option<Vec<String>>,
287    /// Scope records with their sync authorities and tombstones; see
288    /// `crate::scopes`. Shared by clones of this handler, so every connection
289    /// reads and writes one table.
290    scopes: Arc<RwLock<ScopeTable>>,
291    /// Wakes the expiry loop when an accepted scope change may have added a
292    /// deadline, so the loop can wait without ticking while no live scope has
293    /// one. A permit is stored when nothing waits, so no wake is lost.
294    scope_deadline_added: Arc<tokio::sync::Notify>,
295    /// The configured `scope_authority_owners`, kept so a rescan can report a
296    /// changed value as needing a daemon restart; rescan never applies it.
297    scope_authority_owners: Vec<String>,
298    flow_scope_authority_owners: Vec<String>,
299    federated_scope_owner: String,
300    /// Fixed at startup so rescan cannot change the policy that guards rescan itself.
301    privileged_operator_prompt: PrivilegedOperatorPrompt,
302    /// The local and peer address of each accepted TCP client connection, read
303    /// from the daemon's own socket, so a privileged request can name its caller.
304    caller_endpoints: Arc<Mutex<HashMap<ConnectionId, (SocketAddr, SocketAddr)>>>,
305    route_openers: Arc<Mutex<HashMap<ConnectionId, RouteOpenerConnection>>>,
306    build_class_warned: Arc<Mutex<HashSet<ConnectionId>>>,
307    observed_peers: Arc<Mutex<HashMap<ConnectionId, ObservedPeer>>>,
308    captured_peers: Arc<Mutex<HashMap<ConnectionId, Arc<peer_identity::PeerCapture>>>>,
309    config_desktop_stamps:
310        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
311    local_connections: Arc<Mutex<HashSet<ConnectionId>>>,
312    pub(crate) operator_app_policy: crate::operator_apps::OperatorAppPolicy,
313    pub(crate) operator_apps:
314        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
315    /// One launch entry per app, behind a leaf lock: no other lock is taken
316    /// while it is held. Entries are memory-only, so a daemon or
317    /// installed-service restart drops them and a relaunched daemon never
318    /// mistakes an older process for its own launch.
319    pub(crate) launch_table: std::sync::Arc<crate::app_open::LaunchTable>,
320    /// Serializes `app.open` launches: the liveness check in the decision and
321    /// the later publish must not interleave across concurrent calls, or two
322    /// calls could both launch and the second publish would orphan the first
323    /// process. Refusals and `already_running` answers share the same lock;
324    /// `app.open` is rare, so the cost is negligible.
325    pub(crate) app_open_launch_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
326    // Portable wire samples exercise dispatch without starting an OS process.
327    #[cfg(test)]
328    pub(crate) app_open_test_platform: Option<crate::operator_apps::AppOpenPlatform>,
329    #[cfg(test)]
330    pub(crate) app_open_test_launch: Option<fn() -> Result<u32, crate::app_open::AppOpenRefusal>>,
331    #[cfg(test)]
332    pub(crate) config_review_test_reply: Option<subc_protocol::config::ConfigReviewReply>,
333    #[cfg(test)]
334    pub(crate) config_review_test_replies:
335        std::collections::BTreeMap<String, subc_protocol::config::ConfigReviewReply>,
336    #[cfg(test)]
337    pub(crate) config_review_test_seen: Option<tokio::sync::mpsc::UnboundedSender<String>>,
338    #[cfg(test)]
339    pub(crate) config_review_test_refuse: Arc<std::sync::Mutex<std::collections::BTreeSet<String>>>,
340    #[cfg(test)]
341    pub(crate) config_review_test_fail_once: Arc<std::sync::atomic::AtomicBool>,
342    #[cfg(test)]
343    recovery_exit_test_after_step: Option<fn(usize) -> Result<(), crate::config_gate::GateError>>,
344    #[cfg(test)]
345    recovery_exit_test_completed: Option<fn(u64)>,
346    #[cfg(test)]
347    apply_reconcile_pause: Arc<Mutex<Option<AsyncTestPause>>>,
348    #[cfg(test)]
349    recovery_exit_test_quiet_retry: bool,
350    #[cfg(test)]
351    recovery_exit_test_retry_pause: Option<fn(u64) -> Option<PathBuf>>,
352    #[cfg(test)]
353    config_delivery_test_wakes:
354        Option<tokio::sync::mpsc::UnboundedSender<(&'static str, tokio::time::Instant)>>,
355    #[cfg(all(test, unix))]
356    config_delivery_test_idle:
357        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
358    #[cfg(all(test, unix))]
359    settings_poll_test_idle:
360        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
361    /// Test-only Windows signature and flash hooks. Production builds carry
362    /// neither: with the publisher unset, the production table never reaches
363    /// verification, and the default attention hook only logs.
364    #[allow(dead_code)]
365    #[cfg(windows)]
366    pub(crate) windows_verify: Option<crate::app_open::WindowsVerifyFn>,
367    #[allow(dead_code)]
368    #[cfg(windows)]
369    pub(crate) windows_flash: Option<crate::app_open::WindowsFlashFn>,
370    /// Test-only tracking fault hook: makes opening the tracking handle on
371    /// the launched pid fail, so a test can prove an untrackable launch is
372    /// stopped rather than left running.
373    #[allow(dead_code)]
374    #[cfg(windows)]
375    pub(crate) windows_track: Option<crate::app_open::WindowsTrackFn>,
376    /// Test-only count of Windows spawn attempts, so a test can prove a
377    /// refused launch started no process. Unit tests only.
378    #[cfg(all(test, windows))]
379    pub(crate) windows_spawn_attempts: Arc<std::sync::atomic::AtomicU64>,
380    #[cfg(test)]
381    caller_lookup: Option<TestCallerLookup>,
382    /// The launch nonce each module connection presented at HELLO, which is how
383    /// a `scope.sync` is matched to the owner's current launch.
384    hello_launch_nonces: Arc<Mutex<HelloLaunchNonces>>,
385    rescan: Option<SupervisorRescanContext>,
386    connected_clients: ConnectedClients,
387    counters: DaemonCounters,
388    /// Why this daemon serves no local endpoint, when binding one failed. `None`
389    /// when the endpoint is served, and also on a handler that was never told.
390    local_endpoint_unavailable: Option<String>,
391    capability_evaluator: Arc<CapabilityRequirementEvaluator>,
392    /// The supervisor's daemon-shutdown flag. Once it is set, requirement
393    /// changes are logged at INFO with `cause=daemon_shutdown` instead of at
394    /// their usual severity (see [`log_requirement_events`]). A handler built
395    /// without one has a flag that is never set.
396    daemon_shutdown: DaemonShutdownFlag,
397    #[cfg(any(target_os = "linux", target_os = "macos"))]
398    pub(crate) upgrade: Option<Arc<upgrade_in_place::Runtime>>,
399    daemon_provenance: DaemonProvenanceFacts,
400    #[cfg(test)]
401    control_dispatch_delay: Option<Duration>,
402    #[cfg(test)]
403    provenance_probe_override: Option<subc_control::RunningImageAgreement>,
404    /// Holds `route.open` after the route.bind is queued to the module and
405    /// before it is marked enqueued, so a test can make the module's reply (or
406    /// a client teardown) land exactly inside that window.
407    #[cfg(test)]
408    route_bind_relay_sent_hold: Option<Arc<tokio::sync::Barrier>>,
409    /// Holds a HELLO after its registry entry is reserved and before its
410    /// forwarding endpoint is installed, so a test can read the catalog and
411    /// open routes while the module is registered but not yet routable. A
412    /// blocking barrier because the HELLO handler is synchronous; the test
413    /// runs the HELLO on its own thread.
414    #[cfg(test)]
415    hello_registry_to_forwarding_hold: Option<Arc<std::sync::Barrier>>,
416    #[cfg(test)]
417    hello_ack_to_publication_hold: Option<Arc<std::sync::Barrier>>,
418    #[cfg(test)]
419    hello_before_publication_hold: Option<Arc<std::sync::Barrier>>,
420    #[cfg(test)]
421    hello_after_launch_check_hold: Option<Arc<std::sync::Barrier>>,
422    #[cfg(test)]
423    hello_inside_publication_hold: Option<Arc<std::sync::Barrier>>,
424}
425
426impl fmt::Debug for ControlHandler {
427    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428        f.debug_struct("ControlHandler")
429            .field("registry", &self.registry)
430            .field("forwarding", &self.forwarding)
431            .field("process_liveness", &self.process_liveness.is_some())
432            .field("supervisor", &self.supervisor)
433            .field("subc_capabilities", &self.subc_capabilities)
434            .finish()
435    }
436}
437
438impl ControlHandler {
439    pub(crate) fn install_registration_service(
440        &self,
441        router: std::sync::Weak<crate::Router>,
442        auth: crate::server::ServerAuth,
443    ) {
444        self.supervisor.install_registration_service(router, auth);
445    }
446    pub fn new(registry: Arc<Registry>) -> Self {
447        Self::with_forwarding(registry, Arc::new(ForwardingTable::default()))
448    }
449
450    pub fn with_forwarding(registry: Arc<Registry>, forwarding: Arc<ForwardingTable>) -> Self {
451        let counters = forwarding.counters();
452        // Taken from the forwarding table rather than created here, so that the
453        // breaker a `route.open` consults is the same one a module's
454        // registration resets, however many handlers are built over one table.
455        let route_bind_breakers = forwarding.route_bind_breakers();
456        let route_bind_concurrency = forwarding.route_bind_concurrency();
457        let route_outages = forwarding.route_outages();
458        Self {
459            registry,
460            control_usage: Arc::new(Mutex::new(usage::ControlUsage::default())),
461            catalog_cache: Arc::new(Mutex::new(catalog::CatalogCache::default())),
462            catalog_readiness_revision: Arc::new(std::sync::atomic::AtomicU64::new(0)),
463            #[cfg(test)]
464            activity_request_pause: Arc::new(Mutex::new(None)),
465            #[cfg(test)]
466            cleanup_pause: Arc::new(Mutex::new(None)),
467            #[cfg(test)]
468            after_nonce_attestation: Arc::new(Mutex::new(None)),
469            #[cfg(test)]
470            hello_ingress_pause: Arc::new(Mutex::new(None)),
471            #[cfg(test)]
472            agent_commands_pause: Arc::new(Mutex::new(None)),
473            claims: Arc::new(claims::Claims::default()),
474            config_runtime: None,
475            config_review_admission: Arc::new(crate::config_gate::MissingReviewAdmission),
476            config_review_admission_is_default: true,
477            activity: None,
478            activity_streams: Arc::new(Mutex::new(HashMap::new())),
479            activity_reservations: Default::default(),
480            catalog_streams: Arc::new(Mutex::new(HashMap::new())),
481            config_settings_streams: Arc::new(Mutex::new(HashMap::new())),
482            scope_streams: Arc::new(Mutex::new(HashMap::new())),
483            forwarding,
484            process_liveness: None,
485            supervisor: SupervisorHandle::new(),
486            resource_tracker: Arc::new(crate::resource_totals::Tracker::new(
487                env!("CARGO_PKG_VERSION").to_owned(),
488            )),
489            agent_declarations: agent_commands::Queues::default(),
490            list_admission: Arc::new(tokio::sync::Semaphore::new(4)),
491            subc_capabilities: Arc::from([
492                CAP_MANIFEST_REGISTRATION.to_string(),
493                CAP_CHANNEL_LIFECYCLE.to_string(),
494                CAP_PING_PONG.to_string(),
495                CAP_SESSION_ATTACH.to_string(),
496                CAP_ADMISSION_FACTS_RELAY.to_string(),
497                CAP_SCOPES_V1.to_string(),
498                subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY.to_string(),
499                subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY.to_string(),
500                subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY.to_string(),
501                PEER_BUILD_CAPABILITY.to_string(),
502                CAP_ROUTE_ROLE_VERSIONS_V1.to_string(),
503                subc_protocol::manifest::CAP_CATALOG_EVENTS_V1.to_string(),
504                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1.to_string(),
505                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2.to_string(),
506                subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1.to_string(),
507                subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY.to_string(),
508                subc_protocol::scope::WORKER_RUNS_CAPABILITY.to_string(),
509                subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY.to_string(),
510                subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY.to_string(),
511                subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.to_string(),
512                subc_control::ACTIVITY_LEDGER_CAPABILITY.to_string(),
513                subc_protocol::ROUTE_CLOSE_REASONS_CAPABILITY.to_string(),
514                subc_protocol::session::ACCEPTING_DRAIN_CAPABILITY.to_string(),
515            ]),
516            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
517            route_bind_relay_timeouts: BTreeMap::new(),
518            route_bind_breakers,
519            route_bind_concurrency,
520            route_outages,
521            route_refusal_log: Default::default(),
522            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
523            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
524            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
525            storage_config: None,
526            machine_id: None,
527            admission_facts_carrier_module_id: None,
528            admission_facts_targets: None,
529            scopes: Arc::new(RwLock::new(ScopeTable::new(
530                crate::daemon_config::default_scope_authority_owners(),
531            ))),
532            scope_deadline_added: Arc::new(tokio::sync::Notify::new()),
533            scope_authority_owners: crate::daemon_config::default_scope_authority_owners(),
534            flow_scope_authority_owners: Vec::new(),
535            federated_scope_owner: crate::daemon_config::default_federated_scope_owner(),
536            privileged_operator_prompt: PrivilegedOperatorPrompt::default(),
537            caller_endpoints: Arc::new(Mutex::new(HashMap::new())),
538            route_openers: Arc::new(Mutex::new(HashMap::new())),
539            build_class_warned: Arc::new(Mutex::new(HashSet::new())),
540            observed_peers: Arc::new(Mutex::new(HashMap::new())),
541            captured_peers: Arc::new(Mutex::new(HashMap::new())),
542            config_desktop_stamps: Arc::new(Mutex::new(HashMap::new())),
543            local_connections: Arc::new(Mutex::new(HashSet::new())),
544            operator_app_policy: Default::default(),
545            operator_apps: Arc::new(Mutex::new(HashMap::new())),
546            launch_table: std::sync::Arc::new(crate::app_open::LaunchTable::new()),
547            app_open_launch_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
548            #[cfg(test)]
549            app_open_test_platform: None,
550            #[cfg(test)]
551            app_open_test_launch: None,
552            #[cfg(test)]
553            config_review_test_reply: None,
554            #[cfg(test)]
555            config_review_test_replies: Default::default(),
556            #[cfg(test)]
557            config_review_test_seen: None,
558            #[cfg(test)]
559            config_review_test_refuse: Default::default(),
560            #[cfg(test)]
561            config_review_test_fail_once: Default::default(),
562            #[cfg(test)]
563            recovery_exit_test_after_step: None,
564            #[cfg(test)]
565            recovery_exit_test_completed: None,
566            #[cfg(test)]
567            apply_reconcile_pause: Arc::new(Mutex::new(None)),
568            #[cfg(test)]
569            recovery_exit_test_quiet_retry: false,
570            #[cfg(test)]
571            recovery_exit_test_retry_pause: None,
572            #[cfg(test)]
573            config_delivery_test_wakes: None,
574            #[cfg(all(test, unix))]
575            config_delivery_test_idle: None,
576            #[cfg(all(test, unix))]
577            settings_poll_test_idle: None,
578            #[cfg(windows)]
579            windows_verify: None,
580            #[cfg(windows)]
581            windows_flash: None,
582            #[cfg(windows)]
583            windows_track: None,
584            #[cfg(all(test, windows))]
585            windows_spawn_attempts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
586            #[cfg(test)]
587            caller_lookup: None,
588            hello_launch_nonces: Arc::new(Mutex::new(HelloLaunchNonces::default())),
589            rescan: None,
590            connected_clients: ConnectedClients::new(),
591            local_endpoint_unavailable: None,
592            counters,
593            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
594            daemon_shutdown: DaemonShutdownFlag::default(),
595            #[cfg(any(target_os = "linux", target_os = "macos"))]
596            upgrade: None,
597            daemon_provenance: DaemonProvenanceFacts::default(),
598            #[cfg(test)]
599            control_dispatch_delay: None,
600            #[cfg(test)]
601            provenance_probe_override: None,
602            #[cfg(test)]
603            route_bind_relay_sent_hold: None,
604            #[cfg(test)]
605            hello_registry_to_forwarding_hold: None,
606            #[cfg(test)]
607            hello_ack_to_publication_hold: None,
608            #[cfg(test)]
609            hello_before_publication_hold: None,
610            #[cfg(test)]
611            hello_after_launch_check_hold: None,
612            #[cfg(test)]
613            hello_inside_publication_hold: None,
614        }
615    }
616
617    /// Set the central storage policy: registering modules then receive their
618    /// resolved storage descriptor in HELLO_ACK.
619    pub fn with_storage_config(
620        mut self,
621        storage_config: Option<crate::daemon_config::StorageConfig>,
622    ) -> Self {
623        self.storage_config = storage_config;
624        self
625    }
626
627    /// Set the machine id served to every registering module (HELLO_ACK) and on
628    /// `server.describe`.
629    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
630        self.machine_id = machine_id;
631        self
632    }
633
634    /// Configure the exact reserved module and target ids permitted to relay
635    /// opaque admission facts. Config-file loading validates this authority;
636    /// this builder keeps the same policy available to embedded test daemons.
637    pub fn with_admission_facts_config(
638        mut self,
639        carrier_module_id: Option<String>,
640        targets: Option<Vec<String>>,
641    ) -> Self {
642        self.admission_facts_carrier_module_id = carrier_module_id;
643        self.admission_facts_targets = targets;
644        self
645    }
646
647    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
648    /// Replaces the scope table with an empty one under the new list, so call it
649    /// while building the handler, before any module can sync.
650    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
651        self.scopes = Arc::new(RwLock::new(
652            ScopeTable::new(owners.iter().cloned())
653                .with_flow_scope_authority_owners(self.flow_scope_authority_owners.iter().cloned())
654                .with_federated_owner(self.federated_scope_owner.clone()),
655        ));
656        self.scope_authority_owners = owners;
657        self
658    }
659
660    /// Set the module ids with narrow authority over head and ephemeral flow
661    /// scopes. Like the full authority list, this replaces an empty table and
662    /// must be called before any module can sync.
663    pub fn with_flow_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
664        self.scopes = Arc::new(RwLock::new(
665            ScopeTable::new(self.scope_authority_owners.iter().cloned())
666                .with_flow_scope_authority_owners(owners.iter().cloned())
667                .with_federated_owner(self.federated_scope_owner.clone()),
668        ));
669        self.flow_scope_authority_owners = owners;
670        self
671    }
672
673    /// Set the exclusive federated owner while building the handler, before syncs.
674    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
675        self.scopes = Arc::new(RwLock::new(
676            ScopeTable::new(self.scope_authority_owners.iter().cloned())
677                .with_flow_scope_authority_owners(self.flow_scope_authority_owners.iter().cloned())
678                .with_federated_owner(owner.clone()),
679        ));
680        self.federated_scope_owner = owner;
681        self
682    }
683
684    /// Set the startup policy before installing the rescan context or serving requests.
685    pub fn with_privileged_operator_prompt(mut self, mode: PrivilegedOperatorPrompt) -> Self {
686        self.privileged_operator_prompt = mode;
687        self
688    }
689
690    #[cfg(test)]
691    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
692        self.control_dispatch_delay = Some(delay);
693        self
694    }
695
696    pub fn with_process_liveness(
697        mut self,
698        process_liveness: Arc<dyn ModuleProcessLiveness>,
699    ) -> Self {
700        self.process_liveness = Some(process_liveness);
701        self
702    }
703
704    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
705        self.supervisor = supervisor;
706        if let Some(owner) = &self.config_runtime {
707            self.supervisor.install_binding_retirement(owner);
708        }
709        self.supervisor.set_activity(self.activity.clone());
710        self
711    }
712
713    /// Install the configured module set and its reserved capability bindings.
714    /// Bindings are configuration-scoped and may point at a provider that has not
715    /// been installed yet, so this does not require the bound module to exist.
716    pub fn with_capability_config(
717        self,
718        modules: impl IntoIterator<Item = (String, bool)>,
719        reserved_capabilities: BTreeMap<String, String>,
720    ) -> Self {
721        self.capability_evaluator
722            .configure(modules, reserved_capabilities);
723        self
724    }
725
726    /// Share the supervisor's daemon-shutdown flag with this handler, so
727    /// requirement changes after the daemon has begun its announced shutdown
728    /// are not reported as faults.
729    pub(crate) fn with_daemon_shutdown_flag(mut self, flag: DaemonShutdownFlag) -> Self {
730        self.daemon_shutdown = flag;
731        self
732    }
733
734    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
735        self.connected_clients = connected_clients;
736        self
737    }
738
739    /// Report why this daemon serves no local endpoint, in `server.describe`, so
740    /// an operator can see a bind failure without reading the daemon log.
741    pub fn with_local_endpoint_unavailable(mut self, reason: Option<String>) -> Self {
742        self.local_endpoint_unavailable = reason;
743        self
744    }
745
746    pub fn forwarding(&self) -> Arc<ForwardingTable> {
747        Arc::clone(&self.forwarding)
748    }
749
750    pub(crate) fn counters(&self) -> DaemonCounters {
751        self.counters.clone()
752    }
753
754    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
755    /// registration-release watch. The signal is what the supervisor waits on
756    /// before spawning a replacement, so it must only fire once forwarding
757    /// teardown is also done (see [`Self::cleanup_connection`] /
758    /// [`Self::handle_goodbye`]). Unpublished HELLO rollback uses the separate
759    /// registry-only path below because publication already owns the spawn lock.
760    fn deregister_connection(
761        &self,
762        connection_id: ConnectionId,
763        reason: RegistrationEndReason,
764    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
765        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
766            spawn.end_primary_registration();
767        }
768        self.registry
769            .deregister_connection_with_reason(connection_id, reason)
770    }
771
772    fn request_refusal_close(
773        &self,
774        connection: ConnectionId,
775        sink: Option<&crate::FrameSink>,
776        reason: CloseReason,
777    ) {
778        if let Some(sink) = sink {
779            sink.terminate_ingress();
780        }
781        if self.claims.close_notifications_enabled() {
782            self.forwarding.request_connection_close(connection, reason);
783        }
784    }
785
786    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
787    ///
788    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
789    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
790    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
791    #[cfg(test)]
792    pub fn handle_control(
793        &self,
794        connection_id: ConnectionId,
795        frame: Frame,
796    ) -> Result<Vec<Frame>, RouterError> {
797        match frame.header.ty {
798            FrameType::Ping => Ok(vec![pong(&frame)?]),
799            FrameType::Hello => self.handle_hello(connection_id, None, frame),
800            FrameType::Goodbye => self.handle_goodbye(connection_id),
801            ty => Ok(vec![control_error_frame(
802                &frame,
803                "unsupported_control_frame",
804                format!("unsupported channel-0 frame {ty:?}"),
805            )?]),
806        }
807    }
808
809    pub async fn handle_control_frame(
810        &self,
811        ctx: &RouteCtx,
812        frame: Frame,
813    ) -> Result<Vec<Frame>, RouterError> {
814        self.handle_control_frame_timed(ctx, frame, None).await
815    }
816
817    #[cfg(any(test, feature = "test-support"))]
818    pub fn with_test_operator_app_policy(
819        mut self,
820        policy: crate::operator_apps::TestOperatorAppPolicy,
821    ) -> Self {
822        self.operator_app_policy = policy.into();
823        self
824    }
825
826    /// Inject the Windows signature check for tests. The injected check
827    /// answers the verified version string or the rejection reason; the
828    /// daemon enforces the floor itself on the returned version.
829    #[cfg(all(windows, any(test, feature = "test-support")))]
830    pub fn with_test_windows_verifier(mut self, verify: crate::app_open::WindowsVerifyFn) -> Self {
831        self.windows_verify = Some(verify);
832        self
833    }
834
835    /// Record which pids the daemon would flash for `already_running`.
836    #[cfg(all(windows, any(test, feature = "test-support")))]
837    pub fn with_test_windows_flash(mut self, flash: crate::app_open::WindowsFlashFn) -> Self {
838        self.windows_flash = Some(flash);
839        self
840    }
841
842    /// Inject a tracking failure for tests: makes `track_launched_process`
843    /// fail so a test can prove a launch that cannot be tracked is stopped,
844    /// never left running.
845    #[cfg(all(windows, any(test, feature = "test-support")))]
846    pub fn with_test_windows_track(mut self, track: crate::app_open::WindowsTrackFn) -> Self {
847        self.windows_track = Some(track);
848        self
849    }
850
851    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
852        self.local_connections
853            .lock()
854            .unwrap_or_else(|p| p.into_inner())
855            .insert(connection);
856    }
857
858    pub(crate) fn record_route_opener(
859        &self,
860        connection: ConnectionId,
861        opener: RouteOpenerConnection,
862    ) {
863        self.route_openers
864            .lock()
865            .unwrap_or_else(|p| p.into_inner())
866            .insert(connection, opener);
867    }
868
869    // Keep the connection-level delivery decision shared with route.bind. The
870    // target's capability opt-in is separate from recognition of the caller.
871    fn connection_operator_app(
872        &self,
873        stamp: Option<&crate::operator_apps::OperatorAppStamp>,
874    ) -> Option<subc_protocol::peer::OperatorApp> {
875        stamp
876            .filter(|stamp| stamp.delivery_enabled(&self.operator_app_policy))
877            .map(|stamp| stamp.app.clone())
878    }
879
880    pub(crate) fn record_observed_peer(
881        &self,
882        connection: ConnectionId,
883        peer: subc_os::local_peer::ObservedPeer,
884    ) {
885        use subc_os::local_peer::{ObservedPeer as OsPeer, PeerUser};
886        let peer = match peer {
887            OsPeer::Unobserved => ObservedPeer::unobserved(),
888            OsPeer::Observed(peer) => {
889                let observed = match peer.user {
890                    PeerUser::Uid(uid) => ObservedPeer::observed_uid(uid),
891                    PeerUser::Sid(sid) => ObservedPeer::observed_sid(sid),
892                };
893                observed
894                    .with_exe(
895                        peer.exe
896                            .and_then(|path| path.into_os_string().into_string().ok()),
897                    )
898                    .with_signing_id(peer.signing_id)
899            }
900        };
901        self.observed_peers
902            .lock()
903            .unwrap_or_else(|p| p.into_inner())
904            .insert(connection, peer);
905    }
906
907    pub(crate) fn record_caller_endpoints(
908        &self,
909        connection: ConnectionId,
910        endpoints: Option<(SocketAddr, SocketAddr)>,
911    ) {
912        let mut callers = self
913            .caller_endpoints
914            .lock()
915            .unwrap_or_else(|p| p.into_inner());
916        callers.remove(&connection);
917        if let Some(endpoints) = endpoints {
918            callers.insert(connection, endpoints);
919        }
920    }
921
922    #[cfg(test)]
923    pub(crate) fn with_caller_lookup_for_test(
924        mut self,
925        lookup: impl Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync + 'static,
926    ) -> Self {
927        self.caller_lookup = Some(Arc::new(lookup));
928        self
929    }
930
931    async fn resolve_caller(&self, connection: ConnectionId) -> CallerIdentity {
932        let endpoints = self
933            .caller_endpoints
934            .lock()
935            .unwrap_or_else(|p| p.into_inner())
936            .get(&connection)
937            .copied();
938        #[cfg(test)]
939        let lookup = self.caller_lookup.clone();
940        tokio::task::spawn_blocking(move || {
941            #[cfg(test)]
942            if let Some(lookup) = lookup {
943                return lookup(endpoints);
944            }
945            endpoints
946                .map(|(local, peer)| CallerIdentity::lookup_endpoints(local, peer))
947                .unwrap_or_default()
948        })
949        .await
950        .unwrap_or_default()
951    }
952
953    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
954        frame.header.channel == 0
955            && frame.header.ty == FrameType::Request
956            && self
957                .forwarding
958                .module_endpoint_for_connection(ctx.connection_id)
959                .is_ok_and(|endpoint| endpoint.is_none())
960            && parse_client_control_request(&frame.body)
961                .ok()
962                .is_some_and(|request| privileged_operation(&request).is_some())
963    }
964
965    pub(crate) async fn handle_control_frame_timed(
966        &self,
967        ctx: &RouteCtx,
968        frame: Frame,
969        dispatch_started_at: Option<StdInstant>,
970    ) -> Result<Vec<Frame>, RouterError> {
971        let first = ctx.egress.first_ingress_frame();
972        self.handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
973            .await
974    }
975
976    pub(crate) async fn handle_control_frame_ingress(
977        &self,
978        ctx: &RouteCtx,
979        frame: Frame,
980        dispatch_started_at: Option<StdInstant>,
981        first: bool,
982    ) -> Result<Vec<Frame>, RouterError> {
983        if ctx.egress.ingress_terminal() {
984            return Ok(Vec::new());
985        }
986        #[cfg(test)]
987        self.claims.record_dispatch(frame.header.corr);
988        let claim_binding = self.claims.binding(ctx.connection_id);
989        let mut prefix_attempt = (frame.header.ty == FrameType::Hello
990            && claim_binding
991                .as_ref()
992                .is_some_and(|binding| binding.prefix_module_id().is_some()))
993        .then(|| self.prefix_hello_attempt(ctx));
994        if claim_binding
995            .as_ref()
996            .is_some_and(|binding| binding.prefix_module_id().is_some())
997        {
998            let registered = self
999                .forwarding
1000                .module_endpoint_for_connection(ctx.connection_id)
1001                .map_err(RouterError::Forwarding)?
1002                .is_some();
1003            if !registered && frame.header.ty != FrameType::Hello {
1004                return self
1005                    .refuse_claim_connection(ctx, &frame, "claim_hello_required")
1006                    .await;
1007            }
1008            if registered && frame.header.ty == FrameType::Goodbye {
1009                ctx.egress.terminate_ingress();
1010                let result = self.handle_goodbye(ctx.connection_id);
1011                self.claims.connection_closed(ctx.connection_id);
1012                self.request_refusal_close(
1013                    ctx.connection_id,
1014                    Some(&ctx.egress),
1015                    CloseReason::new("claim_registration_ended", "prefix registration ended"),
1016                );
1017                return result;
1018            }
1019            if registered && frame.header.ty == FrameType::Request {
1020                let allowed =
1021                    serde_json::from_slice::<ControlOpProbe>(&frame.body).is_ok_and(|probe| {
1022                        matches!(
1023                            probe.op.as_str(),
1024                            "catalog.update"
1025                                | "catalog.update_role_declarations"
1026                                | "scope.describe"
1027                                | "scope.watch"
1028                                | "supervisor.live_roots"
1029                                | subc_protocol::policy_root::GET_OP
1030                                | "activity.record"
1031                        )
1032                    });
1033                if !allowed {
1034                    return Ok(vec![control_error_frame(
1035                        &frame,
1036                        channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
1037                        "prefix registrations have only brokered module operations",
1038                    )?]);
1039                }
1040            }
1041            if registered
1042                && frame.header.ty == FrameType::Push
1043                && !serde_json::from_slice::<ControlOpProbe>(&frame.body)
1044                    .is_ok_and(|probe| probe.op == "route.status")
1045            {
1046                return Ok(vec![control_error_frame(
1047                    &frame,
1048                    channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
1049                    "prefix registrations may push only route.status for routes they serve",
1050                )?]);
1051            }
1052        }
1053        match frame.header.ty {
1054            FrameType::Ping => Ok(vec![pong(&frame)?]),
1055            FrameType::Hello => {
1056                if claim_binding
1057                    .as_ref()
1058                    .is_some_and(|binding| binding.prefix_module_id().is_none())
1059                {
1060                    return self
1061                        .refuse_claim_connection(ctx, &frame, "claim_hello_not_allowed")
1062                        .await;
1063                }
1064                // Resolve before the blocking HELLO can outlive channel cleanup.
1065                let channel_spawn = self.supervisor.registration_spawn(ctx.connection_id);
1066                if let Some(spawn) = &channel_spawn {
1067                    spawn.wait_launch().await;
1068                    // Refused launches close the channel. Leave their pending
1069                    // HELLO unanswered instead of racing a reply against shutdown.
1070                    if !spawn.launch_ready() {
1071                        ctx.egress.terminate_ingress();
1072                        return Ok(Vec::new());
1073                    }
1074                    #[cfg(test)]
1075                    self.pause_hello_ingress_for_test().await;
1076                } else if claim_binding.is_none() {
1077                    if let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&frame.body) {
1078                        if crate::supervise::resume_hello::has_resume_token(&hello) {
1079                            self.wait_for_resume_preparation(ctx.connection_id, &hello)
1080                                .await;
1081                        } else if let (Some(module), Some(nonce)) = (
1082                            hello
1083                                .get("manifest")
1084                                .and_then(|value| value.get("module_id"))
1085                                .and_then(|value| value.as_str()),
1086                            hello.get("launch_nonce").and_then(|value| value.as_str()),
1087                        ) {
1088                            if !self
1089                                .config_runtime
1090                                .as_ref()
1091                                .is_some_and(|owner| owner.module_is_gated(module))
1092                                && !self.supervisor.wait_program_binding(module, nonce).await
1093                            {
1094                                self.request_refusal_close(
1095                                    ctx.connection_id,
1096                                    Some(&ctx.egress),
1097                                    CloseReason::new(
1098                                        "program_refused",
1099                                        "the spawned program binding failed",
1100                                    ),
1101                                );
1102                                return Ok(vec![control_error_frame(
1103                                    &frame,
1104                                    if self
1105                                        .config_runtime
1106                                        .as_ref()
1107                                        .is_some_and(|owner| owner.is_recovering())
1108                                    {
1109                                        "config_gated"
1110                                    } else {
1111                                        "program_refused"
1112                                    },
1113                                    "the spawned program binding failed",
1114                                )?]);
1115                            }
1116                            if let Some(spawn) = self.supervisor.nonce_hello_spawn(module, nonce) {
1117                                // The child can dial before the supervisor has
1118                                // installed its durable roster entry.
1119                                spawn.wait_launch().await;
1120                            }
1121                        }
1122                    }
1123                }
1124                let handler = self.clone();
1125                let connection = ctx.connection_id;
1126                let egress = ctx.egress.clone();
1127                let correlation = frame.header.corr;
1128                let dispatcher = tracing::dispatcher::get_default(|dispatcher| dispatcher.clone());
1129                let span = tracing::Span::current();
1130                let hello_binding = claim_binding.clone();
1131                let replies = tokio::task::spawn_blocking(move || {
1132                    tracing::dispatcher::with_default(&dispatcher, || {
1133                        span.in_scope(|| {
1134                            handler.handle_hello_checked(
1135                                connection,
1136                                Some(egress),
1137                                frame,
1138                                true,
1139                                hello_binding,
1140                                channel_spawn,
1141                            )
1142                        })
1143                    })
1144                })
1145                .await
1146                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))??;
1147                #[cfg(test)]
1148                if prefix_attempt.is_some() {
1149                    self.claims.pause_prefix_commit_for_test(false).await;
1150                }
1151                if let Some(attempt) = &mut prefix_attempt {
1152                    let accepted = !replies
1153                        .iter()
1154                        .any(|reply| reply.header.ty == FrameType::Error)
1155                        && self
1156                            .registry
1157                            .get_module_by_connection(ctx.connection_id)
1158                            .map_err(|err| RouterError::backend(0, correlation, err.to_string()))?
1159                            .is_some();
1160                    if accepted {
1161                        attempt.accepted = true;
1162                    } else {
1163                        ctx.egress.terminate_ingress();
1164                        for reply in replies {
1165                            ctx.egress.send_flushed(reply).await?;
1166                        }
1167                        return Ok(Vec::new());
1168                    }
1169                }
1170                Ok(replies)
1171            }
1172            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
1173            FrameType::Cancel => {
1174                // Channel-0 cancellation withdraws approvals and subscriptions
1175                // and fences pending agent declarations;
1176                // successful cancellation has no ordinary reply.
1177                // A config Apply may also own an OS prompt. Cancel that prompt
1178                // before config cancellation can report the request handled.
1179                if self
1180                    .agent_declarations
1181                    .cancel(ctx.connection_id, frame.header.corr)
1182                    || self
1183                        .forwarding
1184                        .operator_confirms()
1185                        .cancel(ctx.connection_id, frame.header.corr)
1186                    || self.cancel_config_approval(ctx.connection_id, frame.header.corr)
1187                    || self
1188                        .supervisor
1189                        .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
1190                    || self.cancel_activity_subscription(ctx, &frame)?
1191                    || self.cancel_catalog_subscription(ctx.connection_id, frame.header.corr)
1192                    || self
1193                        .cancel_config_settings_subscription(ctx.connection_id, frame.header.corr)
1194                    || self.cancel_scope_subscription(ctx.connection_id, frame.header.corr)
1195                {
1196                    Ok(Vec::new())
1197                } else {
1198                    Ok(vec![control_error_frame(
1199                        &frame,
1200                        "unknown_subscription",
1201                        "no subscription has this correlation id",
1202                    )?])
1203                }
1204            }
1205            FrameType::Request => {
1206                // This additive operation is not part of the existing exhaustive
1207                // module-control enum. Probe the op before decoding that enum.
1208                let op = serde_json::from_slice::<ControlOpProbe>(&frame.body).ok();
1209                if let Some(probe) = &op {
1210                    self.record_control_usage(ctx.connection_id, &probe.op);
1211                }
1212                let claim_present = op.as_ref().is_some_and(|probe| probe.op == "claim.present");
1213                if let Some(refusal) = self.recovery_request_refusal(
1214                    ctx,
1215                    &frame,
1216                    op.as_ref().map(|probe| probe.op.as_str()),
1217                )? {
1218                    if claim_present {
1219                        self.reclaim_presented_expiry(&frame);
1220                        return self
1221                            .refuse_claim_connection(ctx, &frame, "config_gated")
1222                            .await;
1223                    }
1224                    return Ok(vec![refusal]);
1225                }
1226                if claim_present {
1227                    return self.handle_claim_present(ctx, &frame, first).await;
1228                }
1229                if op.as_ref().is_some_and(|probe| probe.op == "claim.mint") {
1230                    return self.handle_claim_mint(ctx, &frame).await;
1231                }
1232                if let Some(refusal) = self.registration_operation_refusal(
1233                    ctx,
1234                    &frame,
1235                    op.as_ref().map(|probe| probe.op.as_str()),
1236                )? {
1237                    return Ok(vec![refusal]);
1238                }
1239                if let Some(probe) = op.as_ref().filter(|probe| policy_root::is_op(&probe.op)) {
1240                    return self.handle_policy_root(ctx, frame, &probe.op).await;
1241                }
1242                if op
1243                    .as_ref()
1244                    .is_some_and(|probe| probe.op == ops::CATALOG_WATCH)
1245                {
1246                    return self.handle_catalog_watch(ctx, frame);
1247                }
1248                if op
1249                    .as_ref()
1250                    .is_some_and(|probe| probe.op == ops::SCOPE_WATCH)
1251                {
1252                    return self.handle_scope_watch(ctx, frame);
1253                }
1254                if op
1255                    .as_ref()
1256                    .is_some_and(|probe| probe.op == MODULE_TO_SUBC_OP_CATALOG_UPDATE)
1257                    && subc_protocol::provider_declarations::catalog_update_has_provider_declarations(&frame.body)
1258                        .unwrap_or(false)
1259                {
1260                    return Ok(vec![control_error_frame(
1261                        &frame,
1262                        error_codes::CATALOG_UPDATE_FROZEN_DECLARATIONS,
1263                        "provider_declarations are fixed at HELLO; restart the module to change them",
1264                    )?]);
1265                }
1266                if let Some(probe) = op
1267                    .as_ref()
1268                    .filter(|probe| config_gate::is_module_config_op(&probe.op))
1269                {
1270                    return self
1271                        .handle_module_config_request(ctx, frame, &probe.op)
1272                        .await;
1273                }
1274                if let Some(probe) = op
1275                    .as_ref()
1276                    .filter(|probe| config_gate::is_config_op(&probe.op))
1277                {
1278                    return self.handle_config_gate_request(ctx, frame, &probe.op).await;
1279                }
1280                if op
1281                    .as_ref()
1282                    .is_some_and(|probe| probe.op == ops::ACTIVITY_RECORD)
1283                {
1284                    return self.handle_activity_record(ctx, frame).await;
1285                }
1286                if op.as_ref().is_some_and(|probe| {
1287                    probe.op == ops::ACTIVITY_QUERY || probe.op == ops::ACTIVITY_SUBSCRIBE
1288                }) {
1289                    // A refusal and a CANCEL that won must not both end the stream.
1290                    let key = (ctx.connection_id, frame.header.corr);
1291                    let replies = self.handle_activity_read(ctx, frame).await?;
1292                    return Ok(self.activity_reservations.settle(key, replies));
1293                }
1294                if op
1295                    .as_ref()
1296                    .is_some_and(|probe| probe.op == "operator.confirm")
1297                {
1298                    return self.handle_operator_confirm(ctx, frame).await;
1299                }
1300                if op.as_ref().is_some_and(|probe| probe.op == ops::APP_OPEN) {
1301                    return self
1302                        .observe_control_wait(
1303                            ctx,
1304                            None,
1305                            ops::APP_OPEN,
1306                            self.handle_app_open(ctx, frame),
1307                        )
1308                        .await;
1309                }
1310                if op
1311                    .as_ref()
1312                    .is_some_and(|probe| probe.op == ops::CONNECTION_DESCRIBE)
1313                {
1314                    return self.handle_connection_describe(ctx, frame).await;
1315                }
1316                if op
1317                    .as_ref()
1318                    .is_some_and(|probe| probe.op == subc_control::SCOPE_SERVED_BY_OP)
1319                {
1320                    return self.handle_scope_served_by(ctx.connection_id, frame);
1321                }
1322                if self
1323                    .forwarding
1324                    .module_endpoint_for_connection(ctx.connection_id)
1325                    .map_err(RouterError::Forwarding)?
1326                    .is_some()
1327                {
1328                    if !is_known_module_request_op(&frame.body) {
1329                        return Ok(vec![control_error_frame(
1330                            &frame,
1331                            "unsupported_control_frame",
1332                            "module-originated channel-0 REQUEST is not supported",
1333                        )?]);
1334                    }
1335                    if op.as_ref().is_some_and(|probe| {
1336                        probe.op == subc_protocol::session::MODULE_DRAIN_READY_OP
1337                    }) {
1338                        return self.handle_module_drain_ready(ctx.connection_id, frame);
1339                    }
1340                    let request = match parse_module_control_request_from_module(&frame.body) {
1341                        Ok(request) => request,
1342                        Err((err, ControlRequestBodyError::UnknownOp)) => {
1343                            return Ok(vec![control_error_frame(
1344                                &frame,
1345                                "unsupported_control_frame",
1346                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
1347                            )?])
1348                        }
1349                        Err((err, ControlRequestBodyError::InvalidBody)) => {
1350                            return Ok(vec![control_error_frame(
1351                                &frame,
1352                                "invalid_control_body",
1353                                format!("malformed module control body: {err}"),
1354                            )?])
1355                        }
1356                    };
1357                    let op = module_control_request_op(&request);
1358                    let corr = frame.header.corr;
1359                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
1360                    if let ModuleControlRequestFromModule::AgentCommands {
1361                        started,
1362                        finished,
1363                        known,
1364                    } = request
1365                    {
1366                        return self
1367                            .agent_declarations
1368                            .enqueue(
1369                                self,
1370                                ctx,
1371                                frame,
1372                                crate::resource_totals::Declaration {
1373                                    started,
1374                                    finished,
1375                                    known,
1376                                },
1377                            )
1378                            .await;
1379                    }
1380                    let result =
1381                        self.handle_module_control_request(ctx.connection_id, frame, request);
1382                    log_slow_control_dispatch(
1383                        dispatch_started_at,
1384                        op,
1385                        ctx.connection_id,
1386                        corr,
1387                        None,
1388                    );
1389                    return result;
1390                }
1391
1392                if is_known_module_request_op(&frame.body) {
1393                    let is_agents = serde_json::from_slice::<ControlOpProbe>(&frame.body)
1394                        .is_ok_and(|probe| probe.op == "supervisor.agent_commands");
1395                    let code = if is_agents {
1396                        "not_supervised"
1397                    } else if op
1398                        .as_ref()
1399                        .is_some_and(|probe| probe.op == subc_protocol::scope::ROUTE_AUTHORIZE_OP)
1400                    {
1401                        error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED
1402                    } else {
1403                        "not_registered"
1404                    };
1405                    return Ok(vec![control_error_frame(
1406                        &frame,
1407                        code,
1408                        "module-originated control requests require the module's own registered connection",
1409                    )?]);
1410                }
1411
1412                let request = match parse_client_control_request(&frame.body) {
1413                    Ok(request) => request,
1414                    Err((err, ControlRequestBodyError::UnknownOp)) => {
1415                        return Ok(vec![control_error_frame(
1416                            &frame,
1417                            "unknown_control_op",
1418                            format!("unknown client control op: {err}"),
1419                        )?])
1420                    }
1421                    Err((err, ControlRequestBodyError::InvalidBody)) => {
1422                        return Ok(vec![control_error_frame(
1423                            &frame,
1424                            "invalid_control_body",
1425                            format!("malformed client control body: {err}"),
1426                        )?])
1427                    }
1428                };
1429                let op = client_control_request_op(&request);
1430                let corr = frame.header.corr;
1431                log_control_dispatch_arrival(op, ctx.connection_id, corr);
1432                let mut route_open_timings = (op == ops::ROUTE_OPEN).then(RouteOpenTimings::new);
1433                #[cfg(test)]
1434                if let Some(delay) = self.control_dispatch_delay {
1435                    tokio::time::sleep(delay).await;
1436                }
1437                let result = self
1438                    .handle_client_control_request(ctx, frame, request, &mut route_open_timings)
1439                    .await;
1440                if let Some(timings) = route_open_timings.as_mut() {
1441                    timings.finish();
1442                }
1443                log_slow_control_dispatch(
1444                    dispatch_started_at,
1445                    op,
1446                    ctx.connection_id,
1447                    corr,
1448                    route_open_timings.as_ref(),
1449                );
1450                result
1451            }
1452            FrameType::Push => {
1453                let Some(endpoint) = self
1454                    .forwarding
1455                    .module_endpoint_for_connection(ctx.connection_id)
1456                    .map_err(RouterError::Forwarding)?
1457                else {
1458                    return Ok(vec![control_error_frame(
1459                        &frame,
1460                        "unsupported_control_frame",
1461                        "client-originated channel-0 PUSH is not supported",
1462                    )?]);
1463                };
1464                self.handle_status_update(endpoint, frame)
1465            }
1466            FrameType::Response | FrameType::Error
1467                if self
1468                    .forwarding
1469                    .module_endpoint_for_connection(ctx.connection_id)
1470                    .map_err(RouterError::Forwarding)?
1471                    .is_some() =>
1472            {
1473                self.handle_module_relay_response(ctx.connection_id, frame)
1474            }
1475            ty => Ok(vec![control_error_frame(
1476                &frame,
1477                "unsupported_control_frame",
1478                format!("unsupported channel-0 frame {ty:?}"),
1479            )?]),
1480        }
1481    }
1482
1483    #[cfg(test)]
1484    fn pause_cleanup_for_test(&self, stage: u8) {
1485        let mut slot = self.cleanup_pause.lock().unwrap_or_else(|p| p.into_inner());
1486        if slot.as_ref().is_some_and(|(at, _)| *at == stage) {
1487            let (_, (reached, release)) = slot.take().unwrap();
1488            drop(slot);
1489            let _ = reached.send(());
1490            let _ = release.recv_timeout(Duration::from_secs(5));
1491        }
1492    }
1493
1494    /// Run `hook` once, in the next `route.open` that attests a launch nonce,
1495    /// right after the nonce is resolved.
1496    #[cfg(all(test, unix, feature = "test-support"))]
1497    pub(crate) fn after_nonce_attestation_for_test(&self, hook: impl FnOnce() + Send + 'static) {
1498        *self
1499            .after_nonce_attestation
1500            .lock()
1501            .unwrap_or_else(|p| p.into_inner()) = Some(Box::new(hook));
1502    }
1503
1504    #[cfg(test)]
1505    pub(super) fn pause_after_nonce_attestation_for_test(&self) {
1506        let hook = self
1507            .after_nonce_attestation
1508            .lock()
1509            .unwrap_or_else(|p| p.into_inner())
1510            .take();
1511        if let Some(hook) = hook {
1512            hook();
1513        }
1514    }
1515
1516    pub fn cleanup_connection(
1517        &self,
1518        connection_id: ConnectionId,
1519    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1520        // The server loop joins its offloaded request tasks (route opens,
1521        // privileged requests and activity reads) before this cleanup runs, and
1522        // inline dispatch has ended. Two kinds of work are not joined. Agent
1523        // command declarations run on their queue's detached worker, so the
1524        // queue is closed first: every declaration still queued or validating
1525        // has its commit fence cancelled before anything below can change how
1526        // the connection resolves. A HELLO whose reader was dropped keeps
1527        // running on its blocking thread. It carries the channel spawn its
1528        // reader resolved at ingress instead of re-reading the index forgotten
1529        // below, so it is still judged as that channel's HELLO: the retired
1530        // spawn refuses it before it records anything, and a channel HELLO
1531        // never records a launch nonce, so it cannot leave this connection any
1532        // nonce authority.
1533        self.agent_declarations.close(connection_id);
1534        self.close_catalog_subscriptions(connection_id);
1535        self.close_config_settings_subscriptions(connection_id);
1536        self.close_scope_subscriptions(connection_id);
1537        #[cfg(test)]
1538        self.pause_cleanup_for_test(0);
1539        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
1540            spawn.retire_registration_channel();
1541        }
1542        self.supervisor
1543            .forget_registration_connection(connection_id);
1544        #[cfg(test)]
1545        self.pause_cleanup_for_test(1);
1546        self.local_connections
1547            .lock()
1548            .unwrap_or_else(|p| p.into_inner())
1549            .remove(&connection_id);
1550        self.caller_endpoints
1551            .lock()
1552            .unwrap_or_else(|p| p.into_inner())
1553            .remove(&connection_id);
1554        self.route_openers
1555            .lock()
1556            .unwrap_or_else(|p| p.into_inner())
1557            .remove(&connection_id);
1558        self.build_class_warned
1559            .lock()
1560            .unwrap_or_else(|p| p.into_inner())
1561            .remove(&connection_id);
1562        // Retire the capture before its published facts so an in-flight
1563        // verification cannot recreate them after cleanup.
1564        self.captured_peers
1565            .lock()
1566            .unwrap_or_else(|p| p.into_inner())
1567            .remove(&connection_id);
1568        self.observed_peers
1569            .lock()
1570            .unwrap_or_else(|p| p.into_inner())
1571            .remove(&connection_id);
1572        self.config_desktop_stamps
1573            .lock()
1574            .unwrap_or_else(|p| p.into_inner())
1575            .remove(&connection_id);
1576        self.operator_apps
1577            .lock()
1578            .unwrap_or_else(|p| p.into_inner())
1579            .remove(&connection_id);
1580        self.forwarding
1581            .operator_confirms()
1582            .connection_closed(connection_id);
1583        let cleanup = self.cleanup_connection_with_end_reason(
1584            connection_id,
1585            RegistrationEndReason::ConnectionClosed,
1586        );
1587        // A draining writer can still be reached by a route until forwarding
1588        // cleanup finishes. Keep its claim sink visible to launch retirement.
1589        self.claims.connection_closed(connection_id);
1590        cleanup
1591    }
1592
1593    fn cleanup_connection_with_end_reason(
1594        &self,
1595        connection_id: ConnectionId,
1596        requested_reason: RegistrationEndReason,
1597    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1598        #[cfg(test)]
1599        if let Some(pause) = self
1600            .activity_request_pause
1601            .lock()
1602            .unwrap()
1603            .as_ref()
1604            .filter(|pause| pause.connection == connection_id)
1605        {
1606            pause
1607                .cleanup_started
1608                .store(true, std::sync::atomic::Ordering::Release);
1609        }
1610        if let Some(runtime) = &self.config_runtime {
1611            runtime.disconnected(connection_id);
1612        }
1613        self.agent_declarations.close(connection_id);
1614        let end_reason = if requested_reason == RegistrationEndReason::ConnectionClosed {
1615            self.registry
1616                .get_module_by_connection(connection_id)?
1617                .and_then(|registration| self.supervisor.get(&registration.manifest.module_id))
1618                .and_then(|module| module.registration_end_reason().ok().flatten())
1619                .unwrap_or(requested_reason)
1620        } else {
1621            requested_reason
1622        };
1623        let crash_closed = self
1624            .registry
1625            .get_module_by_connection(connection_id)?
1626            .and_then(|registration| {
1627                self.forwarding
1628                    .module_endpoint_for_connection(connection_id)
1629                    .ok()
1630                    .flatten()
1631                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
1632                    .map(|routes| (registration.manifest.module_id, routes))
1633            });
1634        let crash_closed = crash_closed.map(|(module_id, routes)| {
1635            let terminal = match self.supervisor.get(&module_id) {
1636                None => false,
1637                Some(module) => match module.will_recover_after_connection_loss() {
1638                    Ok(will_recover) => !will_recover,
1639                    Err(err) => {
1640                        warn!(
1641                            %module_id,
1642                            error = %err,
1643                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
1644                        );
1645                        false
1646                    }
1647                },
1648            };
1649            // The forwarding table gates all providers at the start of daemon
1650            // shutdown, before their connections are closed. An ordinary
1651            // module disconnect still reports crash if that gate is not set.
1652            let (reason, drained) = match self
1653                .forwarding
1654                .daemon_drain_result_for_connection(connection_id)
1655            {
1656                Ok(Some(drained)) => (RouteCloseReason::Restart, drained),
1657                Ok(None) => (RouteCloseReason::Crash, false),
1658                Err(err) => {
1659                    warn!(error = %err, "failed to read daemon drain state; reporting crash conservatively");
1660                    (RouteCloseReason::Crash, false)
1661                }
1662            };
1663            (module_id, routes, reason, drained, terminal)
1664        });
1665        let registrations = self.deregister_connection(connection_id, end_reason);
1666        // Read before teardown: the spawn whose registration this connection
1667        // was. Its registration ending is an authority change for it.
1668        let ended_authority = self
1669            .forwarding
1670            .target_authority_for_connection(connection_id)
1671            .ok()
1672            .flatten();
1673        let cleanup = if crash_closed.is_some() {
1674            self.forwarding.cleanup_connection_counted(connection_id)
1675        } else {
1676            // A module connection's teardown needs the count of abandoned
1677            // route.bind relays for its route.closed notice below. Any other
1678            // connection, such as a client's, sends no such notice and needs
1679            // only its routes released, so it uses the route-only wrapper and
1680            // reports zero.
1681            self.forwarding
1682                .cleanup_connection(connection_id)
1683                .map(|released| crate::forwarding::ConnectionCleanup {
1684                    released,
1685                    abandoned_relays: 0,
1686                })
1687        };
1688        // The route.closed push waits for forwarding teardown because only
1689        // teardown knows how many pending route.bind relays it aborted. It still
1690        // goes out before the GOODBYEs for the released routes, and its targets
1691        // were captured above, before teardown removed those routes.
1692        if let Some((module_id, routes, reason, drained, terminal)) = crash_closed {
1693            let abandoned = cleanup
1694                .as_ref()
1695                .map_or(0, |cleanup| cleanup.abandoned_relays);
1696            send_route_control_pushes(
1697                &self.forwarding,
1698                routes,
1699                ClientControlPush::RouteClosed {
1700                    module_id,
1701                    channels: Vec::new(),
1702                    reason,
1703                    drained,
1704                    abandoned,
1705                    excluded_subscriptions: 0,
1706                    terminal: Some(terminal),
1707                },
1708            );
1709        }
1710        if let Ok(cleanup) = cleanup {
1711            self.emit_route_goodbyes(cleanup.released);
1712        }
1713        if let Some(record) = ended_authority {
1714            self.change_spawn_authority(&record);
1715        }
1716        // Signal the registration-release watch only now that BOTH registry and
1717        // forwarding teardown are done, so a supervisor waiting to spawn a
1718        // replacement never observes release while old routes still exist.
1719        if matches!(&registrations, Ok(r) if !r.is_empty()) {
1720            crate::supervise::notify_registration_release();
1721            self.capability_evaluator.wake_deadline_loop();
1722            self.refresh_capability_requirements();
1723        }
1724        self.supervisor.remove_spawn_subscribers(connection_id);
1725        self.activity_streams
1726            .lock()
1727            .unwrap_or_else(|p| p.into_inner())
1728            .retain(|(id, _), task| {
1729                if *id == connection_id {
1730                    task.abort();
1731                    false
1732                } else {
1733                    true
1734                }
1735            });
1736        // Sync authority dies with its connection, so the owner's next
1737        // connection can take it; the owner's scopes stay as they are.
1738        self.hello_launch_nonces
1739            .lock()
1740            .unwrap_or_else(|poisoned| poisoned.into_inner())
1741            .forget(connection_id);
1742        self.scopes
1743            .write()
1744            .unwrap_or_else(|poisoned| poisoned.into_inner())
1745            .release_connection(connection_id);
1746        registrations
1747    }
1748
1749    pub(crate) fn handle_route_goodbye(
1750        &self,
1751        connection_id: ConnectionId,
1752        route_channel: u16,
1753        route_epoch: u32,
1754    ) -> Result<bool, RouterError> {
1755        debug!(
1756            connection_id = connection_id.get(),
1757            route_channel, route_epoch, "handling route GOODBYE"
1758        );
1759        let RouteRelease::Removed(released_route) = self
1760            .forwarding
1761            .release_client_route(connection_id, route_channel, route_epoch)
1762            .map_err(RouterError::Forwarding)?
1763        else {
1764            return Ok(false);
1765        };
1766        self.emit_route_goodbyes(vec![released_route]);
1767        Ok(true)
1768    }
1769
1770    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
1771        scope_expiry::ScopeExpiryContext::new(self).emit_route_goodbyes(released_routes);
1772    }
1773
1774    async fn handle_client_control_request(
1775        &self,
1776        ctx: &RouteCtx,
1777        frame: Frame,
1778        request: ClientControlRequest,
1779        route_open_timings: &mut Option<RouteOpenTimings>,
1780    ) -> Result<Vec<Frame>, RouterError> {
1781        if let Some(owner) = &self.config_runtime {
1782            let module = match &request {
1783                ClientControlRequest::SupervisorRestart { module_id, .. }
1784                | ClientControlRequest::SupervisorReload { module_id }
1785                | ClientControlRequest::SupervisorSwap { module_id, .. }
1786                | ClientControlRequest::SupervisorSetEnabled {
1787                    module_id,
1788                    enabled: true,
1789                } => Some(module_id.as_str()),
1790                _ => None,
1791            };
1792            let rescan = matches!(
1793                &request,
1794                ClientControlRequest::SupervisorRescan { preview: false }
1795                    | ClientControlRequest::SupervisorRescanChecked { preview: false, .. }
1796            );
1797            let held = if module.is_some() || rescan {
1798                let module = module.map(str::to_owned);
1799                owner
1800                    .on_blocking(move |owner| owner.checked_admission_hold(module.as_deref()))
1801                    .await
1802            } else {
1803                Ok(())
1804            };
1805            if let Err(error) = held {
1806                if error.code != "config_delivery_deferred" {
1807                    let code = if error.code == "store_tampered" {
1808                        "store_tampered"
1809                    } else {
1810                        "config_gated"
1811                    };
1812                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
1813                }
1814            }
1815        }
1816        if let Some(operation) = privileged_operation(&request) {
1817            #[cfg(any(target_os = "macos", target_os = "linux"))]
1818            if operation == PrivilegedOperation::UpgradeInPlace {
1819                if let Some(upgrade) = &self.upgrade {
1820                    if !upgrade.wait_for_identity().await {
1821                        return Ok(vec![control_error_frame(
1822                            &frame,
1823                            subc_control::upgrade_in_place::UPGRADE_IN_PLACE_UNSUPPORTED,
1824                            "running executable identity is unavailable",
1825                        )?]);
1826                    }
1827                }
1828            }
1829            let caller = self.resolve_caller(ctx.connection_id).await;
1830            let op = client_control_request_op(&request);
1831            let text = prompt_text(operation, &caller);
1832            match if operation == PrivilegedOperation::UpgradeInPlace {
1833                PrivilegedOperatorPrompt::Enforce
1834            } else {
1835                self.privileged_operator_prompt
1836            } {
1837                PrivilegedOperatorPrompt::Log => {
1838                    info!(target: "subc_daemon::privileged_prompt", operation = op,
1839                        target = ?operation, caller = %caller.description(), summary = %text,
1840                        "privileged request would prompt the operator");
1841                }
1842                PrivilegedOperatorPrompt::Enforce => {
1843                    let key =
1844                        crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1845                    let shortcut = if operation == PrivilegedOperation::UpgradeInPlace {
1846                        None
1847                    } else {
1848                        self.operator_shortcut_stamp(ctx.connection_id)
1849                            .await
1850                            .map(|stamp| {
1851                                self.shortcut_context(Some(stamp), None, None, ctx.connection_id)
1852                            })
1853                    };
1854                    let outcome = self
1855                        .forwarding
1856                        .operator_confirms()
1857                        .approve_privileged_with_shortcut(
1858                            ctx,
1859                            &frame,
1860                            op,
1861                            text,
1862                            caller.description(),
1863                            key,
1864                            shortcut,
1865                        )
1866                        .await;
1867                    if outcome.code != "confirmed" {
1868                        return Ok(vec![outcome.frame(&frame)]);
1869                    }
1870                }
1871            }
1872        }
1873        match request {
1874            ClientControlRequest::DaemonUpgradeInPlace { executable_sha256 } => {
1875                self.upgrade_in_place(ctx, frame, executable_sha256)
1876            }
1877            ClientControlRequest::DaemonShutdownIntent { intent } => {
1878                self.daemon_restart_intent(frame, intent).await
1879            }
1880            // Clients probe capabilities here before opening routes. A cold
1881            // boot hash is optional metadata, not a prerequisite to serving.
1882            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
1883            ClientControlRequest::PolicyRoot(_)
1884            | ClientControlRequest::PolicyRootSet(_)
1885            | ClientControlRequest::PolicyRootRecover(_) => {
1886                unreachable!("policy root ops dispatch before the client-only path")
1887            }
1888            ClientControlRequest::CatalogList { module_id } => {
1889                self.handle_catalog_list(frame, module_id)
1890            }
1891            ClientControlRequest::RouteOpen {
1892                target,
1893                identity,
1894                consumer_identity,
1895                consumer_capabilities,
1896                role_versions,
1897                busy_refusals,
1898                admission_facts,
1899                scope,
1900                ..
1901            } => {
1902                let extensions = match serde_json::from_slice::<subc_control::RouteOpenRequestExt>(
1903                    &frame.body,
1904                ) {
1905                    Ok(extensions) => extensions,
1906                    Err(err) => {
1907                        return Ok(vec![control_error_frame(
1908                            &frame,
1909                            "invalid_control_body",
1910                            format!("malformed route.open extensions: {err}"),
1911                        )?]);
1912                    }
1913                };
1914                self.handle_route_open(
1915                    ctx,
1916                    frame,
1917                    RouteOpenRequest {
1918                        target,
1919                        identity,
1920                        consumer_identity,
1921                        consumer_capabilities,
1922                        role_versions,
1923                        busy_refusals,
1924                        admission_facts,
1925                        scope,
1926                        accepts_close_reasons: extensions.accepts_close_reasons,
1927                    },
1928                    route_open_timings.get_or_insert_with(RouteOpenTimings::new),
1929                )
1930                .await
1931            }
1932            ClientControlRequest::RoutePoll {
1933                route_channel,
1934                route_epoch,
1935                kind,
1936            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
1937            ClientControlRequest::SupervisorList {} => {
1938                let Ok(permit) = Arc::clone(&self.list_admission).try_acquire_owned() else {
1939                    self.agent_declarations.refuse(
1940                        self,
1941                        ctx,
1942                        control_error_frame(
1943                            &frame,
1944                            "busy",
1945                            "supervisor list work is at capacity; retry",
1946                        )?,
1947                    );
1948                    return Ok(Vec::new());
1949                };
1950                // Filesystem-backed diagnostics must not hold up this connection's reader.
1951                let handler = self.clone();
1952                let sink = ctx.egress.clone();
1953                tokio::spawn(
1954                    async move {
1955                        let _permit = permit;
1956                        let result = handler.handle_supervisor_list(frame.clone()).await;
1957                        let replies = match result {
1958                            Ok(replies) => replies,
1959                            Err(error) => {
1960                                control_error_frame(&frame, "backend_error", error.to_string())
1961                                    .into_iter()
1962                                    .collect()
1963                            }
1964                        };
1965                        for reply in replies {
1966                            if !matches!(
1967                                tokio::time::timeout(Duration::from_millis(200), sink.send(reply))
1968                                    .await,
1969                                Ok(Ok(()))
1970                            ) {
1971                                break;
1972                            }
1973                        }
1974                    }
1975                    .with_current_subscriber(),
1976                );
1977                Ok(Vec::new())
1978            }
1979            ClientControlRequest::SupervisorSpawnSnapshot {} => {
1980                self.handle_supervisor_spawn_snapshot(frame)
1981            }
1982            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
1983                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
1984            }
1985            ClientControlRequest::SupervisorRestart {
1986                module_id,
1987                drain_timeout_ms,
1988            } => {
1989                self.log_supervisor_request_received(
1990                    ctx,
1991                    frame.header.corr,
1992                    ops::SUPERVISOR_RESTART,
1993                    Some(&module_id),
1994                    None,
1995                )?;
1996                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
1997                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms, requester)
1998                    .await
1999            }
2000            ClientControlRequest::SupervisorSwap {
2001                module_id,
2002                ready_timeout_ms,
2003            } => {
2004                self.log_supervisor_request_received(
2005                    ctx,
2006                    frame.header.corr,
2007                    ops::SUPERVISOR_SWAP,
2008                    Some(&module_id),
2009                    None,
2010                )?;
2011                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2012                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms, requester)
2013                    .await
2014            }
2015            ClientControlRequest::SupervisorReload { module_id } => {
2016                self.log_supervisor_request_received(
2017                    ctx,
2018                    frame.header.corr,
2019                    ops::SUPERVISOR_RELOAD,
2020                    Some(&module_id),
2021                    None,
2022                )?;
2023                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2024                self.handle_supervisor_reload(frame, module_id, requester)
2025                    .await
2026            }
2027            ClientControlRequest::SupervisorRescan { preview } => {
2028                if !preview {
2029                    self.log_supervisor_request_received(
2030                        ctx,
2031                        frame.header.corr,
2032                        ops::SUPERVISOR_RESCAN,
2033                        None,
2034                        None,
2035                    )?;
2036                }
2037                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2038                let operation = self.handle_supervisor_rescan(
2039                    frame,
2040                    if preview {
2041                        RescanMode::Preview
2042                    } else {
2043                        RescanMode::Execute
2044                    },
2045                    requester,
2046                );
2047                self.observe_control_wait(ctx, None, ops::SUPERVISOR_RESCAN, operation)
2048                    .await
2049            }
2050            ClientControlRequest::SupervisorRescanChecked {
2051                preview,
2052                candidate,
2053                expect,
2054            } => {
2055                self.observe_control_wait(
2056                    ctx,
2057                    None,
2058                    ops::SUPERVISOR_RESCAN,
2059                    self.handle_supervisor_rescan_checked(ctx, frame, preview, candidate, expect),
2060                )
2061                .await
2062            }
2063            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
2064                self.log_supervisor_request_received(
2065                    ctx,
2066                    frame.header.corr,
2067                    ops::SUPERVISOR_RELEASE_RESERVED,
2068                    Some(&module_id),
2069                    None,
2070                )?;
2071                self.handle_supervisor_release_reserved(frame, module_id)
2072                    .await
2073            }
2074            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
2075                self.log_supervisor_request_received(
2076                    ctx,
2077                    frame.header.corr,
2078                    ops::SUPERVISOR_SET_ENABLED,
2079                    Some(&module_id),
2080                    Some(enabled),
2081                )?;
2082                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2083                self.handle_supervisor_set_enabled(frame, module_id, enabled, requester)
2084                    .await
2085            }
2086            ClientControlRequest::SupervisorHealthProbe { module_id } => {
2087                self.handle_supervisor_health_probe(ctx, frame, module_id)
2088                    .await
2089            }
2090            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
2091            ClientControlRequest::SupervisorRoutes { module_id } => {
2092                self.handle_supervisor_routes(frame, module_id)
2093            }
2094            ClientControlRequest::SupervisorProvenance { module_id } => {
2095                self.handle_supervisor_provenance(ctx, frame, module_id)
2096                    .await
2097            }
2098            ClientControlRequest::SupervisorStderrTail {
2099                module_id,
2100                max_lines,
2101                max_bytes,
2102            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
2103            ClientControlRequest::SupervisorTerminals { module_id } => {
2104                self.handle_supervisor_terminals(ctx, frame, module_id)
2105                    .await
2106            }
2107        }
2108    }
2109
2110    /// Explicit test-only phone policy; daemon configuration cannot select it.
2111    #[cfg(any(test, feature = "test-support"))]
2112    pub fn with_test_phone_shortcut(mut self, enabled: bool) -> Self {
2113        self.operator_app_policy.phone_enabled = enabled;
2114        self
2115    }
2116
2117    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
2118        debug!(connection_id = connection_id.get(), "handling GOODBYE");
2119        // GOODBYE ends the connection's logical session even when its socket
2120        // stays open. Use disconnect teardown so verdicts, client notices and
2121        // scope authority are released at the same lifecycle boundary.
2122        self.cleanup_connection_with_end_reason(
2123            connection_id,
2124            RegistrationEndReason::ExplicitGoodbye,
2125        )
2126        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
2127        Ok(Vec::new())
2128    }
2129}
2130
2131impl Default for ControlHandler {
2132    fn default() -> Self {
2133        Self::new(Arc::new(Registry::default()))
2134    }
2135}
2136
2137impl crate::supervise::SwapPromotionObserver for ControlHandler {
2138    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
2139        self.apply_registration_capabilities(registration);
2140    }
2141}
2142
2143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2144enum ControlRequestBodyError {
2145    UnknownOp,
2146    InvalidBody,
2147}
2148
2149#[derive(Debug, Deserialize)]
2150struct ControlOpProbe {
2151    op: String,
2152}
2153
2154fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
2155    debug!(
2156        op = %op,
2157        connection_id = connection_id.get(),
2158        corr,
2159        "control dispatch"
2160    );
2161}
2162
2163fn log_slow_control_dispatch(
2164    dispatch_started_at: Option<StdInstant>,
2165    op: &'static str,
2166    connection_id: ConnectionId,
2167    corr: u64,
2168    route_open_timings: Option<&RouteOpenTimings>,
2169) {
2170    let Some(dispatch_started_at) = dispatch_started_at else {
2171        return;
2172    };
2173    // Use the same monotonic clock as the phase timers and relay deadline.
2174    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
2175    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
2176        if let Some(timings) = route_open_timings {
2177            warn!(
2178                op = %op,
2179                connection_id = connection_id.get(),
2180                corr,
2181                elapsed_ms = elapsed.as_millis() as u64,
2182                module_id = ?timings.module_id,
2183                principal = %timings.principal,
2184                admission_ms = timings.admission.as_millis() as u64,
2185                project_root_ms = timings.project_root.as_millis() as u64,
2186                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
2187                bind_send_ms = timings.bind_send.as_millis() as u64,
2188                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
2189                "slow control dispatch"
2190            );
2191            return;
2192        }
2193        warn!(
2194            op = %op,
2195            connection_id = connection_id.get(),
2196            corr,
2197            elapsed_ms = elapsed.as_millis() as u64,
2198            "slow control dispatch"
2199        );
2200    }
2201}
2202
2203/// A test stand-in for the OS caller lookup, given the recorded endpoints.
2204#[cfg(test)]
2205type TestCallerLookup =
2206    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
2207
2208/// Every new client operation needs an explicit privilege decision here.
2209fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
2210    request.privileged_operation()
2211}
2212
2213trait PrivilegedRequest {
2214    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
2215}
2216
2217impl PrivilegedRequest for ClientControlRequest {
2218    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
2219        let request = self;
2220        match request {
2221        ClientControlRequest::SupervisorRestart { module_id, .. } => {
2222            Some(PrivilegedOperation::Restart { module_id })
2223        }
2224        ClientControlRequest::DaemonUpgradeInPlace { .. } => Some(PrivilegedOperation::UpgradeInPlace),
2225        ClientControlRequest::SupervisorSwap { module_id, .. } => {
2226            Some(PrivilegedOperation::Swap { module_id })
2227        }
2228        ClientControlRequest::SupervisorReload { module_id } => {
2229            Some(PrivilegedOperation::Reload { module_id })
2230        }
2231        ClientControlRequest::SupervisorRescan { preview } => {
2232            if *preview {
2233                None
2234            } else {
2235                Some(PrivilegedOperation::Rescan)
2236            }
2237        }
2238        // Only the well-formed apply can change state, so only it needs approval.
2239        ClientControlRequest::SupervisorRescanChecked {
2240            preview,
2241            candidate,
2242            expect,
2243        } => (!*preview && candidate.is_none() && expect.is_some())
2244            .then_some(PrivilegedOperation::Rescan),
2245        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
2246            Some(PrivilegedOperation::SetEnabled {
2247                module_id,
2248                enabled: *enabled,
2249            })
2250        }
2251        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
2252            Some(PrivilegedOperation::ReleaseReserved { module_id })
2253        }
2254        ClientControlRequest::ServerDescribe {}
2255        | ClientControlRequest::PolicyRoot(_)
2256        | ClientControlRequest::PolicyRootSet(_)
2257        | ClientControlRequest::PolicyRootRecover(_)
2258        // A restart announcement cannot stop anything and requires no prompt.
2259        | ClientControlRequest::DaemonShutdownIntent { .. }
2260        | ClientControlRequest::CatalogList { .. }
2261        | ClientControlRequest::RouteOpen { .. }
2262        | ClientControlRequest::RoutePoll { .. }
2263        | ClientControlRequest::SupervisorList {}
2264        | ClientControlRequest::SupervisorHealth {}
2265        | ClientControlRequest::SupervisorHealthProbe { .. }
2266        | ClientControlRequest::SupervisorRoutes { .. }
2267        | ClientControlRequest::SupervisorProvenance { .. }
2268        | ClientControlRequest::SupervisorStderrTail { .. }
2269        | ClientControlRequest::SupervisorTerminals { .. }
2270        | ClientControlRequest::SupervisorSpawnSnapshot {}
2271        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
2272    }
2273    }
2274}
2275
2276fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
2277    match request {
2278        ClientControlRequest::PolicyRoot(_) => subc_protocol::policy_root::GET_OP,
2279        ClientControlRequest::PolicyRootSet(_) => subc_control::policy_root::SET_OP,
2280        ClientControlRequest::PolicyRootRecover(_) => subc_control::policy_root::RECOVER_OP,
2281        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
2282        ClientControlRequest::DaemonUpgradeInPlace { .. } => ops::DAEMON_UPGRADE_IN_PLACE,
2283        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
2284        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
2285        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
2286        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
2287        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
2288        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
2289        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
2290        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
2291        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
2292        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
2293        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
2294        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
2295        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
2296        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
2297        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
2298        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
2299        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
2300        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
2301        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
2302        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
2303    }
2304}
2305
2306fn parse_client_control_request(
2307    body: &[u8],
2308) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
2309    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
2310        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
2311            Ok(probe)
2312                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
2313                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
2314            {
2315                ControlRequestBodyError::InvalidBody
2316            }
2317            Ok(_) => ControlRequestBodyError::UnknownOp,
2318            Err(_) => ControlRequestBodyError::InvalidBody,
2319        };
2320        (err, classification)
2321    })
2322}
2323
2324fn pong(frame: &Frame) -> Result<Frame, RouterError> {
2325    Frame::build_with_version(
2326        response_version(frame),
2327        FrameType::Pong,
2328        frame.header.flags,
2329        0,
2330        0,
2331        frame.header.corr,
2332        Vec::new(),
2333    )
2334    .map_err(RouterError::FrameBuild)
2335}
2336
2337pub(crate) fn control_error_frame(
2338    frame: &Frame,
2339    code: &'static str,
2340    message: impl Into<String>,
2341) -> Result<Frame, RouterError> {
2342    control_error_body_frame(
2343        frame,
2344        ErrorBody {
2345            code: code.to_string(),
2346            message: message.into(),
2347            detail: None,
2348        },
2349    )
2350}
2351
2352/// A channel-0 ERROR for a refusal the daemon decided itself: every
2353/// route.open refusal, the drain `module_reloading` and scope-change/end
2354/// bodies, spawn-subscription and supervisor refusals. Carries the
2355/// daemon-origin bit, which is what lets a client treat `module_reloading`
2356/// as proof that its request never reached a module. Response, push,
2357/// goodbye and relay-request frames keep the plain control flags in their
2358/// own builders.
2359pub(crate) fn control_error_body_frame(
2360    frame: &Frame,
2361    error: ErrorBody,
2362) -> Result<Frame, RouterError> {
2363    control_error_frame_with_flags(frame, error, daemon_error_flags())
2364}
2365
2366/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
2367/// refused route.bind answered as a route.open refusal, or a refused
2368/// module-control RPC. Plain control flags — the code and message are
2369/// module-chosen, so the frame must not claim daemon authorship, even when
2370/// the module picks a daemon code like `module_reloading`.
2371fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
2372    control_error_frame_with_flags(frame, error, control_flags())
2373}
2374
2375fn control_error_frame_with_flags(
2376    frame: &Frame,
2377    error: ErrorBody,
2378    flags: Flags,
2379) -> Result<Frame, RouterError> {
2380    let body = serde_json::to_vec(&error).map_err(|err| {
2381        RouterError::backend(
2382            0,
2383            frame.header.corr,
2384            format!("failed to encode control ERROR: {err}"),
2385        )
2386    })?;
2387
2388    Frame::build_with_version(
2389        response_version(frame),
2390        FrameType::Error,
2391        flags,
2392        0,
2393        0,
2394        frame.header.corr,
2395        body,
2396    )
2397    .map_err(RouterError::FrameBuild)
2398}
2399
2400pub(crate) fn control_response_body_frame<T: Serialize>(
2401    frame: &Frame,
2402    reply: &T,
2403    label: &'static str,
2404) -> Result<Frame, RouterError> {
2405    let body = serde_json::to_vec(reply).map_err(|err| {
2406        RouterError::backend(
2407            0,
2408            frame.header.corr,
2409            format!("failed to encode {label}: {err}"),
2410        )
2411    })?;
2412
2413    Frame::build_with_version(
2414        response_version(frame),
2415        FrameType::Response,
2416        control_flags(),
2417        0,
2418        0,
2419        frame.header.corr,
2420        body,
2421    )
2422    .map_err(RouterError::FrameBuild)
2423}
2424
2425fn forwarding_error_code(err: &ForwardingError) -> &'static str {
2426    match err {
2427        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
2428        ForwardingError::NoModuleConnection => "target_unavailable",
2429        ForwardingError::ModuleReloading { .. } => "module_reloading",
2430        ForwardingError::ClientRouteChannelExhausted { .. }
2431        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
2432        ForwardingError::StaleModuleEndpoint
2433        | ForwardingError::UnknownReservation { .. }
2434        | ForwardingError::ConnectionClosing { .. }
2435        | ForwardingError::ClientEgressClosed { .. }
2436        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
2437        // Only a swap candidate's registration can produce this, and it means
2438        // exactly what a second active HELLO for a live id means.
2439        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
2440        ForwardingError::HelloRegistrationRefused(code) => code,
2441        ForwardingError::TargetRegistrationChanged(_) => "capability_forbidden",
2442        ForwardingError::RelayDeadlineElapsed => "module_timeout",
2443        ForwardingError::RelayCorrelationExhausted
2444        | ForwardingError::RouteOpenBuild(_)
2445        | ForwardingError::Poisoned => "forwarding_error",
2446    }
2447}
2448
2449fn response_version(frame: &Frame) -> u8 {
2450    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
2451        frame.header.ver
2452    } else {
2453        PROTOCOL_VERSION
2454    }
2455}
2456
2457pub(crate) fn control_flags() -> Flags {
2458    Flags::new(false, Priority::Passive, false)
2459}
2460
2461/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
2462/// channel. The target is the module (a client never saw the route), so this
2463/// takes the module path: delivered late rather than dropped when the module's
2464/// queue is momentarily full, and never closing its connection.
2465fn send_goodbye_target_best_effort(
2466    counters: &DaemonCounters,
2467    target: &GoodbyeTarget,
2468    context: &'static str,
2469) {
2470    let Ok(frame) = Frame::build_with_version(
2471        target.negotiated_ver,
2472        FrameType::Goodbye,
2473        control_flags(),
2474        target.channel,
2475        target.epoch,
2476        0,
2477        Vec::new(),
2478    ) else {
2479        return;
2480    };
2481    crate::forwarding::send_module_route_goodbye(
2482        counters,
2483        &target.sink,
2484        frame,
2485        target.module_id.as_deref(),
2486        context,
2487    );
2488}
2489
2490fn route_close_reason_for_opener(
2491    reason: RouteCloseReason,
2492    accepts_close_reasons: Option<&[String]>,
2493) -> RouteCloseReason {
2494    if reason == RouteCloseReason::AuthorityChanged
2495        && !accepts_close_reasons
2496            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
2497    {
2498        // Older readers forbid reopening for unknown reasons. Reload already
2499        // permits reopening and, like an authority change, requires a new bind.
2500        RouteCloseReason::Reload
2501    } else {
2502        reason
2503    }
2504}
2505
2506pub(crate) fn send_route_control_pushes(
2507    forwarding: &ForwardingTable,
2508    routes: Vec<EndpointRoute>,
2509    push: ClientControlPush,
2510) {
2511    let reason = match &push {
2512        ClientControlPush::RouteClosing { reason, .. }
2513        | ClientControlPush::RouteClosed { reason, .. } => *reason,
2514    };
2515    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
2516    for route in routes {
2517        let recipient_reason =
2518            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
2519        let target = route.goodbye_target;
2520        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
2521            existing.connection_id == target.connection_id && *reason == recipient_reason
2522        }) {
2523            debug_assert_eq!(
2524                existing.negotiated_ver, target.negotiated_ver,
2525                "one connection cannot negotiate multiple frame versions"
2526            );
2527            if !channels.contains(&target.channel) {
2528                channels.push(target.channel);
2529            }
2530            continue;
2531        }
2532        let channel = target.channel;
2533        targets.push((target, recipient_reason, vec![channel]));
2534    }
2535    for (target, recipient_reason, mut channels) in targets {
2536        channels.sort_unstable();
2537        let mut push = push.clone();
2538        match &mut push {
2539            ClientControlPush::RouteClosing {
2540                channels: covered,
2541                reason,
2542                ..
2543            }
2544            | ClientControlPush::RouteClosed {
2545                channels: covered,
2546                reason,
2547                ..
2548            } => {
2549                *covered = channels;
2550                *reason = recipient_reason;
2551            }
2552        }
2553        let body = match serde_json::to_vec(&push) {
2554            Ok(body) => body,
2555            Err(err) => {
2556                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
2557                continue;
2558            }
2559        };
2560        let frame = match Frame::build_with_version(
2561            target.negotiated_ver,
2562            FrameType::Push,
2563            control_flags(),
2564            0,
2565            0,
2566            0,
2567            body.clone(),
2568        ) {
2569            Ok(frame) => frame,
2570            Err(err) => {
2571                warn!(
2572                    route_channel = target.channel,
2573                    error = %err,
2574                    "failed to build route lifecycle control PUSH frame"
2575                );
2576                continue;
2577            }
2578        };
2579        if let Err(err) = target.sink.try_send(frame) {
2580            if target.close_on_delivery_failure() {
2581                warn!(
2582                    target_connection_id = target.connection_id.get(),
2583                    route_channel = target.channel,
2584                    error = %err,
2585                    "route lifecycle control PUSH was not delivered to client; closing target connection"
2586                );
2587                let _ = forwarding.escalate_client_delivery_failure(
2588                    target.connection_id,
2589                    target.channel,
2590                    target.epoch,
2591                    CloseReason::new(
2592                        "route_lifecycle_push_delivery_failed",
2593                        format!(
2594                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
2595                            target.channel
2596                        ),
2597                    ),
2598                    crate::forwarding::UndeliveredFrame {
2599                        module_id: target.module_id.as_deref(),
2600                        sink: &target.sink,
2601                    },
2602                );
2603            }
2604        }
2605    }
2606}
2607
2608#[cfg(test)]
2609#[path = "control/scope_outcome_count_tests.rs"]
2610mod scope_outcome_count_tests;
2611
2612#[cfg(test)]
2613#[path = "control/control_tests.rs"]
2614mod tests;
2615
2616#[cfg(test)]
2617#[path = "control/concurrency_default_exposure_tests.rs"]
2618mod concurrency_default_exposure_tests;