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