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
99const CAP_MANIFEST_REGISTRATION: &str = "manifest_registration_v1";
100const CAP_CHANNEL_LIFECYCLE: &str = "channel_lifecycle_v1";
101const CAP_PING_PONG: &str = "ping_pong_v1";
102const CAP_SESSION_ATTACH: &str = "session_attach_v1";
103const CAP_ADMISSION_FACTS_RELAY: &str = "admission_facts_relay_v1";
104
105mod advertised_ops;
106use advertised_ops::*;
107mod caller_attestation;
108mod channel_operations;
109#[cfg(all(test, unix, feature = "test-support"))]
110#[path = "control/channel_operations_tests.rs"]
111mod channel_operations_tests;
112pub(crate) mod claims;
113#[cfg(test)]
114#[path = "control/config_advertisement_tests.rs"]
115mod config_advertisement_tests;
116mod config_gate;
117#[path = "operator_apps/connection.rs"]
118mod peer_identity;
119use caller_attestation::{caller_for_target, scope_acts_for_another};
120mod activity_reservations;
121#[cfg(all(test, unix, feature = "test-support"))]
122#[path = "control/caller_attestation_tests.rs"]
123mod caller_attestation_tests;
124mod capability_census;
125mod route_bind_settlement;
126mod scope_expiry;
127mod scope_watch;
128mod usage;
129
130mod agent_commands;
131pub(crate) mod catalog;
132mod policy_root;
133mod rescan_checked;
134use rescan_checked::{RescanMode, RescanPlan};
135
136/// Module-originated ops the daemon answers but does not advertise in
137/// `HELLO_ACK`. Empty today; an op is served from here while the feature it
138/// belongs to is incomplete, so no module is told it works before it does.
139const MODULE_TO_SUBC_UNADVERTISED_OPS: &[&str] = &[];
140
141const MODULE_BASELINE_CONTROL_OPS: &[&str] = &["route.bind", "route.status"];
142
143/// How long subc waits for a module to ack a relayed route.bind before returning
144/// `module_timeout`. The ack waits on the module's own configure, which for AFT
145/// includes a synchronous bounded project walk (up to ~20k files) plus gitignore
146/// and DB-open work — on a cold page cache or a large repo that legitimately
147/// exceeds a couple of seconds. The default is generous because rejecting a VALID
148/// bind is far worse than waiting on a slow one; a consumer that wants a tighter
149/// bound retries the bind itself (the sanctioned warm-bind-retry pattern).
150pub const DEFAULT_ROUTE_BIND_RELAY_TIMEOUT: Duration = Duration::from_secs(12);
151
152/// How many CONSECUTIVE full-budget relay timeouts against one target module
153/// open that module's bind-relay breaker.
154///
155/// Three, so that the breaker is NOT REACHABLE INSIDE ONE CLIENT CALL. Both
156/// SDKs default to a 30s request deadline and the relay budget defaults to 12s,
157/// so three consecutive full-budget timeouts take ~36s to observe: every client
158/// whose open contributed to opening the breaker had already given up on its
159/// own. That is what makes opening the breaker unable to turn a call that would
160/// have succeeded into a refusal — it can only make an already-failing module
161/// fail faster.
162///
163/// Two would be reachable inside one default deadline. One would convict a
164/// module on a single cold-cache bind, which is exactly the valid-but-slow case
165/// `DEFAULT_ROUTE_BIND_RELAY_TIMEOUT`'s own doc comment exists to protect.
166pub const DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD: u32 = 3;
167
168/// How long a module's bind-relay breaker stays open before exactly one
169/// `route.open` is let through as a probe.
170///
171/// Bounded BELOW by the relay budget: a cooldown at or under the 12s budget
172/// re-pays a full-budget stall almost continuously, and the breaker stops being
173/// a saving worth its own state. Bounded ABOVE by the SDKs' 30s default request
174/// deadline: a client that starts retrying after the module recovers has to get
175/// a probe opportunity inside its own deadline, or the breaker converts a
176/// recovered module into a failed call — the failure it exists to prevent,
177/// pointed the other way.
178///
179/// 20s sits between those with room on both sides, and it caps what a wedged
180/// module can cost at one full-budget wait per 20s ACROSS THE WHOLE DAEMON
181/// rather than one per `route.open` per connection. The stall that motivated
182/// this, with its measurements, is written up in
183/// `docs/designs/route-open-head-of-line.md`: 268 opens against one module each
184/// waited the whole budget out.
185pub const DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN: Duration = Duration::from_secs(20);
186
187const DEFAULT_HEALTH_PROBE_TIMEOUT: Duration = Duration::from_secs(5);
188const SLOW_CONTROL_DISPATCH_THRESHOLD: Duration = Duration::from_secs(1);
189
190fn reload_verdict(
191    configured: &Path,
192    spawned_from: Option<&Path>,
193    image: subc_control::RunningImageAgreement,
194) -> PendingReloadVerdict {
195    let path = match spawned_from {
196        Some(spawned_from) if reload_paths_match(configured, spawned_from) => {
197            ReloadPathAgreement::Match
198        }
199        Some(spawned_from) => ReloadPathAgreement::Mismatch {
200            configured: configured.to_path_buf(),
201            spawned_from: spawned_from.to_path_buf(),
202        },
203        None => ReloadPathAgreement::Unavailable {
204            reason: if matches!(
205                image,
206                subc_control::RunningImageAgreement::Unavailable {
207                    reason: subc_control::RunningImageUnavailableReason::NotRunning
208                }
209            ) {
210                ReloadPathUnavailableReason::NotRunning
211            } else {
212                ReloadPathUnavailableReason::SpawnedPathUnavailable
213            },
214        },
215    };
216    PendingReloadVerdict::new(path, image)
217}
218
219fn launch_spec_agreement(
220    configured: &crate::supervise::ModuleSpec,
221    running: bool,
222    spawned: Option<&crate::supervise::LaunchSpecDigest>,
223) -> subc_control::LaunchSpecAgreement {
224    use subc_control::{LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason};
225    if !running {
226        return Agreement::Unavailable {
227            reason: Reason::NotRunning,
228        };
229    }
230    match spawned {
231        None => Agreement::Unavailable {
232            reason: Reason::SpawnedSpecUnavailable,
233        },
234        Some(digest) if *digest == crate::supervise::LaunchSpecDigest::from_spec(configured) => {
235            Agreement::Match
236        }
237        Some(_) => Agreement::Mismatch,
238    }
239}
240
241fn reload_paths_match(configured: &Path, spawned_from: &Path) -> bool {
242    if configured == spawned_from {
243        return true;
244    }
245    #[cfg(windows)]
246    {
247        // Windows spawn records the resolved verbatim path (\\?\...), while
248        // configuration keeps its original spelling. Resolve both with the OS
249        // instead of stripping prefixes or folding case, which could conflate
250        // distinct names in case-sensitive directories. Different resolved
251        // paths still differ even if their files have identical content.
252        match (
253            std::fs::canonicalize(configured),
254            std::fs::canonicalize(spawned_from),
255        ) {
256            (Ok(configured), Ok(spawned_from)) => configured == spawned_from,
257            _ => false,
258        }
259    }
260    #[cfg(not(windows))]
261    {
262        false
263    }
264}
265
266#[derive(Clone)]
267struct DaemonProvenanceFacts {
268    build: DaemonBuildProvenance,
269    pid: Option<u32>,
270    started_at_ms: Option<u64>,
271    start_clock: Option<crate::clock::StartClock>,
272    executable_path: Option<PathBuf>,
273    executable_identity: Option<SpawnedFileIdentity>,
274    process_start_time: Option<u64>,
275    probe: ExecutableIdentityProbe,
276}
277
278impl Default for DaemonProvenanceFacts {
279    fn default() -> Self {
280        Self {
281            build: DaemonBuildProvenance {
282                build_git_sha: None,
283                build_lock_digest: None,
284            },
285            pid: None,
286            started_at_ms: None,
287            start_clock: None,
288            executable_path: None,
289            executable_identity: None,
290            process_start_time: None,
291            probe: ExecutableIdentityProbe::default(),
292        }
293    }
294}
295
296#[derive(Debug, Clone)]
297struct SupervisorRescanContext {
298    supervisor: Supervisor,
299    config_path: PathBuf,
300    configured_port: Option<u16>,
301    storage_config: Option<crate::daemon_config::StorageConfig>,
302    admission_facts_carrier_module_id: Option<String>,
303    admission_facts_targets: Option<Vec<String>>,
304    scope_authority_owners: Vec<String>,
305    federated_scope_owner: String,
306    privileged_operator_prompt: PrivilegedOperatorPrompt,
307    /// Counts executed rescans that set out to change the supervised modules'
308    /// staged or applied configuration, counted before the first change so a
309    /// rescan that fails partway still counts. With the daemon incarnation it
310    /// names the state a `supervisor.rescan_checked` preview was computed
311    /// against.
312    generation: Arc<std::sync::atomic::AtomicU64>,
313    rescan_lock: Arc<tokio::sync::Mutex<()>>,
314    module_entries: Arc<Mutex<rescan_checked::ModuleEntries>>,
315}
316
317/// Refusal labels passed to `observe_route_open_refusal` that mean the target
318/// module is not serving right now, and so open or extend an outage in the
319/// route outage tracker. Every one of them is only reachable after the target
320/// was found in the registry, which is what keeps an arbitrary client-chosen
321/// id from ever creating tracker state.
322///
323/// Deliberately absent: `not_registered` and `removed` (the id may be
324/// anything a client sent, and a removed module is gone on purpose),
325/// `protocol_none` (such a module never serves routes, so nothing is out),
326/// `role_not_provided`, `op_not_allowed`, `bad_consumer_identity`, the
327/// capability and admission-facts refusals (they refuse the caller, not a
328/// module outage), and `relay_reservation_failed` (its code ranges over
329/// capacity limits as well as a vanished connection). Capacity, breaker,
330/// relay-timeout and module-rejection refusals do not pass through that
331/// function at all; the breaker logs its own transitions.
332///
333/// The two not-serving refusals that bypass that function record themselves
334/// at their own sites: `supervised_not_registered` and `declared_not_ready`.
335/// `required_capability_unprovided` is not tracked: the module itself is up,
336/// and the outage belongs to the missing provider.
337const ROUTE_OPEN_NOT_SERVING_REASONS: &[&str] = &[
338    "reloading",
339    "supervisor_not_live",
340    "registration_not_active",
341    "no_forwarding_connection",
342    "relay_send_failed",
343];
344
345/// Observe test request cancellation relative to the connection's cleanup.
346#[cfg(test)]
347struct ActivityRequestPause {
348    connection: ConnectionId,
349    started: tokio::sync::Notify,
350    cancelled: tokio::sync::Notify,
351    cleanup_started: std::sync::atomic::AtomicBool,
352    cancelled_after_cleanup: std::sync::atomic::AtomicBool,
353}
354
355#[cfg(test)]
356struct ActivityRequestCancellation(Arc<ActivityRequestPause>);
357
358#[cfg(test)]
359impl Drop for ActivityRequestCancellation {
360    fn drop(&mut self) {
361        self.0.cancelled_after_cleanup.store(
362            self.0
363                .cleanup_started
364                .load(std::sync::atomic::Ordering::Acquire),
365            std::sync::atomic::Ordering::Release,
366        );
367        self.0.cancelled.notify_one();
368    }
369}
370
371/// A test hold: signal arrival, then wait for release on the holding thread.
372#[cfg(test)]
373type TestPause = (
374    tokio::sync::oneshot::Sender<()>,
375    std::sync::mpsc::Receiver<()>,
376);
377
378/// A test hook run once at a fixed point in a handler.
379#[cfg(test)]
380type TestHook = Box<dyn FnOnce() + Send>;
381
382/// A test hold for async code: signal arrival, then await release.
383#[cfg(test)]
384type AsyncTestPause = (
385    tokio::sync::oneshot::Sender<()>,
386    tokio::sync::oneshot::Receiver<()>,
387);
388
389/// Real channel-0 control handler for subc itself.
390#[derive(Clone)]
391pub struct ControlHandler {
392    #[cfg(test)]
393    activity_request_pause: Arc<Mutex<Option<Arc<ActivityRequestPause>>>>,
394    /// Holds connection cleanup at a numbered point: 0 is just after the agent
395    /// declaration queue closes, 1 just after the registration channel is
396    /// forgotten.
397    #[cfg(test)]
398    cleanup_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
399    /// Runs once in `route.open`'s launch-nonce attestation, right after the
400    /// nonce is resolved, to interleave a nonce withdrawal there.
401    #[cfg(test)]
402    after_nonce_attestation: Arc<Mutex<Option<TestHook>>>,
403    /// Holds a registration channel's HELLO after its reader resolved the
404    /// channel and before the blocking HELLO handler starts.
405    #[cfg(test)]
406    hello_ingress_pause: Arc<Mutex<Option<AsyncTestPause>>>,
407    /// Holds an agent command declaration at a numbered point in its handler.
408    #[cfg(test)]
409    agent_commands_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
410    claims: Arc<claims::Claims>,
411    registry: Arc<Registry>,
412    control_usage: Arc<Mutex<usage::ControlUsage>>,
413    catalog_cache: Arc<Mutex<catalog::CatalogCache>>,
414    catalog_readiness_revision: Arc<std::sync::atomic::AtomicU64>,
415    config_runtime: Option<Arc<crate::config_gate::runtime::RuntimeOwner>>,
416    config_review_admission: Arc<dyn crate::config_gate::ReviewAdmission>,
417    config_review_admission_is_default: bool,
418    activity: Option<crate::activity::ActivityLedger>,
419    activity_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
420    activity_reservations: activity_reservations::ActivityReservations,
421    catalog_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
422    config_settings_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
423    scope_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
424    forwarding: Arc<ForwardingTable>,
425    process_liveness: Option<Arc<dyn ModuleProcessLiveness>>,
426    supervisor: SupervisorHandle,
427    pub(crate) resource_tracker: Arc<crate::resource_totals::Tracker>,
428    agent_declarations: agent_commands::Queues,
429    list_admission: Arc<tokio::sync::Semaphore>,
430    subc_capabilities: Arc<[String]>,
431    /// Daemon-wide route.bind relay budget. Used as the fallback when the
432    /// target module has no per-module override in
433    /// `route_bind_relay_timeouts`.
434    route_bind_relay_timeout: Duration,
435    /// Per-module route.bind relay budget overrides, keyed by module id. When
436    /// `handle_route_open` resolves the deadline for a target module, a
437    /// per-module entry wins over the daemon-wide value above.
438    route_bind_relay_timeouts: BTreeMap<String, Duration>,
439    /// Per-target-module bind-relay breaker state. Shared with the forwarding
440    /// table, which is where a new module connection resets it.
441    route_bind_breakers: RouteBindBreakers,
442    /// Live relay admissions keyed by target module. Shared through the
443    /// forwarding table so cloned or separately built handlers enforce one cap.
444    route_bind_concurrency: RouteBindConcurrency,
445    /// Start and end of each module's not-serving period as seen by
446    /// `route.open`, so an outage gets one line at each edge instead of only
447    /// the per-refusal INFO lines. Taken from the forwarding table, so every
448    /// handler built over one table shares it.
449    route_outages: Arc<crate::route_outage::RouteOutageTracker>,
450    route_refusal_log: route_open_refusal_log::RefusalLog,
451    /// Consecutive relay timeouts that open a module's breaker.
452    route_bind_breaker_threshold: u32,
453    /// How long a breaker stays open before one probe is admitted.
454    route_bind_breaker_cooldown: Duration,
455    health_probe_timeout: Duration,
456    /// Central storage policy. When set, each registering module receives its
457    /// resolved storage descriptor in HELLO_ACK; `None` leaves the field absent.
458    storage_config: Option<crate::daemon_config::StorageConfig>,
459    /// The machine id established at boot, served on every HELLO_ACK and on
460    /// `server.describe`. Fixed for the daemon's lifetime: `ck machine adopt`
461    /// changes the file, never this value. `None` serves no id.
462    machine_id: Option<crate::machine_id::MachineId>,
463    admission_facts_carrier_module_id: Option<String>,
464    admission_facts_targets: Option<Vec<String>>,
465    /// Scope records with their sync authorities and tombstones; see
466    /// `crate::scopes`. Shared by clones of this handler, so every connection
467    /// reads and writes one table.
468    scopes: Arc<RwLock<ScopeTable>>,
469    /// Wakes the expiry loop when an accepted scope change may have added a
470    /// deadline, so the loop can wait without ticking while no live scope has
471    /// one. A permit is stored when nothing waits, so no wake is lost.
472    scope_deadline_added: Arc<tokio::sync::Notify>,
473    /// The configured `scope_authority_owners`, kept so a rescan can report a
474    /// changed value as needing a daemon restart; rescan never applies it.
475    scope_authority_owners: Vec<String>,
476    federated_scope_owner: String,
477    /// Fixed at startup so rescan cannot change the policy that guards rescan itself.
478    privileged_operator_prompt: PrivilegedOperatorPrompt,
479    /// The local and peer address of each accepted TCP client connection, read
480    /// from the daemon's own socket, so a privileged request can name its caller.
481    caller_endpoints: Arc<Mutex<HashMap<ConnectionId, (SocketAddr, SocketAddr)>>>,
482    build_class_warned: Arc<Mutex<HashSet<ConnectionId>>>,
483    observed_peers: Arc<Mutex<HashMap<ConnectionId, ObservedPeer>>>,
484    captured_peers: Arc<Mutex<HashMap<ConnectionId, Arc<peer_identity::PeerCapture>>>>,
485    config_desktop_stamps:
486        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
487    local_connections: Arc<Mutex<HashSet<ConnectionId>>>,
488    pub(crate) operator_app_policy: crate::operator_apps::OperatorAppPolicy,
489    pub(crate) operator_apps:
490        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
491    /// One launch entry per app, behind a leaf lock: no other lock is taken
492    /// while it is held. Entries are memory-only, so a daemon or
493    /// installed-service restart drops them and a relaunched daemon never
494    /// mistakes an older process for its own launch.
495    pub(crate) launch_table: std::sync::Arc<crate::app_open::LaunchTable>,
496    /// Serializes `app.open` launches: the liveness check in the decision and
497    /// the later publish must not interleave across concurrent calls, or two
498    /// calls could both launch and the second publish would orphan the first
499    /// process. Refusals and `already_running` answers share the same lock;
500    /// `app.open` is rare, so the cost is negligible.
501    pub(crate) app_open_launch_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
502    // Portable wire samples exercise dispatch without starting an OS process.
503    #[cfg(test)]
504    pub(crate) app_open_test_platform: Option<crate::operator_apps::AppOpenPlatform>,
505    #[cfg(test)]
506    pub(crate) app_open_test_launch: Option<fn() -> Result<u32, crate::app_open::AppOpenRefusal>>,
507    #[cfg(test)]
508    pub(crate) config_review_test_reply: Option<subc_protocol::config::ConfigReviewReply>,
509    #[cfg(test)]
510    recovery_exit_test_after_step: Option<fn(usize) -> Result<(), crate::config_gate::GateError>>,
511    #[cfg(test)]
512    recovery_exit_test_completed: Option<fn(u64)>,
513    #[cfg(test)]
514    apply_reconcile_pause: Arc<Mutex<Option<AsyncTestPause>>>,
515    #[cfg(test)]
516    recovery_exit_test_quiet_retry: bool,
517    #[cfg(test)]
518    recovery_exit_test_retry_pause: Option<fn(u64) -> Option<PathBuf>>,
519    #[cfg(test)]
520    config_delivery_test_wakes:
521        Option<tokio::sync::mpsc::UnboundedSender<(&'static str, tokio::time::Instant)>>,
522    #[cfg(all(test, unix))]
523    config_delivery_test_idle:
524        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
525    /// Test-only Windows signature and flash hooks. Production builds carry
526    /// neither: with the publisher unset, the production table never reaches
527    /// verification, and the default attention hook only logs.
528    #[allow(dead_code)]
529    #[cfg(windows)]
530    pub(crate) windows_verify: Option<crate::app_open::WindowsVerifyFn>,
531    #[allow(dead_code)]
532    #[cfg(windows)]
533    pub(crate) windows_flash: Option<crate::app_open::WindowsFlashFn>,
534    /// Test-only tracking fault hook: makes opening the tracking handle on
535    /// the launched pid fail, so a test can prove an untrackable launch is
536    /// stopped rather than left running.
537    #[allow(dead_code)]
538    #[cfg(windows)]
539    pub(crate) windows_track: Option<crate::app_open::WindowsTrackFn>,
540    /// Test-only count of Windows spawn attempts, so a test can prove a
541    /// refused launch started no process. Unit tests only.
542    #[cfg(all(test, windows))]
543    pub(crate) windows_spawn_attempts: Arc<std::sync::atomic::AtomicU64>,
544    #[cfg(test)]
545    caller_lookup: Option<TestCallerLookup>,
546    /// The launch nonce each module connection presented at HELLO, which is how
547    /// a `scope.sync` is matched to the owner's current launch.
548    hello_launch_nonces: Arc<Mutex<HelloLaunchNonces>>,
549    rescan: Option<SupervisorRescanContext>,
550    connected_clients: ConnectedClients,
551    counters: DaemonCounters,
552    /// Why this daemon serves no local endpoint, when binding one failed. `None`
553    /// when the endpoint is served, and also on a handler that was never told.
554    local_endpoint_unavailable: Option<String>,
555    capability_evaluator: Arc<CapabilityRequirementEvaluator>,
556    /// The supervisor's daemon-shutdown flag. Once it is set, requirement
557    /// changes are logged at INFO with `cause=daemon_shutdown` instead of at
558    /// their usual severity (see [`log_requirement_events`]). A handler built
559    /// without one has a flag that is never set.
560    daemon_shutdown: DaemonShutdownFlag,
561    daemon_provenance: DaemonProvenanceFacts,
562    #[cfg(test)]
563    control_dispatch_delay: Option<Duration>,
564    #[cfg(test)]
565    provenance_probe_override: Option<subc_control::RunningImageAgreement>,
566    /// Holds `route.open` after the route.bind is queued to the module and
567    /// before it is marked enqueued, so a test can make the module's reply (or
568    /// a client teardown) land exactly inside that window.
569    #[cfg(test)]
570    route_bind_relay_sent_hold: Option<Arc<tokio::sync::Barrier>>,
571    /// Holds a HELLO after its registry entry is reserved and before its
572    /// forwarding endpoint is installed, so a test can read the catalog and
573    /// open routes while the module is registered but not yet routable. A
574    /// blocking barrier because the HELLO handler is synchronous; the test
575    /// runs the HELLO on its own thread.
576    #[cfg(test)]
577    hello_registry_to_forwarding_hold: Option<Arc<std::sync::Barrier>>,
578    #[cfg(test)]
579    hello_ack_to_publication_hold: Option<Arc<std::sync::Barrier>>,
580    #[cfg(test)]
581    hello_before_publication_hold: Option<Arc<std::sync::Barrier>>,
582    #[cfg(test)]
583    hello_after_launch_check_hold: Option<Arc<std::sync::Barrier>>,
584    #[cfg(test)]
585    hello_inside_publication_hold: Option<Arc<std::sync::Barrier>>,
586}
587
588impl fmt::Debug for ControlHandler {
589    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
590        f.debug_struct("ControlHandler")
591            .field("registry", &self.registry)
592            .field("forwarding", &self.forwarding)
593            .field("process_liveness", &self.process_liveness.is_some())
594            .field("supervisor", &self.supervisor)
595            .field("subc_capabilities", &self.subc_capabilities)
596            .finish()
597    }
598}
599
600struct RouteOpenRequest {
601    target: RouteTarget,
602    identity: BindIdentity,
603    consumer_identity: Option<ConsumerIdentity>,
604    consumer_capabilities: Option<Vec<String>>,
605    role_versions: Option<BTreeMap<String, String>>,
606    busy_refusals: Option<bool>,
607    admission_facts: Option<serde_json::Value>,
608    scope: Option<ScopeSelector>,
609    accepts_close_reasons: Option<Vec<String>>,
610}
611
612#[derive(Clone, Copy)]
613enum RouteOpenPhase {
614    Admission,
615    ProjectRoot,
616    EgressReservation,
617    BindSend,
618    BindAckWait,
619}
620
621/// Store elapsed time for each route-open phase, including attempts that end
622/// in an early refusal or backend error. Admission also includes rechecks and
623/// commit bookkeeping performed between the other timed phases.
624struct RouteOpenTimings {
625    module_id: String,
626    principal: String,
627    admission: Duration,
628    project_root: Duration,
629    egress_reservation: Duration,
630    bind_send: Duration,
631    bind_ack_wait: Duration,
632    phase: Option<RouteOpenPhase>,
633    phase_started_at: Instant,
634}
635
636impl RouteOpenTimings {
637    fn new() -> Self {
638        Self {
639            module_id: String::new(),
640            // Refusals before attestation must not claim a verified principal.
641            principal: "unresolved".to_string(),
642            admission: Duration::ZERO,
643            project_root: Duration::ZERO,
644            egress_reservation: Duration::ZERO,
645            bind_send: Duration::ZERO,
646            bind_ack_wait: Duration::ZERO,
647            phase: Some(RouteOpenPhase::Admission),
648            phase_started_at: Instant::now(),
649        }
650    }
651
652    fn finish(&mut self) {
653        let elapsed = self.phase_started_at.elapsed();
654        match self.phase.take() {
655            Some(RouteOpenPhase::Admission) => self.admission += elapsed,
656            Some(RouteOpenPhase::ProjectRoot) => self.project_root += elapsed,
657            Some(RouteOpenPhase::EgressReservation) => self.egress_reservation += elapsed,
658            Some(RouteOpenPhase::BindSend) => self.bind_send += elapsed,
659            Some(RouteOpenPhase::BindAckWait) => self.bind_ack_wait += elapsed,
660            None => {}
661        }
662    }
663
664    fn enter(&mut self, phase: RouteOpenPhase) {
665        self.finish();
666        self.phase = Some(phase);
667        self.phase_started_at = Instant::now();
668    }
669}
670
671struct RouteBindReservationGuard {
672    forwarding: Arc<ForwardingTable>,
673    endpoint: ModuleEndpointId,
674    relay_corr: u64,
675    armed: bool,
676}
677
678struct ModuleControlRpcGuard {
679    forwarding: Arc<ForwardingTable>,
680    endpoint: ModuleEndpointId,
681    corr: u64,
682    armed: bool,
683}
684
685impl ModuleControlRpcGuard {
686    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, corr: u64) -> Self {
687        Self {
688            forwarding,
689            endpoint,
690            corr,
691            armed: true,
692        }
693    }
694
695    fn disarm(&mut self) {
696        self.armed = false;
697    }
698}
699
700impl Drop for ModuleControlRpcGuard {
701    fn drop(&mut self) {
702        if self.armed {
703            let _ = self
704                .forwarding
705                .cancel_module_control_rpc(self.endpoint, self.corr);
706        }
707    }
708}
709
710impl RouteBindReservationGuard {
711    fn new(forwarding: Arc<ForwardingTable>, endpoint: ModuleEndpointId, relay_corr: u64) -> Self {
712        Self {
713            forwarding,
714            endpoint,
715            relay_corr,
716            armed: true,
717        }
718    }
719
720    fn release_and_disarm(&mut self) {
721        if !self.armed {
722            return;
723        }
724        if let Ok(Some(target)) = self.forwarding.abort_pending_relay(
725            self.endpoint,
726            self.relay_corr,
727            RouteBindRelayOutcome::ModuleGone("route.open handler canceled".to_string()),
728        ) {
729            send_goodbye_target_best_effort(
730                &self.forwarding.counters(),
731                &target,
732                "canceled route.bind",
733            );
734        }
735        self.armed = false;
736    }
737
738    fn disarm(&mut self) {
739        self.armed = false;
740    }
741}
742
743impl Drop for RouteBindReservationGuard {
744    fn drop(&mut self) {
745        self.release_and_disarm();
746    }
747}
748
749/// Per-target-module circuit breaker around the `route.bind` relay.
750///
751/// The connection reader is serial per connection, so a module whose `on_bind`
752/// sits on the ack blocks every LATER frame on the connections that call it,
753/// including calls to unrelated modules. This does not make any module's bind
754/// fast; it stops the daemon paying the full budget again and again for a
755/// condition it has already observed.
756///
757/// State is keyed by TARGET MODULE and shared by every connection: a wedged
758/// module wedges everyone, so what one connection learned should protect the
759/// rest.
760///
761/// THE MAP IS EMPTY WHILE THE FLEET IS HEALTHY. An entry appears only when a
762/// relay to that module has actually timed out, and is removed again when a
763/// relay is accepted or the module reconnects, so it cannot grow with traffic
764/// or with modules that behave.
765///
766/// # Why a `std` mutex here is not the head-of-line defect again
767///
768/// Acquisition never awaits. The critical section is a hash lookup plus a few
769/// integer updates, with no I/O and no `.await` inside it, so a reader task
770/// cannot be descheduled behind it the way it can behind
771/// `tokio::sync::Mutex::lock().await` or a semaphore permit. It is the same
772/// primitive, held for the same kind of work, as the refusal counter this very
773/// path already increments.
774///
775/// It is also NOT on the data-plane splice path: only `route.open` and module
776/// registration touch it, so bound-route frames gain no state check and no
777/// contention.
778#[derive(Debug, Clone, Default)]
779pub(crate) struct RouteBindBreakers {
780    modules: Arc<Mutex<HashMap<String, ModuleBreakerState>>>,
781}
782
783#[derive(Debug, Clone, Default)]
784pub(crate) struct RouteBindConcurrency {
785    modules: Arc<Mutex<HashMap<String, usize>>>,
786}
787
788struct RouteBindConcurrencyGuard {
789    concurrency: RouteBindConcurrency,
790    module_id: String,
791}
792
793impl RouteBindConcurrency {
794    /// Admit without waiting. Waiting here would move the bind stall from the
795    /// module reply to a semaphore and restore reader head-of-line blocking.
796    fn try_admit(&self, module_id: &str, limit: usize) -> Result<RouteBindConcurrencyGuard, usize> {
797        let mut modules = self
798            .modules
799            .lock()
800            .expect("route.bind concurrency mutex poisoned");
801        let in_flight = modules.entry(module_id.to_string()).or_default();
802        if *in_flight >= limit {
803            return Err(*in_flight);
804        }
805        *in_flight += 1;
806        Ok(RouteBindConcurrencyGuard {
807            concurrency: self.clone(),
808            module_id: module_id.to_string(),
809        })
810    }
811}
812
813impl Drop for RouteBindConcurrencyGuard {
814    fn drop(&mut self) {
815        let mut modules = self
816            .concurrency
817            .modules
818            .lock()
819            .expect("route.bind concurrency mutex poisoned");
820        let remove = {
821            let in_flight = modules
822                .get_mut(&self.module_id)
823                .expect("admitted route.bind has a concurrency entry");
824            *in_flight -= 1;
825            *in_flight == 0
826        };
827        if remove {
828            modules.remove(&self.module_id);
829        }
830    }
831}
832
833#[derive(Debug, Default)]
834struct ModuleBreakerState {
835    /// Relay timeouts observed with no accepted relay in between.
836    consecutive_timeouts: u32,
837    /// `Some` while the breaker is open: the instant the cooldown expires and
838    /// the next arrival may probe. `None` means closed.
839    cooldown_until: Option<Instant>,
840    /// A half-open probe has been admitted and has not settled yet. This is
841    /// what makes the probe EXACTLY ONE: the flag is set under the same lock
842    /// that read the cooldown, so concurrent opens arriving at the moment the
843    /// cooldown expires cannot all decide that they are the probe.
844    probe_in_flight: Option<Arc<()>>,
845}
846
847/// What the breaker decided for one `route.open`, before any relay work.
848enum RouteBindAdmission<'a> {
849    Admitted {
850        guard: RouteBindBreakerGuard<'a>,
851        /// This open is the single half-open probe, so the transition is worth
852        /// one log line.
853        probe: bool,
854    },
855    Refused {
856        consecutive_timeouts: u32,
857        /// What is left of the cooldown. Zero when the refusal is because the
858        /// one probe is already in flight rather than because the cooldown has
859        /// not elapsed.
860        retry_in: Duration,
861        probe_in_flight: bool,
862    },
863}
864
865/// An outstanding admission, which must be told how its relay settled.
866///
867/// `Drop` settles it as inconclusive, so an early return between admission and
868/// the relay -- or the whole handler being cancelled when the client
869/// disconnects -- releases a half-open probe slot instead of leaving the
870/// breaker wedged half-open with no further probes.
871struct RouteBindBreakerGuard<'a> {
872    breakers: RouteBindBreakers,
873    module_id: &'a str,
874    probe_token: Option<Arc<()>>,
875    settled: bool,
876}
877
878impl RouteBindBreakerGuard<'_> {
879    /// The module answered within the budget and took the bind. THE ONLY
880    /// OUTCOME THAT CLEARS THE COUNT. Returns true when this closed an open
881    /// breaker, which is a transition worth logging.
882    fn record_accepted(&mut self) -> bool {
883        self.settled = true;
884        self.breakers.record_accepted(self.module_id)
885    }
886
887    /// The relay burned the whole budget with no answer. THE ONLY ARM THAT
888    /// COUNTS TOWARD OPENING.
889    fn record_timeout(&mut self, threshold: u32, cooldown: Duration) -> Option<BreakerOpened> {
890        self.settled = true;
891        self.breakers.record_timeout(
892            self.module_id,
893            self.probe_token.as_ref(),
894            threshold,
895            cooldown,
896        )
897    }
898
899    /// Everything else: the module REJECTED the bind, its connection went away
900    /// mid-relay, or the waiter was cancelled.
901    ///
902    /// None of these is evidence that a module is slow, and each already has
903    /// its own refusal with its own code. A module that rejects a bind in
904    /// microseconds is healthy and must never be convicted for it; a module
905    /// that died has said nothing about the module that replaces it. So these
906    /// neither increment nor reset the count -- they only release a probe slot.
907    fn record_inconclusive(&mut self) {
908        self.settled = true;
909        self.breakers
910            .record_inconclusive(self.module_id, self.probe_token.as_ref());
911    }
912}
913
914impl Drop for RouteBindBreakerGuard<'_> {
915    fn drop(&mut self) {
916        if !self.settled {
917            self.breakers
918                .record_inconclusive(self.module_id, self.probe_token.as_ref());
919        }
920    }
921}
922
923/// The breaker moved to open, reported so the caller can log it outside the
924/// lock. Opening is rare and load-bearing; the refusals that follow are
925/// frequent and are counted rather than logged.
926struct BreakerOpened {
927    consecutive_timeouts: u32,
928    /// True when a failed probe re-opened an already-open breaker, which reads
929    /// very differently in a log from a first opening.
930    reopened_after_probe: bool,
931}
932
933impl RouteBindBreakers {
934    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, ModuleBreakerState>> {
935        self.modules
936            .lock()
937            .expect("route.bind breaker mutex poisoned")
938    }
939
940    /// Decide whether this `route.open` may attempt its relay. Takes the map
941    /// lock and nothing else, and never awaits.
942    fn admit<'a>(&self, module_id: &'a str) -> RouteBindAdmission<'a> {
943        let admitted = |probe_token: Option<Arc<()>>| RouteBindAdmission::Admitted {
944            probe: probe_token.is_some(),
945            guard: RouteBindBreakerGuard {
946                breakers: self.clone(),
947                module_id,
948                probe_token,
949                settled: false,
950            },
951        };
952
953        let mut modules = self.lock();
954        let Some(state) = modules.get_mut(module_id) else {
955            return admitted(None);
956        };
957        let Some(cooldown_until) = state.cooldown_until else {
958            return admitted(None);
959        };
960        if state.probe_in_flight.is_some() {
961            return RouteBindAdmission::Refused {
962                consecutive_timeouts: state.consecutive_timeouts,
963                retry_in: Duration::ZERO,
964                probe_in_flight: true,
965            };
966        }
967        let now = Instant::now();
968        if now < cooldown_until {
969            return RouteBindAdmission::Refused {
970                consecutive_timeouts: state.consecutive_timeouts,
971                retry_in: cooldown_until - now,
972                probe_in_flight: false,
973            };
974        }
975        let token = Arc::new(());
976        state.probe_in_flight = Some(Arc::clone(&token));
977        admitted(Some(token))
978    }
979
980    fn record_accepted(&self, module_id: &str) -> bool {
981        self.lock()
982            .remove(module_id)
983            .is_some_and(|state| state.cooldown_until.is_some())
984    }
985
986    fn record_timeout(
987        &self,
988        module_id: &str,
989        probe_token: Option<&Arc<()>>,
990        threshold: u32,
991        cooldown: Duration,
992    ) -> Option<BreakerOpened> {
993        let mut modules = self.lock();
994        let state = modules.entry(module_id.to_string()).or_default();
995        let was_open = state.cooldown_until.is_some();
996        let was_probe = Self::owns_probe(state, probe_token);
997        if was_probe {
998            state.probe_in_flight = None;
999        }
1000        state.consecutive_timeouts = state.consecutive_timeouts.saturating_add(1);
1001        if state.consecutive_timeouts < threshold {
1002            return None;
1003        }
1004        state.cooldown_until = Some(Instant::now() + cooldown);
1005        Some(BreakerOpened {
1006            consecutive_timeouts: state.consecutive_timeouts,
1007            reopened_after_probe: was_open && was_probe,
1008        })
1009    }
1010
1011    fn owns_probe(state: &ModuleBreakerState, token: Option<&Arc<()>>) -> bool {
1012        // A relay can finish after the breaker was reset or after it opened
1013        // again and started a new probe. Only the guard whose token matches the
1014        // active probe may release it, so a late relay never frees a newer probe.
1015        state
1016            .probe_in_flight
1017            .as_ref()
1018            .zip(token)
1019            .is_some_and(|(active, token)| Arc::ptr_eq(active, token))
1020    }
1021
1022    fn record_inconclusive(&self, module_id: &str, probe_token: Option<&Arc<()>>) {
1023        if let Some(state) = self.lock().get_mut(module_id) {
1024            if Self::owns_probe(state, probe_token) {
1025                state.probe_in_flight = None;
1026            }
1027        }
1028    }
1029
1030    /// Discard what was learned about a module, because the process it was
1031    /// learned about is gone. Returns the discarded count when it was non-zero.
1032    ///
1033    /// A BREAKER IS A CACHED VERDICT ABOUT A PROCESS, NOT ABOUT A NAME. A
1034    /// `module_id` is a configuration identity that outlives any particular
1035    /// child; what the breaker observed was the process behind the module
1036    /// connection of the moment. When a new connection registers under that id
1037    /// the verdict's subject no longer exists, so the verdict is stale by
1038    /// construction rather than merely likely to be wrong. Keeping it would
1039    /// apply a dead process's record to a live one, which is the same defect
1040    /// class this breaker exists to stop the daemon committing.
1041    ///
1042    /// A half-open probe in flight is discarded with the rest: it was a
1043    /// question about the old process.
1044    pub(crate) fn reset_for_new_module_connection(&self, module_id: &str) -> Option<u32> {
1045        self.lock()
1046            .remove(module_id)
1047            .map(|state| state.consecutive_timeouts)
1048            .filter(|discarded| *discarded > 0)
1049    }
1050
1051    /// Open breakers, for the `server.describe` counters object. `None` when
1052    /// none is open, so the key stays absent rather than present-and-empty.
1053    ///
1054    /// This is the operator's answer to "is this module refusing instantly or
1055    /// is it fine?", which look identical from a client that retries and then
1056    /// succeeds.
1057    fn open_snapshot(&self) -> Option<serde_json::Value> {
1058        let now = Instant::now();
1059        let modules = self.lock();
1060        let open = modules
1061            .iter()
1062            .filter_map(|(module_id, state)| {
1063                let cooldown_until = state.cooldown_until?;
1064                Some((
1065                    module_id.clone(),
1066                    serde_json::json!({
1067                        "consecutive_timeouts": state.consecutive_timeouts,
1068                        "cooldown_remaining_ms":
1069                            cooldown_until.saturating_duration_since(now).as_millis() as u64,
1070                        "probe_in_flight": state.probe_in_flight.is_some(),
1071                    }),
1072                ))
1073            })
1074            .collect::<serde_json::Map<String, serde_json::Value>>();
1075        (!open.is_empty()).then_some(serde_json::Value::Object(open))
1076    }
1077}
1078
1079impl ControlHandler {
1080    pub(crate) fn install_registration_service(
1081        &self,
1082        router: std::sync::Weak<crate::Router>,
1083        auth: crate::server::ServerAuth,
1084    ) {
1085        self.supervisor.install_registration_service(router, auth);
1086    }
1087    pub fn new(registry: Arc<Registry>) -> Self {
1088        Self::with_forwarding(registry, Arc::new(ForwardingTable::default()))
1089    }
1090
1091    pub fn with_forwarding(registry: Arc<Registry>, forwarding: Arc<ForwardingTable>) -> Self {
1092        let counters = forwarding.counters();
1093        // Taken from the forwarding table rather than created here, so that the
1094        // breaker a `route.open` consults is the same one a module's
1095        // registration resets, however many handlers are built over one table.
1096        let route_bind_breakers = forwarding.route_bind_breakers();
1097        let route_bind_concurrency = forwarding.route_bind_concurrency();
1098        let route_outages = forwarding.route_outages();
1099        Self {
1100            registry,
1101            control_usage: Arc::new(Mutex::new(usage::ControlUsage::default())),
1102            catalog_cache: Arc::new(Mutex::new(catalog::CatalogCache::default())),
1103            catalog_readiness_revision: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1104            #[cfg(test)]
1105            activity_request_pause: Arc::new(Mutex::new(None)),
1106            #[cfg(test)]
1107            cleanup_pause: Arc::new(Mutex::new(None)),
1108            #[cfg(test)]
1109            after_nonce_attestation: Arc::new(Mutex::new(None)),
1110            #[cfg(test)]
1111            hello_ingress_pause: Arc::new(Mutex::new(None)),
1112            #[cfg(test)]
1113            agent_commands_pause: Arc::new(Mutex::new(None)),
1114            claims: Arc::new(claims::Claims::default()),
1115            config_runtime: None,
1116            config_review_admission: Arc::new(crate::config_gate::MissingReviewAdmission),
1117            config_review_admission_is_default: true,
1118            activity: None,
1119            activity_streams: Arc::new(Mutex::new(HashMap::new())),
1120            activity_reservations: Default::default(),
1121            catalog_streams: Arc::new(Mutex::new(HashMap::new())),
1122            config_settings_streams: Arc::new(Mutex::new(HashMap::new())),
1123            scope_streams: Arc::new(Mutex::new(HashMap::new())),
1124            forwarding,
1125            process_liveness: None,
1126            supervisor: SupervisorHandle::new(),
1127            resource_tracker: Arc::new(crate::resource_totals::Tracker::new(
1128                env!("CARGO_PKG_VERSION").to_owned(),
1129            )),
1130            agent_declarations: agent_commands::Queues::default(),
1131            list_admission: Arc::new(tokio::sync::Semaphore::new(4)),
1132            subc_capabilities: Arc::from([
1133                CAP_MANIFEST_REGISTRATION.to_string(),
1134                CAP_CHANNEL_LIFECYCLE.to_string(),
1135                CAP_PING_PONG.to_string(),
1136                CAP_SESSION_ATTACH.to_string(),
1137                CAP_ADMISSION_FACTS_RELAY.to_string(),
1138                CAP_SCOPES_V1.to_string(),
1139                subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY.to_string(),
1140                subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY.to_string(),
1141                subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY.to_string(),
1142                PEER_BUILD_CAPABILITY.to_string(),
1143                CAP_ROUTE_ROLE_VERSIONS_V1.to_string(),
1144                subc_protocol::manifest::CAP_CATALOG_EVENTS_V1.to_string(),
1145                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1.to_string(),
1146                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2.to_string(),
1147                subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1.to_string(),
1148                subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY.to_string(),
1149                subc_protocol::scope::WORKER_RUNS_CAPABILITY.to_string(),
1150                subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY.to_string(),
1151                subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY.to_string(),
1152                subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.to_string(),
1153                subc_control::ACTIVITY_LEDGER_CAPABILITY.to_string(),
1154                subc_protocol::ROUTE_CLOSE_REASONS_CAPABILITY.to_string(),
1155            ]),
1156            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
1157            route_bind_relay_timeouts: BTreeMap::new(),
1158            route_bind_breakers,
1159            route_bind_concurrency,
1160            route_outages,
1161            route_refusal_log: Default::default(),
1162            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
1163            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
1164            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
1165            storage_config: None,
1166            machine_id: None,
1167            admission_facts_carrier_module_id: None,
1168            admission_facts_targets: None,
1169            scopes: Arc::new(RwLock::new(ScopeTable::new(
1170                crate::daemon_config::default_scope_authority_owners(),
1171            ))),
1172            scope_deadline_added: Arc::new(tokio::sync::Notify::new()),
1173            scope_authority_owners: crate::daemon_config::default_scope_authority_owners(),
1174            federated_scope_owner: crate::daemon_config::default_federated_scope_owner(),
1175            privileged_operator_prompt: PrivilegedOperatorPrompt::default(),
1176            caller_endpoints: Arc::new(Mutex::new(HashMap::new())),
1177            build_class_warned: Arc::new(Mutex::new(HashSet::new())),
1178            observed_peers: Arc::new(Mutex::new(HashMap::new())),
1179            captured_peers: Arc::new(Mutex::new(HashMap::new())),
1180            config_desktop_stamps: Arc::new(Mutex::new(HashMap::new())),
1181            local_connections: Arc::new(Mutex::new(HashSet::new())),
1182            operator_app_policy: Default::default(),
1183            operator_apps: Arc::new(Mutex::new(HashMap::new())),
1184            launch_table: std::sync::Arc::new(crate::app_open::LaunchTable::new()),
1185            app_open_launch_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
1186            #[cfg(test)]
1187            app_open_test_platform: None,
1188            #[cfg(test)]
1189            app_open_test_launch: None,
1190            #[cfg(test)]
1191            config_review_test_reply: None,
1192            #[cfg(test)]
1193            recovery_exit_test_after_step: None,
1194            #[cfg(test)]
1195            recovery_exit_test_completed: None,
1196            #[cfg(test)]
1197            apply_reconcile_pause: Arc::new(Mutex::new(None)),
1198            #[cfg(test)]
1199            recovery_exit_test_quiet_retry: false,
1200            #[cfg(test)]
1201            recovery_exit_test_retry_pause: None,
1202            #[cfg(test)]
1203            config_delivery_test_wakes: None,
1204            #[cfg(all(test, unix))]
1205            config_delivery_test_idle: None,
1206            #[cfg(windows)]
1207            windows_verify: None,
1208            #[cfg(windows)]
1209            windows_flash: None,
1210            #[cfg(windows)]
1211            windows_track: None,
1212            #[cfg(all(test, windows))]
1213            windows_spawn_attempts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
1214            #[cfg(test)]
1215            caller_lookup: None,
1216            hello_launch_nonces: Arc::new(Mutex::new(HelloLaunchNonces::default())),
1217            rescan: None,
1218            connected_clients: ConnectedClients::new(),
1219            local_endpoint_unavailable: None,
1220            counters,
1221            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
1222            daemon_shutdown: DaemonShutdownFlag::default(),
1223            daemon_provenance: DaemonProvenanceFacts::default(),
1224            #[cfg(test)]
1225            control_dispatch_delay: None,
1226            #[cfg(test)]
1227            provenance_probe_override: None,
1228            #[cfg(test)]
1229            route_bind_relay_sent_hold: None,
1230            #[cfg(test)]
1231            hello_registry_to_forwarding_hold: None,
1232            #[cfg(test)]
1233            hello_ack_to_publication_hold: None,
1234            #[cfg(test)]
1235            hello_before_publication_hold: None,
1236            #[cfg(test)]
1237            hello_after_launch_check_hold: None,
1238            #[cfg(test)]
1239            hello_inside_publication_hold: None,
1240        }
1241    }
1242
1243    /// Set the central storage policy: registering modules then receive their
1244    /// resolved storage descriptor in HELLO_ACK.
1245    pub fn with_storage_config(
1246        mut self,
1247        storage_config: Option<crate::daemon_config::StorageConfig>,
1248    ) -> Self {
1249        self.storage_config = storage_config;
1250        self
1251    }
1252
1253    /// Open the ledger on its own writer thread; an unavailable sink does not
1254    /// prevent the daemon from serving routing or supervisor requests.
1255    pub fn with_activity_ledger(mut self, run_dir: &Path, incarnation: String) -> Self {
1256        self.activity = Some(crate::activity::ActivityLedger::open(
1257            run_dir.join("activity.jsonl"),
1258            incarnation,
1259        ));
1260        self.supervisor.set_activity(self.activity.clone());
1261        self
1262    }
1263
1264    /// Set the machine id served to every registering module (HELLO_ACK) and on
1265    /// `server.describe`.
1266    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
1267        self.machine_id = machine_id;
1268        self
1269    }
1270
1271    /// Configure the exact reserved module and target ids permitted to relay
1272    /// opaque admission facts. Config-file loading validates this authority;
1273    /// this builder keeps the same policy available to embedded test daemons.
1274    pub fn with_admission_facts_config(
1275        mut self,
1276        carrier_module_id: Option<String>,
1277        targets: Option<Vec<String>>,
1278    ) -> Self {
1279        self.admission_facts_carrier_module_id = carrier_module_id;
1280        self.admission_facts_targets = targets;
1281        self
1282    }
1283
1284    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
1285    /// Replaces the scope table with an empty one under the new list, so call it
1286    /// while building the handler, before any module can sync.
1287    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
1288        self.scopes = Arc::new(RwLock::new(
1289            ScopeTable::new(owners.iter().cloned())
1290                .with_federated_owner(self.federated_scope_owner.clone()),
1291        ));
1292        self.scope_authority_owners = owners;
1293        self
1294    }
1295
1296    /// Set the exclusive federated owner while building the handler, before syncs.
1297    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
1298        self.scopes = Arc::new(RwLock::new(
1299            ScopeTable::new(self.scope_authority_owners.iter().cloned())
1300                .with_federated_owner(owner.clone()),
1301        ));
1302        self.federated_scope_owner = owner;
1303        self
1304    }
1305
1306    /// Set the startup policy before installing the rescan context or serving requests.
1307    pub fn with_privileged_operator_prompt(mut self, mode: PrivilegedOperatorPrompt) -> Self {
1308        self.privileged_operator_prompt = mode;
1309        self
1310    }
1311
1312    /// Override the route.bind relay timeout. Used by tests that assert the
1313    /// timeout path so they don't block on the production-safe default.
1314    pub fn with_route_bind_relay_timeout(mut self, timeout: Duration) -> Self {
1315        self.route_bind_relay_timeout = timeout;
1316        self
1317    }
1318
1319    /// Install per-module route.bind relay budget overrides. A module id
1320    /// listed here wins over the daemon-wide default set via
1321    /// `with_route_bind_relay_timeout`. Values are pre-resolved at parse time
1322    /// from `subc.jsonc` (per-module > daemon-wide > absent), so callers pass
1323    /// the same `Duration` the bind path will use.
1324    pub fn with_route_bind_relay_timeouts(
1325        mut self,
1326        timeouts: impl IntoIterator<Item = (String, Duration)>,
1327    ) -> Self {
1328        self.route_bind_relay_timeouts = timeouts.into_iter().collect();
1329        self
1330    }
1331
1332    /// Resolve the route.bind relay budget for a specific target module id.
1333    /// Per-module overrides win; the daemon-wide value (set via
1334    /// `with_route_bind_relay_timeout` or the built-in default) is the
1335    /// fallback. Exposed so config-aware callers (bootstrap, tests) can audit
1336    /// the same resolution `handle_route_open` will use.
1337    pub fn route_bind_relay_timeout_for(&self, module_id: &str) -> Duration {
1338        self.route_bind_relay_timeouts
1339            .get(module_id)
1340            .copied()
1341            .unwrap_or(self.route_bind_relay_timeout)
1342    }
1343
1344    /// Override the per-module bind-relay breaker policy.
1345    ///
1346    /// Used by tests, which cannot spend three production budgets opening a
1347    /// breaker or twenty seconds waiting for its cooldown. The production
1348    /// values are `DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD` and
1349    /// `DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN`, whose doc comments carry the
1350    /// reasoning for the numbers.
1351    pub fn with_route_bind_breaker(mut self, threshold: u32, cooldown: Duration) -> Self {
1352        self.route_bind_breaker_threshold = threshold.max(1);
1353        self.route_bind_breaker_cooldown = cooldown;
1354        self
1355    }
1356
1357    #[cfg(test)]
1358    pub(crate) fn with_health_probe_timeout(mut self, timeout: Duration) -> Self {
1359        self.health_probe_timeout = timeout;
1360        self
1361    }
1362
1363    #[cfg(test)]
1364    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
1365        self.control_dispatch_delay = Some(delay);
1366        self
1367    }
1368
1369    /// `route.open` waits on `hold` twice after queueing a route.bind: once to
1370    /// announce it is parked, once to be released. Build the barrier for two
1371    /// parties, the test being the other one.
1372    #[cfg(test)]
1373    pub(crate) fn with_route_bind_relay_sent_hold(
1374        mut self,
1375        hold: Arc<tokio::sync::Barrier>,
1376    ) -> Self {
1377        self.route_bind_relay_sent_hold = Some(hold);
1378        self
1379    }
1380
1381    /// A HELLO waits on `hold` twice between reserving its registry entry and
1382    /// installing its forwarding endpoint: once to announce it is parked, once
1383    /// to be released. Build the barrier for two parties, the test being the
1384    /// other one, and run the HELLO on a thread of its own.
1385    #[cfg(test)]
1386    pub(crate) fn with_hello_registry_to_forwarding_hold(
1387        mut self,
1388        hold: Arc<std::sync::Barrier>,
1389    ) -> Self {
1390        self.hello_registry_to_forwarding_hold = Some(hold);
1391        self
1392    }
1393
1394    #[cfg(test)]
1395    fn hold_between_registry_and_forwarding(&self) {
1396        if let Some(hold) = &self.hello_registry_to_forwarding_hold {
1397            hold.wait();
1398            hold.wait();
1399        }
1400    }
1401
1402    /// Park after the ACK is queued and forwarding is installed, until a test
1403    /// has read the ACK and issued a registry lookup from another connection.
1404    #[cfg(test)]
1405    fn hold_between_ack_and_publication(&self) {
1406        if let Some(hold) = &self.hello_ack_to_publication_hold {
1407            hold.wait();
1408            hold.wait();
1409        }
1410    }
1411
1412    #[cfg(all(test, unix))]
1413    pub(crate) fn with_hello_before_publication_hold(
1414        mut self,
1415        hold: Arc<std::sync::Barrier>,
1416    ) -> Self {
1417        self.hello_before_publication_hold = Some(hold);
1418        self
1419    }
1420
1421    #[cfg(all(test, unix))]
1422    pub(crate) fn with_hello_after_launch_check_hold(
1423        mut self,
1424        hold: Arc<std::sync::Barrier>,
1425    ) -> Self {
1426        self.hello_after_launch_check_hold = Some(hold);
1427        self
1428    }
1429
1430    #[cfg(all(test, unix))]
1431    pub(crate) fn with_hello_inside_publication_hold(
1432        mut self,
1433        hold: Arc<std::sync::Barrier>,
1434    ) -> Self {
1435        self.hello_inside_publication_hold = Some(hold);
1436        self
1437    }
1438
1439    pub fn with_process_liveness(
1440        mut self,
1441        process_liveness: Arc<dyn ModuleProcessLiveness>,
1442    ) -> Self {
1443        self.process_liveness = Some(process_liveness);
1444        self
1445    }
1446
1447    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
1448        self.supervisor = supervisor;
1449        if let Some(owner) = &self.config_runtime {
1450            self.supervisor.install_binding_retirement(owner);
1451        }
1452        self.supervisor.set_activity(self.activity.clone());
1453        self
1454    }
1455
1456    pub fn with_daemon_provenance(
1457        mut self,
1458        pid: u32,
1459        started_at_ms: u64,
1460        executable_path: Option<PathBuf>,
1461        build_git_sha: Option<String>,
1462        build_lock_digest: Option<String>,
1463    ) -> Self {
1464        let executable_identity = executable_path.as_deref().and_then(spawned_file_identity);
1465        let process_start_time = process_start_time(pid);
1466        self.daemon_provenance = DaemonProvenanceFacts {
1467            build: DaemonBuildProvenance {
1468                build_git_sha,
1469                build_lock_digest,
1470            },
1471            pid: Some(pid),
1472            started_at_ms: Some(started_at_ms),
1473            start_clock: None,
1474            executable_path,
1475            executable_identity,
1476            process_start_time,
1477            probe: ExecutableIdentityProbe::default(),
1478        };
1479        self
1480    }
1481
1482    pub(crate) fn with_daemon_start_clock(mut self, clock: crate::clock::StartClock) -> Self {
1483        self.daemon_provenance.start_clock = Some(clock);
1484        self
1485    }
1486
1487    /// Inject the Unix wall-clock millisecond source used by every scope expiry check.
1488    pub fn with_wall_clock(self, clock: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
1489        self.scopes
1490            .write()
1491            .unwrap_or_else(|poisoned| poisoned.into_inner())
1492            .set_wall_clock(Arc::new(clock));
1493        self
1494    }
1495
1496    #[cfg(test)]
1497    fn with_provenance_probe_result(mut self, result: subc_control::RunningImageAgreement) -> Self {
1498        self.provenance_probe_override = Some(result);
1499        self
1500    }
1501
1502    /// Install the configured module set and its reserved capability bindings.
1503    /// Bindings are configuration-scoped and may point at a provider that has not
1504    /// been installed yet, so this does not require the bound module to exist.
1505    pub fn with_capability_config(
1506        self,
1507        modules: impl IntoIterator<Item = (String, bool)>,
1508        reserved_capabilities: BTreeMap<String, String>,
1509    ) -> Self {
1510        self.capability_evaluator
1511            .configure(modules, reserved_capabilities);
1512        self
1513    }
1514
1515    /// Share the supervisor's daemon-shutdown flag with this handler, so
1516    /// requirement changes after the daemon has begun its announced shutdown
1517    /// are not reported as faults.
1518    pub(crate) fn with_daemon_shutdown_flag(mut self, flag: DaemonShutdownFlag) -> Self {
1519        self.daemon_shutdown = flag;
1520        self
1521    }
1522
1523    pub fn with_supervisor_rescan(
1524        mut self,
1525        supervisor: Supervisor,
1526        config_path: impl Into<PathBuf>,
1527        configured_port: Option<u16>,
1528    ) -> Self {
1529        self.rescan = Some(SupervisorRescanContext {
1530            supervisor,
1531            config_path: config_path.into(),
1532            configured_port,
1533            storage_config: self.storage_config.clone(),
1534            admission_facts_carrier_module_id: self.admission_facts_carrier_module_id.clone(),
1535            admission_facts_targets: self.admission_facts_targets.clone(),
1536            scope_authority_owners: self.scope_authority_owners.clone(),
1537            federated_scope_owner: self.federated_scope_owner.clone(),
1538            privileged_operator_prompt: self.privileged_operator_prompt,
1539            generation: Arc::default(),
1540            rescan_lock: Arc::default(),
1541            module_entries: Arc::default(),
1542        });
1543        self
1544    }
1545
1546    pub(crate) fn with_supervisor_rescan_entries(
1547        self,
1548        modules: &[crate::daemon_config::ConfiguredModule],
1549    ) -> Self {
1550        if let Some(context) = &self.rescan {
1551            let mut entries = context
1552                .module_entries
1553                .lock()
1554                .unwrap_or_else(|e| e.into_inner());
1555            entries.seed(modules);
1556        }
1557        self
1558    }
1559
1560    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
1561        self.connected_clients = connected_clients;
1562        self
1563    }
1564
1565    /// Report why this daemon serves no local endpoint, in `server.describe`, so
1566    /// an operator can see a bind failure without reading the daemon log.
1567    pub fn with_local_endpoint_unavailable(mut self, reason: Option<String>) -> Self {
1568        self.local_endpoint_unavailable = reason;
1569        self
1570    }
1571
1572    pub fn forwarding(&self) -> Arc<ForwardingTable> {
1573        Arc::clone(&self.forwarding)
1574    }
1575
1576    pub(crate) fn counters(&self) -> DaemonCounters {
1577        self.counters.clone()
1578    }
1579
1580    /// Wake at each candidate's own deadline so a stalled fresh exec emits its
1581    /// requirement event without depending on an operator polling a status command.
1582    pub fn spawn_capability_deadline_loop(self: Arc<Self>) {
1583        let handler = Arc::downgrade(&self);
1584        let evaluator = self.capability_evaluator.clone();
1585        tokio::spawn(async move {
1586            loop {
1587                evaluator.wait_for_change_or_deadline().await;
1588                let Some(handler) = handler.upgrade() else {
1589                    break;
1590                };
1591                handler.refresh_capability_requirements();
1592            }
1593        });
1594    }
1595
1596    /// The timer only prompts sweeps. Each sweep reads wall time again, so a
1597    /// deadline passed during sleep is enforced on the first tick after wake.
1598    /// While no live scope carries a deadline the loop waits for an accepted
1599    /// scope change instead of ticking, so a daemon without deadlines never
1600    /// wakes for expiry.
1601    pub(crate) fn spawn_scope_expiry_loop(self: Arc<Self>) {
1602        let context = scope_expiry::ScopeExpiryContext::new(&self);
1603        let deadline_added = self.scope_deadline_added.clone();
1604        tokio::spawn(async move {
1605            loop {
1606                if !context.has_deadlines() {
1607                    deadline_added.notified().await;
1608                    continue;
1609                }
1610                tokio::time::sleep(Duration::from_secs(1)).await;
1611                if let Err(error) = context.sweep() {
1612                    warn!(%error, "scope expiry sweep failed");
1613                }
1614            }
1615        });
1616    }
1617
1618    #[cfg(test)]
1619    pub(crate) fn sweep_expired_scopes(&self) -> Result<(), RouterError> {
1620        scope_expiry::ScopeExpiryContext::new(self).sweep()
1621    }
1622
1623    fn publish_scope_changes(
1624        &self,
1625        changes: &[crate::scopes::ScopeTagChange],
1626        expired: &[crate::scopes::ScopeExpired],
1627    ) -> Result<Vec<crate::forwarding::ScopeDrainedRoute>, RouterError> {
1628        scope_expiry::ScopeExpiryContext::new(self).publish_scope_changes(changes, expired)
1629    }
1630
1631    fn runtime_capability_snapshot(
1632        &self,
1633    ) -> Result<(Vec<RuntimeModule>, Vec<RegisteredModule>), RouterError> {
1634        let runtime = self
1635            .supervisor
1636            .list()
1637            .into_iter()
1638            .map(|module| {
1639                let status = module.status().map_err(|err| {
1640                    RouterError::backend(0, 0, format!("failed to read capability status: {err}"))
1641                })?;
1642                Ok(RuntimeModule {
1643                    module_id: status.module_id,
1644                    state: status.state,
1645                    enabled: status.enabled,
1646                })
1647            })
1648            .collect::<Result<Vec<_>, RouterError>>()?;
1649        // Include every registration, published or not. The capability
1650        // evaluator counts a module as providing its capabilities as soon as it
1651        // has registered, even before `catalog.list` shows it, so a HELLO in
1652        // progress does not change other modules' required-capability
1653        // verdicts. See `Registry::list_registered_modules`.
1654        let registrations = self.registry.list_registered_modules().map_err(|err| {
1655            RouterError::backend(
1656                0,
1657                0,
1658                format!("failed to list capability registrations: {err}"),
1659            )
1660        })?;
1661        let registrations = registrations
1662            .into_iter()
1663            .map(|registration| RegisteredModule {
1664                module_id: registration.manifest.module_id,
1665                module_version: registration.manifest.module_version,
1666                capabilities: registration.manifest.capabilities,
1667            })
1668            .collect();
1669        Ok((runtime, registrations))
1670    }
1671
1672    /// The capability side effects of a module becoming the active registration
1673    /// for its id: cache its manifest (logging how it differs from the cached
1674    /// one), run the deny census when its declarations call for one, and recompute the
1675    /// requirement statuses. An ordinary HELLO does this as it registers; a swap
1676    /// candidate's does not, and the supervisor does it at promotion instead,
1677    /// through [`crate::supervise::SwapPromotionObserver`].
1678    fn apply_registration_capabilities(&self, registration: &crate::registry::ModuleRegistration) {
1679        let cached_registration = RegisteredModule {
1680            module_id: registration.manifest.module_id.clone(),
1681            module_version: registration.manifest.module_version.clone(),
1682            capabilities: registration.manifest.capabilities.clone(),
1683        };
1684        let change = self.capability_evaluator.record_hello(&cached_registration);
1685        log_manifest_change(&cached_registration.module_id, &change);
1686        if capability_census_trigger(None, registration.manifest.capabilities.as_ref()) {
1687            self.enforce_capability_denies();
1688        }
1689        self.refresh_capability_requirements();
1690    }
1691
1692    /// Point the shared supervisor handle at this handler for swap promotions.
1693    /// Called wherever a handler is put behind the `Arc` the router serves, so
1694    /// it can be held weakly.
1695    pub(crate) fn install_swap_promotion_observer(self: &Arc<Self>) {
1696        let observer: std::sync::Weak<dyn crate::supervise::SwapPromotionObserver> =
1697            Arc::downgrade(self) as std::sync::Weak<ControlHandler>;
1698        self.supervisor.set_swap_promotion_observer(observer);
1699    }
1700
1701    pub fn refresh_capability_requirements(&self) {
1702        match self.runtime_capability_snapshot() {
1703            Ok((runtime, registrations)) => {
1704                let events = self
1705                    .capability_evaluator
1706                    .evaluate_now(&runtime, &registrations);
1707                if !events.is_empty() {
1708                    self.catalog_readiness_revision
1709                        .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1710                }
1711                log_requirement_events(events, &self.daemon_shutdown);
1712            }
1713            Err(err) => warn!(error = %err, "failed to recompute capability requirements"),
1714        }
1715    }
1716
1717    /// Why a registered module is not accepting new route binds, or `None` when
1718    /// it is. This is the module's effective readiness: its declared readiness
1719    /// first, then every `need: required` capability it declares evaluating to
1720    /// `provided`. `route.open` and `catalog.list` both read it here so the
1721    /// catalog never reports a module routable that `route.open` would refuse.
1722    fn not_ready_reason(
1723        &self,
1724        registration: &crate::registry::ModuleRegistration,
1725    ) -> Option<NotReadyReason> {
1726        if !registration.ready {
1727            return Some(NotReadyReason {
1728                reason: NotReadyReason::DECLARED_NOT_READY.to_string(),
1729                capability: None,
1730            });
1731        }
1732        self.first_unprovided_required_capability(registration)
1733            .map(|capability| NotReadyReason {
1734                reason: NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED.to_string(),
1735                capability: Some(capability),
1736            })
1737    }
1738
1739    /// The lexicographically first capability this registration declares
1740    /// `need: required` whose evaluator verdict is not `provided`.
1741    ///
1742    /// The verdicts are the capability evaluator's own; nothing here decides
1743    /// what "provided" means. The evaluator counts a capability provided as
1744    /// soon as a module claiming it has REGISTERED, not once that module is
1745    /// ready. That distinction is what keeps two modules that require each
1746    /// other's capabilities from deadlocking: if "provided" meant "the claimant
1747    /// is ready", each would wait for the other to become ready first and
1748    /// neither ever would. Do not tighten it to readiness.
1749    ///
1750    /// A required capability with no verdict at all means this registration's
1751    /// HELLO or catalog.update landed after the last recompute; recompute once
1752    /// rather than let a missing verdict read as either answer. If it is still
1753    /// missing (the recompute itself failed) the capability counts as
1754    /// unprovided: the refusal is retryable, and routing a module whose
1755    /// required provider is unknown is the outcome this check exists to stop.
1756    fn first_unprovided_required_capability(
1757        &self,
1758        registration: &crate::registry::ModuleRegistration,
1759    ) -> Option<String> {
1760        self.first_unprovided_required_capability_for(
1761            &registration.manifest.module_id,
1762            registration.manifest.capabilities.as_ref(),
1763        )
1764    }
1765
1766    fn first_unprovided_required_capability_for(
1767        &self,
1768        module_id: &str,
1769        capabilities: Option<&subc_protocol::manifest::CapabilityDeclarations>,
1770    ) -> Option<String> {
1771        let required = capabilities
1772            .into_iter()
1773            .flat_map(|declarations| declarations.requires.iter())
1774            .filter(|requirement| requirement.need == CapabilityNeed::Required)
1775            .map(|requirement| requirement.capability.as_str())
1776            .collect::<BTreeSet<_>>();
1777        if required.is_empty() {
1778            return None;
1779        }
1780        let verdict = |capability: &str| self.capability_evaluator.verdict(module_id, capability);
1781        if required
1782            .iter()
1783            .any(|capability| verdict(capability).is_none())
1784        {
1785            self.refresh_capability_requirements();
1786        }
1787        required
1788            .into_iter()
1789            .find(|capability| verdict(capability) != Some(CapabilityVerdict::Provided))
1790            .map(str::to_string)
1791    }
1792
1793    fn capability_requirement_statuses(&self) -> Vec<CapabilityRequirementStatus> {
1794        self.capability_evaluator
1795            .statuses()
1796            .into_iter()
1797            .map(RequirementStatus::into_wire)
1798            .collect()
1799    }
1800
1801    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
1802    /// registration-release watch. The signal is what the supervisor waits on
1803    /// before spawning a replacement, so it must only fire once forwarding
1804    /// teardown is also done (see [`Self::cleanup_connection`] /
1805    /// [`Self::handle_goodbye`]). Unpublished HELLO rollback uses the separate
1806    /// registry-only path below because publication already owns the spawn lock.
1807    fn deregister_connection(
1808        &self,
1809        connection_id: ConnectionId,
1810        reason: RegistrationEndReason,
1811    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1812        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
1813            spawn.end_primary_registration();
1814        }
1815        self.registry
1816            .deregister_connection_with_reason(connection_id, reason)
1817    }
1818
1819    // HELLO publication owns the spawn transition guard. claim.mint is allowed
1820    // only after HELLO acceptance, so a failed first HELLO has no bearer tokens
1821    // or claim-bound consumers to revoke. Remove only its unpublished registry
1822    // entry without re-entering primary-registration teardown.
1823    fn rollback_unpublished_hello(
1824        &self,
1825        connection: ConnectionId,
1826    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1827        self.registry.deregister_connection_with_reason(
1828            connection,
1829            RegistrationEndReason::RegistrationFailed,
1830        )
1831    }
1832
1833    fn request_refusal_close(
1834        &self,
1835        connection: ConnectionId,
1836        sink: Option<&crate::FrameSink>,
1837        reason: CloseReason,
1838    ) {
1839        if let Some(sink) = sink {
1840            sink.terminate_ingress();
1841        }
1842        if self.claims.close_notifications_enabled() {
1843            self.forwarding.request_connection_close(connection, reason);
1844        }
1845    }
1846
1847    pub(crate) fn route_open_target(&self, frame: &Frame) -> Option<String> {
1848        if frame.header.channel != 0 || frame.header.ty != FrameType::Request {
1849            return None;
1850        }
1851        let Ok(ClientControlRequest::RouteOpen { target, .. }) =
1852            parse_client_control_request(&frame.body)
1853        else {
1854            return None;
1855        };
1856        Some(target_module_id(&target).to_string())
1857    }
1858
1859    pub(crate) fn route_open_capacity_refusal(
1860        &self,
1861        ctx: &RouteCtx,
1862        frame: &Frame,
1863        target_module_id: &str,
1864        in_flight: usize,
1865        limit: usize,
1866    ) -> Result<Frame, RouterError> {
1867        // Sent before the request reaches `handle_route_open`, so the caller
1868        // fields come from the raw frame here.
1869        let caller = self.route_open_caller_from_frame(ctx, frame);
1870        self.route_open_admission_refusal_frame(
1871            ctx,
1872            &caller,
1873            frame,
1874            target_module_id,
1875            "open_admission_full",
1876            (in_flight, limit),
1877            format!(
1878                "connection already has {in_flight} route.open binds in flight (limit {limit}); retry after one settles"
1879            ),
1880        )
1881    }
1882
1883    fn route_open_target_capacity_refusal(
1884        &self,
1885        ctx: &RouteCtx,
1886        caller: &RouteOpenCaller,
1887        frame: &Frame,
1888        target_module_id: &str,
1889        in_flight: usize,
1890    ) -> Result<Frame, RouterError> {
1891        self.route_open_admission_refusal_frame(
1892            ctx,
1893            caller,
1894            frame,
1895            target_module_id,
1896            "target_binds_full",
1897            (in_flight, MAX_PENDING_ROUTE_BINDS_PER_TARGET),
1898            format!(
1899                "module_id '{target_module_id}' already has {in_flight} route.bind relays in flight; retry after one settles"
1900            ),
1901        )
1902    }
1903
1904    /// Admission pressure clears as existing binds settle, so its refusal must
1905    /// remain in the deployed SDKs' closed retryable set: `unknown_module`,
1906    /// `module_reloading`, `module_warming`, `target_unavailable`, or
1907    /// `module_timeout`. `target_unavailable` is honest for an attempt that
1908    /// cannot currently reach its target; `module_timeout` would falsely claim
1909    /// that a wait expired. A new, cleaner code would be terminal to deployed
1910    /// clients, so it requires a client-tolerance rollout before daemon emission.
1911    #[allow(clippy::too_many_arguments)]
1912    fn route_open_admission_refusal_frame(
1913        &self,
1914        ctx: &RouteCtx,
1915        caller: &RouteOpenCaller,
1916        frame: &Frame,
1917        target_module_id: &str,
1918        reason: &'static str,
1919        (in_flight, limit): (usize, usize),
1920        message: impl Into<String>,
1921    ) -> Result<Frame, RouterError> {
1922        let code = error_codes::TARGET_UNAVAILABLE;
1923        self.counters.increment_route_open_refused(code);
1924        info!(
1925            target: "control",
1926            code,
1927            reason,
1928            module_id = ?target_module_id,
1929            connection_id = ctx.connection_id.get(),
1930            principal = %caller.principal,
1931            scope = %caller.scope,
1932            harness = %caller.harness,
1933            in_flight,
1934            limit,
1935            "route.open refused"
1936        );
1937        control_error_frame(frame, code, message.into())
1938    }
1939
1940    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
1941    ///
1942    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
1943    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
1944    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
1945    #[cfg(test)]
1946    pub fn handle_control(
1947        &self,
1948        connection_id: ConnectionId,
1949        frame: Frame,
1950    ) -> Result<Vec<Frame>, RouterError> {
1951        match frame.header.ty {
1952            FrameType::Ping => Ok(vec![pong(&frame)?]),
1953            FrameType::Hello => self.handle_hello(connection_id, None, frame),
1954            FrameType::Goodbye => self.handle_goodbye(connection_id),
1955            ty => Ok(vec![control_error_frame(
1956                &frame,
1957                "unsupported_control_frame",
1958                format!("unsupported channel-0 frame {ty:?}"),
1959            )?]),
1960        }
1961    }
1962
1963    pub async fn handle_control_frame(
1964        &self,
1965        ctx: &RouteCtx,
1966        frame: Frame,
1967    ) -> Result<Vec<Frame>, RouterError> {
1968        self.handle_control_frame_timed(ctx, frame, None).await
1969    }
1970
1971    #[cfg(any(test, feature = "test-support"))]
1972    pub fn with_test_operator_app_policy(
1973        mut self,
1974        policy: crate::operator_apps::TestOperatorAppPolicy,
1975    ) -> Self {
1976        self.operator_app_policy = policy.into();
1977        self
1978    }
1979
1980    /// Inject the Windows signature check for tests. The injected check
1981    /// answers the verified version string or the rejection reason; the
1982    /// daemon enforces the floor itself on the returned version.
1983    #[cfg(all(windows, any(test, feature = "test-support")))]
1984    pub fn with_test_windows_verifier(mut self, verify: crate::app_open::WindowsVerifyFn) -> Self {
1985        self.windows_verify = Some(verify);
1986        self
1987    }
1988
1989    /// Record which pids the daemon would flash for `already_running`.
1990    #[cfg(all(windows, any(test, feature = "test-support")))]
1991    pub fn with_test_windows_flash(mut self, flash: crate::app_open::WindowsFlashFn) -> Self {
1992        self.windows_flash = Some(flash);
1993        self
1994    }
1995
1996    /// Inject a tracking failure for tests: makes `track_launched_process`
1997    /// fail so a test can prove a launch that cannot be tracked is stopped,
1998    /// never left running.
1999    #[cfg(all(windows, any(test, feature = "test-support")))]
2000    pub fn with_test_windows_track(mut self, track: crate::app_open::WindowsTrackFn) -> Self {
2001        self.windows_track = Some(track);
2002        self
2003    }
2004
2005    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
2006        self.local_connections
2007            .lock()
2008            .unwrap_or_else(|p| p.into_inner())
2009            .insert(connection);
2010    }
2011
2012    // Keep the connection-level delivery decision shared with route.bind. The
2013    // target's capability opt-in is separate from recognition of the caller.
2014    fn connection_operator_app(
2015        &self,
2016        stamp: Option<&crate::operator_apps::OperatorAppStamp>,
2017    ) -> Option<subc_protocol::peer::OperatorApp> {
2018        stamp
2019            .filter(|stamp| stamp.delivery_enabled(&self.operator_app_policy))
2020            .map(|stamp| stamp.app.clone())
2021    }
2022
2023    pub(crate) fn record_observed_peer(
2024        &self,
2025        connection: ConnectionId,
2026        peer: subc_os::local_peer::ObservedPeer,
2027    ) {
2028        use subc_os::local_peer::{ObservedPeer as OsPeer, PeerUser};
2029        let peer = match peer {
2030            OsPeer::Unobserved => ObservedPeer::unobserved(),
2031            OsPeer::Observed(peer) => {
2032                let observed = match peer.user {
2033                    PeerUser::Uid(uid) => ObservedPeer::observed_uid(uid),
2034                    PeerUser::Sid(sid) => ObservedPeer::observed_sid(sid),
2035                };
2036                observed
2037                    .with_exe(
2038                        peer.exe
2039                            .and_then(|path| path.into_os_string().into_string().ok()),
2040                    )
2041                    .with_signing_id(peer.signing_id)
2042            }
2043        };
2044        self.observed_peers
2045            .lock()
2046            .unwrap_or_else(|p| p.into_inner())
2047            .insert(connection, peer);
2048    }
2049
2050    pub(crate) fn record_caller_endpoints(
2051        &self,
2052        connection: ConnectionId,
2053        endpoints: Option<(SocketAddr, SocketAddr)>,
2054    ) {
2055        let mut callers = self
2056            .caller_endpoints
2057            .lock()
2058            .unwrap_or_else(|p| p.into_inner());
2059        callers.remove(&connection);
2060        if let Some(endpoints) = endpoints {
2061            callers.insert(connection, endpoints);
2062        }
2063    }
2064
2065    #[cfg(test)]
2066    pub(crate) fn with_caller_lookup_for_test(
2067        mut self,
2068        lookup: impl Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync + 'static,
2069    ) -> Self {
2070        self.caller_lookup = Some(Arc::new(lookup));
2071        self
2072    }
2073
2074    async fn resolve_caller(&self, connection: ConnectionId) -> CallerIdentity {
2075        let endpoints = self
2076            .caller_endpoints
2077            .lock()
2078            .unwrap_or_else(|p| p.into_inner())
2079            .get(&connection)
2080            .copied();
2081        #[cfg(test)]
2082        let lookup = self.caller_lookup.clone();
2083        tokio::task::spawn_blocking(move || {
2084            #[cfg(test)]
2085            if let Some(lookup) = lookup {
2086                return lookup(endpoints);
2087            }
2088            endpoints
2089                .map(|(local, peer)| CallerIdentity::lookup_endpoints(local, peer))
2090                .unwrap_or_default()
2091        })
2092        .await
2093        .unwrap_or_default()
2094    }
2095
2096    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
2097        frame.header.channel == 0
2098            && frame.header.ty == FrameType::Request
2099            && self
2100                .forwarding
2101                .module_endpoint_for_connection(ctx.connection_id)
2102                .is_ok_and(|endpoint| endpoint.is_none())
2103            && parse_client_control_request(&frame.body)
2104                .ok()
2105                .is_some_and(|request| privileged_operation(&request).is_some())
2106    }
2107
2108    pub(crate) async fn handle_control_frame_timed(
2109        &self,
2110        ctx: &RouteCtx,
2111        frame: Frame,
2112        dispatch_started_at: Option<StdInstant>,
2113    ) -> Result<Vec<Frame>, RouterError> {
2114        let first = ctx.egress.first_ingress_frame();
2115        self.handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
2116            .await
2117    }
2118
2119    pub(crate) async fn handle_control_frame_ingress(
2120        &self,
2121        ctx: &RouteCtx,
2122        frame: Frame,
2123        dispatch_started_at: Option<StdInstant>,
2124        first: bool,
2125    ) -> Result<Vec<Frame>, RouterError> {
2126        if ctx.egress.ingress_terminal() {
2127            return Ok(Vec::new());
2128        }
2129        #[cfg(test)]
2130        self.claims.record_dispatch(frame.header.corr);
2131        let claim_binding = self.claims.binding(ctx.connection_id);
2132        let mut prefix_attempt = (frame.header.ty == FrameType::Hello
2133            && claim_binding
2134                .as_ref()
2135                .is_some_and(|binding| binding.prefix_module_id().is_some()))
2136        .then(|| self.prefix_hello_attempt(ctx));
2137        if claim_binding
2138            .as_ref()
2139            .is_some_and(|binding| binding.prefix_module_id().is_some())
2140        {
2141            let registered = self
2142                .forwarding
2143                .module_endpoint_for_connection(ctx.connection_id)
2144                .map_err(RouterError::Forwarding)?
2145                .is_some();
2146            if !registered && frame.header.ty != FrameType::Hello {
2147                return self
2148                    .refuse_claim_connection(ctx, &frame, "claim_hello_required")
2149                    .await;
2150            }
2151            if registered && frame.header.ty == FrameType::Goodbye {
2152                ctx.egress.terminate_ingress();
2153                let result = self.handle_goodbye(ctx.connection_id);
2154                self.claims.connection_closed(ctx.connection_id);
2155                self.request_refusal_close(
2156                    ctx.connection_id,
2157                    Some(&ctx.egress),
2158                    CloseReason::new("claim_registration_ended", "prefix registration ended"),
2159                );
2160                return result;
2161            }
2162            if registered && frame.header.ty == FrameType::Request {
2163                let allowed =
2164                    serde_json::from_slice::<ControlOpProbe>(&frame.body).is_ok_and(|probe| {
2165                        matches!(
2166                            probe.op.as_str(),
2167                            "catalog.update"
2168                                | "catalog.update_role_declarations"
2169                                | "scope.describe"
2170                                | "scope.watch"
2171                                | "supervisor.live_roots"
2172                                | subc_protocol::policy_root::GET_OP
2173                                | "activity.record"
2174                        )
2175                    });
2176                if !allowed {
2177                    return Ok(vec![control_error_frame(
2178                        &frame,
2179                        channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2180                        "prefix registrations have only brokered module operations",
2181                    )?]);
2182                }
2183            }
2184            if registered
2185                && frame.header.ty == FrameType::Push
2186                && !serde_json::from_slice::<ControlOpProbe>(&frame.body)
2187                    .is_ok_and(|probe| probe.op == "route.status")
2188            {
2189                return Ok(vec![control_error_frame(
2190                    &frame,
2191                    channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
2192                    "prefix registrations may push only route.status for routes they serve",
2193                )?]);
2194            }
2195        }
2196        match frame.header.ty {
2197            FrameType::Ping => Ok(vec![pong(&frame)?]),
2198            FrameType::Hello => {
2199                if claim_binding
2200                    .as_ref()
2201                    .is_some_and(|binding| binding.prefix_module_id().is_none())
2202                {
2203                    return self
2204                        .refuse_claim_connection(ctx, &frame, "claim_hello_not_allowed")
2205                        .await;
2206                }
2207                // Resolved once, here: the blocking HELLO below may outlive this
2208                // reader and run after cleanup has forgotten the channel, and it
2209                // must still be judged as this channel's HELLO.
2210                let channel_spawn = self.supervisor.registration_spawn(ctx.connection_id);
2211                if let Some(spawn) = &channel_spawn {
2212                    spawn.wait_launch().await;
2213                    // Refused launches close the channel. Leave their pending
2214                    // HELLO unanswered instead of racing a reply against shutdown.
2215                    if !spawn.launch_ready() {
2216                        ctx.egress.terminate_ingress();
2217                        return Ok(Vec::new());
2218                    }
2219                    #[cfg(test)]
2220                    self.pause_hello_ingress_for_test().await;
2221                } else if claim_binding.is_none() {
2222                    if let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&frame.body) {
2223                        if let (Some(module), Some(nonce)) = (
2224                            hello
2225                                .get("manifest")
2226                                .and_then(|value| value.get("module_id"))
2227                                .and_then(|value| value.as_str()),
2228                            hello.get("launch_nonce").and_then(|value| value.as_str()),
2229                        ) {
2230                            if !self
2231                                .config_runtime
2232                                .as_ref()
2233                                .is_some_and(|owner| owner.module_is_gated(module))
2234                                && !self.supervisor.wait_program_binding(module, nonce).await
2235                            {
2236                                self.request_refusal_close(
2237                                    ctx.connection_id,
2238                                    Some(&ctx.egress),
2239                                    CloseReason::new(
2240                                        "program_refused",
2241                                        "the spawned program binding failed",
2242                                    ),
2243                                );
2244                                return Ok(vec![control_error_frame(
2245                                    &frame,
2246                                    if self
2247                                        .config_runtime
2248                                        .as_ref()
2249                                        .is_some_and(|owner| owner.is_recovering())
2250                                    {
2251                                        "config_gated"
2252                                    } else {
2253                                        "program_refused"
2254                                    },
2255                                    "the spawned program binding failed",
2256                                )?]);
2257                            }
2258                        }
2259                    }
2260                }
2261                let handler = self.clone();
2262                let connection = ctx.connection_id;
2263                let egress = ctx.egress.clone();
2264                let correlation = frame.header.corr;
2265                let dispatcher = tracing::dispatcher::get_default(|dispatcher| dispatcher.clone());
2266                let span = tracing::Span::current();
2267                let hello_binding = claim_binding.clone();
2268                let replies = tokio::task::spawn_blocking(move || {
2269                    tracing::dispatcher::with_default(&dispatcher, || {
2270                        span.in_scope(|| {
2271                            handler.handle_hello_checked(
2272                                connection,
2273                                Some(egress),
2274                                frame,
2275                                true,
2276                                hello_binding,
2277                                channel_spawn,
2278                            )
2279                        })
2280                    })
2281                })
2282                .await
2283                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))??;
2284                #[cfg(test)]
2285                if prefix_attempt.is_some() {
2286                    self.claims.pause_prefix_commit_for_test(false).await;
2287                }
2288                if let Some(attempt) = &mut prefix_attempt {
2289                    let accepted = !replies
2290                        .iter()
2291                        .any(|reply| reply.header.ty == FrameType::Error)
2292                        && self
2293                            .registry
2294                            .get_module_by_connection(ctx.connection_id)
2295                            .map_err(|err| RouterError::backend(0, correlation, err.to_string()))?
2296                            .is_some();
2297                    if accepted {
2298                        attempt.accepted = true;
2299                    } else {
2300                        ctx.egress.terminate_ingress();
2301                        for reply in replies {
2302                            ctx.egress.send_flushed(reply).await?;
2303                        }
2304                        return Ok(Vec::new());
2305                    }
2306                }
2307                Ok(replies)
2308            }
2309            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
2310            FrameType::Cancel => {
2311                // Channel-0 cancellation withdraws approvals and subscriptions
2312                // and fences pending agent declarations;
2313                // successful cancellation has no ordinary reply.
2314                // A config Apply may also own an OS prompt. Cancel that prompt
2315                // before config cancellation can report the request handled.
2316                if self
2317                    .agent_declarations
2318                    .cancel(ctx.connection_id, frame.header.corr)
2319                    || self
2320                        .forwarding
2321                        .operator_confirms()
2322                        .cancel(ctx.connection_id, frame.header.corr)
2323                    || self.cancel_config_approval(ctx.connection_id, frame.header.corr)
2324                    || self
2325                        .supervisor
2326                        .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
2327                    || self.cancel_activity_subscription(ctx, &frame)?
2328                    || self.cancel_catalog_subscription(ctx.connection_id, frame.header.corr)
2329                    || self
2330                        .cancel_config_settings_subscription(ctx.connection_id, frame.header.corr)
2331                    || self.cancel_scope_subscription(ctx.connection_id, frame.header.corr)
2332                {
2333                    Ok(Vec::new())
2334                } else {
2335                    Ok(vec![control_error_frame(
2336                        &frame,
2337                        "unknown_subscription",
2338                        "no subscription has this correlation id",
2339                    )?])
2340                }
2341            }
2342            FrameType::Request => {
2343                // This additive operation is not part of the existing exhaustive
2344                // module-control enum. Probe the op before decoding that enum.
2345                let op = serde_json::from_slice::<ControlOpProbe>(&frame.body).ok();
2346                if let Some(probe) = &op {
2347                    self.record_control_usage(ctx.connection_id, &probe.op);
2348                }
2349                let claim_present = op.as_ref().is_some_and(|probe| probe.op == "claim.present");
2350                if let Some(refusal) = self
2351                    .recovery_request_refusal(
2352                        ctx,
2353                        &frame,
2354                        op.as_ref().map(|probe| probe.op.as_str()),
2355                    )
2356                    .await?
2357                {
2358                    if claim_present {
2359                        self.reclaim_presented_expiry(&frame);
2360                        return self
2361                            .refuse_claim_connection(ctx, &frame, "config_gated")
2362                            .await;
2363                    }
2364                    return Ok(vec![refusal]);
2365                }
2366                if claim_present {
2367                    return self.handle_claim_present(ctx, &frame, first).await;
2368                }
2369                if op.as_ref().is_some_and(|probe| probe.op == "claim.mint") {
2370                    return self.handle_claim_mint(ctx, &frame).await;
2371                }
2372                if let Some(refusal) = self.registration_operation_refusal(
2373                    ctx,
2374                    &frame,
2375                    op.as_ref().map(|probe| probe.op.as_str()),
2376                )? {
2377                    return Ok(vec![refusal]);
2378                }
2379                if let Some(probe) = op.as_ref().filter(|probe| policy_root::is_op(&probe.op)) {
2380                    return self.handle_policy_root(ctx, frame, &probe.op).await;
2381                }
2382                if op
2383                    .as_ref()
2384                    .is_some_and(|probe| probe.op == ops::CATALOG_WATCH)
2385                {
2386                    return self.handle_catalog_watch(ctx, frame);
2387                }
2388                if op
2389                    .as_ref()
2390                    .is_some_and(|probe| probe.op == ops::SCOPE_WATCH)
2391                {
2392                    return self.handle_scope_watch(ctx, frame);
2393                }
2394                if op
2395                    .as_ref()
2396                    .is_some_and(|probe| probe.op == MODULE_TO_SUBC_OP_CATALOG_UPDATE)
2397                    && subc_protocol::provider_declarations::catalog_update_has_provider_declarations(&frame.body)
2398                        .unwrap_or(false)
2399                {
2400                    return Ok(vec![control_error_frame(
2401                        &frame,
2402                        error_codes::CATALOG_UPDATE_FROZEN_DECLARATIONS,
2403                        "provider_declarations are fixed at HELLO; restart the module to change them",
2404                    )?]);
2405                }
2406                if let Some(probe) = op
2407                    .as_ref()
2408                    .filter(|probe| config_gate::is_module_config_op(&probe.op))
2409                {
2410                    return self
2411                        .handle_module_config_request(ctx, frame, &probe.op)
2412                        .await;
2413                }
2414                if op
2415                    .as_ref()
2416                    .is_some_and(|probe| config_gate::is_config_op(&probe.op))
2417                {
2418                    return self.handle_config_gate_request(ctx, frame).await;
2419                }
2420                if op
2421                    .as_ref()
2422                    .is_some_and(|probe| probe.op == ops::ACTIVITY_RECORD)
2423                {
2424                    return self.handle_activity_record(ctx, frame).await;
2425                }
2426                if op.as_ref().is_some_and(|probe| {
2427                    probe.op == ops::ACTIVITY_QUERY || probe.op == ops::ACTIVITY_SUBSCRIBE
2428                }) {
2429                    // A refusal and a CANCEL that won must not both end the stream.
2430                    let key = (ctx.connection_id, frame.header.corr);
2431                    let replies = self.handle_activity_read(ctx, frame).await?;
2432                    return Ok(self.activity_reservations.settle(key, replies));
2433                }
2434                if op
2435                    .as_ref()
2436                    .is_some_and(|probe| probe.op == "operator.confirm")
2437                {
2438                    return self.handle_operator_confirm(ctx, frame).await;
2439                }
2440                if op.as_ref().is_some_and(|probe| probe.op == ops::APP_OPEN) {
2441                    return self
2442                        .observe_control_wait(
2443                            ctx,
2444                            None,
2445                            ops::APP_OPEN,
2446                            self.handle_app_open(ctx, frame),
2447                        )
2448                        .await;
2449                }
2450                if op
2451                    .as_ref()
2452                    .is_some_and(|probe| probe.op == ops::CONNECTION_DESCRIBE)
2453                {
2454                    return self.handle_connection_describe(ctx, frame).await;
2455                }
2456                if op
2457                    .as_ref()
2458                    .is_some_and(|probe| probe.op == subc_control::SCOPE_SERVED_BY_OP)
2459                {
2460                    return self.handle_scope_served_by(ctx.connection_id, frame);
2461                }
2462                if self
2463                    .forwarding
2464                    .module_endpoint_for_connection(ctx.connection_id)
2465                    .map_err(RouterError::Forwarding)?
2466                    .is_some()
2467                {
2468                    if !is_known_module_request_op(&frame.body) {
2469                        return Ok(vec![control_error_frame(
2470                            &frame,
2471                            "unsupported_control_frame",
2472                            "module-originated channel-0 REQUEST is not supported",
2473                        )?]);
2474                    }
2475                    let request = match parse_module_control_request_from_module(&frame.body) {
2476                        Ok(request) => request,
2477                        Err((err, ControlRequestBodyError::UnknownOp)) => {
2478                            return Ok(vec![control_error_frame(
2479                                &frame,
2480                                "unsupported_control_frame",
2481                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
2482                            )?])
2483                        }
2484                        Err((err, ControlRequestBodyError::InvalidBody)) => {
2485                            return Ok(vec![control_error_frame(
2486                                &frame,
2487                                "invalid_control_body",
2488                                format!("malformed module control body: {err}"),
2489                            )?])
2490                        }
2491                    };
2492                    let op = module_control_request_op(&request);
2493                    let corr = frame.header.corr;
2494                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
2495                    if let ModuleControlRequestFromModule::AgentCommands {
2496                        started,
2497                        finished,
2498                        known,
2499                    } = request
2500                    {
2501                        return self
2502                            .agent_declarations
2503                            .enqueue(
2504                                self,
2505                                ctx,
2506                                frame,
2507                                crate::resource_totals::Declaration {
2508                                    started,
2509                                    finished,
2510                                    known,
2511                                },
2512                            )
2513                            .await;
2514                    }
2515                    let result =
2516                        self.handle_module_control_request(ctx.connection_id, frame, request);
2517                    log_slow_control_dispatch(
2518                        dispatch_started_at,
2519                        op,
2520                        ctx.connection_id,
2521                        corr,
2522                        None,
2523                    );
2524                    return result;
2525                }
2526
2527                if is_known_module_request_op(&frame.body) {
2528                    let is_agents = serde_json::from_slice::<ControlOpProbe>(&frame.body)
2529                        .is_ok_and(|probe| probe.op == "supervisor.agent_commands");
2530                    let code = if is_agents {
2531                        "not_supervised"
2532                    } else if op
2533                        .as_ref()
2534                        .is_some_and(|probe| probe.op == subc_protocol::scope::ROUTE_AUTHORIZE_OP)
2535                    {
2536                        error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED
2537                    } else {
2538                        "not_registered"
2539                    };
2540                    return Ok(vec![control_error_frame(
2541                        &frame,
2542                        code,
2543                        "module-originated control requests require the module's own registered connection",
2544                    )?]);
2545                }
2546
2547                let request = match parse_client_control_request(&frame.body) {
2548                    Ok(request) => request,
2549                    Err((err, ControlRequestBodyError::UnknownOp)) => {
2550                        return Ok(vec![control_error_frame(
2551                            &frame,
2552                            "unknown_control_op",
2553                            format!("unknown client control op: {err}"),
2554                        )?])
2555                    }
2556                    Err((err, ControlRequestBodyError::InvalidBody)) => {
2557                        return Ok(vec![control_error_frame(
2558                            &frame,
2559                            "invalid_control_body",
2560                            format!("malformed client control body: {err}"),
2561                        )?])
2562                    }
2563                };
2564                let op = client_control_request_op(&request);
2565                let corr = frame.header.corr;
2566                log_control_dispatch_arrival(op, ctx.connection_id, corr);
2567                let mut route_open_timings = (op == ops::ROUTE_OPEN).then(RouteOpenTimings::new);
2568                #[cfg(test)]
2569                if let Some(delay) = self.control_dispatch_delay {
2570                    tokio::time::sleep(delay).await;
2571                }
2572                let result = self
2573                    .handle_client_control_request(ctx, frame, request, &mut route_open_timings)
2574                    .await;
2575                if let Some(timings) = route_open_timings.as_mut() {
2576                    timings.finish();
2577                }
2578                log_slow_control_dispatch(
2579                    dispatch_started_at,
2580                    op,
2581                    ctx.connection_id,
2582                    corr,
2583                    route_open_timings.as_ref(),
2584                );
2585                result
2586            }
2587            FrameType::Push => {
2588                let Some(endpoint) = self
2589                    .forwarding
2590                    .module_endpoint_for_connection(ctx.connection_id)
2591                    .map_err(RouterError::Forwarding)?
2592                else {
2593                    return Ok(vec![control_error_frame(
2594                        &frame,
2595                        "unsupported_control_frame",
2596                        "client-originated channel-0 PUSH is not supported",
2597                    )?]);
2598                };
2599                self.handle_status_update(endpoint, frame)
2600            }
2601            FrameType::Response | FrameType::Error
2602                if self
2603                    .forwarding
2604                    .module_endpoint_for_connection(ctx.connection_id)
2605                    .map_err(RouterError::Forwarding)?
2606                    .is_some() =>
2607            {
2608                self.handle_module_relay_response(ctx.connection_id, frame)
2609            }
2610            ty => Ok(vec![control_error_frame(
2611                &frame,
2612                "unsupported_control_frame",
2613                format!("unsupported channel-0 frame {ty:?}"),
2614            )?]),
2615        }
2616    }
2617
2618    #[cfg(test)]
2619    fn pause_cleanup_for_test(&self, stage: u8) {
2620        let mut slot = self.cleanup_pause.lock().unwrap_or_else(|p| p.into_inner());
2621        if slot.as_ref().is_some_and(|(at, _)| *at == stage) {
2622            let (_, (reached, release)) = slot.take().unwrap();
2623            drop(slot);
2624            let _ = reached.send(());
2625            let _ = release.recv_timeout(Duration::from_secs(5));
2626        }
2627    }
2628
2629    /// Run `hook` once, in the next `route.open` that attests a launch nonce,
2630    /// right after the nonce is resolved.
2631    #[cfg(all(test, unix, feature = "test-support"))]
2632    pub(crate) fn after_nonce_attestation_for_test(&self, hook: impl FnOnce() + Send + 'static) {
2633        *self
2634            .after_nonce_attestation
2635            .lock()
2636            .unwrap_or_else(|p| p.into_inner()) = Some(Box::new(hook));
2637    }
2638
2639    #[cfg(test)]
2640    pub(super) fn pause_after_nonce_attestation_for_test(&self) {
2641        let hook = self
2642            .after_nonce_attestation
2643            .lock()
2644            .unwrap_or_else(|p| p.into_inner())
2645            .take();
2646        if let Some(hook) = hook {
2647            hook();
2648        }
2649    }
2650
2651    #[cfg(test)]
2652    async fn pause_hello_ingress_for_test(&self) {
2653        let pause = self
2654            .hello_ingress_pause
2655            .lock()
2656            .unwrap_or_else(|p| p.into_inner())
2657            .take();
2658        if let Some((reached, release)) = pause {
2659            let _ = reached.send(());
2660            let _ = release.await;
2661        }
2662    }
2663
2664    pub fn cleanup_connection(
2665        &self,
2666        connection_id: ConnectionId,
2667    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2668        // The server loop joins its offloaded request tasks (route opens,
2669        // privileged requests and activity reads) before this cleanup runs, and
2670        // inline dispatch has ended. Two kinds of work are not joined. Agent
2671        // command declarations run on their queue's detached worker, so the
2672        // queue is closed first: every declaration still queued or validating
2673        // has its commit fence cancelled before anything below can change how
2674        // the connection resolves. A HELLO whose reader was dropped keeps
2675        // running on its blocking thread. It carries the channel spawn its
2676        // reader resolved at ingress instead of re-reading the index forgotten
2677        // below, so it is still judged as that channel's HELLO: the retired
2678        // spawn refuses it before it records anything, and a channel HELLO
2679        // never records a launch nonce, so it cannot leave this connection any
2680        // nonce authority.
2681        self.agent_declarations.close(connection_id);
2682        self.close_catalog_subscriptions(connection_id);
2683        self.close_config_settings_subscriptions(connection_id);
2684        self.close_scope_subscriptions(connection_id);
2685        #[cfg(test)]
2686        self.pause_cleanup_for_test(0);
2687        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
2688            spawn.retire_registration_channel();
2689        }
2690        self.supervisor
2691            .forget_registration_connection(connection_id);
2692        #[cfg(test)]
2693        self.pause_cleanup_for_test(1);
2694        self.local_connections
2695            .lock()
2696            .unwrap_or_else(|p| p.into_inner())
2697            .remove(&connection_id);
2698        self.caller_endpoints
2699            .lock()
2700            .unwrap_or_else(|p| p.into_inner())
2701            .remove(&connection_id);
2702        self.build_class_warned
2703            .lock()
2704            .unwrap_or_else(|p| p.into_inner())
2705            .remove(&connection_id);
2706        // Retire the capture before its published facts so an in-flight
2707        // verification cannot recreate them after cleanup.
2708        self.captured_peers
2709            .lock()
2710            .unwrap_or_else(|p| p.into_inner())
2711            .remove(&connection_id);
2712        self.observed_peers
2713            .lock()
2714            .unwrap_or_else(|p| p.into_inner())
2715            .remove(&connection_id);
2716        self.config_desktop_stamps
2717            .lock()
2718            .unwrap_or_else(|p| p.into_inner())
2719            .remove(&connection_id);
2720        self.operator_apps
2721            .lock()
2722            .unwrap_or_else(|p| p.into_inner())
2723            .remove(&connection_id);
2724        self.forwarding
2725            .operator_confirms()
2726            .connection_closed(connection_id);
2727        let cleanup = self.cleanup_connection_with_end_reason(
2728            connection_id,
2729            RegistrationEndReason::ConnectionClosed,
2730        );
2731        // A draining writer can still be reached by a route until forwarding
2732        // cleanup finishes. Keep its claim sink visible to launch retirement.
2733        self.claims.connection_closed(connection_id);
2734        cleanup
2735    }
2736
2737    fn cleanup_connection_with_end_reason(
2738        &self,
2739        connection_id: ConnectionId,
2740        requested_reason: RegistrationEndReason,
2741    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
2742        #[cfg(test)]
2743        if let Some(pause) = self
2744            .activity_request_pause
2745            .lock()
2746            .unwrap()
2747            .as_ref()
2748            .filter(|pause| pause.connection == connection_id)
2749        {
2750            pause
2751                .cleanup_started
2752                .store(true, std::sync::atomic::Ordering::Release);
2753        }
2754        if let Some(runtime) = &self.config_runtime {
2755            runtime.disconnected(connection_id);
2756        }
2757        self.agent_declarations.close(connection_id);
2758        let end_reason = if requested_reason == RegistrationEndReason::ConnectionClosed {
2759            self.registry
2760                .get_module_by_connection(connection_id)?
2761                .and_then(|registration| self.supervisor.get(&registration.manifest.module_id))
2762                .and_then(|module| module.registration_end_reason().ok().flatten())
2763                .unwrap_or(requested_reason)
2764        } else {
2765            requested_reason
2766        };
2767        let crash_closed = self
2768            .registry
2769            .get_module_by_connection(connection_id)?
2770            .and_then(|registration| {
2771                self.forwarding
2772                    .module_endpoint_for_connection(connection_id)
2773                    .ok()
2774                    .flatten()
2775                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
2776                    .map(|routes| (registration.manifest.module_id, routes))
2777            });
2778        let crash_closed = crash_closed.map(|(module_id, routes)| {
2779            let terminal = match self.supervisor.get(&module_id) {
2780                None => false,
2781                Some(module) => match module.will_recover_after_connection_loss() {
2782                    Ok(will_recover) => !will_recover,
2783                    Err(err) => {
2784                        warn!(
2785                            %module_id,
2786                            error = %err,
2787                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
2788                        );
2789                        false
2790                    }
2791                },
2792            };
2793            // The forwarding table gates all providers at the start of daemon
2794            // shutdown, before their connections are closed. An ordinary
2795            // module disconnect still reports crash if that gate is not set.
2796            let (reason, drained) = match self
2797                .forwarding
2798                .daemon_drain_result_for_connection(connection_id)
2799            {
2800                Ok(Some(drained)) => (RouteCloseReason::Restart, drained),
2801                Ok(None) => (RouteCloseReason::Crash, false),
2802                Err(err) => {
2803                    warn!(error = %err, "failed to read daemon drain state; reporting crash conservatively");
2804                    (RouteCloseReason::Crash, false)
2805                }
2806            };
2807            (module_id, routes, reason, drained, terminal)
2808        });
2809        let registrations = self.deregister_connection(connection_id, end_reason);
2810        // Read before teardown: the spawn whose registration this connection
2811        // was. Its registration ending is an authority change for it.
2812        let ended_authority = self
2813            .forwarding
2814            .target_authority_for_connection(connection_id)
2815            .ok()
2816            .flatten();
2817        let cleanup = if crash_closed.is_some() {
2818            self.forwarding.cleanup_connection_counted(connection_id)
2819        } else {
2820            // A module connection's teardown needs the count of abandoned
2821            // route.bind relays for its route.closed notice below. Any other
2822            // connection, such as a client's, sends no such notice and needs
2823            // only its routes released, so it uses the route-only wrapper and
2824            // reports zero.
2825            self.forwarding
2826                .cleanup_connection(connection_id)
2827                .map(|released| crate::forwarding::ConnectionCleanup {
2828                    released,
2829                    abandoned_relays: 0,
2830                })
2831        };
2832        // The route.closed push waits for forwarding teardown because only
2833        // teardown knows how many pending route.bind relays it aborted. It still
2834        // goes out before the GOODBYEs for the released routes, and its targets
2835        // were captured above, before teardown removed those routes.
2836        if let Some((module_id, routes, reason, drained, terminal)) = crash_closed {
2837            let abandoned = cleanup
2838                .as_ref()
2839                .map_or(0, |cleanup| cleanup.abandoned_relays);
2840            send_route_control_pushes(
2841                &self.forwarding,
2842                routes,
2843                ClientControlPush::RouteClosed {
2844                    module_id,
2845                    channels: Vec::new(),
2846                    reason,
2847                    drained,
2848                    abandoned,
2849                    excluded_subscriptions: 0,
2850                    terminal: Some(terminal),
2851                },
2852            );
2853        }
2854        if let Ok(cleanup) = cleanup {
2855            self.emit_route_goodbyes(cleanup.released);
2856        }
2857        if let Some(record) = ended_authority {
2858            self.change_spawn_authority(&record);
2859        }
2860        // Signal the registration-release watch only now that BOTH registry and
2861        // forwarding teardown are done, so a supervisor waiting to spawn a
2862        // replacement never observes release while old routes still exist.
2863        if matches!(&registrations, Ok(r) if !r.is_empty()) {
2864            crate::supervise::notify_registration_release();
2865            self.capability_evaluator.wake_deadline_loop();
2866            self.refresh_capability_requirements();
2867        }
2868        self.supervisor.remove_spawn_subscribers(connection_id);
2869        self.activity_streams
2870            .lock()
2871            .unwrap_or_else(|p| p.into_inner())
2872            .retain(|(id, _), task| {
2873                if *id == connection_id {
2874                    task.abort();
2875                    false
2876                } else {
2877                    true
2878                }
2879            });
2880        // Sync authority dies with its connection, so the owner's next
2881        // connection can take it; the owner's scopes stay as they are.
2882        self.hello_launch_nonces
2883            .lock()
2884            .unwrap_or_else(|poisoned| poisoned.into_inner())
2885            .forget(connection_id);
2886        self.scopes
2887            .write()
2888            .unwrap_or_else(|poisoned| poisoned.into_inner())
2889            .release_connection(connection_id);
2890        registrations
2891    }
2892
2893    pub(crate) fn handle_route_goodbye(
2894        &self,
2895        connection_id: ConnectionId,
2896        route_channel: u16,
2897        route_epoch: u32,
2898    ) -> Result<bool, RouterError> {
2899        debug!(
2900            connection_id = connection_id.get(),
2901            route_channel, route_epoch, "handling route GOODBYE"
2902        );
2903        let RouteRelease::Removed(released_route) = self
2904            .forwarding
2905            .release_client_route(connection_id, route_channel, route_epoch)
2906            .map_err(RouterError::Forwarding)?
2907        else {
2908            return Ok(false);
2909        };
2910        self.emit_route_goodbyes(vec![released_route]);
2911        Ok(true)
2912    }
2913
2914    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
2915        scope_expiry::ScopeExpiryContext::new(self).emit_route_goodbyes(released_routes);
2916    }
2917
2918    /// Best-effort GOODBYE to a module for a route channel subc reserved but then
2919    /// abandoned (route.bind relay timed out, its waiter was cancelled, or subc's
2920    /// own commit failed after the module had already accepted). Without this, a
2921    /// module that accepts late keeps a binding subc has torn down, so a later
2922    /// frame on that module channel could misdeliver if the channel is reused.
2923    ///
2924    /// Never closes the shared module connection on failure: a dropped notification
2925    /// only wastes a bounded amount of warm module-side state, which the module's
2926    /// own idle reaper reclaims. Only call this once the route.bind relay was
2927    /// actually enqueued to the module — if the relay send itself failed, the
2928    /// module never created a binding and there is nothing to tear down.
2929    fn send_abandoned_route_bind_goodbye(
2930        &self,
2931        module_sink: &crate::FrameSink,
2932        negotiated_ver: u8,
2933        module_channel: u16,
2934        module_epoch: u32,
2935    ) {
2936        let frame = match Frame::build_with_version(
2937            negotiated_ver,
2938            FrameType::Goodbye,
2939            control_flags(),
2940            module_channel,
2941            module_epoch,
2942            0,
2943            Vec::new(),
2944        ) {
2945            Ok(frame) => frame,
2946            Err(err) => {
2947                warn!(
2948                    route_channel = module_channel,
2949                    error = %err,
2950                    "failed to build GOODBYE for abandoned route.bind"
2951                );
2952                return;
2953            }
2954        };
2955        crate::forwarding::send_module_route_goodbye(
2956            &self.counters,
2957            module_sink,
2958            frame,
2959            None,
2960            "abandoned route.bind",
2961        );
2962    }
2963
2964    #[cfg(test)]
2965    fn handle_hello(
2966        &self,
2967        connection_id: ConnectionId,
2968        egress: Option<crate::router::FrameSink>,
2969        frame: Frame,
2970    ) -> Result<Vec<Frame>, RouterError> {
2971        let binding = self.claims.binding(connection_id);
2972        let channel_spawn = self.supervisor.registration_spawn(connection_id);
2973        self.handle_hello_checked(connection_id, egress, frame, false, binding, channel_spawn)
2974    }
2975
2976    fn handle_hello_checked(
2977        &self,
2978        connection_id: ConnectionId,
2979        sink: Option<crate::FrameSink>,
2980        frame: Frame,
2981        wait_for_gate: bool,
2982        prefix_binding: Option<claims::ClaimBinding>,
2983        channel_spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
2984    ) -> Result<Vec<Frame>, RouterError> {
2985        let primary_sink = channel_spawn.as_ref().and_then(|_| sink.clone());
2986        #[cfg(test)]
2987        if prefix_binding.is_some() {
2988            self.claims.pause_prefix_hello_for_test(5);
2989            match self.claims.take_prefix_hello_failure_for_test() {
2990                Some("error") => {
2991                    return Err(RouterError::backend(
2992                        0,
2993                        frame.header.corr,
2994                        "injected HELLO failure",
2995                    ))
2996                }
2997                Some("panic") => panic!("injected HELLO task panic"),
2998                _ => {}
2999            }
3000        }
3001        if let Some(binding) = &prefix_binding {
3002            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3003            let module = value
3004                .as_ref()
3005                .and_then(|value| value["manifest"]["module_id"].as_str());
3006            if !binding.admit_prefix_hello(module)
3007                || !self.prefix_binding_live(binding, connection_id)
3008                || !module.is_some_and(|module| {
3009                    self.supervisor
3010                        .prefix_claim_authorized(&binding.registration.module_id, module)
3011                })
3012                || binding.registration.check().is_err()
3013            {
3014                return Ok(vec![control_error_frame(
3015                    &frame,
3016                    "claim_prefix_refused",
3017                    "HELLO must name the prefix claim's exact module id once",
3018                )?]);
3019            }
3020        }
3021        struct RefuseUnregisteredChannel {
3022            spawn: Option<Arc<crate::supervise::RegistrationSpawn>>,
3023            sink: Option<crate::FrameSink>,
3024        }
3025        impl Drop for RefuseUnregisteredChannel {
3026            fn drop(&mut self) {
3027                if let Some(spawn) = &self.spawn {
3028                    if !spawn.registered() {
3029                        if let Some(sink) = &self.sink {
3030                            sink.terminate_ingress();
3031                        }
3032                        spawn.retire_registration_channel();
3033                    }
3034                }
3035            }
3036        }
3037        let _channel_attempt = RefuseUnregisteredChannel {
3038            spawn: channel_spawn.clone(),
3039            sink: sink.clone(),
3040        };
3041        if let Some(spawn) = &channel_spawn {
3042            let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
3043            if let Err(code) = spawn.admit_hello(
3044                value
3045                    .as_ref()
3046                    .and_then(|value| value["manifest"]["module_id"].as_str()),
3047            ) {
3048                return Ok(vec![control_error_frame(
3049                    &frame,
3050                    code,
3051                    "registration channel HELLO refused",
3052                )?]);
3053            }
3054        }
3055        debug!(
3056            connection_id = connection_id.get(),
3057            corr = frame.header.corr,
3058            "handling HELLO"
3059        );
3060        // A module connection has one identity for its entire lifetime. A second
3061        // registration would leave the old registry owner behind while replacing
3062        // its forwarding endpoint and launch nonce.
3063        if self
3064            .registry
3065            .get_module_by_connection(connection_id)
3066            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
3067            .is_some()
3068        {
3069            return Ok(vec![control_error_frame(
3070                &frame,
3071                "invalid_hello",
3072                "connection is already registered as a module",
3073            )?]);
3074        }
3075        let hello_value = match serde_json::from_slice::<serde_json::Value>(&frame.body) {
3076            Ok(value) => value,
3077            Err(err) => {
3078                return Ok(vec![control_error_frame(
3079                    &frame,
3080                    "invalid_hello",
3081                    format!("malformed HELLO body: {err}"),
3082                )?])
3083            }
3084        };
3085        if let Err(detail) = catalog::validate_hello_declarations(&hello_value) {
3086            return Ok(vec![control_error_frame(
3087                &frame,
3088                error_codes::INVALID_PROVIDER_DECLARATIONS,
3089                detail,
3090            )?]);
3091        }
3092        if let Some(module) = hello_value
3093            .get("manifest")
3094            .and_then(|value| value.get("module_id"))
3095            .and_then(|value| value.as_str())
3096        {
3097            let recovering = self
3098                .config_runtime
3099                .as_ref()
3100                .is_some_and(|owner| owner.check_recovery().unwrap_or(true));
3101            // Defence in depth: RuntimeOwner::module_is_gated in
3102            // config_gate/admission.rs already gates every id during recovery.
3103            // A registration channel still never uses the nonce fallback.
3104            if recovering
3105                && channel_spawn.as_ref().is_none_or(|spawn| {
3106                    !self.supervisor.has_live_verified_channel_binding(spawn)
3107                        || spawn.check().is_err()
3108                })
3109                && !(channel_spawn.is_none()
3110                    && hello_value
3111                        .get("launch_nonce")
3112                        .and_then(|value| value.as_str())
3113                        .is_some_and(|nonce| {
3114                            self.supervisor.spawned_consumer_authorized(module, nonce)
3115                                && self
3116                                    .supervisor
3117                                    .has_live_verified_program_binding(module, nonce)
3118                        }))
3119            {
3120                return Ok(vec![control_error_frame(
3121                    &frame,
3122                    "config_gated",
3123                    "recovery admits only previously bound supervised launches",
3124                )?]);
3125            }
3126            if self
3127                .config_runtime
3128                .as_ref()
3129                .is_some_and(|owner| owner.module_is_gated(module))
3130                && (channel_spawn
3131                    .as_ref()
3132                    .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3133                    || self.config_runtime.as_ref().is_some_and(|owner| {
3134                        !recovering && owner.check_module_hold(module).is_err()
3135                    }))
3136            {
3137                return Ok(vec![control_error_frame(
3138                    &frame,
3139                    "reserved_module",
3140                    "a gated identity belongs only to its supervised child",
3141                )?]);
3142            }
3143        }
3144        if channel_spawn.is_none() {
3145            if let (Some(module), Some(nonce)) = (
3146                hello_value
3147                    .get("manifest")
3148                    .and_then(|value| value.get("module_id"))
3149                    .and_then(|value| value.as_str()),
3150                hello_value
3151                    .get("launch_nonce")
3152                    .and_then(|value| value.as_str()),
3153            ) {
3154                let binding = self.supervisor.has_program_binding_record(module, nonce);
3155                let required = self
3156                    .config_runtime
3157                    .as_ref()
3158                    .is_some_and(|owner| owner.module_is_gated(module));
3159                if let Some(error) = (binding || required)
3160                    .then(|| {
3161                        self.supervisor
3162                            .check_current_program_binding(module, nonce)
3163                            .err()
3164                    })
3165                    .flatten()
3166                {
3167                    let code = if error.code == "program_refused" {
3168                        "program_refused"
3169                    } else {
3170                        "config_delivery_deferred"
3171                    };
3172                    self.request_refusal_close(
3173                        connection_id,
3174                        sink.as_ref(),
3175                        CloseReason::new(code, error.detail.clone()),
3176                    );
3177                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3178                }
3179            }
3180        }
3181        if let Err(err) = validate_hello_display_name(&hello_value) {
3182            return Ok(vec![control_error_frame(
3183                &frame,
3184                "invalid_manifest",
3185                err.to_string(),
3186            )?]);
3187        }
3188        if let Err(err) = validate_hello_capability_grammar(&hello_value) {
3189            return Ok(vec![control_error_frame(
3190                &frame,
3191                "invalid_capability_grammar",
3192                err.to_string(),
3193            )?]);
3194        }
3195        if let Err(err) = validate_hello_self_signal_declarations(&hello_value) {
3196            return Ok(vec![control_error_frame(
3197                &frame,
3198                "invalid_manifest",
3199                err.to_string(),
3200            )?]);
3201        }
3202        if let Err(err) = validate_hello_event_declarations(&hello_value) {
3203            return Ok(vec![control_error_frame(
3204                &frame,
3205                "invalid_event_declaration",
3206                err.to_string(),
3207            )?]);
3208        }
3209        if let Err(err) = validate_hello_rich_ui_descriptor(&hello_value) {
3210            return Ok(vec![control_error_frame(
3211                &frame,
3212                "invalid_manifest",
3213                err.to_string(),
3214            )?]);
3215        }
3216        if let Some(provenance) = hello_value
3217            .get("manifest")
3218            .and_then(|manifest| manifest.get("provenance"))
3219        {
3220            if let Err(err) = serde_json::from_value::<ManifestProvenance>(provenance.clone()) {
3221                return Ok(vec![control_error_frame(
3222                    &frame,
3223                    "invalid_manifest",
3224                    format!("malformed manifest provenance: {err}"),
3225                )?]);
3226            }
3227        }
3228        if let Err(reason) = validate_hello_role_declarations(&hello_value) {
3229            let module_id = hello_value["manifest"]["module_id"]
3230                .as_str()
3231                .unwrap_or("<unknown>");
3232            warn!(module_id, %reason, "dropping whole role_declarations map from HELLO");
3233        }
3234        if let Err(reason) = validate_hello_operation_deferral(&hello_value) {
3235            let module_id = hello_value
3236                .get("manifest")
3237                .and_then(|m| m.get("module_id"))
3238                .and_then(serde_json::Value::as_str)
3239                .unwrap_or("unknown");
3240            warn!(module_id, %reason, "dropping operation_deferral from HELLO");
3241        }
3242        if let Err(reason) = validate_hello_flow_operations(&hello_value) {
3243            let module_id = hello_value["manifest"]["module_id"]
3244                .as_str()
3245                .unwrap_or("<unknown>");
3246            warn!(module_id, %reason, "dropping flow_operations from HELLO");
3247        }
3248        if let Err(reason) = validate_hello_confirm_operations(&hello_value) {
3249            let module_id = hello_value["manifest"]["module_id"]
3250                .as_str()
3251                .unwrap_or("<unknown>");
3252            warn!(module_id, %reason, "dropping confirm_operations from HELLO");
3253        }
3254        let hello = match serde_json::from_value::<ModuleHelloBody>(hello_value) {
3255            Ok(hello) => hello,
3256            Err(err) => {
3257                return Ok(vec![control_error_frame(
3258                    &frame,
3259                    "invalid_hello",
3260                    format!("malformed HELLO body: {err}"),
3261                )?])
3262            }
3263        };
3264
3265        if hello.protocol_ver != hello.manifest.protocol_ver {
3266            return Ok(vec![control_error_frame(
3267                &frame,
3268                "invalid_manifest",
3269                format!(
3270                    "HELLO protocol_ver {} does not match manifest protocol_ver {}",
3271                    hello.protocol_ver, hello.manifest.protocol_ver
3272                ),
3273            )?]);
3274        }
3275
3276        if hello.manifest.module_id.trim().is_empty() {
3277            return Ok(vec![control_error_frame(
3278                &frame,
3279                "invalid_manifest",
3280                "manifest module_id must not be empty",
3281            )?]);
3282        }
3283
3284        let negotiated_ver = match negotiate_version(hello.protocol_ver) {
3285            Ok(negotiated_ver) => negotiated_ver,
3286            Err(message) => {
3287                return Ok(vec![control_error_frame(
3288                    &frame,
3289                    "version_unsupported",
3290                    message,
3291                )?])
3292            }
3293        };
3294
3295        // Registration and forwarding publication use the same module gate as
3296        // stamp, unstamp and spawning. Recheck after taking it; parsing may
3297        // precede those transitions. A program-refusal hold blocks future
3298        // spawns, but does not take this gate or revoke a HELLO whose supervised
3299        // child's image has already passed the check.
3300        let _publication_gate = if let Some(owner) = &self.config_runtime {
3301            let gate = owner
3302                .module_gate(&hello.manifest.module_id)
3303                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
3304            Some(if wait_for_gate {
3305                gate.blocking_lock_owned()
3306            } else {
3307                match gate.try_lock_owned() {
3308                    Ok(guard) => guard,
3309                    Err(_) => {
3310                        return Ok(vec![control_error_frame(
3311                            &frame,
3312                            "config_delivery_deferred",
3313                            "module admission is busy",
3314                        )?])
3315                    }
3316                }
3317            })
3318        } else {
3319            None
3320        };
3321        #[cfg(test)]
3322        if let Some(hold) = &self.hello_before_publication_hold {
3323            hold.wait();
3324            hold.wait();
3325        }
3326        let module = &hello.manifest.module_id;
3327        let required = self
3328            .config_runtime
3329            .as_ref()
3330            .is_some_and(|owner| owner.module_is_gated(module));
3331        let recovering = self
3332            .config_runtime
3333            .as_ref()
3334            .is_some_and(|owner| owner.is_recovering());
3335        // Both entry paths (handle_control -> handle_hello and
3336        // handle_control_frame_timed -> spawn_blocking) enter this same
3337        // handle_hello_checked function. Its fresh, fail-closed store check
3338        // precedes parsing and this publication-gate check; this cached read
3339        // also observes any recovery transition published during that work.
3340        // The nonce-connection-only fallback is defence in depth alongside
3341        // RuntimeOwner::module_is_gated's all-id recovery gate.
3342        if recovering
3343            && channel_spawn.as_ref().is_none_or(|spawn| {
3344                !self.supervisor.has_live_verified_channel_binding(spawn) || spawn.check().is_err()
3345            })
3346            && !(channel_spawn.is_none()
3347                && hello.launch_nonce.as_deref().is_some_and(|nonce| {
3348                    self.supervisor.spawned_consumer_authorized(module, nonce)
3349                        && self
3350                            .supervisor
3351                            .has_live_verified_program_binding(module, nonce)
3352                }))
3353        {
3354            return Ok(vec![control_error_frame(
3355                &frame,
3356                "config_gated",
3357                "recovery admits only previously bound supervised launches",
3358            )?]);
3359        }
3360        if required
3361            && (channel_spawn
3362                .as_ref()
3363                .is_none_or(|spawn| !self.supervisor.has_live_verified_channel_binding(spawn))
3364                || self
3365                    .config_runtime
3366                    .as_ref()
3367                    .is_some_and(|owner| !recovering && owner.check_module_hold(module).is_err()))
3368        {
3369            return Ok(vec![control_error_frame(
3370                &frame,
3371                "reserved_module",
3372                "gated admission requires the current supervised child's registration channel and verified image binding",
3373            )?]);
3374        }
3375        if let Some(spawn) = &channel_spawn {
3376            if let Err(code) = spawn.check() {
3377                return Ok(vec![control_error_frame(
3378                    &frame,
3379                    code,
3380                    "registration launch is no longer live",
3381                )?]);
3382            }
3383        } else if let Some(nonce) = hello.launch_nonce.as_deref() {
3384            if required || self.supervisor.has_program_binding_record(module, nonce) {
3385                if let Err(error) = self.supervisor.check_current_program_binding(module, nonce) {
3386                    let code = if error.code == "program_refused" {
3387                        "program_refused"
3388                    } else {
3389                        "config_delivery_deferred"
3390                    };
3391                    self.request_refusal_close(
3392                        connection_id,
3393                        sink.as_ref(),
3394                        CloseReason::new(code, error.detail.clone()),
3395                    );
3396                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
3397                }
3398            }
3399        }
3400
3401        // Swap gate, ahead of the reserved gate on purpose. While a blue/green
3402        // swap is open for this id, the only HELLO admitted as a second process
3403        // is the one carrying the candidate's launch nonce (the swap token), and
3404        // it registers into the candidate slot rather than being refused as a
3405        // duplicate. Run after the reserved gate, a reserved module's candidate
3406        // would be refused `reserved_module` for presenting a nonce that gate
3407        // does not know. See `SupervisorHandle::swap_hello_admission`.
3408        let swap_admission = match &channel_spawn {
3409            Some(spawn) if spawn.is_candidate() => SwapHelloAdmission::Candidate,
3410            Some(_) => SwapHelloAdmission::NotSwapping,
3411            None if prefix_binding.is_some() => SwapHelloAdmission::NotSwapping,
3412            None => self
3413                .supervisor
3414                .swap_hello_admission(&hello.manifest.module_id, hello.launch_nonce.as_deref()),
3415        };
3416        if swap_admission == SwapHelloAdmission::ProtocolNone {
3417            warn!(
3418                module_id = %hello.manifest.module_id,
3419                connection_id = connection_id.get(),
3420                "HELLO refused: the module_id belongs to a protocol:none module, which never registers"
3421            );
3422            // The code stays `swap_token_invalid` for existing callers; only the
3423            // explanation names the actual reason.
3424            return Ok(vec![control_error_frame(
3425                &frame,
3426                "swap_token_invalid",
3427                format!(
3428                    "module_id '{}' is a protocol:none module; a protocol:none module may not register",
3429                    hello.manifest.module_id
3430                ),
3431            )?]);
3432        }
3433        if swap_admission == SwapHelloAdmission::ChannelRequired {
3434            warn!(
3435                module_id = %hello.manifest.module_id,
3436                connection_id = connection_id.get(),
3437                "HELLO refused: the module_id is gated and the HELLO did not arrive over its registration channel"
3438            );
3439            // The code stays `swap_token_invalid` for existing callers; only the
3440            // explanation names the actual reason.
3441            return Ok(vec![control_error_frame(
3442                &frame,
3443                "swap_token_invalid",
3444                format!(
3445                    "module_id '{}' is gated; it must register over its supervised registration channel",
3446                    hello.manifest.module_id
3447                ),
3448            )?]);
3449        }
3450        if swap_admission == SwapHelloAdmission::Refused {
3451            warn!(
3452                module_id = %hello.manifest.module_id,
3453                connection_id = connection_id.get(),
3454                "HELLO refused: a swap is open for this module_id and the launch nonce is not one the supervisor minted for it"
3455            );
3456            return Ok(vec![control_error_frame(
3457                &frame,
3458                "swap_token_invalid",
3459                format!(
3460                    "module_id '{}' is being swapped; HELLO without the swap candidate's launch nonce is rejected",
3461                    hello.manifest.module_id
3462                ),
3463            )?]);
3464        }
3465        let swap_candidate = swap_admission == SwapHelloAdmission::Candidate;
3466
3467        // A swap candidate proves its identity with the candidate nonce above.
3468        // Other registrations receive this catalog fact only when reserved-module
3469        // policy required and accepted a nonce; unreserved registrations require
3470        // no nonce check.
3471        let verification = if swap_candidate && channel_spawn.is_none() {
3472            ReservedHelloVerification {
3473                nonce_verified: true,
3474                prefix_owner: None,
3475            }
3476        } else {
3477            let verification = if let Some(binding) = &prefix_binding {
3478                if !self.supervisor.prefix_claim_authorized(
3479                    &binding.registration.module_id,
3480                    &hello.manifest.module_id,
3481                ) {
3482                    return Ok(vec![control_error_frame(
3483                        &frame,
3484                        "claim_prefix_refused",
3485                        "prefix ownership changed",
3486                    )?]);
3487                }
3488                Ok(ReservedHelloVerification {
3489                    nonce_verified: true,
3490                    prefix_owner: Some(binding.registration.module_id.clone()),
3491                })
3492            } else if channel_spawn.is_some() {
3493                self.supervisor
3494                    .channel_hello_verification(&hello.manifest.module_id)
3495            } else {
3496                self.supervisor.reserved_hello_verification(
3497                    &hello.manifest.module_id,
3498                    hello.launch_nonce.as_deref(),
3499                )
3500            };
3501            match verification {
3502                Ok(verified) => verified,
3503                Err(rejection) => {
3504                    let message = match rejection {
3505                        ReservedHelloRejection::Exact { module_id } => format!(
3506                            "module_id '{module_id}' is reserved; HELLO without a valid launch nonce is rejected"
3507                        ),
3508                        ReservedHelloRejection::Prefix {
3509                            prefix,
3510                            owner_module_id,
3511                        } => format!(
3512                            "module_id '{}' matches reserved prefix '{prefix}' owned by '{owner_module_id}'; HELLO without the owner launch nonce is rejected",
3513                            hello.manifest.module_id
3514                        ),
3515                    };
3516                    return Ok(vec![control_error_frame(
3517                        &frame,
3518                        "reserved_module",
3519                        message,
3520                    )?]);
3521                }
3522            }
3523        };
3524
3525        let reserved_capability_refusals = self.capability_evaluator.reserved_hello_refusals(
3526            &hello.manifest.module_id,
3527            hello.manifest.capabilities.as_ref(),
3528        );
3529        if let Some(refusal) = reserved_capability_refusals.first() {
3530            let capability = refusal.capability.clone();
3531            let bound_module = refusal.claimants[0].clone();
3532            log_duplicate_claim_events(reserved_capability_refusals);
3533            return Ok(vec![control_error_frame(
3534                &frame,
3535                "reserved_capability",
3536                format!(
3537                    "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
3538                    capability, bound_module, hello.manifest.module_id
3539                ),
3540            )?]);
3541        }
3542
3543        // A connection that already opened client routes must not also register as
3544        // a module: cleanup would then release only one side and leak the other.
3545        if self
3546            .forwarding
3547            .connection_has_client_routes(connection_id)
3548            .map_err(RouterError::Forwarding)?
3549        {
3550            return Ok(vec![control_error_frame(
3551                &frame,
3552                "invalid_hello",
3553                "connection has open client routes and cannot also register as a module",
3554            )?]);
3555        }
3556
3557        // Kept for scope sync authority, which goes only to the connection that
3558        // presented the module's current launch nonce. Recorded before the
3559        // registration is attempted: a connection whose registration then fails
3560        // has no registration, so it cannot sync anyway, and cleanup forgets it.
3561        // A registration channel's authority is the channel itself, never a
3562        // nonce it also presented, and a prefix registration's is its claim:
3563        // neither records one, so neither can fall back to nonce authority.
3564        self.hello_launch_nonces
3565            .lock()
3566            .unwrap_or_else(|poisoned| poisoned.into_inner())
3567            .record(
3568                connection_id,
3569                if prefix_binding.is_some() || channel_spawn.is_some() {
3570                    None
3571                } else {
3572                    hello.launch_nonce.as_deref()
3573                },
3574            );
3575        let control_ops = effective_module_control_ops(hello.control_ops);
3576        let prefix_submodule = verification.prefix_owner.is_some();
3577        // Built before anything is registered so an encoding failure leaves no
3578        // registry or forwarding state behind.
3579        let hello_ack = self.build_hello_ack(&frame, negotiated_ver, &hello.manifest.module_id)?;
3580        #[cfg(test)]
3581        struct PublicationFinished(Arc<std::sync::Barrier>);
3582        #[cfg(test)]
3583        impl Drop for PublicationFinished {
3584            fn drop(&mut self) {
3585                self.0.wait();
3586            }
3587        }
3588        #[cfg(test)]
3589        let _publication_finished = self.hello_after_launch_check_hold.as_ref().map(|hold| {
3590            hold.wait();
3591            hold.wait();
3592            PublicationFinished(hold.clone())
3593        });
3594        let publication_spawn = channel_spawn
3595            .as_ref()
3596            .or_else(|| prefix_binding.as_ref().map(|binding| &binding.registration));
3597        #[cfg(test)]
3598        if prefix_binding.is_some() {
3599            self.claims.pause_prefix_hello_for_test(7);
3600        }
3601        let _registration_publication = match publication_spawn {
3602            Some(spawn) => Some(match spawn.begin_publication() {
3603                Ok(guard) => guard,
3604                Err(code) => {
3605                    return Ok(vec![control_error_frame(
3606                        &frame,
3607                        code,
3608                        "registration ended before HELLO publication",
3609                    )?])
3610                }
3611            }),
3612            None => None,
3613        };
3614        let (_prefix_live, _prefix_ownership) = if let Some(binding) = &prefix_binding {
3615            let live = self.claims.lock_prefix_binding(binding, connection_id);
3616            let ownership = self.supervisor.prefix_claim_publication(
3617                &binding.registration.module_id,
3618                &hello.manifest.module_id,
3619            );
3620            if live.is_none()
3621                || ownership.is_none()
3622                || !self.claim_primary_registered(binding.spawn, &binding.registration)
3623                || binding.prefix_module_id() != Some(hello.manifest.module_id.as_str())
3624            {
3625                return Ok(vec![control_error_frame(
3626                    &frame,
3627                    "claim_prefix_refused",
3628                    "prefix authority ended before publication",
3629                )?]);
3630            }
3631            (live, ownership)
3632        } else {
3633            (None, None)
3634        };
3635        if let Some(spawn) = publication_spawn {
3636            self.forwarding
3637                .bind_spawn(connection_id, spawn)
3638                .map_err(RouterError::Forwarding)?;
3639        }
3640        // The spawn whose own registration this HELLO is, for `target` on
3641        // the route.open reply: its channel, or the launch its nonce was
3642        // minted for. A prefix child's HELLO names no spawn of its own. It is
3643        // only looked up here. The connection is bound to it and its
3644        // requested declarations are frozen once the registry has accepted
3645        // this HELLO (`admit_hello_authority`), so a HELLO refused as a
3646        // duplicate, or for any other reason, leaves the spawn untouched: its
3647        // closing connection is then no registration of the spawn and ends
3648        // none of the spawn's routes.
3649        let hello_authority = match (&channel_spawn, &prefix_binding) {
3650            (Some(spawn), _) => Some(spawn.authority.clone()),
3651            (None, None) => hello.launch_nonce.as_deref().and_then(|nonce| {
3652                self.supervisor
3653                    .spawned_consumer_record(&hello.manifest.module_id, nonce)
3654            }),
3655            (None, Some(_)) => None,
3656        }
3657        .map(|record| HelloAuthority {
3658            record,
3659            requested: hello
3660                .manifest
3661                .provider_declarations
3662                .clone()
3663                .unwrap_or_default(),
3664            froze: Default::default(),
3665        });
3666        #[cfg(test)]
3667        if prefix_binding.is_some() {
3668            self.claims.pause_prefix_hello_for_test(8);
3669        }
3670        if swap_candidate {
3671            let module_id = hello.manifest.module_id.clone();
3672            let mut differing_declarations = Default::default();
3673            let reply = self.register_swap_candidate(
3674                connection_id,
3675                sink,
3676                &frame,
3677                hello.manifest,
3678                negotiated_ver,
3679                control_ops,
3680                hello_ack,
3681                hello_authority.as_ref(),
3682                &mut differing_declarations,
3683                #[cfg(windows)]
3684                hello.launch_nonce.as_deref(),
3685            )?;
3686            if let Some(spawn) = &channel_spawn {
3687                if self
3688                    .registry
3689                    .get_module_by_connection(connection_id)
3690                    .ok()
3691                    .flatten()
3692                    .is_some()
3693                {
3694                    if let Some(sink) = primary_sink {
3695                        spawn.bind_primary_sink(sink);
3696                    }
3697                    spawn.hello_accepted();
3698                }
3699            } else if self
3700                .registry
3701                .get_module_by_connection(connection_id)
3702                .ok()
3703                .flatten()
3704                .is_some()
3705            {
3706                self.supervisor
3707                    .retire_unused_registration_channel(&module_id, true);
3708            }
3709            if self
3710                .registry
3711                .get_module_by_connection(connection_id)
3712                .ok()
3713                .flatten()
3714                .is_some()
3715            {
3716                self.file_development_widening(
3717                    hello_authority.map(|authority| authority.record),
3718                    differing_declarations,
3719                );
3720            }
3721            return Ok(reply);
3722        }
3723        // Registered unpublished: the module id is claimed, so a duplicate HELLO
3724        // is refused, but `catalog.list` does not show the module and the
3725        // catalog generation does not move until it is published below, once
3726        // its forwarding endpoint exists. Listing it now would advertise a
3727        // module that `route.open` still refuses for having no forwarding
3728        // connection.
3729        let registration = match self
3730            .registry
3731            .register_unpublished_verified_with_control_ops(
3732                hello.manifest,
3733                negotiated_ver,
3734                connection_id,
3735                control_ops,
3736                verification.nonce_verified,
3737            ) {
3738            Ok(registration) => registration,
3739            Err(RegistryError::DuplicateModuleId { module_id }) => {
3740                return Ok(vec![control_error_frame(
3741                    &frame,
3742                    "duplicate_module_id",
3743                    format!(
3744                        "module_id '{module_id}' is already registered; duplicate HELLO rejected"
3745                    ),
3746                )?])
3747            }
3748            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
3749                return Ok(vec![control_error_frame(
3750                    &frame,
3751                    "invalid_module_id",
3752                    err.to_string(),
3753                )?])
3754            }
3755            Err(err) => {
3756                return Ok(vec![control_error_frame(
3757                    &frame,
3758                    "registry_error",
3759                    err.to_string(),
3760                )?])
3761            }
3762        };
3763        let differing_declarations =
3764            match self.admit_hello_authority(connection_id, hello_authority.as_ref()) {
3765                Ok(differing) => differing,
3766                Err(err) => {
3767                    if matches!(
3768                        self.rollback_unpublished_hello(connection_id),
3769                        Ok(r) if !r.is_empty()
3770                    ) {
3771                        crate::supervise::notify_registration_release();
3772                    }
3773                    return Err(RouterError::Forwarding(err));
3774                }
3775            };
3776        #[cfg(test)]
3777        self.hold_between_registry_and_forwarding();
3778
3779        let mut reply = Vec::new();
3780        // Registry readers must wait from before the ACK can be read until
3781        // publication. Nest forwarding inside the registry lock, never reverse.
3782        let publication = self
3783            .registry
3784            .publish_registration_after(connection_id, || {
3785                if let Some(sink) = sink {
3786                    // The forwarding table's module store is also the daemon-to-module
3787                    // control-RPC lane, so every HELLO gets a live endpoint even when the
3788                    // manifest has no routable provider role. Non-routable modules still
3789                    // cannot receive route.bind in production: `handle_route_open` checks
3790                    // the registry manifest with `target_has_required_role` before the
3791                    // only production call to `begin_route_bind_relay_for` below that
3792                    // route.open path. The remaining direct relay callers are unit tests
3793                    // and benchmark harnesses that construct forwarding state explicitly.
3794                    //
3795                    // The HELLO_ACK is queued by the forwarding table itself, before the
3796                    // endpoint becomes visible, and is NOT returned as a reply. A module
3797                    // reads HELLO_ACK first and exits on anything else; a reply is only
3798                    // written after this handler returns, by which time a route.open on
3799                    // another connection could already have queued a route.bind request
3800                    // for this module ahead of it.
3801                    let concurrency = manifest_concurrency(&registration.manifest);
3802                    self.forwarding.register_module_connection_acked(
3803                        connection_id,
3804                        registration.manifest.module_id.clone(),
3805                        negotiated_ver,
3806                        concurrency,
3807                        sink,
3808                        crate::forwarding::ModuleHelloAck {
3809                            frame: hello_ack,
3810                            verified_prefix_owner: verification.prefix_owner,
3811                        },
3812                    )?;
3813                } else {
3814                    // No sink means no forwarding endpoint, so nothing can be routed
3815                    // ahead of the ack; it goes out as the reply.
3816                    reply.push(hello_ack);
3817                }
3818                #[cfg(test)]
3819                self.hold_between_ack_and_publication();
3820                Ok(())
3821            })
3822            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
3823        let published = match publication {
3824            Ok(published) => published,
3825            Err(err) => {
3826                // The registry lock has been released, so rollback can take it
3827                // again. No forwarding endpoint or route was published. Keep
3828                // forwarding's weak connection-to-spawn association until the
3829                // connection's read loop ends and removes its remaining routes.
3830                // Removing this unpublished entry does not advance the catalog
3831                // generation.
3832                if matches!(
3833                    self.rollback_unpublished_hello(connection_id),
3834                    Ok(r) if !r.is_empty()
3835                ) {
3836                    crate::supervise::notify_registration_release();
3837                }
3838                self.refuse_hello_authority(connection_id, hello_authority.as_ref());
3839                return Ok(vec![control_error_frame(
3840                    &frame,
3841                    if matches!(err, ForwardingError::ConnectionRoleConflict { .. }) {
3842                        "invalid_hello"
3843                    } else {
3844                        forwarding_error_code(&err)
3845                    },
3846                    err.to_string(),
3847                )?]);
3848            }
3849        };
3850        if !published {
3851            debug!(
3852                module_id = %registration.manifest.module_id,
3853                connection_id = connection_id.get(),
3854                "registration was removed before it could be published"
3855            );
3856            self.refuse_hello_authority(connection_id, hello_authority.as_ref());
3857            return Ok(reply);
3858        }
3859
3860        drop(_prefix_ownership);
3861        drop(_prefix_live);
3862
3863        // Exposure over assumption: Concurrency's serde default is pinned to the
3864        // pre-field behavior (ModuleManaged), so a management surface that is
3865        // genuinely Serial and just never declared it inherits concurrent
3866        // delivery silently. Logging which registrations RESOLVED BY DEFAULT
3867        // turns "no module has been bitten yet" into the checkable claim "no
3868        // module is exposed" -- one read of the boot log instead of a fleet
3869        // audit. Detected from the raw HELLO bytes because the serde default
3870        // deliberately erases the absent/declared distinction from the type.
3871        if manifest_concurrency_was_defaulted(&frame.body, &registration.manifest) {
3872            info!(
3873                module_id = %registration.manifest.module_id,
3874                "management surface registered with DEFAULTED concurrency=module_managed (manifest predates the field; declare the real lane)"
3875            );
3876        }
3877        if registration.manifest.registration_channel == Some(false)
3878            && self
3879                .supervisor
3880                .module_is_gated(&registration.manifest.module_id)
3881            && self
3882                .config_runtime
3883                .as_ref()
3884                .and_then(|owner| owner.registration_declaration(&registration.manifest.module_id))
3885                .as_deref()
3886                == Some("declared")
3887        {
3888            warn!(module_id = %registration.manifest.module_id,
3889                "HELLO registration_channel is false despite the approved channel declaration; registration remains admitted");
3890        }
3891
3892        self.apply_registration_capabilities(&registration);
3893
3894        self.supervisor
3895            .record_activity_registration(&registration.manifest.module_id);
3896
3897        info!(
3898            module_id = %registration.manifest.module_id,
3899            module_version = %registration.manifest.module_version,
3900            negotiated_ver,
3901            routable_provider = manifest_provides_routable_role(&registration.manifest),
3902            connection_id = connection_id.get(),
3903            "module registered"
3904        );
3905
3906        if let Some(spawn) = &channel_spawn {
3907            if let Some(sink) = primary_sink {
3908                spawn.bind_primary_sink(sink);
3909            }
3910            spawn.hello_accepted();
3911        } else if !prefix_submodule {
3912            self.supervisor
3913                .retire_unused_registration_channel(&registration.manifest.module_id, false);
3914        }
3915        self.file_development_widening(
3916            hello_authority.map(|authority| authority.record),
3917            differing_declarations,
3918        );
3919        #[cfg(windows)]
3920        if let Some(nonce) = hello.launch_nonce.as_deref() {
3921            self.supervisor
3922                .program_hello_accepted(&registration.manifest.module_id, nonce);
3923        }
3924
3925        #[cfg(test)]
3926        if let Some(hold) = &self.hello_inside_publication_hold {
3927            hold.wait();
3928            hold.wait();
3929        }
3930
3931        Ok(reply)
3932    }
3933
3934    /// Register a HELLO the swap gate admitted into the candidate slot of the
3935    /// registry and of forwarding, where it is reachable over its own
3936    /// connection (its `catalog.update` finds it) but by no by-id lookup, so
3937    /// nothing routes to it until the supervisor cuts over.
3938    ///
3939    /// Registry first (unpublished), then forwarding, then publication, the
3940    /// same order as an ordinary HELLO; a forwarding failure removes the
3941    /// registry entry again. The swap supervisor treats a published, ready
3942    /// candidate as registered and promotes it, and promotion needs the
3943    /// candidate's forwarding endpoint, so the candidate is published only
3944    /// once that endpoint exists. Unlike an ordinary HELLO, this does not
3945    /// recompute capability verdicts or run the capability deny census
3946    /// (`enforce_capability_denies`): both are about the module in the active
3947    /// slot, which `route.open` can target. A candidate sits in the candidate
3948    /// slot, so it neither provides capabilities to other modules nor can be
3949    /// routed to until promotion moves it into the active slot.
3950    #[allow(clippy::too_many_arguments)]
3951    fn register_swap_candidate(
3952        &self,
3953        connection_id: ConnectionId,
3954        sink: Option<crate::FrameSink>,
3955        frame: &Frame,
3956        manifest: ModuleManifest,
3957        negotiated_ver: u8,
3958        control_ops: Vec<String>,
3959        hello_ack: Frame,
3960        hello_authority: Option<&HelloAuthority>,
3961        differing_declarations: &mut ProviderDeclarations,
3962        #[cfg(windows)] launch_nonce: Option<&str>,
3963    ) -> Result<Vec<Frame>, RouterError> {
3964        let module_id = manifest.module_id.clone();
3965        // Closing a swap and publishing its candidate must be ordered. The
3966        // spawn role proves which slot is intended, not that the slot is open.
3967        self.supervisor
3968            .with_swap_candidate_admission(&module_id, || {
3969                let reply = self.publish_swap_candidate(
3970                    connection_id,
3971                    sink,
3972                    frame,
3973                    manifest,
3974                    negotiated_ver,
3975                    control_ops,
3976                    hello_ack,
3977                    hello_authority,
3978                    differing_declarations,
3979                    #[cfg(windows)]
3980                    launch_nonce,
3981                );
3982                let admitted = self
3983                    .registry
3984                    .get_candidate(&module_id)
3985                    .ok()
3986                    .flatten()
3987                    .is_some_and(|candidate| candidate.connection_id == connection_id);
3988                (reply, admitted)
3989            })
3990            .unwrap_or_else(|| {
3991                Ok(vec![control_error_frame(
3992                    frame,
3993                    "swap_token_invalid",
3994                    "swap ended before candidate HELLO publication",
3995                )?])
3996            })
3997    }
3998
3999    #[allow(clippy::too_many_arguments)]
4000    fn publish_swap_candidate(
4001        &self,
4002        connection_id: ConnectionId,
4003        sink: Option<crate::FrameSink>,
4004        frame: &Frame,
4005        manifest: ModuleManifest,
4006        negotiated_ver: u8,
4007        control_ops: Vec<String>,
4008        hello_ack: Frame,
4009        hello_authority: Option<&HelloAuthority>,
4010        differing_declarations: &mut ProviderDeclarations,
4011        #[cfg(windows)] launch_nonce: Option<&str>,
4012    ) -> Result<Vec<Frame>, RouterError> {
4013        let module_id = manifest.module_id.clone();
4014        let registration = match self.registry.register_unpublished_verified_candidate_with_control_ops(
4015            manifest,
4016            negotiated_ver,
4017            connection_id,
4018            control_ops,
4019        ) {
4020            Ok(registration) => registration,
4021            Err(RegistryError::DuplicateModuleId { module_id }) => {
4022                return Ok(vec![control_error_frame(
4023                    frame,
4024                    "duplicate_module_id",
4025                    format!(
4026                        "module_id '{module_id}' already has a swap candidate registered; duplicate HELLO rejected"
4027                    ),
4028                )?])
4029            }
4030            Err(err @ RegistryError::PathHazardModuleId { .. }) => {
4031                return Ok(vec![control_error_frame(
4032                    frame,
4033                    "invalid_module_id",
4034                    err.to_string(),
4035                )?])
4036            }
4037            Err(err) => {
4038                return Ok(vec![control_error_frame(
4039                    frame,
4040                    "registry_error",
4041                    err.to_string(),
4042                )?])
4043            }
4044        };
4045        *differing_declarations = match self.admit_hello_authority(connection_id, hello_authority) {
4046            Ok(differing) => differing,
4047            Err(err) => {
4048                if matches!(
4049                    self.rollback_unpublished_hello(connection_id),
4050                    Ok(r) if !r.is_empty()
4051                ) {
4052                    crate::supervise::notify_registration_release();
4053                }
4054                return Err(RouterError::Forwarding(err));
4055            }
4056        };
4057        #[cfg(test)]
4058        self.hold_between_registry_and_forwarding();
4059        let mut reply = Vec::new();
4060        let publication = self
4061            .registry
4062            .publish_registration_after(connection_id, || {
4063                if let Some(sink) = sink {
4064                    // Same ordering as an ordinary HELLO: queue the ACK before
4065                    // inserting the endpoint, and keep registry readers excluded
4066                    // until the candidate is published.
4067                    let concurrency = manifest_concurrency(&registration.manifest);
4068                    self.forwarding.register_candidate_module_connection_acked(
4069                        connection_id,
4070                        module_id.clone(),
4071                        negotiated_ver,
4072                        concurrency,
4073                        sink,
4074                        hello_ack,
4075                    )?;
4076                } else {
4077                    reply.push(hello_ack);
4078                }
4079                #[cfg(test)]
4080                self.hold_between_ack_and_publication();
4081                Ok(())
4082            })
4083            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4084        let published = match publication {
4085            Ok(published) => published,
4086            Err(err) => {
4087                if matches!(
4088                    self.rollback_unpublished_hello(connection_id),
4089                    Ok(r) if !r.is_empty()
4090                ) {
4091                    crate::supervise::notify_registration_release();
4092                }
4093                self.refuse_hello_authority(connection_id, hello_authority);
4094                return Ok(vec![control_error_frame(
4095                    frame,
4096                    forwarding_error_code(&err),
4097                    err.to_string(),
4098                )?]);
4099            }
4100        };
4101        if !published {
4102            debug!(
4103                module_id = %module_id,
4104                connection_id = connection_id.get(),
4105                "swap candidate registration was removed before it could be published"
4106            );
4107            self.refuse_hello_authority(connection_id, hello_authority);
4108            return Ok(reply);
4109        }
4110        info!(
4111            module_id = %module_id,
4112            module_version = %registration.manifest.module_version,
4113            negotiated_ver,
4114            ready = registration.ready,
4115            connection_id = connection_id.get(),
4116            "swap candidate registered; not routable until cutover"
4117        );
4118        #[cfg(windows)]
4119        if let Some(nonce) = launch_nonce {
4120            self.supervisor.program_hello_accepted(&module_id, nonce);
4121        }
4122        Ok(reply)
4123    }
4124
4125    /// Bind `connection` to the spawn its HELLO registers as and freeze the
4126    /// spawn's requested provider declarations. Runs only once the registry
4127    /// has accepted the HELLO, before its endpoint is published, so a route
4128    /// reserved on the endpoint always finds the spawn. Returns the requested
4129    /// entries that differ from the saved approvals, for a widening request.
4130    fn admit_hello_authority(
4131        &self,
4132        connection: ConnectionId,
4133        authority: Option<&HelloAuthority>,
4134    ) -> Result<ProviderDeclarations, ForwardingError> {
4135        let Some(authority) = authority else {
4136            return Ok(ProviderDeclarations::new());
4137        };
4138        let froze = authority
4139            .record
4140            .freeze_declarations(authority.requested.clone());
4141        authority
4142            .froze
4143            .store(froze.is_some(), std::sync::atomic::Ordering::Relaxed);
4144        self.forwarding
4145            .bind_target_authority(connection, authority.record.clone())
4146            .inspect_err(|_| self.refuse_hello_authority(connection, Some(authority)))?;
4147        Ok(froze.unwrap_or_default())
4148    }
4149
4150    /// Undo [`Self::admit_hello_authority`] for a HELLO refused after the
4151    /// registry accepted it, so the refused connection is no registration of
4152    /// the spawn and the spawn's declarations are left for the HELLO that
4153    /// does register it to freeze.
4154    fn refuse_hello_authority(&self, connection: ConnectionId, authority: Option<&HelloAuthority>) {
4155        let Some(authority) = authority else {
4156            return;
4157        };
4158        if let Err(err) = self.forwarding.unbind_target_authority(connection) {
4159            warn!(error = %err, "failed to unbind a refused HELLO from its spawn");
4160        }
4161        if authority
4162            .froze
4163            .swap(false, std::sync::atomic::Ordering::Relaxed)
4164        {
4165            authority.record.unfreeze_refused_declarations();
4166        }
4167    }
4168
4169    fn build_hello_ack(
4170        &self,
4171        frame: &Frame,
4172        negotiated_ver: u8,
4173        module_id: &str,
4174    ) -> Result<Frame, RouterError> {
4175        let ack = ModuleHelloAckBody {
4176            negotiated_ver,
4177            subc_ops: module_subc_ops(),
4178            subc_capabilities: self.subc_capabilities.as_ref().to_vec(),
4179            storage: self
4180                .storage_config
4181                .as_ref()
4182                .map(|cfg| cfg.descriptor_for(module_id)),
4183            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
4184        };
4185        let body = serde_json::to_vec(&ack).map_err(|err| {
4186            RouterError::backend(
4187                0,
4188                frame.header.corr,
4189                format!("failed to encode HELLO_ACK: {err}"),
4190            )
4191        })?;
4192
4193        Frame::build_with_version(
4194            negotiated_ver,
4195            FrameType::HelloAck,
4196            control_flags(),
4197            0,
4198            0,
4199            frame.header.corr,
4200            body,
4201        )
4202        .map_err(RouterError::FrameBuild)
4203    }
4204
4205    async fn handle_client_control_request(
4206        &self,
4207        ctx: &RouteCtx,
4208        frame: Frame,
4209        request: ClientControlRequest,
4210        route_open_timings: &mut Option<RouteOpenTimings>,
4211    ) -> Result<Vec<Frame>, RouterError> {
4212        if let Some(owner) = &self.config_runtime {
4213            let module = match &request {
4214                ClientControlRequest::SupervisorRestart { module_id, .. }
4215                | ClientControlRequest::SupervisorReload { module_id }
4216                | ClientControlRequest::SupervisorSwap { module_id, .. }
4217                | ClientControlRequest::SupervisorSetEnabled {
4218                    module_id,
4219                    enabled: true,
4220                } => Some(module_id.as_str()),
4221                _ => None,
4222            };
4223            let rescan = matches!(
4224                &request,
4225                ClientControlRequest::SupervisorRescan { preview: false }
4226                    | ClientControlRequest::SupervisorRescanChecked { preview: false, .. }
4227            );
4228            let held = if module.is_some() || rescan {
4229                let module = module.map(str::to_owned);
4230                owner
4231                    .on_blocking(move |owner| owner.checked_admission_hold(module.as_deref()))
4232                    .await
4233            } else {
4234                Ok(())
4235            };
4236            if let Err(error) = held {
4237                if error.code != "config_delivery_deferred" {
4238                    let code = if error.code == "store_tampered" {
4239                        "store_tampered"
4240                    } else {
4241                        "config_gated"
4242                    };
4243                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
4244                }
4245            }
4246        }
4247        if let Some(operation) = privileged_operation(&request) {
4248            let caller = self.resolve_caller(ctx.connection_id).await;
4249            let op = client_control_request_op(&request);
4250            let text = prompt_text(operation, &caller);
4251            match self.privileged_operator_prompt {
4252                PrivilegedOperatorPrompt::Log => {
4253                    info!(target: "subc_daemon::privileged_prompt", operation = op,
4254                        target = ?operation, caller = %caller.description(), summary = %text,
4255                        "privileged request would prompt the operator");
4256                }
4257                PrivilegedOperatorPrompt::Enforce => {
4258                    let key =
4259                        crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
4260                    let shortcut =
4261                        self.operator_shortcut_stamp(ctx.connection_id)
4262                            .await
4263                            .map(|stamp| {
4264                                self.shortcut_context(Some(stamp), None, None, ctx.connection_id)
4265                            });
4266                    let outcome = self
4267                        .forwarding
4268                        .operator_confirms()
4269                        .approve_privileged_with_shortcut(
4270                            ctx,
4271                            &frame,
4272                            op,
4273                            text,
4274                            caller.description(),
4275                            key,
4276                            shortcut,
4277                        )
4278                        .await;
4279                    if outcome.code != "confirmed" {
4280                        return Ok(vec![outcome.frame(&frame)]);
4281                    }
4282                }
4283            }
4284        }
4285        match request {
4286            ClientControlRequest::DaemonShutdownIntent { intent } => {
4287                if intent.as_str() != Some("restart") {
4288                    return Ok(vec![control_error_frame(
4289                        &frame,
4290                        "invalid_params",
4291                        "intent must be 'restart'",
4292                    )?]);
4293                }
4294                // A stamped daemon boots a newer approved generation only from a
4295                // durable restart intent, written here before the daemon exits.
4296                // Failing to write it never blocks the restart: the next start
4297                // then boots the last active generation and the newer one waits.
4298                if let Some(owner) = &self.config_runtime {
4299                    match owner
4300                        .on_blocking(|owner| owner.assign_daemon_restart())
4301                        .await
4302                    {
4303                        Ok(Some(generation)) => {
4304                            info!(
4305                                generation,
4306                                "daemon restart will warm up approved generation"
4307                            )
4308                        }
4309                        Ok(None) => {}
4310                        Err(error) => warn!(
4311                            %error,
4312                            "daemon restart intent not recorded; the next start boots the last active generation"
4313                        ),
4314                    }
4315                }
4316                let response = ClientControlResponse::DaemonShutdownIntent {
4317                    intent: "restart".to_owned(),
4318                    expires_at_ms: self.supervisor.announce_daemon_restart(),
4319                };
4320                Ok(vec![control_response_body_frame(
4321                    &frame,
4322                    &response,
4323                    "ClientControlResponse::DaemonShutdownIntent",
4324                )?])
4325            }
4326            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
4327            ClientControlRequest::PolicyRoot(_)
4328            | ClientControlRequest::PolicyRootSet(_)
4329            | ClientControlRequest::PolicyRootRecover(_) => {
4330                unreachable!("policy root ops dispatch before the client-only path")
4331            }
4332            ClientControlRequest::CatalogList { module_id } => {
4333                self.handle_catalog_list(frame, module_id)
4334            }
4335            ClientControlRequest::RouteOpen {
4336                target,
4337                identity,
4338                consumer_identity,
4339                consumer_capabilities,
4340                role_versions,
4341                busy_refusals,
4342                admission_facts,
4343                scope,
4344                ..
4345            } => {
4346                let extensions = match serde_json::from_slice::<subc_control::RouteOpenRequestExt>(
4347                    &frame.body,
4348                ) {
4349                    Ok(extensions) => extensions,
4350                    Err(err) => {
4351                        return Ok(vec![control_error_frame(
4352                            &frame,
4353                            "invalid_control_body",
4354                            format!("malformed route.open extensions: {err}"),
4355                        )?]);
4356                    }
4357                };
4358                self.handle_route_open(
4359                    ctx,
4360                    frame,
4361                    RouteOpenRequest {
4362                        target,
4363                        identity,
4364                        consumer_identity,
4365                        consumer_capabilities,
4366                        role_versions,
4367                        busy_refusals,
4368                        admission_facts,
4369                        scope,
4370                        accepts_close_reasons: extensions.accepts_close_reasons,
4371                    },
4372                    route_open_timings.get_or_insert_with(RouteOpenTimings::new),
4373                )
4374                .await
4375            }
4376            ClientControlRequest::RoutePoll {
4377                route_channel,
4378                route_epoch,
4379                kind,
4380            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
4381            ClientControlRequest::SupervisorList {} => {
4382                let Ok(permit) = Arc::clone(&self.list_admission).try_acquire_owned() else {
4383                    self.agent_declarations.refuse(
4384                        self,
4385                        ctx,
4386                        control_error_frame(
4387                            &frame,
4388                            "busy",
4389                            "supervisor list work is at capacity; retry",
4390                        )?,
4391                    );
4392                    return Ok(Vec::new());
4393                };
4394                // Filesystem-backed diagnostics must not hold up this connection's reader.
4395                let handler = self.clone();
4396                let sink = ctx.egress.clone();
4397                tokio::spawn(
4398                    async move {
4399                        let _permit = permit;
4400                        let result = handler.handle_supervisor_list(frame.clone()).await;
4401                        let replies = match result {
4402                            Ok(replies) => replies,
4403                            Err(error) => {
4404                                control_error_frame(&frame, "backend_error", error.to_string())
4405                                    .into_iter()
4406                                    .collect()
4407                            }
4408                        };
4409                        for reply in replies {
4410                            if !matches!(
4411                                tokio::time::timeout(Duration::from_millis(200), sink.send(reply))
4412                                    .await,
4413                                Ok(Ok(()))
4414                            ) {
4415                                break;
4416                            }
4417                        }
4418                    }
4419                    .with_current_subscriber(),
4420                );
4421                Ok(Vec::new())
4422            }
4423            ClientControlRequest::SupervisorSpawnSnapshot {} => {
4424                self.handle_supervisor_spawn_snapshot(frame)
4425            }
4426            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
4427                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
4428            }
4429            ClientControlRequest::SupervisorRestart {
4430                module_id,
4431                drain_timeout_ms,
4432            } => {
4433                self.log_supervisor_request_received(
4434                    ctx,
4435                    frame.header.corr,
4436                    ops::SUPERVISOR_RESTART,
4437                    Some(&module_id),
4438                    None,
4439                )?;
4440                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4441                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms, requester)
4442                    .await
4443            }
4444            ClientControlRequest::SupervisorSwap {
4445                module_id,
4446                ready_timeout_ms,
4447            } => {
4448                self.log_supervisor_request_received(
4449                    ctx,
4450                    frame.header.corr,
4451                    ops::SUPERVISOR_SWAP,
4452                    Some(&module_id),
4453                    None,
4454                )?;
4455                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4456                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms, requester)
4457                    .await
4458            }
4459            ClientControlRequest::SupervisorReload { module_id } => {
4460                self.log_supervisor_request_received(
4461                    ctx,
4462                    frame.header.corr,
4463                    ops::SUPERVISOR_RELOAD,
4464                    Some(&module_id),
4465                    None,
4466                )?;
4467                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4468                self.handle_supervisor_reload(frame, module_id, requester)
4469                    .await
4470            }
4471            ClientControlRequest::SupervisorRescan { preview } => {
4472                if !preview {
4473                    self.log_supervisor_request_received(
4474                        ctx,
4475                        frame.header.corr,
4476                        ops::SUPERVISOR_RESCAN,
4477                        None,
4478                        None,
4479                    )?;
4480                }
4481                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4482                let operation = self.handle_supervisor_rescan(
4483                    frame,
4484                    if preview {
4485                        RescanMode::Preview
4486                    } else {
4487                        RescanMode::Execute
4488                    },
4489                    requester,
4490                );
4491                self.observe_control_wait(ctx, None, ops::SUPERVISOR_RESCAN, operation)
4492                    .await
4493            }
4494            ClientControlRequest::SupervisorRescanChecked {
4495                preview,
4496                candidate,
4497                expect,
4498            } => {
4499                self.observe_control_wait(
4500                    ctx,
4501                    None,
4502                    ops::SUPERVISOR_RESCAN,
4503                    self.handle_supervisor_rescan_checked(ctx, frame, preview, candidate, expect),
4504                )
4505                .await
4506            }
4507            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
4508                self.log_supervisor_request_received(
4509                    ctx,
4510                    frame.header.corr,
4511                    ops::SUPERVISOR_RELEASE_RESERVED,
4512                    Some(&module_id),
4513                    None,
4514                )?;
4515                self.handle_supervisor_release_reserved(frame, module_id)
4516                    .await
4517            }
4518            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
4519                self.log_supervisor_request_received(
4520                    ctx,
4521                    frame.header.corr,
4522                    ops::SUPERVISOR_SET_ENABLED,
4523                    Some(&module_id),
4524                    Some(enabled),
4525                )?;
4526                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
4527                self.handle_supervisor_set_enabled(frame, module_id, enabled, requester)
4528                    .await
4529            }
4530            ClientControlRequest::SupervisorHealthProbe { module_id } => {
4531                self.handle_supervisor_health_probe(ctx, frame, module_id)
4532                    .await
4533            }
4534            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
4535            ClientControlRequest::SupervisorRoutes { module_id } => {
4536                self.handle_supervisor_routes(frame, module_id)
4537            }
4538            ClientControlRequest::SupervisorProvenance { module_id } => {
4539                self.handle_supervisor_provenance(ctx, frame, module_id)
4540                    .await
4541            }
4542            ClientControlRequest::SupervisorStderrTail {
4543                module_id,
4544                max_lines,
4545                max_bytes,
4546            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
4547            ClientControlRequest::SupervisorTerminals { module_id } => {
4548                self.handle_supervisor_terminals(ctx, frame, module_id)
4549                    .await
4550            }
4551        }
4552    }
4553
4554    fn log_supervisor_request_received(
4555        &self,
4556        ctx: &RouteCtx,
4557        corr: u64,
4558        op: &'static str,
4559        module_id: Option<&str>,
4560        enabled: Option<bool>,
4561    ) -> Result<(), RouterError> {
4562        let caller = self.supervisor_requester(ctx, corr)?;
4563        let caller = principal_label(&caller);
4564        // `Option` fields are recorded only when present, so a request with no
4565        // module id (rescan) or no enabled flag simply omits that field.
4566        info!(
4567            target: "control",
4568            op,
4569            module_id,
4570            enabled,
4571            connection_id = ctx.connection_id.get(),
4572            caller = %caller,
4573            "supervisor request received"
4574        );
4575        Ok(())
4576    }
4577
4578    fn supervisor_requester(&self, ctx: &RouteCtx, corr: u64) -> Result<Principal, RouterError> {
4579        Ok(self
4580            .registry
4581            .get_module_by_connection(ctx.connection_id)
4582            .map_err(|err| RouterError::backend(0, corr, err.to_string()))?
4583            .map(|registration| Principal::Reserved {
4584                module_id: registration.manifest.module_id,
4585            })
4586            .unwrap_or(Principal::Direct))
4587    }
4588
4589    fn handle_module_control_request(
4590        &self,
4591        connection_id: ConnectionId,
4592        frame: Frame,
4593        request: ModuleControlRequestFromModule,
4594    ) -> Result<Vec<Frame>, RouterError> {
4595        match request {
4596            ModuleControlRequestFromModule::RouteAuthorize {
4597                principal,
4598                scope,
4599                target,
4600                expected,
4601            } => self.handle_route_authorize(
4602                connection_id,
4603                frame,
4604                principal,
4605                scope,
4606                target,
4607                expected,
4608            ),
4609            ModuleControlRequestFromModule::CatalogUpdate {
4610                provides,
4611                capabilities,
4612                ready,
4613            } => self.handle_catalog_update(connection_id, frame, provides, capabilities, ready),
4614            ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { role_declarations } => {
4615                self.handle_catalog_update_role_declarations(
4616                    connection_id,
4617                    frame,
4618                    role_declarations,
4619                )
4620            }
4621            ModuleControlRequestFromModule::LiveRoots {} => {
4622                let registered = self
4623                    .registry
4624                    .get_module_by_connection(connection_id)
4625                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4626                let Some(registration) = registered else {
4627                    return Ok(vec![control_error_frame(&frame, "not_registered", "supervisor.live_roots requires an active module registration owned by this connection")?]);
4628                };
4629                let response = self
4630                    .forwarding
4631                    .live_roots(&registration.manifest.module_id)
4632                    .map_err(RouterError::Forwarding)?;
4633                Ok(vec![control_response_body_frame(
4634                    &frame,
4635                    &response,
4636                    "ModuleControlResponseToModule::LiveRoots",
4637                )?])
4638            }
4639            ModuleControlRequestFromModule::AgentCommands {
4640                started,
4641                finished,
4642                known,
4643            } => self.handle_agent_commands(connection_id, frame, started, finished, known),
4644            ModuleControlRequestFromModule::ScopeSync { generation, scopes } => {
4645                self.handle_scope_sync(connection_id, frame, generation, scopes)
4646            }
4647            ModuleControlRequestFromModule::ScopeApply {
4648                generation,
4649                upsert,
4650                end,
4651            } => self.handle_scope_change(connection_id, frame, generation, upsert, Some(end)),
4652            ModuleControlRequestFromModule::ScopeDescribe { owner, scope_ref } => {
4653                self.handle_scope_describe(connection_id, frame, owner, scope_ref)
4654            }
4655            _ => Ok(vec![control_error_frame(
4656                &frame,
4657                "unsupported_control_frame",
4658                "unsupported module control operation",
4659            )?]),
4660        }
4661    }
4662
4663    fn handle_scope_served_by(
4664        &self,
4665        connection_id: ConnectionId,
4666        frame: Frame,
4667    ) -> Result<Vec<Frame>, RouterError> {
4668        let registered = self
4669            .registry
4670            .get_module_by_connection(connection_id)
4671            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4672        let Some(registered) = registered else {
4673            return Ok(vec![control_error_frame(
4674                &frame,
4675                "not_registered",
4676                "scope.served_by requires an active module registration owned by this connection",
4677            )?]);
4678        };
4679        let request: subc_control::ScopeServedByRequest = match serde_json::from_slice(&frame.body)
4680        {
4681            Ok(request) => request,
4682            Err(err) => {
4683                return Ok(vec![control_error_frame(
4684                    &frame,
4685                    "invalid_control_body",
4686                    format!("malformed scope.served_by body: {err}"),
4687                )?])
4688            }
4689        };
4690        let answer = self
4691            .scopes
4692            .read()
4693            .unwrap_or_else(|poisoned| poisoned.into_inner())
4694            .served_by(
4695                &registered.manifest.module_id,
4696                &request.scope_ref,
4697                request.scope_epoch,
4698                &request.module_id,
4699            );
4700        let reply = subc_control::ScopeServedByReply::new(
4701            answer,
4702            self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
4703        );
4704        Ok(vec![control_response_body_frame(
4705            &frame,
4706            &reply,
4707            "ScopeServedByReply",
4708        )?])
4709    }
4710
4711    /// Explicit test-only phone policy; daemon configuration cannot select it.
4712    #[cfg(any(test, feature = "test-support"))]
4713    pub fn with_test_phone_shortcut(mut self, enabled: bool) -> Self {
4714        self.operator_app_policy.phone_enabled = enabled;
4715        self
4716    }
4717
4718    /// Resolve folders before taking the scope-table lock: a slow filesystem
4719    /// must not hold up admissions for unrelated scoped routes.
4720    pub(crate) fn prepare_scope_records(scopes: Vec<ScopeRecord>) -> ScopeRecords {
4721        let mut scopes = ScopeRecords::from(scopes);
4722        for (index, record) in scopes.records.iter_mut().enumerate() {
4723            if let Some(refusal) = Self::canonicalize_workdir(record) {
4724                scopes.refusals.insert(index, refusal);
4725            }
4726        }
4727        scopes
4728    }
4729
4730    fn canonicalize_workdir(record: &mut ScopeRecord) -> Option<crate::scopes::RecordRefusal> {
4731        let workdir = record.workdir.as_mut()?;
4732        let path = std::path::Path::new(workdir);
4733        if !path.is_absolute() {
4734            return Some((
4735                error_codes::INVALID_WORKDIR,
4736                "workdir must be absolute".to_string(),
4737            ));
4738        }
4739        match ProjectRootId::from_path_allowing_missing(path) {
4740            Ok(root) => match root.as_path().to_str() {
4741                Some(canonical) => {
4742                    *workdir = canonical.to_string();
4743                    None
4744                }
4745                None => Some((
4746                    error_codes::INVALID_WORKDIR,
4747                    "canonical workdir is not UTF-8".to_string(),
4748                )),
4749            },
4750            Err(error) => Some((error_codes::INVALID_WORKDIR, error.to_string())),
4751        }
4752    }
4753
4754    /// `scope.sync`: the owner is the module registered on this connection.
4755    /// A connection with no registration (every client connection, `direct`
4756    /// included) is refused `not_registered` before the table is consulted.
4757    fn handle_scope_sync(
4758        &self,
4759        connection_id: ConnectionId,
4760        frame: Frame,
4761        generation: u64,
4762        scopes: Vec<ScopeRecord>,
4763    ) -> Result<Vec<Frame>, RouterError> {
4764        self.handle_scope_change(connection_id, frame, generation, scopes, None)
4765    }
4766
4767    fn handle_scope_change(
4768        &self,
4769        connection_id: ConnectionId,
4770        frame: Frame,
4771        generation: u64,
4772        scopes: Vec<ScopeRecord>,
4773        end: Option<Vec<ScopeEnd>>,
4774    ) -> Result<Vec<Frame>, RouterError> {
4775        let is_apply = end.is_some();
4776        let Some(registration) = self
4777            .registry
4778            .get_module_by_connection(connection_id)
4779            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
4780        else {
4781            return Ok(vec![control_error_frame(
4782                &frame,
4783                "not_registered",
4784                "scope.sync and scope.apply require an active module registration owned by this connection",
4785            )?]);
4786        };
4787        let owner = registration.manifest.module_id;
4788        let scopes = Self::prepare_scope_records(scopes);
4789        let current_nonce = self.supervisor.spawn_launch_nonce_for(&owner);
4790        let is_current_launch = |connection: ConnectionId| {
4791            self.connection_is_current_launch(&owner, connection, current_nonce.as_deref())
4792        };
4793        // Lock order is the scope table, then the forwarding table: the new
4794        // tags are published, and the routes the change closes are selected,
4795        // while the scope table is still write-locked, so no admission can read
4796        // a record whose tag is not yet published.
4797        let mut table = self
4798            .scopes
4799            .write()
4800            .unwrap_or_else(|poisoned| poisoned.into_inner());
4801        let outcome = match end {
4802            Some(end) => table.apply(
4803                &owner,
4804                connection_id,
4805                is_current_launch,
4806                generation,
4807                scopes,
4808                end,
4809            ),
4810            None => table.sync(&owner, connection_id, is_current_launch, generation, scopes),
4811        };
4812        let drained = match &outcome {
4813            Ok(applied) => self.publish_scope_changes(&applied.tag_changes, &applied.expired)?,
4814            Err(_) => Vec::new(),
4815        };
4816        let has_deadlines = outcome.is_ok() && table.has_deadlines();
4817        drop(table);
4818        if has_deadlines {
4819            self.scope_deadline_added.notify_one();
4820        }
4821        match outcome {
4822            Ok(applied) => {
4823                let counts = ScopeOutcomeCounts::of(&applied.results);
4824                info!(
4825                    owner = %owner,
4826                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
4827                    generation,
4828                    records = applied.results.len(),
4829                    created = counts.created,
4830                    replaced = counts.replaced,
4831                    updated = counts.updated,
4832                    unchanged = counts.unchanged,
4833                    refused = counts.refused,
4834                    ended = applied.ended.len(),
4835                    tag_changes = applied.tag_changes.len(),
4836                    routes_closed = drained.len(),
4837                    "scope change accepted"
4838                );
4839                // An accepted scope change can still refuse individual records, and the
4840                // owner is the only party that sees the reply. Name them here so
4841                // an operator can tell a refused session from a missing one
4842                // without the owner's logs. Capped so a call that refuses
4843                // thousands cannot flood the log; the count above is complete.
4844                for refused in applied
4845                    .results
4846                    .iter()
4847                    .filter(|result| result.outcome == ScopeRecordOutcome::Refused)
4848                    .take(MAX_LOGGED_REFUSED_SCOPE_RECORDS)
4849                {
4850                    warn!(
4851                        owner = %owner,
4852                        generation,
4853                        scope_ref = %refused.scope_ref,
4854                        scope_epoch = refused.scope_epoch,
4855                        code = refused.code.as_deref().unwrap_or(""),
4856                        "scope record refused"
4857                    );
4858                }
4859                self.close_scope_drained_routes(drained);
4860                let response = if is_apply {
4861                    ModuleControlResponseToModule::ScopeApply {
4862                        generation,
4863                        results: applied.results,
4864                        end_results: applied.end_results,
4865                        ended: applied.ended,
4866                    }
4867                } else {
4868                    ModuleControlResponseToModule::ScopeSync {
4869                        generation,
4870                        results: applied.results,
4871                        ended: applied.ended,
4872                    }
4873                };
4874                Ok(vec![control_response_body_frame(
4875                    &frame,
4876                    &response,
4877                    "scope change response",
4878                )?])
4879            }
4880            Err(refusal) => {
4881                info!(
4882                    owner = %owner,
4883                    op = if is_apply { SCOPE_APPLY_OP } else { SCOPE_SYNC_OP },
4884                    generation,
4885                    code = refusal.code,
4886                    "scope change refused"
4887                );
4888                Ok(vec![control_error_frame(
4889                    &frame,
4890                    refusal.code,
4891                    refusal.message,
4892                )?])
4893            }
4894        }
4895    }
4896
4897    /// Notify both endpoints of routes drained by a scope change.
4898    fn close_scope_drained_routes(&self, drained: Vec<crate::forwarding::ScopeDrainedRoute>) {
4899        scope_expiry::ScopeExpiryContext::new(self).close_scope_drained_routes(drained);
4900    }
4901
4902    /// Re-authorize a stored source on a principal the module supplies.
4903    ///
4904    /// That principal carries no spawn or authority epoch, so this reply never
4905    /// conveys a caller attestation or a first-party mark, and a provider must
4906    /// not apply automatic grants on anything it authorizes.
4907    fn handle_route_authorize(
4908        &self,
4909        connection_id: ConnectionId,
4910        frame: Frame,
4911        principal: Principal,
4912        scope: subc_protocol::scope::RouteAuthorizeScope,
4913        target: String,
4914        expected: subc_protocol::scope::RouteAuthorizeExpected,
4915    ) -> Result<Vec<Frame>, RouterError> {
4916        use crate::scopes::admission::{admit_route, AdmissionMode};
4917        use subc_protocol::scope::{
4918            RouteAuthorizeOutcome, RouteAuthorizeResponse, ROUTE_AUTHORIZE_CAPABILITY,
4919        };
4920        let registry = self
4921            .registry
4922            .route_admission_snapshot()
4923            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4924        let owner_configured = match &scope.owner {
4925            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
4926            _ => false,
4927        };
4928        let selector = ScopeSelector::new(scope.owner, scope.scope_ref, Some(scope.epoch));
4929        let answer = {
4930            let scopes = self.scopes.read().unwrap_or_else(|p| p.into_inner());
4931            let permitted = registry
4932                .iter()
4933                .find(|r| r.connection_id == connection_id)
4934                .is_some_and(|r| {
4935                    scopes.is_federated_owner(&Principal::Reserved {
4936                        module_id: r.module_id.clone(),
4937                    }) && r.capabilities.as_ref().is_some_and(|caps| {
4938                        caps.provides
4939                            .iter()
4940                            .any(|cap| cap == ROUTE_AUTHORIZE_CAPABILITY)
4941                    })
4942                });
4943            if !permitted {
4944                drop(scopes);
4945                return Ok(vec![control_error_frame(&frame, error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED,
4946                    "route.authorize requires the configured federated owner's route-authorize/v1 registration")?]);
4947            }
4948            admit_route(
4949                &scopes,
4950                &registry,
4951                &principal,
4952                &target,
4953                Some(&selector),
4954                owner_configured,
4955                AdmissionMode::Authorize(&expected),
4956            )
4957        };
4958        let response = match answer {
4959            Ok(admission) => {
4960                let mut response = RouteAuthorizeResponse::new(
4961                    RouteAuthorizeOutcome::Authorized,
4962                    "route admission authorized",
4963                );
4964                response.content_version = admission.content_version;
4965                response
4966            }
4967            Err(refusal) => refusal.response(),
4968        };
4969        Ok(vec![control_response_body_frame(
4970            &frame,
4971            &response,
4972            "RouteAuthorizeResponse",
4973        )?])
4974    }
4975
4976    /// `scope.describe`: any registered module may read any scope, because a
4977    /// provider must read the scope a route it serves is stamped with.
4978    fn handle_scope_describe(
4979        &self,
4980        connection_id: ConnectionId,
4981        frame: Frame,
4982        owner: Principal,
4983        scope_ref: String,
4984    ) -> Result<Vec<Frame>, RouterError> {
4985        let registered = self
4986            .registry
4987            .get_module_by_connection(connection_id)
4988            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
4989        let Some(registered) = registered else {
4990            return Ok(vec![control_error_frame(
4991                &frame,
4992                "not_registered",
4993                "scope.describe requires an active module registration owned by this connection",
4994            )?]);
4995        };
4996        let scopes = self
4997            .scopes
4998            .read()
4999            .unwrap_or_else(|poisoned| poisoned.into_inner());
5000        if !scopes.reader_permitted(&owner, registered.manifest.capabilities.as_ref()) {
5001            return Ok(vec![control_error_frame(
5002                &frame,
5003                error_codes::SCOPE_FEDERATED_UNSUPPORTED,
5004                "scope.describe of the federated owner requires scope-federated/v1",
5005            )?]);
5006        }
5007        let mut description = scopes.describe(&owner, &scope_ref);
5008        drop(scopes);
5009        if owner
5010            != (Principal::Reserved {
5011                module_id: registered.manifest.module_id.clone(),
5012            })
5013        {
5014            if let Some(facts) = description
5015                .stamp
5016                .as_mut()
5017                .and_then(|stamp| stamp.attributes.federated.as_mut())
5018            {
5019                facts.stamp_required = false;
5020            }
5021        }
5022        // Describe readers also decode strict ScopeAttributes. Attribution is
5023        // safe to omit unless the requesting module declares it understands it.
5024        if !registered
5025            .manifest
5026            .capabilities
5027            .as_ref()
5028            .is_some_and(|caps| {
5029                caps.provides
5030                    .iter()
5031                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
5032            })
5033        {
5034            if let Some(stamp) = description.stamp.as_mut() {
5035                stamp.attributes.on_behalf_of_agent = None;
5036            }
5037        }
5038        if !registered
5039            .manifest
5040            .capabilities
5041            .as_ref()
5042            .is_some_and(|caps| {
5043                caps.provides
5044                    .iter()
5045                    .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
5046            })
5047        {
5048            if let Some(stamp) = description.stamp.as_mut() {
5049                stamp.attributes.flow_version = None;
5050                stamp.attributes.flow_code_hash = None;
5051                stamp.attributes.flow_install_id = None;
5052            }
5053        }
5054        let owner_configured = match &owner {
5055            // Ask whether the owner is configured (`is_configured`), not
5056            // whether it is on the roster (`get(..).is_some()`): a supervised
5057            // module's process can register and describe a scope before the
5058            // supervisor has put it on the roster.
5059            Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
5060            _ => false,
5061        };
5062        let response = ModuleControlResponseToModule::ScopeDescribe {
5063            status: description.status,
5064            scope_epoch: description.scope_epoch,
5065            daemon_incarnation: self.supervisor.spawn_snapshot().cursor.daemon_incarnation,
5066            owner_synced: description.owner_synced,
5067            owner_configured,
5068            scope: description.stamp,
5069        };
5070        Ok(vec![control_response_body_frame(
5071            &frame,
5072            &response,
5073            "ModuleControlResponseToModule::ScopeDescribe",
5074        )?])
5075    }
5076
5077    fn handle_catalog_update_role_declarations(
5078        &self,
5079        connection_id: ConnectionId,
5080        frame: Frame,
5081        role_declarations: serde_json::Value,
5082    ) -> Result<Vec<Frame>, RouterError> {
5083        if let Err(err) = validate_role_declarations_value(Some(&role_declarations)) {
5084            return Ok(vec![control_error_frame(
5085                &frame,
5086                "invalid_role_declarations",
5087                err.to_string(),
5088            )?]);
5089        }
5090        let declarations = serde_json::from_value(role_declarations)
5091            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
5092        if self
5093            .registry
5094            .replace_role_declarations_for_connection(connection_id, declarations)
5095            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5096            .is_none()
5097        {
5098            return Ok(vec![control_error_frame(
5099                &frame,
5100                "not_registered",
5101                "catalog.update_role_declarations requires an active module registration owned by this connection",
5102            )?]);
5103        }
5104        control_response_body_frame(
5105            &frame,
5106            &ModuleControlResponseToModule::CatalogUpdateRoleDeclarations {},
5107            "ModuleControlResponseToModule::CatalogUpdateRoleDeclarations",
5108        )
5109        .map(|frame| vec![frame])
5110    }
5111
5112    fn handle_catalog_update(
5113        &self,
5114        connection_id: ConnectionId,
5115        frame: Frame,
5116        provides: Vec<ProviderRole>,
5117        capabilities: Option<CapabilityDeclarations>,
5118        ready: Option<bool>,
5119    ) -> Result<Vec<Frame>, RouterError> {
5120        self.refresh_capability_requirements();
5121        let Some(registration) = self
5122            .registry
5123            .get_module_by_connection(connection_id)
5124            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5125        else {
5126            return Ok(vec![control_error_frame(
5127                &frame,
5128                "not_registered",
5129                "catalog.update requires an active module registration owned by this connection",
5130            )?]);
5131        };
5132
5133        if let Some(message) =
5134            catalog_update_frozen_field_message(&registration.manifest, &provides)
5135        {
5136            return Ok(vec![control_error_frame(
5137                &frame,
5138                "catalog_update_frozen_field",
5139                message,
5140            )?]);
5141        }
5142
5143        let mut candidate = registration.manifest.clone();
5144        candidate.provides = provides.clone();
5145        candidate.capabilities = capabilities
5146            .clone()
5147            .or_else(|| registration.manifest.capabilities.clone());
5148        if let Some(rich_ui) = &candidate.rich_ui {
5149            if let Err(err) = rich_ui.validate() {
5150                return Ok(vec![control_error_frame(
5151                    &frame,
5152                    "invalid_manifest",
5153                    err.to_string(),
5154                )?]);
5155            }
5156        }
5157        if let Err(err) = candidate.validate_capability_grammar() {
5158            return Ok(vec![control_error_frame(
5159                &frame,
5160                "invalid_capability_grammar",
5161                err.to_string(),
5162            )?]);
5163        }
5164
5165        // Updates must honor the same reserved owner as initial registration;
5166        // otherwise an empty HELLO could acquire the claim after admission.
5167        let mut conflicts = self
5168            .capability_evaluator
5169            .reserved_hello_refusals(&candidate.module_id, candidate.capabilities.as_ref());
5170        if let Some(conflict) = conflicts.first() {
5171            let message = format!(
5172                "capability '{}' is reserved for module_id '{}'; claimant '{}' was refused",
5173                conflict.capability, conflict.claimants[0], candidate.module_id
5174            );
5175            for conflict in &mut conflicts {
5176                conflict.source = DuplicateClaimSource::CatalogUpdate;
5177            }
5178            log_duplicate_claim_events(conflicts);
5179            return Ok(vec![control_error_frame(
5180                &frame,
5181                "reserved_capability",
5182                message,
5183            )?]);
5184        }
5185
5186        let updated = match self.registry.replace_catalog_for_connection(
5187            connection_id,
5188            provides,
5189            capabilities,
5190            ready,
5191        ) {
5192            Err(crate::registry::RegistryError::FederatedCapabilityChanged) => {
5193                return Ok(vec![control_error_frame(
5194                    &frame,
5195                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5196                    "scope-federated/v1 is fixed at HELLO; restart the module to change it",
5197                )?])
5198            }
5199            Err(crate::registry::RegistryError::CallerAttestationCapabilityChanged) => {
5200                return Ok(vec![control_error_frame(
5201                    &frame,
5202                    error_codes::CATALOG_UPDATE_FROZEN_CAPABILITY,
5203                    "caller-attestation/v1 is fixed at HELLO; restart the module to change it",
5204                )?])
5205            }
5206            result => {
5207                result.map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
5208            }
5209        };
5210        if updated.is_none() {
5211            return Ok(vec![control_error_frame(
5212                &frame,
5213                "not_registered",
5214                "catalog.update requires an active module registration owned by this connection",
5215            )?]);
5216        }
5217        if let Ok((_, registrations)) = self.runtime_capability_snapshot() {
5218            log_duplicate_claim_events(
5219                self.capability_evaluator
5220                    .duplicate_claims(DuplicateClaimSource::CatalogUpdate, &registrations),
5221            );
5222        }
5223        if capability_census_trigger(
5224            registration.manifest.capabilities.as_ref(),
5225            updated
5226                .as_ref()
5227                .and_then(|entry| entry.manifest.capabilities.as_ref()),
5228        ) {
5229            self.enforce_capability_denies();
5230        }
5231        self.refresh_capability_requirements();
5232
5233        let response = ModuleControlResponseToModule::CatalogUpdate {};
5234        control_response_body_frame(
5235            &frame,
5236            &response,
5237            "ModuleControlResponseToModule::CatalogUpdate",
5238        )
5239        .map(|frame| vec![frame])
5240    }
5241
5242    pub(crate) fn with_activity_ledger_config(
5243        mut self,
5244        run_dir: &Path,
5245        incarnation: String,
5246        config: crate::activity::ActivityConfig,
5247    ) -> Self {
5248        self.activity = Some(crate::activity::ActivityLedger::open_config(
5249            run_dir.join("activity.jsonl"),
5250            incarnation,
5251            config,
5252        ));
5253        self.supervisor.set_activity(self.activity.clone());
5254        self
5255    }
5256
5257    pub(crate) async fn configure_activity(
5258        &self,
5259        config: crate::activity::ActivityConfig,
5260    ) -> Result<(), &'static str> {
5261        match &self.activity {
5262            Some(ledger) => ledger.configure(config).await,
5263            None => Ok(()),
5264        }
5265    }
5266
5267    fn cancel_activity_subscription(
5268        &self,
5269        ctx: &RouteCtx,
5270        frame: &Frame,
5271    ) -> Result<bool, RouterError> {
5272        let key = (ctx.connection_id, frame.header.corr);
5273        let mut streams = self
5274            .activity_streams
5275            .lock()
5276            .unwrap_or_else(|p| p.into_inner());
5277        // A subscription still being set up is cancelled through the
5278        // reservation the reader made, under the same stream lock.
5279        match streams.remove(&key) {
5280            Some(task) => task.abort(),
5281            None if self.activity_reservations.cancel(key) => {}
5282            None => return Ok(false),
5283        }
5284        drop(streams);
5285        let end = Frame::build_with_version(
5286            response_version(frame),
5287            FrameType::StreamEnd,
5288            control_flags(),
5289            0,
5290            0,
5291            frame.header.corr,
5292            Vec::new(),
5293        )
5294        .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
5295        let sink = ctx.egress.clone();
5296        tokio::spawn(async move {
5297            let _ = sink.send(end).await;
5298        });
5299        Ok(true)
5300    }
5301
5302    async fn handle_activity_read(
5303        &self,
5304        ctx: &RouteCtx,
5305        frame: Frame,
5306    ) -> Result<Vec<Frame>, RouterError> {
5307        #[cfg(test)]
5308        {
5309            let pause = self
5310                .activity_request_pause
5311                .lock()
5312                .unwrap()
5313                .clone()
5314                .filter(|pause| pause.connection == ctx.connection_id);
5315            if let Some(pause) = pause {
5316                let _cancelled = ActivityRequestCancellation(pause.clone());
5317                pause.started.notify_one();
5318                std::future::pending::<()>().await;
5319            }
5320        }
5321        use subc_control::{
5322            ActivityQueryRequest, ActivitySubscribeRequest, ActivitySubscribeResponse,
5323            ACTIVITY_MALFORMED, ACTIVITY_READ_FORBIDDEN, ACTIVITY_UNAVAILABLE,
5324        };
5325        #[derive(Deserialize)]
5326        struct Identity {
5327            #[serde(default)]
5328            consumer_identity: Option<ConsumerIdentity>,
5329        }
5330        // A registration channel or claim-bound connection carries its module in
5331        // its binding, so no request field can name another principal, and its
5332        // subscription ends when the bound spawn's authority does.
5333        let mut bound_spawn = None;
5334        let legacy = match self.activity_reader(ctx.connection_id) {
5335            channel_operations::ActivityReader::Module { module_id, spawn } => {
5336                bound_spawn = Some(spawn);
5337                Some(Ok(Principal::Reserved { module_id }))
5338            }
5339            // Refused outright: falling back to `direct` would admit it.
5340            channel_operations::ActivityReader::Refused => {
5341                return Ok(vec![control_error_frame(
5342                    &frame,
5343                    ACTIVITY_READ_FORBIDDEN,
5344                    "helper, relay and retired connections cannot read activity",
5345                )?]);
5346            }
5347            channel_operations::ActivityReader::Legacy => None,
5348        };
5349        // A registered module connection already identifies its caller. Ignore
5350        // consumer_identity there so a module cannot borrow a mirror's identity.
5351        // Only separate consumer connections use the Direct/nonce trust boundary.
5352        let principal = match legacy {
5353            Some(principal) => principal,
5354            None => match self
5355                .forwarding
5356                .module_id_for_connection(ctx.connection_id)
5357                .map_err(RouterError::Forwarding)?
5358            {
5359                Some(module_id) => Ok(Principal::Reserved { module_id }),
5360                None => {
5361                    let identity: Identity = match serde_json::from_slice(&frame.body) {
5362                        Ok(identity) => identity,
5363                        Err(_) => {
5364                            return Ok(vec![control_error_frame(
5365                                &frame,
5366                                ACTIVITY_MALFORMED,
5367                                "malformed activity read",
5368                            )?])
5369                        }
5370                    };
5371                    self.route_open_principal(
5372                        ctx.connection_id,
5373                        &frame,
5374                        identity.consumer_identity,
5375                    )?
5376                }
5377            },
5378        };
5379        let admitted = matches!(principal, Ok(Principal::Direct))
5380            || matches!(&principal, Ok(Principal::Reserved { module_id }) if module_id == "callosum" || module_id == "ckbus");
5381        if !admitted {
5382            return Ok(vec![control_error_frame(
5383                &frame,
5384                ACTIVITY_READ_FORBIDDEN,
5385                "activity reads require an operator or trusted mirror principal",
5386            )?]);
5387        }
5388        let Some(ledger) = &self.activity else {
5389            return Ok(vec![control_error_frame(
5390                &frame,
5391                ACTIVITY_UNAVAILABLE,
5392                "activity ledger unavailable",
5393            )?]);
5394        };
5395        if serde_json::from_slice::<ControlOpProbe>(&frame.body)
5396            .is_ok_and(|probe| probe.op == ops::ACTIVITY_QUERY)
5397        {
5398            let result = match serde_json::from_slice::<ActivityQueryRequest>(&frame.body) {
5399                Ok(request) => ledger.query(request).await,
5400                Err(_) => Err(ACTIVITY_MALFORMED),
5401            };
5402            return match result {
5403                Ok(reply) => Ok(vec![control_response_body_frame(
5404                    &frame,
5405                    &reply,
5406                    ops::ACTIVITY_QUERY,
5407                )?]),
5408                Err(code) => Ok(vec![control_error_frame(
5409                    &frame,
5410                    code,
5411                    "activity query refused",
5412                )?]),
5413            };
5414        }
5415        let request: ActivitySubscribeRequest = match serde_json::from_slice(&frame.body) {
5416            Ok(request) => request,
5417            Err(_) => {
5418                return Ok(vec![control_error_frame(
5419                    &frame,
5420                    ACTIVITY_MALFORMED,
5421                    "malformed activity subscription",
5422                )?])
5423            }
5424        };
5425        let mut subscription = match ledger.subscribe(request.since).await {
5426            Ok(subscription) => subscription,
5427            Err(code) => {
5428                return Ok(vec![control_error_frame(
5429                    &frame,
5430                    code,
5431                    "activity subscription refused",
5432                )?])
5433            }
5434        };
5435        let key = (ctx.connection_id, frame.header.corr);
5436        let sink = ctx.egress.clone();
5437        let mut streams = self
5438            .activity_streams
5439            .lock()
5440            .unwrap_or_else(|p| p.into_inner());
5441        streams.retain(|_, task| !task.is_finished());
5442        if self.activity_reservations.cancelled(key) {
5443            return Ok(Vec::new()); // Its CANCEL already sent STREAM_END.
5444        }
5445        if streams.get(&key).is_some_and(|task| !task.is_finished()) {
5446            return Ok(vec![control_error_frame(
5447                &frame,
5448                "duplicate_subscription",
5449                "activity subscription correlation id already in use",
5450            )?]);
5451        }
5452        let stream = async move {
5453            loop {
5454                let entry = if let Some(entry) = subscription.replay.pop_front() {
5455                    Some(entry)
5456                } else {
5457                    subscription.receiver.recv().await
5458                };
5459                let Some(entry) = entry else {
5460                    break;
5461                };
5462                let Ok(body) = serde_json::to_vec(&ActivitySubscribeResponse { entry }) else {
5463                    return;
5464                };
5465                let Ok(next) = Frame::build_with_version(
5466                    response_version(&frame),
5467                    FrameType::StreamData,
5468                    control_flags(),
5469                    0,
5470                    0,
5471                    frame.header.corr,
5472                    body,
5473                ) else {
5474                    return;
5475                };
5476                if sink.send(next).await.is_err() {
5477                    return;
5478                }
5479            }
5480            // Dropping a full subscriber's sender drains its accepted entries
5481            // before the terminal error, preserving their order on the wire.
5482            if let Some(code) = subscription.terminal_code() {
5483                if let Ok(end) =
5484                    control_error_frame(&frame, code, "activity subscriber fell behind")
5485                {
5486                    let _ = sink.send(end).await;
5487                }
5488            }
5489        };
5490        // The spawn's retirement revokes this connection's authority. End the
5491        // subscription then, rather than when the connection's close is
5492        // eventually processed or the next entry fails to send.
5493        let task = tokio::spawn(async move {
5494            match bound_spawn {
5495                Some(spawn) => {
5496                    tokio::select! {
5497                        () = stream => {}
5498                        () = spawn.wait_closed() => {}
5499                    }
5500                }
5501                None => stream.await,
5502            }
5503        });
5504        streams.insert(key, task.abort_handle());
5505        Ok(Vec::new())
5506    }
5507
5508    async fn handle_activity_record(
5509        &self,
5510        ctx: &RouteCtx,
5511        frame: Frame,
5512    ) -> Result<Vec<Frame>, RouterError> {
5513        use subc_control::{
5514            ActivityRecordRequest, ActivityRecordResponse, ACTIVITY_ACTOR_UNKNOWN,
5515            ACTIVITY_MALFORMED, ACTIVITY_UNAVAILABLE,
5516        };
5517        let result = async {
5518            let module = self
5519                .forwarding
5520                .module_id_for_connection(ctx.connection_id)
5521                .ok()
5522                .flatten()
5523                .ok_or(ACTIVITY_ACTOR_UNKNOWN)?;
5524            let request: ActivityRecordRequest =
5525                serde_json::from_slice(&frame.body).map_err(|_| ACTIVITY_MALFORMED)?;
5526            crate::activity::validate(&module, &request)?;
5527            let actor = self.activity_actor(ctx.connection_id, &module, request.on.as_ref())?;
5528            let ledger = self.activity.as_ref().ok_or(ACTIVITY_UNAVAILABLE)?;
5529            let at_ms = std::time::SystemTime::now()
5530                .duration_since(std::time::UNIX_EPOCH)
5531                .unwrap_or_default()
5532                .as_millis() as u64;
5533            ledger.record(module, request, actor, at_ms).await
5534        }
5535        .await;
5536        match result {
5537            Ok(entry) => Ok(vec![control_response_body_frame(
5538                &frame,
5539                &ActivityRecordResponse { seq: entry.seq },
5540                "activity.record",
5541            )?]),
5542            Err(code) => Ok(vec![control_error_frame(
5543                &frame,
5544                code,
5545                "activity recording refused",
5546            )?]),
5547        }
5548    }
5549
5550    fn activity_actor(
5551        &self,
5552        connection: ConnectionId,
5553        module: &str,
5554        on: Option<&subc_control::ActivityOn>,
5555    ) -> Result<subc_control::ActivityActor, &'static str> {
5556        use crate::forwarding::{DataRoute, DataRouteState};
5557        use subc_control::{ActivityActor, ActivityOn, ACTIVITY_ACTOR_UNKNOWN};
5558        let principal = |id: &str| Principal::Reserved {
5559            module_id: id.to_owned(),
5560        };
5561        let mut actor = ActivityActor {
5562            principal: principal(module),
5563            scope_owner: None,
5564            agent_id: None,
5565            run_id: None,
5566            flow_id: None,
5567            project_root: None,
5568            workdir: None,
5569            project_id: None,
5570        };
5571        let scope = match on {
5572            None => return Ok(actor),
5573            Some(ActivityOn::Scope(scope)) => {
5574                let selector = subc_protocol::scope::ScopeSelector::new(
5575                    principal(module),
5576                    scope.scope_ref.clone(),
5577                    Some(scope.epoch),
5578                );
5579                self.scopes
5580                    .read()
5581                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5582                    .attribute(&principal(module), module, &selector, true)
5583                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5584            }
5585            Some(ActivityOn::Route(route)) => {
5586                let DataRoute::Module(DataRouteState::Bound(binding)) = self
5587                    .forwarding
5588                    .lookup_data_route(connection, route.channel, route.epoch)
5589                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5590                else {
5591                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5592                };
5593                if binding.module_id != module {
5594                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5595                }
5596                actor.principal = binding.principal.clone();
5597                actor.project_root = binding
5598                    .project_root
5599                    .as_ref()
5600                    .map(|root| root.as_path().to_path_buf());
5601                let Some(bound) = &binding.scope else {
5602                    return Ok(actor);
5603                };
5604                let owner = principal(&bound.owner);
5605                let selector = subc_protocol::scope::ScopeSelector::new(
5606                    owner.clone(),
5607                    bound.scope_ref.clone(),
5608                    Some(bound.tag.scope_epoch),
5609                );
5610                let admitted = self
5611                    .scopes
5612                    .read()
5613                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?
5614                    .attribute(&owner, module, &selector, true)
5615                    .map_err(|_| ACTIVITY_ACTOR_UNKNOWN)?;
5616                if admitted.tag != bound.tag {
5617                    return Err(ACTIVITY_ACTOR_UNKNOWN);
5618                }
5619                admitted
5620            }
5621        };
5622        actor.scope_owner = Some(scope.stamp.owner);
5623        actor.agent_id = scope.stamp.attributes.agent_id;
5624        actor.run_id = scope.stamp.attributes.run_id;
5625        actor.flow_id = scope.stamp.attributes.flow_id;
5626        actor.workdir = scope.stamp.workdir.map(std::path::PathBuf::from);
5627        actor.project_id = scope.stamp.project_id;
5628        Ok(actor)
5629    }
5630
5631    fn record_control_usage(&self, connection: ConnectionId, op: &str) {
5632        let module_id = self
5633            .claims
5634            .binding(connection)
5635            .filter(|binding| {
5636                binding.consumer_live(connection) && binding.registration.authority.alive()
5637            })
5638            .map(|binding| binding.registration.module_id.clone())
5639            .or_else(|| {
5640                self.registry
5641                    .module_id_for_connection(connection)
5642                    .ok()
5643                    .flatten()
5644            });
5645        let principal = module_id
5646            .map(|module_id| format!("reserved:{module_id}"))
5647            .unwrap_or_else(|| "direct".to_owned());
5648        self.control_usage
5649            .lock()
5650            .unwrap_or_else(|poisoned| poisoned.into_inner())
5651            .record(op, &principal);
5652    }
5653
5654    fn handle_server_describe(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
5655        self.refresh_capability_requirements();
5656        // A bare connection count is ambiguous between many clients holding a
5657        // route each and one client accumulating hundreds, so publish the
5658        // concentration alongside it. Route state is best-effort here: a
5659        // diagnostic endpoint must still answer if the forwarding lock is
5660        // contended.
5661        let mut counters = self.counters.snapshot();
5662        if let Some(obj) = counters.as_object_mut() {
5663            obj.insert(
5664                "control_usage".into(),
5665                self.control_usage
5666                    .lock()
5667                    .unwrap_or_else(|poisoned| poisoned.into_inner())
5668                    .snapshot(),
5669            );
5670        }
5671        let losses = self.resource_tracker.loss_diagnostics();
5672        if losses.as_object().is_some_and(|losses| !losses.is_empty()) {
5673            if let Some(obj) = counters.as_object_mut() {
5674                obj.insert("agent_command_declaration_loss_by_module".into(), losses);
5675            }
5676        }
5677        if let (Some(ledger), Some(obj)) = (&self.activity, counters.as_object_mut()) {
5678            obj.insert(
5679                "activity_unparseable_lines".into(),
5680                ledger.read_errors().into(),
5681            );
5682            obj.insert(
5683                "activity_lifecycle_append_failures".into(),
5684                ledger.lifecycle_failures().into(),
5685            );
5686            obj.insert(
5687                "activity_started_digest_skips".into(),
5688                ledger.lifecycle_digest_skips().into(),
5689            );
5690        }
5691        if let (Ok((connections_with_routes, max)), Some(obj)) = (
5692            self.forwarding.client_route_concentration(),
5693            counters.as_object_mut(),
5694        ) {
5695            obj.insert(
5696                "client_connections_with_routes".into(),
5697                connections_with_routes.into(),
5698            );
5699            obj.insert("max_routes_on_one_connection".into(), max.into());
5700        }
5701        // A module that is being fast-refused and a module that is fine look
5702        // identical from a client that retries and succeeds, so name the open
5703        // breakers here. This rides the existing free-form counters object
5704        // rather than a new wire field, so no sibling that deserializes
5705        // `ServerDescribe` has to be rebuilt to keep reading it.
5706        if let (Some(open_breakers), Some(obj)) = (
5707            self.route_bind_breakers.open_snapshot(),
5708            counters.as_object_mut(),
5709        ) {
5710            obj.insert("route_bind_breakers_open".into(), open_breakers);
5711        }
5712        // A daemon whose local endpoint could not be bound keeps serving TCP,
5713        // and the connection file names no endpoint. Name the reason here, in
5714        // the free-form counters object, so an operator reading daemon facts
5715        // sees it without searching the log, and no wire field changes.
5716        if let (Some(reason), Some(obj)) = (
5717            self.local_endpoint_unavailable.clone(),
5718            counters.as_object_mut(),
5719        ) {
5720            obj.insert("local_endpoint_unavailable".into(), reason.into());
5721        }
5722        let response = ClientControlResponse::ServerDescribe {
5723            protocol_ver: PROTOCOL_VERSION,
5724            subc_ops: subc_ops(),
5725            capabilities: self.describe_capabilities(),
5726            connected_clients: self.connected_clients.count(),
5727            counters: Some(counters),
5728            build_git_sha: Some(env!("SUBC_BUILD_GIT_SHA").to_string()),
5729            build_lock_digest: Some(env!("SUBC_BUILD_LOCK_DIGEST").to_string()),
5730            capability_requirements: self.capability_requirement_statuses(),
5731            machine_id: self.machine_id.as_ref().map(|id| id.as_str().to_owned()),
5732            config_path: self
5733                .rescan
5734                .as_ref()
5735                .and_then(|context| rescan_checked::reported_config_path(&context.config_path)),
5736        };
5737        Ok(vec![control_response_body_frame(
5738            &frame,
5739            &response,
5740            "ClientControlResponse::ServerDescribe",
5741        )?])
5742    }
5743
5744    fn handle_catalog_list(
5745        &self,
5746        frame: Frame,
5747        module_id: Option<String>,
5748    ) -> Result<Vec<Frame>, RouterError> {
5749        let body = self.cached_catalog_body(frame.header.corr, module_id.as_deref())?;
5750        Ok(vec![Frame::build_with_version(
5751            response_version(&frame),
5752            FrameType::Response,
5753            control_flags(),
5754            0,
5755            0,
5756            frame.header.corr,
5757            body,
5758        )
5759        .map_err(RouterError::FrameBuild)?])
5760    }
5761
5762    #[cfg(test)]
5763    fn uncached_catalog_list(
5764        &self,
5765        corr: u64,
5766        module_id: Option<&str>,
5767    ) -> Result<ClientControlResponse, RouterError> {
5768        self.catalog_list_snapshot(corr, module_id, module_id.is_some())
5769    }
5770
5771    fn catalog_list_snapshot(
5772        &self,
5773        corr: u64,
5774        module_id: Option<&str>,
5775        include_declarations: bool,
5776    ) -> Result<ClientControlResponse, RouterError> {
5777        let (generation, modules) = self
5778            .registry
5779            .list_modules_with_nonce_verification()
5780            .map_err(|err| RouterError::backend(0, corr, format!("registry error: {err}")))?;
5781        let entries = modules
5782            .into_iter()
5783            .filter(|(registration, _)| {
5784                module_id
5785                    .map(|wanted| registration.manifest.module_id == wanted)
5786                    .unwrap_or(true)
5787            })
5788            .map(|(registration, nonce_verified)| {
5789                let entry = self
5790                    .catalog_discovery_entry(&registration, include_declarations)
5791                    .map_err(|err| RouterError::backend(0, corr, err))?;
5792                let not_ready = self.not_ready_reason(&registration);
5793                let mut entry = entry;
5794                entry.roles = registration.manifest.provides;
5795                entry.control_ops = registration.control_ops;
5796                Ok(entry
5797                    .with_ready(not_ready.is_none())
5798                    .with_display_name(registration.manifest.display_name)
5799                    .with_not_ready(not_ready)
5800                    .with_module_version(Some(registration.manifest.module_version))
5801                    .with_provenance(registration.manifest.provenance)
5802                    .with_capabilities(registration.manifest.capabilities)
5803                    .with_self_signals(registration.manifest.self_signals)
5804                    .with_events(registration.manifest.events)
5805                    .with_operation_delivery(registration.manifest.operation_delivery)
5806                    .with_operation_payload(registration.manifest.operation_payload)
5807                    .with_flow_operations(registration.manifest.flow_operations)
5808                    .with_operation_deferral(registration.manifest.operation_deferral)
5809                    .with_confirm_operations(registration.manifest.confirm_operations)
5810                    .with_rich_ui(registration.manifest.rich_ui)
5811                    .with_role_declarations(registration.manifest.role_declarations)
5812                    .with_nonce_verified(nonce_verified))
5813            })
5814            .collect::<Result<Vec<_>, RouterError>>()?;
5815        Ok(ClientControlResponse::CatalogList {
5816            generation,
5817            modules: entries,
5818            subc_ops: subc_ops(),
5819        })
5820    }
5821
5822    /// The caller fields for a refusal that only has the raw request frame,
5823    /// such as the connection-level admission refusal sent before the request
5824    /// reaches [`Self::handle_route_open`].
5825    fn route_open_caller_from_frame(&self, ctx: &RouteCtx, frame: &Frame) -> RouteOpenCaller {
5826        let Ok(ClientControlRequest::RouteOpen {
5827            identity,
5828            consumer_identity,
5829            scope,
5830            ..
5831        }) = parse_client_control_request(&frame.body)
5832        else {
5833            return RouteOpenCaller::unknown();
5834        };
5835        let principal = self
5836            .attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref())
5837            .map(|attested| attested.principal);
5838        RouteOpenCaller::new(principal.as_ref(), scope.as_ref(), &identity)
5839    }
5840
5841    fn route_open_principal(
5842        &self,
5843        connection_id: ConnectionId,
5844        frame: &Frame,
5845        consumer_identity: Option<ConsumerIdentity>,
5846    ) -> Result<Result<Principal, Frame>, RouterError> {
5847        let attested = self
5848            .attest_route_open_consumer(connection_id, consumer_identity.as_ref())
5849            .map(|attested| attested.principal);
5850        self.route_open_principal_attested(frame, consumer_identity, attested)
5851    }
5852
5853    /// [`Self::route_open_principal`] with `attested` already taken by
5854    /// [`Self::attest_route_open_consumer`], so one open resolves its connection
5855    /// claim or launch nonce once.
5856    fn route_open_principal_attested(
5857        &self,
5858        frame: &Frame,
5859        consumer_identity: Option<ConsumerIdentity>,
5860        attested: Option<Principal>,
5861    ) -> Result<Result<Principal, Frame>, RouterError> {
5862        if let Some(principal) = attested {
5863            return Ok(Ok(principal));
5864        }
5865        Ok(Err(control_error_frame(
5866            frame,
5867            "bad_consumer_identity",
5868            consumer_identity.map_or_else(
5869                || "connection claim is no longer authorized for routes".to_string(),
5870                |identity| format!(
5871                    "consumer_identity for module_id '{}' conflicts with its connection claim or did not match a supervised launch nonce",
5872                    identity.module_id
5873                ),
5874            ),
5875        )?))
5876    }
5877
5878    /// Ordinary `route.open` refusals go through here; admission and breaker
5879    /// refusals log separately with their capacity or breaker state. The daemon can
5880    /// attest which code it sent: without the event, a client's "the daemon
5881    /// refused me" and the daemon's own view could only be reconciled by
5882    /// argument. Malformed input (`invalid_project_root`) does not come here;
5883    /// rejecting a request that was never a valid open is not a refusal of one.
5884    #[allow(clippy::too_many_arguments)]
5885    fn route_open_refusal_frame(
5886        &self,
5887        ctx: &RouteCtx,
5888        caller: &RouteOpenCaller,
5889        frame: &Frame,
5890        module_id: &str,
5891        reason: &'static str,
5892        code: &'static str,
5893        message: impl Into<String>,
5894    ) -> Result<Frame, RouterError> {
5895        self.observe_route_open_refusal(ctx, caller, module_id, reason, code);
5896        let detail = if matches!(
5897            reason,
5898            "registration_not_active"
5899                | "supervisor_not_live"
5900                | "no_forwarding_connection"
5901                | "reloading"
5902        ) {
5903            // A planned restart, reload or swap is already replacing the
5904            // process; it does not need a slot in the crash-restart budget.
5905            let expected_back = (reason == "reloading").then_some(true);
5906            self.route_open_recovery_detail(module_id, frame.header.corr, None, expected_back)?
5907        } else {
5908            None
5909        };
5910        control_error_body_frame(
5911            frame,
5912            ErrorBody {
5913                code: code.to_string(),
5914                message: message.into(),
5915                detail,
5916            },
5917        )
5918    }
5919
5920    fn route_open_recovery_detail(
5921        &self,
5922        module_id: &str,
5923        corr: u64,
5924        detail: Option<serde_json::Value>,
5925        expected_back: Option<bool>,
5926    ) -> Result<Option<serde_json::Value>, RouterError> {
5927        let Some((status, _)) = self.supervisor_status(module_id, corr)? else {
5928            return Ok(detail);
5929        };
5930        let mut detail = detail.unwrap_or_else(|| serde_json::json!({}));
5931        detail["state"] = serde_json::json!(status.state.to_string());
5932        if let Some(expected_back) = expected_back {
5933            detail["expected_back"] = serde_json::json!(expected_back);
5934        } else if let Some(module) = self.supervisor.get(module_id) {
5935            match module.will_recover_after_connection_loss() {
5936                Ok(expected_back) => detail["expected_back"] = serde_json::json!(expected_back),
5937                Err(err) => warn!(
5938                    %module_id,
5939                    error = %err,
5940                    "failed to read route.open recovery verdict; omitting expected_back"
5941                ),
5942            }
5943        }
5944        Ok(Some(detail))
5945    }
5946
5947    /// Answer a waiting `route.open` whose relayed bind was refused.
5948    ///
5949    /// `daemon_authored` is provenance, not a code match: the daemon
5950    /// synthesized the refusal itself (a drain, a late reply, a scope that
5951    /// ended mid-bind) or the module refused the bind with its own body. A
5952    /// daemon refusal carries the daemon-origin bit; a module's own
5953    /// rejection is relayed with the bit clear, so a module that refuses
5954    /// with `module_reloading` still cannot mint a daemon refusal.
5955    #[allow(clippy::too_many_arguments)]
5956    fn route_bind_rejection(
5957        &self,
5958        ctx: &RouteCtx,
5959        caller: &RouteOpenCaller,
5960        frame: &Frame,
5961        target_module_id: &str,
5962        body: ErrorBody,
5963        daemon_authored: bool,
5964    ) -> Result<Vec<Frame>, RouterError> {
5965        // The daemon's own commit re-check refused the bind because the
5966        // scope ended or changed after admission. The module accepted;
5967        // counting it as a module rejection would blame the module. This
5968        // branch only runs for daemon-synthesized bodies: a module that
5969        // refuses with a scope code is answered as a module rejection below.
5970        if daemon_authored {
5971            let scope_code = match body.code.as_str() {
5972                error_codes::SCOPE_CHANGED => Some(error_codes::SCOPE_CHANGED),
5973                error_codes::SCOPE_ENDED => Some(error_codes::SCOPE_ENDED),
5974                _ => None,
5975            };
5976            if let Some(code) = scope_code {
5977                self.observe_route_open_refusal(
5978                    ctx,
5979                    caller,
5980                    target_module_id,
5981                    "scope_changed_before_commit",
5982                    code,
5983                );
5984                return Ok(vec![control_error_body_frame(frame, body)?]);
5985            }
5986        }
5987        self.counters
5988            .increment_route_open_refused("module_rejected");
5989        info!(
5990            target: "control",
5991            code = "module_rejected",
5992            module_code = ?body.code,
5993            module_id = ?target_module_id,
5994            connection_id = ctx.connection_id.get(),
5995            principal = %caller.principal,
5996            scope = %caller.scope,
5997            harness = %caller.harness,
5998            "route.open refused"
5999        );
6000        let refusal = if daemon_authored {
6001            control_error_body_frame(frame, body)?
6002        } else {
6003            control_relayed_error_body_frame(frame, body)?
6004        };
6005        Ok(vec![refusal])
6006    }
6007
6008    /// Refuse a `route.open` because the target module's bind-relay breaker is
6009    /// open, without attempting the relay.
6010    ///
6011    /// The wire code is `module_timeout`, which is the truth (the module has
6012    /// not been answering binds) and which both SDKs already classify as
6013    /// retryable with capped backoff. Reusing it is what keeps this change out
6014    /// of both SDKs; the daemon-side distinction lives in the counter key
6015    /// instead.
6016    ///
6017    /// DELIBERATELY NOT LOGGED PER OCCURRENCE, unlike every other refusal.
6018    /// While a breaker is open this fires on every open to that module, and the
6019    /// stall written up in `docs/designs/route-open-head-of-line.md` already
6020    /// produced 261 lines about a single module inside 3000 lines of daemon
6021    /// log. The rare transitions are logged at warn/info instead and the volume
6022    /// is carried by the counter, so the evidence survives without the flood.
6023    /// The debug line keeps a per-refusal record reachable for whoever turns
6024    /// the level up.
6025    #[allow(clippy::too_many_arguments)]
6026    fn route_open_breaker_refusal_frame(
6027        &self,
6028        ctx: &RouteCtx,
6029        caller: &RouteOpenCaller,
6030        frame: &Frame,
6031        module_id: &str,
6032        consecutive_timeouts: u32,
6033        retry_in: Duration,
6034        probe_in_flight: bool,
6035    ) -> Result<Frame, RouterError> {
6036        self.counters
6037            .increment_route_open_refused(crate::observability::ROUTE_OPEN_REFUSED_BREAKER_OPEN);
6038        debug!(
6039            target: "control",
6040            code = "module_timeout",
6041            module_id = ?module_id,
6042            connection_id = ctx.connection_id.get(),
6043            principal = %caller.principal,
6044            scope = %caller.scope,
6045            harness = %caller.harness,
6046            consecutive_timeouts,
6047            retry_in_ms = retry_in.as_millis() as u64,
6048            probe_in_flight,
6049            "route.open refused by open bind-relay breaker"
6050        );
6051        // Say what a caller can act on. An open bind-relay breaker means the
6052        // module timed out accepting several new routes in a row. The module
6053        // is still running and its established routes keep working; only new
6054        // route.open requests are refused until the cooldown ends and one
6055        // test route (the probe) gets through. A message that only counts
6056        // failed relays reads as "the module is down" to a worker that sees it.
6057        let detail = if probe_in_flight {
6058            "one test route is already being tried; retry once it settles".to_string()
6059        } else {
6060            format!("retrying new routes in {}s", retry_in.as_secs().max(1))
6061        };
6062        control_error_frame(
6063            frame,
6064            "module_timeout",
6065            format!(
6066                "module '{module_id}' is slow to accept new routes ({consecutive_timeouts} \
6067                 timed out in a row); {detail}; its established routes are unaffected"
6068            ),
6069        )
6070    }
6071
6072    /// `reason` names the check that refused, because one wire code has
6073    /// several senders: after a module registers, `target_unavailable` can
6074    /// come from a missing role, an inactive registration, a supervisor that
6075    /// has not marked the process live, a missing forwarding connection, or a
6076    /// failed relay, and a log that records only the code cannot say which of
6077    /// them fired. It is a static, daemon-chosen label per branch, so it is
6078    /// safe to print plainly and stays a closed set.
6079    fn observe_route_open_refusal(
6080        &self,
6081        ctx: &RouteCtx,
6082        caller: &RouteOpenCaller,
6083        module_id: &str,
6084        reason: &'static str,
6085        code: &'static str,
6086    ) {
6087        self.counters.increment_route_open_refused(code);
6088        self.route_refusal_log
6089            .record(module_id, code, reason, caller, ctx.connection_id.get());
6090        if ROUTE_OPEN_NOT_SERVING_REASONS.contains(&reason) {
6091            self.route_outages.record_not_serving(module_id, reason);
6092        }
6093    }
6094
6095    /// Record an ACCEPTED route.open.
6096    ///
6097    /// Refusals have been logged and counted since the attestation work; accepts
6098    /// were invisible, so the daemon knew every principal it stamped and wrote
6099    /// none of them down. The party that attests the identity was the only party
6100    /// not recording it, which left a credential vault unable to name the sender
6101    /// of a call that reached it (claustrum #43) and left the launch-nonce
6102    /// concurrency question unanswerable from the outside.
6103    ///
6104    /// FIELD NAMES MATCH `route.open refused` DELIBERATELY, so one grep over
6105    /// `code`/`module_id`/`connection_id` returns both directions of the same
6106    /// decision rather than two shapes a reader has to join by hand.
6107    ///
6108    /// `module_id` IS RENDERED BARE HERE AND DEBUG-ESCAPED ON THE REFUSAL PATH,
6109    /// and the difference carries information rather than being an
6110    /// inconsistency. This line is only reachable after a successful bind to a
6111    /// REGISTERED module, so the value has already passed HELLO validation
6112    /// including the path-hazard refusal and cannot contain control bytes. A
6113    /// refused id may be arbitrary attacker-chosen bytes and must stay escaped.
6114    /// So A QUOTED `module_id` IN THE LOG MEANS THE VALUE WAS NEVER VALIDATED.
6115    ///
6116    /// Bare is also what every other daemon line already emits (`module
6117    /// registered`, `configured module supervised`). Shipping `?module_id` here
6118    /// made this instrument the only one in the file whose ids did not answer
6119    /// `grep module_id=broca` -- 3 hits against 342 for the escaped form, in a
6120    /// line whose whole purpose is being grepped beside its sibling.
6121    ///
6122    /// THIS RENDERING IS UNFENCED AND THE REASON IS WORTH KNOWING: the in-crate
6123    /// `EventCapture` test layer implements only `record_debug`, so `Visit`
6124    /// forwards every field type through it and a bare `&str` and a `?`-escaped
6125    /// one are recorded identically. A test written against that harness passes
6126    /// either way -- I wrote one, measured it, and deleted it rather than ship a
6127    /// green assertion that cannot fail. The same limit applies to the escaping
6128    /// assertion in `route_open_supervised_absence_emits_refusal_fields_and_counts_code`:
6129    /// it reads as a guard on the Debug escaping and cannot detect its removal.
6130    /// Fencing either needs the real formatter, not the capture layer.
6131    ///
6132    /// `peer_addr` is NOT here and cannot be: `SO_PEERCRED`/`LOCAL_PEERPID` are
6133    /// unix-socket options and subc is loopback TCP, so there is no peer identity
6134    /// to record. The ephemeral port would decay within minutes and answer only a
6135    /// live question. The identity question is instead answered by counting
6136    /// distinct live connections presenting one module's `consumer_identity` --
6137    /// "is anyone else holding this secret" rather than "is this the right
6138    /// process".
6139    fn observe_route_open_accept(
6140        &self,
6141        ctx: &RouteCtx,
6142        module_id: &str,
6143        principal: &str,
6144        scope: &str,
6145    ) {
6146        self.route_outages.record_accepted(module_id);
6147        self.counters.increment_route_open_accepted(principal);
6148        debug!(
6149            target: "control",
6150            principal,
6151            module_id,
6152            connection_id = ctx.connection_id.get(),
6153            scope = %scope,
6154            "route.open accepted"
6155        );
6156    }
6157
6158    fn supervised_absent_route_open_refusal_frame(
6159        &self,
6160        ctx: &RouteCtx,
6161        caller: &RouteOpenCaller,
6162        frame: &Frame,
6163        module_id: &str,
6164        code: &'static str,
6165        status: &crate::supervise::ModuleStatus,
6166    ) -> Result<Frame, RouterError> {
6167        self.counters.increment_route_open_refused(code);
6168        info!(
6169            target: "control",
6170            code,
6171            reason = "supervised_not_registered",
6172            module_id = ?module_id,
6173            connection_id = ctx.connection_id.get(),
6174            principal = %caller.principal,
6175            scope = %caller.scope,
6176            harness = %caller.harness,
6177            state = %status.state,
6178            enabled = status.enabled,
6179            live = status.live,
6180            "route.open refused"
6181        );
6182        // A supervised module whose process has not registered is not
6183        // serving, whatever the reason; the supervisor knows this id, so it is
6184        // safe to track.
6185        self.route_outages
6186            .record_not_serving(module_id, "supervised_not_registered");
6187        let message = if let Some(pid) = status.waiting_for_previous_pid {
6188            status.waiting_for_previous_detail.clone().unwrap_or_else(|| {
6189                format!("waiting: previous instance (pid {pid}) is still running but could not be verified")
6190            })
6191        } else {
6192            format!(
6193                "module_id '{module_id}' is supervised but not available (state={}, enabled={}, live={})",
6194                status.state, status.enabled, status.live
6195            )
6196        };
6197        // `module_warming` here means the process is starting, running or
6198        // being restarted and has not registered yet. Nothing has to be
6199        // restarted for it to serve, so the crash budget does not decide it.
6200        let expected_back = (code == error_codes::MODULE_WARMING).then_some(true);
6201        control_error_body_frame(
6202            frame,
6203            ErrorBody {
6204                code: code.to_string(),
6205                message,
6206                detail: self.route_open_recovery_detail(
6207                    module_id,
6208                    frame.header.corr,
6209                    None,
6210                    expected_back,
6211                )?,
6212            },
6213        )
6214    }
6215
6216    async fn handle_route_open(
6217        &self,
6218        ctx: &RouteCtx,
6219        frame: Frame,
6220        request: RouteOpenRequest,
6221        timings: &mut RouteOpenTimings,
6222    ) -> Result<Vec<Frame>, RouterError> {
6223        let RouteOpenRequest {
6224            target,
6225            mut identity,
6226            consumer_identity,
6227            consumer_capabilities,
6228            role_versions,
6229            busy_refusals,
6230            admission_facts,
6231            scope,
6232            accepts_close_reasons,
6233        } = request;
6234        let target_module_id = target_module_id(&target).to_string();
6235        timings.module_id.clone_from(&target_module_id);
6236        if self
6237            .registry
6238            .get_module_by_connection(ctx.connection_id)
6239            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
6240            .is_some()
6241        {
6242            return Ok(vec![control_error_frame(
6243                &frame,
6244                "invalid_request",
6245                "module connections cannot open client routes",
6246            )?]);
6247        }
6248        debug!(
6249            connection_id = ctx.connection_id.get(),
6250            corr = frame.header.corr,
6251            module_id = %target_module_id,
6252            "handling route.open"
6253        );
6254
6255        // The caller's attested principal, requested scope and harness, for
6256        // every `route.open refused` line below. The connection's claim
6257        // binding or launch nonce is checked here, once, and the answer is
6258        // reused where the principal is enforced further down, so the order
6259        // of refusals is unchanged.
6260        let attested =
6261            self.attest_route_open_consumer(ctx.connection_id, consumer_identity.as_ref());
6262        let mut caller = RouteOpenCaller::new(
6263            attested.as_ref().map(|attested| &attested.principal),
6264            scope.as_ref(),
6265            &identity,
6266        );
6267
6268        // A malformed declaration is refused first, before anything about the
6269        // target is looked up: the same body would be refused against any
6270        // module, so the caller learns nothing by retrying or waiting. An empty
6271        // map declares nothing and travels as no field at all, so a provider
6272        // only ever sees a missing field or a non-empty one.
6273        let role_versions = role_versions.filter(|role_versions| !role_versions.is_empty());
6274        if let Some(Err(error)) = role_versions.as_ref().map(validate_role_versions) {
6275            self.observe_route_open_refusal(
6276                ctx,
6277                &caller,
6278                &target_module_id,
6279                "invalid_role_versions",
6280                error_codes::INVALID_REQUEST,
6281            );
6282            return Ok(vec![control_error_body_frame(
6283                &frame,
6284                ErrorBody {
6285                    code: error_codes::INVALID_REQUEST.to_string(),
6286                    message: error.to_string(),
6287                    detail: Some(serde_json::json!({ "field": ROLE_VERSIONS_FIELD })),
6288                },
6289            )?]);
6290        }
6291
6292        if let Some((status, _)) = self.supervisor_status(&target_module_id, frame.header.corr)? {
6293            if status.waiting_for_previous_pid.is_some() {
6294                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6295                    ctx,
6296                    &caller,
6297                    &frame,
6298                    &target_module_id,
6299                    "module_warming",
6300                    &status,
6301                )?]);
6302            }
6303        }
6304
6305        // WHY THESE REPLIES DISCRIMINATE FREELY, since the usual rule is the
6306        // opposite. Below, a caller learns whether a module is unregistered,
6307        // supervised-but-down (with state/enabled/live), or registered without the
6308        // requested role. Elsewhere that is an enumeration leak: a probe learning
6309        // the shape of a fleet it cannot otherwise see.
6310        //
6311        // It is not one here, and the reason is the ACCESS MODEL rather than
6312        // anything about these errors. Reaching route.open requires the
6313        // pre-envelope HMAC handshake, whose key lives in a 0600 user-owned
6314        // connection file, so any caller who completes it already runs as this
6315        // user -- and can read subc.jsonc for the module list and `ck module
6316        // status` for live state. The reply discloses nothing the caller cannot
6317        // read more easily from disk, while the precision is load-bearing:
6318        // `unknown_module` is retryable and a missing role is not.
6319        //
6320        // IF THE HANDSHAKE EVER ADMITS A PRINCIPAL THAT IS NOT THIS USER -- a
6321        // remote transport, a sandboxed caller, a shared-host mode -- THAT
6322        // PREMISE DIES AND THESE THREE REPLIES MUST COLLAPSE INTO ONE.
6323        let admission_registry = self
6324            .registry
6325            .route_admission_snapshot()
6326            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
6327        let Some(registration) =
6328            crate::scopes::admission::registered_target(&admission_registry, &target_module_id)
6329        else {
6330            if let Some((status, warming)) =
6331                self.supervisor_status(&target_module_id, frame.header.corr)?
6332            {
6333                // BEFORE the two availability codes below, because for a module
6334                // that speaks no subc wire both of them are false comfort: they
6335                // say "not right now" and are retried, and this module will
6336                // never register no matter how long the caller waits. The
6337                // absence here is the declaration being honoured, not a module
6338                // that is late.
6339                if status.protocol == ModuleProtocol::None {
6340                    return Ok(vec![self.route_open_refusal_frame(
6341                        ctx,
6342                        &caller,
6343                        &frame,
6344                        &target_module_id,
6345                        "protocol_none",
6346                        error_codes::MODULE_NO_PROTOCOL,
6347                        format!(
6348                            "module_id '{target_module_id}' is declared protocol: none; \
6349                             it speaks no subc wire and serves no routes"
6350                        ),
6351                    )?]);
6352                }
6353                let code = if warming {
6354                    "module_warming"
6355                } else {
6356                    "target_unavailable"
6357                };
6358                return Ok(vec![self.supervised_absent_route_open_refusal_frame(
6359                    ctx,
6360                    &caller,
6361                    &frame,
6362                    &target_module_id,
6363                    code,
6364                    &status,
6365                )?]);
6366            }
6367            if let Some(removed_ago_ms) =
6368                self.supervisor.removal_tombstone_age_ms(&target_module_id)
6369            {
6370                return Ok(vec![self.route_open_refusal_frame(
6371                    ctx,
6372                    &caller,
6373                    &frame,
6374                    &target_module_id,
6375                    "removed",
6376                    error_codes::MODULE_REMOVED,
6377                    format!("module_id '{target_module_id}' was removed {removed_ago_ms} ms ago"),
6378                )?]);
6379            }
6380            return Ok(vec![self.route_open_refusal_frame(
6381                ctx,
6382                &caller,
6383                &frame,
6384                &target_module_id,
6385                "not_registered",
6386                error_codes::UNKNOWN_MODULE,
6387                format!("module_id '{target_module_id}' is not registered"),
6388            )?]);
6389        };
6390
6391        // Best-effort only: registry readiness and forwarding reservation use
6392        // different locks, so a module can flip readiness between this read and
6393        // the relay. Modules must still tolerate an `on_bind` while not ready.
6394        if crate::scopes::admission::target_registration(&admission_registry, &target_module_id)
6395            .is_err()
6396        {
6397            self.counters
6398                .increment_route_open_refused(ROUTE_OPEN_REFUSED_DECLARED_NOT_READY);
6399            info!(
6400                target: "control",
6401                code = error_codes::MODULE_WARMING,
6402                module_id = ?target_module_id,
6403                connection_id = ctx.connection_id.get(),
6404                principal = %caller.principal,
6405                scope = %caller.scope,
6406                harness = %caller.harness,
6407                reason = "declared_not_ready",
6408                "route.open refused"
6409            );
6410            // The module is registered but says it cannot take work, which is
6411            // an outage from the caller's side even though its process is up.
6412            self.route_outages
6413                .record_not_serving(&target_module_id, "declared_not_ready");
6414            // The registered process can declare itself ready without a
6415            // restart, so an exhausted crash budget does not prevent serving.
6416            return Ok(vec![control_error_body_frame(
6417                &frame,
6418                ErrorBody {
6419                    code: error_codes::MODULE_WARMING.to_string(),
6420                    message: format!(
6421                        "module_id '{target_module_id}' is registered and has declared itself not ready; retry"
6422                    ),
6423                    detail: self.route_open_recovery_detail(
6424                        &target_module_id,
6425                        frame.header.corr,
6426                        Some(serde_json::json!({ "reason": "declared_not_ready" })),
6427                        Some(true),
6428                    )?,
6429                },
6430            )?]);
6431        }
6432
6433        // Effective readiness, second half: a module that declares a capability
6434        // `need: required` is not routable while that capability has no
6435        // registered provider. It is enforced HERE, as a retryable routing
6436        // refusal, and deliberately not as spawn ordering or a boot block. The
6437        // module is still started and registered and can make its own calls;
6438        // spawn ordering is a promise that cannot be kept once a provider
6439        // crashes at runtime, and refusing to boot would stop the whole
6440        // machine, including the tools needed to fix its configuration.
6441        //
6442        // "Provided" is the evaluator's verdict, which counts a provider as
6443        // soon as it has REGISTERED, not once it is ready. Two modules that
6444        // require each other's capabilities are therefore both routable once
6445        // both register; counting readiness instead would deadlock them.
6446        //
6447        // Only new opens are refused. Routes already bound when a provider
6448        // goes away stay bound: nothing here tears them down, and the module
6449        // answers them as it can. Like the readiness read above this is
6450        // best-effort against a provider registering or leaving concurrently.
6451        if let Some(capability) = self.first_unprovided_required_capability_for(
6452            &registration.module_id,
6453            registration.capabilities.as_ref(),
6454        ) {
6455            self.counters
6456                .increment_route_open_refused(ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED);
6457            info!(
6458                target: "control",
6459                code = error_codes::MODULE_WARMING,
6460                module_id = ?target_module_id,
6461                connection_id = ctx.connection_id.get(),
6462                principal = %caller.principal,
6463                scope = %caller.scope,
6464                harness = %caller.harness,
6465                reason = NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6466                capability = %capability,
6467                "route.open refused"
6468            );
6469            return Ok(vec![control_error_body_frame(
6470                &frame,
6471                ErrorBody {
6472                    code: error_codes::MODULE_WARMING.to_string(),
6473                    message: format!(
6474                        "module_id '{target_module_id}' requires capability '{capability}', \
6475                         which no registered module provides; retry"
6476                    ),
6477                    detail: Some(serde_json::json!({
6478                        "reason": NotReadyReason::REQUIRED_CAPABILITY_UNPROVIDED,
6479                        "capability": capability,
6480                    })),
6481                },
6482            )?]);
6483        }
6484
6485        if !target_has_required_role(&target, &registration.roles) {
6486            return Ok(vec![self.route_open_refusal_frame(
6487                ctx,
6488                &caller,
6489                &frame,
6490                &target_module_id,
6491                "role_not_provided",
6492                "target_unavailable",
6493                format!("module_id '{target_module_id}' does not provide the requested target"),
6494            )?]);
6495        }
6496
6497        if registration.state != ChannelState::Active {
6498            return Ok(vec![self.route_open_refusal_frame(
6499                ctx,
6500                &caller,
6501                &frame,
6502                &target_module_id,
6503                "registration_not_active",
6504                "target_unavailable",
6505                format!("module_id '{target_module_id}' is not active"),
6506            )?]);
6507        }
6508
6509        if self
6510            .forwarding
6511            .module_is_draining(&target_module_id)
6512            .map_err(RouterError::Forwarding)?
6513        {
6514            return Ok(vec![self.route_open_refusal_frame(
6515                ctx,
6516                &caller,
6517                &frame,
6518                &target_module_id,
6519                "reloading",
6520                "module_reloading",
6521                format!("module_id '{target_module_id}' is reloading"),
6522            )?]);
6523        }
6524
6525        if let Some(process_liveness) = self.process_liveness.as_ref().filter(|process_liveness| {
6526            process_liveness.process_live(&target_module_id) == Some(false)
6527        }) {
6528            // A module the supervisor is restarting or reloading can still hold
6529            // a registration: the old process before its connection closes, or
6530            // a new one that registered while the supervisor was draining. The
6531            // forwarding table does not see that as draining, but the consumer
6532            // should still be told to retry soon, exactly as for the drain
6533            // above, rather than that the target is unavailable.
6534            if process_liveness.process_replacing(&target_module_id) {
6535                return Ok(vec![self.route_open_refusal_frame(
6536                    ctx,
6537                    &caller,
6538                    &frame,
6539                    &target_module_id,
6540                    "reloading",
6541                    "module_reloading",
6542                    format!("module_id '{target_module_id}' is reloading"),
6543                )?]);
6544            }
6545            return Ok(vec![self.route_open_refusal_frame(
6546                ctx,
6547                &caller,
6548                &frame,
6549                &target_module_id,
6550                "supervisor_not_live",
6551                "target_unavailable",
6552                format!("module_id '{target_module_id}' is not live"),
6553            )?]);
6554        }
6555
6556        if !self
6557            .forwarding
6558            .has_live_module_connection(&target_module_id)
6559            .map_err(RouterError::Forwarding)?
6560        {
6561            return Ok(vec![self.route_open_refusal_frame(
6562                ctx,
6563                &caller,
6564                &frame,
6565                &target_module_id,
6566                "no_forwarding_connection",
6567                "target_unavailable",
6568                format!("module_id '{target_module_id}' has no live forwarding connection"),
6569            )?]);
6570        }
6571
6572        if let Some(error) =
6573            self.guard_module_control_op(&frame, &target_module_id, "route.bind")?
6574        {
6575            self.observe_route_open_refusal(
6576                ctx,
6577                &caller,
6578                &target_module_id,
6579                "op_not_allowed",
6580                "op_not_allowed",
6581            );
6582            return Ok(vec![error]);
6583        }
6584
6585        let principal = match (&attested, consumer_identity.is_some()) {
6586            // A claim-bound connection whose launch ended attests nothing,
6587            // and it must never fall back to opening as `direct`.
6588            (None, false) => {
6589                self.observe_route_open_refusal(
6590                    ctx,
6591                    &caller,
6592                    &target_module_id,
6593                    "registration_channel_closed",
6594                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6595                );
6596                return Ok(vec![control_error_frame(
6597                    &frame,
6598                    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6599                    "the claim binding's launch has ended",
6600                )?]);
6601            }
6602            _ => match self.route_open_principal_attested(
6603                &frame,
6604                consumer_identity,
6605                attested.as_ref().map(|attested| attested.principal.clone()),
6606            )? {
6607                Ok(principal) => principal,
6608                Err(error) => {
6609                    self.observe_route_open_refusal(
6610                        ctx,
6611                        &caller,
6612                        &target_module_id,
6613                        "bad_consumer_identity",
6614                        "bad_consumer_identity",
6615                    );
6616                    return Ok(vec![error]);
6617                }
6618            },
6619        };
6620        let attested = attested.expect("an attested principal was resolved above");
6621        timings.principal = principal_label(&principal);
6622
6623        // The opener's spawn authority, read once here and carried with the
6624        // relay; nothing below reads its record again.
6625        let Ok(mut caller_capture) = attested.capture() else {
6626            self.observe_route_open_refusal(
6627                ctx,
6628                &caller,
6629                &target_module_id,
6630                "registration_channel_closed",
6631                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6632            );
6633            return Ok(vec![control_error_frame(
6634                &frame,
6635                crate::supervise::REGISTRATION_CHANNEL_CLOSED,
6636                "the opener's launch has ended",
6637            )?]);
6638        };
6639        // The caller-side checks below read the opener's own spawn: its
6640        // module from its record and its manifest from its own registration,
6641        // never another launch's active registration under the same id.
6642        let caller_module_id = match &attested.spawn {
6643            Some((record, _)) => Some(record.module_id().to_owned()),
6644            None => match &principal {
6645                Principal::Reserved { module_id } => Some(module_id.clone()),
6646                _ => None,
6647            },
6648        };
6649
6650        // Only Callosum can attest a production phone build. Consume the raw
6651        // claim here; opted-in targets receive only the honoured peer fact.
6652        let build_class = identity.build_class.take().filter(|build_class| {
6653            if caller_module_id.as_deref() == Some("callosum") {
6654                build_class == subc_protocol::BUILD_CLASS_PRODUCTION
6655            } else {
6656                if self
6657                    .build_class_warned
6658                    .lock()
6659                    .unwrap_or_else(|p| p.into_inner())
6660                    .insert(ctx.connection_id)
6661                {
6662                    warn!(connection_id = ctx.connection_id.get(), principal = %timings.principal,
6663                        "ignoring build_class from a non-Callosum opener");
6664                }
6665                false
6666            }
6667        });
6668
6669        // This is attested, control-plane policy for supervised module origins.
6670        // Keep it before route reservation and out of the opaque forwarding hot
6671        // path: data frames must never acquire a per-frame capability check.
6672        let opening_registration = self.caller_registration(&attested, &admission_registry);
6673        if let Some(opening_registration) = &opening_registration {
6674            let opening_module_id = opening_registration.module_id.as_str();
6675            if let Some(capability) = denied_capability(
6676                opening_registration.capabilities.as_ref(),
6677                registration.capabilities.as_ref(),
6678            ) {
6679                warn!(
6680                    opening_module_id,
6681                    target_module_id,
6682                    capability,
6683                    "refusing route.open because an attested capability deny edge matches"
6684                );
6685                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6686                    &frame,
6687                    &target_module_id,
6688                    "capability_deny_edge",
6689                    "capability_forbidden",
6690                    format!(
6691                        "module_id '{opening_module_id}' must never reach capability '{capability}' provided by '{target_module_id}'"
6692                    ),
6693                )?]);
6694            }
6695        }
6696
6697        if admission_facts.is_some() {
6698            let carrier_matches = caller_module_id.is_some()
6699                && self.admission_facts_carrier_module_id.as_deref() == caller_module_id.as_deref();
6700            if !carrier_matches {
6701                return Ok(vec![self.route_open_refusal_frame(
6702                    ctx,
6703                    &caller,
6704                    &frame,
6705                    &target_module_id,
6706                    "admission_facts_carrier_not_permitted",
6707                    "admission_facts_not_permitted",
6708                    "admission facts may only be carried by the configured reserved module",
6709                )?]);
6710            }
6711
6712            let target_allowed = self
6713                .admission_facts_targets
6714                .as_ref()
6715                .is_some_and(|targets| targets.iter().any(|id| id == &target_module_id));
6716            if !target_allowed {
6717                return Ok(vec![self.route_open_refusal_frame(ctx, &caller,
6718                    &frame,
6719                    &target_module_id,
6720                    "admission_facts_target_not_listed",
6721                    "admission_facts_target_not_allowed",
6722                    format!(
6723                        "admission facts are not permitted for target module_id '{target_module_id}'"
6724                    ),
6725                )?]);
6726            }
6727
6728            // Keep the value opaque to subc. The downstream admission validator owns
6729            // schema and semantic checks; this daemon only enforces carrier authority
6730            // and the configured destination allowlist.
6731        }
6732
6733        // Scope admission, on the attested principal above and never on the
6734        // request body. The tag read here travels with the pending bind and is
6735        // compared with the published one at commit, so a sync between here
6736        // and the module's ack refuses the open instead of binding a stamp
6737        // that is no longer true.
6738        let (bound_scope, mut scope_stamp, stamp_required) = match &scope {
6739            None => (None, None, false),
6740            Some(selector) => {
6741                let owner_configured = match &selector.owner {
6742                    // A reserved owner counts as configured from before its
6743                    // process is spawned (see `SupervisorHandle::is_configured`).
6744                    // So an owner that has not synced its scopes yet is refused
6745                    // as retryable (`scope_not_synced`), not as one that will
6746                    // never sync.
6747                    Principal::Reserved { module_id } => self.supervisor.is_configured(module_id),
6748                    _ => false,
6749                };
6750                let mut scopes = self
6751                    .scopes
6752                    .write()
6753                    .unwrap_or_else(|poisoned| poisoned.into_inner());
6754                let admitted = crate::scopes::admission::admit_route(
6755                    &scopes,
6756                    &admission_registry,
6757                    &principal,
6758                    &target_module_id,
6759                    Some(selector),
6760                    owner_configured,
6761                    crate::scopes::admission::AdmissionMode::Open,
6762                )
6763                .map(|route| {
6764                    let admission = route.scope.expect("scoped admission");
6765                    let bound = scopes.reserve_bind(
6766                        &admission,
6767                        &principal,
6768                        ctx.connection_id,
6769                        selector.hold_presence,
6770                    );
6771                    (admission, bound)
6772                });
6773                match admitted {
6774                    Ok((admission, bound)) => {
6775                        (Some(bound), Some(admission.stamp), admission.stamp_required)
6776                    }
6777                    Err(refusal) => {
6778                        return Ok(vec![self.route_open_refusal_frame(
6779                            ctx,
6780                            &caller,
6781                            &frame,
6782                            &target_module_id,
6783                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6784                            refusal.code.unwrap_or(error_codes::TARGET_UNAVAILABLE),
6785                            refusal.message,
6786                        )?]);
6787                    }
6788                }
6789            }
6790        };
6791        // From here on a refusal names the scope by the stamp admission
6792        // issued, exactly as the `route.open accepted` line does.
6793        if let Some(stamp) = &scope_stamp {
6794            caller.scope = route_open_scope_label(stamp);
6795        }
6796        // Decided from the admitted stamp, before any field of it is stripped
6797        // for a target that lacks the capability to read it.
6798        if scope_stamp.as_ref().is_some_and(scope_acts_for_another) {
6799            caller_capture = caller_capture.map(crate::spawn_authority::CallerCapture::relayed);
6800        }
6801
6802        // Allow resolvable missing-tail paths so a vanished directory does not
6803        // prevent reopening an existing session for cleanup. Binding does not
6804        // authorize creation of durable provider state.
6805        //
6806        // Resolve real paths rather than lexical cleanup: canonicalize the
6807        // longest existing ancestor and append the missing tail, retaining the
6808        // path's real existing ancestry even when a leaf is missing.
6809        timings.enter(RouteOpenPhase::ProjectRoot);
6810        let legacy_project = match crate::bind_compat::LegacyProject::from_open(&frame.body) {
6811            Ok(project) => project,
6812            Err((code, message)) => return Ok(vec![control_error_frame(&frame, code, message)?]),
6813        };
6814        timings.enter(RouteOpenPhase::Admission);
6815        let project_root = match legacy_project.effective_root(scope_stamp.as_ref()) {
6816            Ok(root) => root,
6817            Err(err) => {
6818                return Ok(vec![control_error_frame(
6819                    &frame,
6820                    "invalid_project_root",
6821                    err.to_string(),
6822                )?])
6823            }
6824        };
6825        // Compute compatibility project fields before stripping optional stamp
6826        // members. Preserve the canonical opener root and its project ID,
6827        // including absence. For rootless openers, use stamp workdir or `/`, and
6828        // opener ID, else stamp ID, else no ID. Emit these identity fields only
6829        // to targets without bind-no-project/v1.
6830        let legacy_bind_project = legacy_project.for_target(scope_stamp.as_ref());
6831
6832        // Last gate before any relay work, and deliberately after the cheap
6833        // registry and availability checks above: those name a more precise
6834        // condition (unknown, removed, reloading) and a caller is better served
6835        // by the precise code than by this one.
6836        //
6837        // Everything below this point costs an egress permit, a reserved handle
6838        // pair and, if the module does not answer, the whole relay budget. The
6839        // reader no longer waits for that budget, so cap each target explicitly;
6840        // serial dispatch used to provide the accidental cap of one relay per
6841        // connection. Admission is a mutex-protected count and never waits.
6842        let _concurrency_guard = match self
6843            .route_bind_concurrency
6844            .try_admit(&target_module_id, MAX_PENDING_ROUTE_BINDS_PER_TARGET)
6845        {
6846            Ok(guard) => guard,
6847            Err(in_flight) => {
6848                return Ok(vec![self.route_open_target_capacity_refusal(
6849                    ctx,
6850                    &caller,
6851                    &frame,
6852                    &target_module_id,
6853                    in_flight,
6854                )?]);
6855            }
6856        };
6857
6858        // A module that has already burned the whole budget `threshold` times
6859        // in a row does not get to charge it again until a probe says it recovered.
6860        let mut breaker = match self.route_bind_breakers.admit(&target_module_id) {
6861            RouteBindAdmission::Admitted { guard, probe } => {
6862                if probe {
6863                    info!(
6864                        module_id = %target_module_id,
6865                        connection_id = ctx.connection_id.get(),
6866                        "route.bind breaker half-open: admitting one probe"
6867                    );
6868                }
6869                guard
6870            }
6871            RouteBindAdmission::Refused {
6872                consecutive_timeouts,
6873                retry_in,
6874                probe_in_flight,
6875            } => {
6876                return Ok(vec![self.route_open_breaker_refusal_frame(
6877                    ctx,
6878                    &caller,
6879                    &frame,
6880                    &target_module_id,
6881                    consecutive_timeouts,
6882                    retry_in,
6883                    probe_in_flight,
6884                )?]);
6885            }
6886        };
6887
6888        let operator_app = self
6889            .route_operator_app(ctx.connection_id, registration.capabilities.as_ref())
6890            .await;
6891        // Resolve the per-module budget here so the wait matches the operator's
6892        // intent for this specific target. A per-module override in
6893        // `subc.jsonc` (or `with_route_bind_relay_timeouts` for embedded
6894        // daemons) wins over the daemon-wide default.
6895        let route_bind_relay_timeout = self.route_bind_relay_timeout_for(&target_module_id);
6896        let relay_deadline = Instant::now() + route_bind_relay_timeout;
6897        let production_peer_build =
6898            build_class.as_deref() == Some(subc_protocol::BUILD_CLASS_PRODUCTION);
6899        timings.enter(RouteOpenPhase::EgressReservation);
6900        let pending = match self
6901            .forwarding
6902            .begin_route_bind_relay_for(
6903                ctx.connection_id,
6904                ctx.egress.clone(),
6905                response_version(&frame),
6906                frame.header.corr,
6907                &target_module_id,
6908                principal.clone(),
6909                bound_scope,
6910                project_root,
6911                identity.harness.clone(),
6912                build_class,
6913                operator_app.clone(),
6914                crate::forwarding::RouteAuthority {
6915                    incarnation: self.supervisor.daemon_incarnation(),
6916                    caller: caller_capture
6917                        .as_ref()
6918                        .map(|caller| caller.authority.pair()),
6919                    capability_fence: route_bind_settlement::fence(
6920                        &opening_registration,
6921                        registration,
6922                    ),
6923                },
6924                relay_deadline,
6925                busy_refusals == Some(true),
6926                accepts_close_reasons,
6927            )
6928            .await
6929        {
6930            Ok(pending) => pending,
6931            Err(err) => {
6932                return Ok(vec![self.route_open_refusal_frame(
6933                    ctx,
6934                    &caller,
6935                    &frame,
6936                    &target_module_id,
6937                    "relay_reservation_failed",
6938                    forwarding_error_code(&err),
6939                    err.to_string(),
6940                )?])
6941            }
6942        };
6943        timings.enter(RouteOpenPhase::Admission);
6944        let crate::forwarding::PendingRouteBindRelay {
6945            endpoint,
6946            module_sink,
6947            negotiated_ver,
6948            client_channel,
6949            client_epoch,
6950            module_channel,
6951            module_epoch,
6952            corr: relay_corr,
6953            receiver,
6954        } = pending;
6955        let mut reservation =
6956            RouteBindReservationGuard::new(Arc::clone(&self.forwarding), endpoint, relay_corr);
6957
6958        // Reserving egress can wait while a module reconnects or a swap cuts
6959        // over. Check the relay's captured connection, not the earlier by-id
6960        // lookup: the original module's flow/run capabilities cannot authorize
6961        // its replacement. The captured sink stays bound to that connection.
6962        let relay_registration = self
6963            .registry
6964            .route_registration_by_connection(endpoint.connection_id)
6965            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
6966        let relay_capabilities = relay_registration
6967            .as_ref()
6968            .and_then(|registration| registration.capabilities.as_ref());
6969        if let Some(selector) = &scope {
6970            // Egress reservation may wait across a scope update. Recheck the
6971            // proof against the current record before sending the captured bind.
6972            if let Err(refusal) = self
6973                .scopes
6974                .read()
6975                .unwrap_or_else(|poisoned| poisoned.into_inner())
6976                .check_bind_proof(&principal, selector)
6977            {
6978                reservation.release_and_disarm();
6979                return Ok(vec![self.route_open_refusal_frame(
6980                    ctx,
6981                    &caller,
6982                    &frame,
6983                    &target_module_id,
6984                    refusal.code,
6985                    refusal.code,
6986                    refusal.message,
6987                )?]);
6988            }
6989        }
6990        if let Some(stamp) = scope_stamp.as_ref() {
6991            if let Err(refusal) = crate::scopes::check_target_required_stamp(
6992                stamp_required,
6993                &target_module_id,
6994                relay_capabilities,
6995            )
6996            .and_then(|()| {
6997                crate::scopes::check_target_flow_support(
6998                    stamp,
6999                    &target_module_id,
7000                    relay_capabilities,
7001                )
7002            })
7003            .and_then(|()| {
7004                crate::scopes::check_target_agent_run_support(
7005                    stamp,
7006                    &target_module_id,
7007                    relay_capabilities,
7008                )
7009            }) {
7010                reservation.release_and_disarm();
7011                return Ok(vec![self.route_open_refusal_frame(
7012                    ctx,
7013                    &caller,
7014                    &frame,
7015                    &target_module_id,
7016                    refusal.code,
7017                    refusal.code,
7018                    refusal.message,
7019                )?]);
7020            }
7021        }
7022
7023        // Older readers may reject unknown fields. Select optional fields from
7024        // the captured endpoint's declaration, including on unscoped binds.
7025        if scope_stamp
7026            .as_ref()
7027            .is_some_and(|stamp| stamp.kind == subc_protocol::scope::ScopeKind::Federated)
7028            && !crate::scopes::target_supports_federated(relay_capabilities)
7029        {
7030            // Keep bound_scope: even an unstamped legacy route belongs to this epoch.
7031            scope_stamp = None;
7032        }
7033        if !relay_capabilities.is_some_and(|caps| {
7034            caps.provides
7035                .iter()
7036                .any(|cap| cap == subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY)
7037        }) {
7038            if let Some(stamp) = scope_stamp.as_mut() {
7039                stamp.workdir = None;
7040                stamp.project_id = None;
7041            }
7042        }
7043        // A worker run has no agent_id; on_behalf_of_agent is its only agent
7044        // attribution. The run gate above has already required the target to
7045        // declare `worker-runs/v1`, which promises to read both
7046        // `on_behalf_of_agent` and `call_mode`.
7047        let worker_run = scope_stamp
7048            .as_ref()
7049            .is_some_and(crate::scopes::is_worker_run)
7050            && relay_capabilities.is_some_and(|caps| {
7051                caps.provides
7052                    .iter()
7053                    .any(|cap| cap == subc_protocol::scope::WORKER_RUNS_CAPABILITY)
7054            });
7055        if !worker_run
7056            && !relay_capabilities.is_some_and(|caps| {
7057                caps.provides
7058                    .iter()
7059                    .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY)
7060            })
7061        {
7062            if let Some(stamp) = scope_stamp.as_mut() {
7063                stamp.attributes.on_behalf_of_agent = None;
7064            }
7065        }
7066        if !relay_capabilities.is_some_and(|caps| {
7067            caps.provides
7068                .iter()
7069                .any(|cap| cap == subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY)
7070        }) {
7071            if let Some(stamp) = scope_stamp.as_mut() {
7072                stamp.attributes.flow_version = None;
7073                stamp.attributes.flow_code_hash = None;
7074                stamp.attributes.flow_install_id = None;
7075            }
7076        }
7077        let call_mode = if worker_run
7078            || relay_capabilities
7079                .is_some_and(|caps| caps.provides.iter().any(|cap| cap == CALL_MODES_CAPABILITY))
7080        {
7081            Some(derive_call_mode(scope_stamp.as_ref()))
7082        } else {
7083            if let Some(stamp) = scope_stamp.as_mut() {
7084                stamp.expires_at_ms = None;
7085            }
7086            None
7087        };
7088
7089        debug!(
7090            connection_id = ctx.connection_id.get(),
7091            client_channel,
7092            client_epoch,
7093            module_channel,
7094            module_epoch,
7095            "reserved route handle pair"
7096        );
7097        // Rendered BEFORE the move into the relay, because the accept arm below
7098        // is where it is logged and the principal is gone by then.
7099        let route_principal_label = principal_label(&principal);
7100        let relay = ModuleControlRequest::RouteBind {
7101            route_channel: module_channel,
7102            epoch: module_epoch,
7103            target,
7104            identity,
7105            principal: Some(principal),
7106            consumer_capabilities,
7107            role_versions,
7108            admission_facts,
7109            scope: scope_stamp,
7110            call_mode,
7111        };
7112        let peer = RouteBindPeer::new()
7113            .with_observed_peer(
7114                relay_capabilities
7115                    .is_some_and(|caps| {
7116                        caps.provides
7117                            .iter()
7118                            .any(|cap| cap == OBSERVED_PEER_CAPABILITY)
7119                    })
7120                    .then(|| {
7121                        self.observed_peers
7122                            .lock()
7123                            .unwrap_or_else(|p| p.into_inner())
7124                            .get(&ctx.connection_id)
7125                            .cloned()
7126                            .unwrap_or_else(ObservedPeer::unobserved)
7127                    }),
7128            )
7129            .with_operator_app(
7130                self.connection_operator_app(operator_app.as_ref())
7131                    .filter(|_| {
7132                        relay_capabilities.is_some_and(|caps| {
7133                            caps.provides
7134                                .iter()
7135                                .any(|cap| cap == OPERATOR_APP_CAPABILITY)
7136                        })
7137                    }),
7138            )
7139            .with_caller(caller_for_target(
7140                caller_capture.as_ref(),
7141                relay_capabilities,
7142                &target_module_id,
7143            ))
7144            .with_peer_build(
7145                (production_peer_build
7146                    && relay_capabilities.is_some_and(|caps| {
7147                        caps.provides.iter().any(|cap| cap == PEER_BUILD_CAPABILITY)
7148                    }))
7149                .then(|| subc_protocol::BUILD_CLASS_PRODUCTION.to_owned()),
7150            );
7151        let relay_body = crate::bind_compat::encode_bind(
7152            &relay,
7153            &peer,
7154            &legacy_bind_project,
7155            relay_capabilities,
7156        )
7157        .map_err(|err| {
7158            RouterError::backend(
7159                0,
7160                frame.header.corr,
7161                format!("failed to encode route.bind request: {err}"),
7162            )
7163        })?;
7164        let relay_frame = Frame::build_with_version(
7165            negotiated_ver,
7166            FrameType::Request,
7167            control_flags(),
7168            0,
7169            0,
7170            relay_corr,
7171            relay_body,
7172        )
7173        .map_err(RouterError::FrameBuild)?;
7174
7175        timings.enter(RouteOpenPhase::BindSend);
7176        // Enqueueing the bind spends the same absolute budget as its ack.
7177        let sent = timeout_at(relay_deadline, module_sink.send(relay_frame)).await;
7178        timings.enter(RouteOpenPhase::Admission);
7179        let Ok(sent) = sent else {
7180            // Never enqueued: the module's queue, not its bind handler, was
7181            // slow, so the ack-timeout breaker is not charged.
7182            reservation.release_and_disarm();
7183            breaker.record_inconclusive();
7184            return Ok(vec![self.unsent_bind_timeout_refusal(
7185                ctx,
7186                &caller,
7187                &frame,
7188                &target_module_id,
7189            )?]);
7190        };
7191        if let Err(err) = sent {
7192            reservation.release_and_disarm();
7193            return Ok(vec![self.route_open_refusal_frame(
7194                ctx,
7195                &caller,
7196                &frame,
7197                &target_module_id,
7198                "relay_send_failed",
7199                "target_unavailable",
7200                err.to_string(),
7201            )?]);
7202        }
7203
7204        #[cfg(test)]
7205        if let Some(hold) = &self.route_bind_relay_sent_hold {
7206            // First wait: tell the test the bind is queued. Second wait: stay
7207            // here until the test has driven whatever it wants to happen
7208            // between queueing the bind and marking it enqueued.
7209            hold.wait().await;
7210            hold.wait().await;
7211        }
7212
7213        // A missing relay is not by itself an abandoned bind: the module may
7214        // already have acked it and the route may be committed. Only a relay
7215        // dropped without any module reply needs this GOODBYE; one a reply
7216        // settled has already had its GOODBYE decided by the reply path.
7217        if self
7218            .forwarding
7219            .mark_route_bind_relay_enqueued(endpoint, relay_corr)
7220            .map_err(RouterError::Forwarding)?
7221            == crate::forwarding::RouteBindRelayMark::ReleasedWithoutReply
7222        {
7223            self.send_abandoned_route_bind_goodbye(
7224                &module_sink,
7225                negotiated_ver,
7226                module_channel,
7227                module_epoch,
7228            );
7229        }
7230
7231        timings.enter(RouteOpenPhase::BindAckWait);
7232        let outcome = timeout_at(relay_deadline, receiver).await;
7233        timings.enter(RouteOpenPhase::Admission);
7234        match outcome {
7235            Ok(Ok(RouteBindRelayOutcome::Accepted)) => {
7236                reservation.disarm();
7237                if breaker.record_accepted() {
7238                    info!(
7239                        module_id = %target_module_id,
7240                        "route.bind breaker closed: the probe was accepted"
7241                    );
7242                }
7243                self.observe_route_open_accept(
7244                    ctx,
7245                    &target_module_id,
7246                    &route_principal_label,
7247                    &caller.scope,
7248                );
7249                Ok(Vec::new())
7250            }
7251            Ok(Ok(RouteBindRelayOutcome::Rejected(body))) => {
7252                reservation.release_and_disarm();
7253                // A module that says no in microseconds is healthy. Rejection
7254                // is a different condition with its own refusal and must not
7255                // move the breaker.
7256                breaker.record_inconclusive();
7257                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, false)
7258            }
7259            Ok(Ok(RouteBindRelayOutcome::DaemonRejected(body))) => {
7260                reservation.release_and_disarm();
7261                breaker.record_inconclusive();
7262                self.route_bind_rejection(ctx, &caller, &frame, &target_module_id, body, true)
7263            }
7264            Ok(Ok(RouteBindRelayOutcome::ModuleGone(message))) => {
7265                reservation.release_and_disarm();
7266                breaker.record_inconclusive();
7267                // Fires when the module's connection closes while a relayed
7268                // bind is pending -- typically a caller racing a module restart
7269                // whose bind was relayed BEFORE the drain mark went up. Logged
7270                // because the caller sees only its own error and the fleet has
7271                // already spent one diagnosis round unable to tell this arm
7272                // from a relay timeout without daemon-side evidence.
7273                tracing::warn!(
7274                    module_id = %target_module_id,
7275                    "route.bind relay abandoned: {message}"
7276                );
7277                Ok(vec![self.route_open_refusal_frame(
7278                    ctx,
7279                    &caller,
7280                    &frame,
7281                    &target_module_id,
7282                    "relay_abandoned",
7283                    "target_unavailable",
7284                    message,
7285                )?])
7286            }
7287            Ok(Err(_)) => {
7288                reservation.release_and_disarm();
7289                breaker.record_inconclusive();
7290                Ok(vec![self.route_open_refusal_frame(
7291                    ctx,
7292                    &caller,
7293                    &frame,
7294                    &target_module_id,
7295                    "relay_waiter_canceled",
7296                    "target_unavailable",
7297                    "route.bind relay waiter was canceled before the module responded",
7298                )?])
7299            }
7300            Err(_) => {
7301                reservation.release_and_disarm();
7302                // THE ONLY ARM THAT MOVES THE BREAKER. Budget exhausted with no
7303                // answer at all is the one condition a fast refusal can
7304                // usefully stand in for; every other arm already answered.
7305                if let Some(opened) = breaker.record_timeout(
7306                    self.route_bind_breaker_threshold,
7307                    self.route_bind_breaker_cooldown,
7308                ) {
7309                    warn!(
7310                        module_id = %target_module_id,
7311                        consecutive_timeouts = opened.consecutive_timeouts,
7312                        cooldown_ms = self.route_bind_breaker_cooldown.as_millis() as u64,
7313                        reopened_after_probe = opened.reopened_after_probe,
7314                        "route.bind breaker open: refusing route.open for this module without relaying until one probe says it recovered"
7315                    );
7316                }
7317                // The generous budget just burned to no answer: the module is
7318                // registered and its connection is up, but its bind handler sat
7319                // on the ack for the full budget (warm-on-bind, cold configure,
7320                // or a wedged handler). Every earlier unavailability shape
7321                // fast-refuses BEFORE the relay, so this arm firing means the
7322                // slowness is module-side -- log it so the per-module timeline
7323                // is reconstructable without client audit rows.
7324                tracing::warn!(
7325                    module_id = %target_module_id,
7326                    timeout_ms = route_bind_relay_timeout.as_millis() as u64,
7327                    "route.bind relay timed out: module did not ack within budget"
7328                );
7329                Ok(vec![self.route_open_refusal_frame(
7330                    ctx,
7331                    &caller,
7332                    &frame,
7333                    &target_module_id,
7334                    "relay_timed_out",
7335                    "module_timeout",
7336                    format!(
7337                        "module_id '{target_module_id}' did not answer route.bind within {:?}",
7338                        route_bind_relay_timeout
7339                    ),
7340                )?])
7341            }
7342        }
7343    }
7344
7345    fn handle_supervisor_spawn_snapshot(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7346        let response = ClientControlResponse::SupervisorSpawnSnapshot {
7347            snapshot: self.supervisor.spawn_snapshot(),
7348        };
7349        Ok(vec![control_response_body_frame(
7350            &frame,
7351            &response,
7352            "ClientControlResponse::SupervisorSpawnSnapshot",
7353        )?])
7354    }
7355
7356    fn handle_supervisor_spawn_subscribe(
7357        &self,
7358        ctx: &RouteCtx,
7359        frame: Frame,
7360        since: Option<SpawnCursor>,
7361    ) -> Result<Vec<Frame>, RouterError> {
7362        match self.supervisor.subscribe_spawns(
7363            ctx.connection_id,
7364            frame.header.corr,
7365            response_version(&frame),
7366            since,
7367            ctx.egress.clone(),
7368        ) {
7369            Ok(()) => Ok(Vec::new()),
7370            Err(SpawnSubscribeRefusal::ForeignIncarnation { current }) => {
7371                Ok(vec![control_error_body_frame(
7372                    &frame,
7373                    ErrorBody {
7374                        code: "spawn_cursor_incarnation_mismatch".to_string(),
7375                        message: "spawn cursor belongs to a different daemon incarnation"
7376                            .to_string(),
7377                        detail: Some(serde_json::json!({
7378                            "current_daemon_incarnation": current
7379                        })),
7380                    },
7381                )?])
7382            }
7383            Err(SpawnSubscribeRefusal::TooOld { oldest }) => Ok(vec![control_error_body_frame(
7384                &frame,
7385                ErrorBody {
7386                    code: "spawn_cursor_too_old".to_string(),
7387                    message: "spawn cursor predates the retained event ring".to_string(),
7388                    detail: Some(serde_json::json!({
7389                        "oldest_retained_cursor": oldest
7390                    })),
7391                },
7392            )?]),
7393            Err(SpawnSubscribeRefusal::Frame(error)) => Err(RouterError::backend(
7394                0,
7395                frame.header.corr,
7396                format!("failed to open supervisor spawn subscription: {error}"),
7397            )),
7398        }
7399    }
7400
7401    async fn handle_supervisor_list(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7402        // Status/configuration snapshots may wait on synchronous supervisor
7403        // locks. Keep that work off the connection's async runtime thread.
7404        let handler = self.clone();
7405        let runtime = tokio::runtime::Handle::current();
7406        // The blocking pool does not inherit the control request's tracing
7407        // subscriber. Preserve it so slow snapshot-lock warnings stay visible.
7408        let subscriber = tracing::dispatcher::get_default(Clone::clone);
7409        let corr = frame.header.corr;
7410        tokio::task::spawn_blocking(move || {
7411            runtime.block_on(
7412                list_diagnostics::scope(handler.handle_supervisor_list_inner(frame))
7413                    .with_subscriber(subscriber),
7414            )
7415        })
7416        .await
7417        .map_err(|error| RouterError::backend(0, corr, error.to_string()))?
7418    }
7419
7420    async fn handle_supervisor_list_inner(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7421        use crate::config_gate::runtime::ApprovedDaemonView;
7422        let publication = self
7423            .config_runtime
7424            .as_ref()
7425            .and_then(|owner| owner.polled_snapshot().ok());
7426        let approved = publication
7427            .as_ref()
7428            .map(|view| view.approved_daemon.clone())
7429            .unwrap_or_else(|| {
7430                if self.config_runtime.is_some() {
7431                    ApprovedDaemonView::Unavailable
7432                } else {
7433                    ApprovedDaemonView::NotStamped
7434                }
7435            });
7436        let generation = self
7437            .registry
7438            .generation()
7439            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7440        let supervised = self.supervisor.list();
7441        let mut statuses = BTreeMap::new();
7442        let mut not_running = BTreeSet::new();
7443        for module in &supervised {
7444            let status = module.status_for_control("list").map_err(|err| {
7445                RouterError::backend(
7446                    0,
7447                    frame.header.corr,
7448                    format!("failed to read supervisor status: {err}"),
7449                )
7450            })?;
7451            if !status.enabled || !status.process_alive {
7452                not_running.insert(module.module_id().to_owned());
7453            }
7454            statuses.insert(module.module_id().to_owned(), status);
7455        }
7456        // Legacy per-process diagnostics keep their shared optional budget.
7457        // The cached tree and accounting export below does not spend it.
7458        let mut process_resources = BTreeMap::new();
7459        for module in &supervised {
7460            process_resources.insert(
7461                module.module_id().to_owned(),
7462                crate::subtree_resources::read_process(module.clone()).await,
7463            );
7464        }
7465        // Image evidence uses the same optional deadline, but an exhausted
7466        // budget must not suppress the committed resource view.
7467        let mut image_readings = BTreeMap::new();
7468        for module in &supervised {
7469            image_readings.insert(
7470                module.module_id().to_owned(),
7471                module.running_image_agreement().await,
7472            );
7473        }
7474        let readings = self.resource_tracker.list(supervised.clone());
7475        let mut modules = Vec::new();
7476        for module in supervised {
7477            let status = statuses
7478                .remove(module.module_id())
7479                .expect("each supervised module has a status snapshot");
7480            let (configured, _) = module.configuration().map_err(|err| {
7481                RouterError::backend(
7482                    0,
7483                    frame.header.corr,
7484                    format!("failed to read module configuration: {err}"),
7485                )
7486            })?;
7487            let next_retry_at_ms = module.next_retry_at_ms().map_err(|err| {
7488                RouterError::backend(
7489                    0,
7490                    frame.header.corr,
7491                    format!("failed to read retry time: {err}"),
7492                )
7493            })?;
7494            let image = image_readings
7495                .remove(module.module_id())
7496                .expect("each supervised module has an image snapshot");
7497            let resources = process_resources.remove(module.module_id());
7498            let mut verdict =
7499                reload_verdict(&configured.program, status.spawned_from.as_deref(), image);
7500            verdict.spec = Some(launch_spec_agreement(
7501                &configured,
7502                status.process_alive,
7503                status.launch_spec_digest.as_ref(),
7504            ));
7505            let pending_reload = Some(verdict);
7506            let pending_entry = match &approved {
7507                ApprovedDaemonView::Approved { config, .. } => config
7508                    .modules
7509                    .iter()
7510                    .find(|m| m.module_id == module.module_id()),
7511                _ => None,
7512            };
7513            let pending = self
7514                .pending_module_fields(
7515                    &module,
7516                    pending_entry,
7517                    false,
7518                    Self::registration_channel_in_force(
7519                        publication
7520                            .as_ref()
7521                            .and_then(|view| view.registration_declaration(module.module_id()))
7522                            .as_deref(),
7523                        pending_entry.map(|entry| entry.registration_channel),
7524                    ),
7525                    publication.as_deref(),
7526                )
7527                .map_err(|err| RouterError::backend(0, frame.header.corr, err))?;
7528            let script = configured.script.as_ref().map(|entry| {
7529                let approved = self
7530                    .config_runtime
7531                    .as_ref()
7532                    .and_then(|owner| owner.approved_script(&status.module_id, &entry.path));
7533                crate::supervise::script::status(entry, approved.as_ref())
7534            });
7535            let configured_enabled = match &approved {
7536                ApprovedDaemonView::Approved {
7537                    config: approved, ..
7538                } => approved
7539                    .modules
7540                    .iter()
7541                    .find(|module| module.module_id == status.module_id)
7542                    .map(|module| module.enabled),
7543                ApprovedDaemonView::NotStamped => self
7544                    .capability_evaluator
7545                    .configured_enabled(&status.module_id),
7546                ApprovedDaemonView::Unavailable => None,
7547            };
7548            let admission_refused = status
7549                .admission_refused
7550                .clone()
7551                .filter(|_| status.enabled && !status.process_alive)
7552                .filter(|_| {
7553                    publication
7554                        .as_ref()
7555                        .and_then(|view| view.registration_declaration(&status.module_id))
7556                        .as_deref()
7557                        == Some("undeclared")
7558                });
7559            // Keep the retired policy field on the wire for one release so
7560            // existing status consumers still receive the platform policy.
7561            let mut entry = SupervisorEntry::new(
7562                status.module_id,
7563                status.state.to_string(),
7564                status.enabled,
7565                status.live,
7566                status.health.status,
7567            )
7568            .with_configured_enabled(configured_enabled)
7569            .with_script(script)
7570            .with_admission_refused(admission_refused)
7571            .with_next_retry_at_ms(next_retry_at_ms)
7572            .with_launch_nonce_env(Some(!cfg!(unix)))
7573            .with_launch_nonce_source(status.launch_nonce_source)
7574            .with_waiting_for_previous_pid(status.waiting_for_previous_pid)
7575            .with_protocol(status.protocol)
7576            .with_pending_reload(pending_reload)
7577            .with_last_probe_ms(status.health.last_probe_ms)
7578            .with_last_exit_code(status.last_exit.as_ref().and_then(|e| e.code))
7579            .with_last_exit_signal(status.last_exit.as_ref().and_then(|e| e.signal))
7580            .with_last_exit_ms(status.last_exit.as_ref().map(|e| e.at_ms))
7581            .with_last_exit_kind(status.last_exit.as_ref().map(|e| e.kind.into()))
7582            .with_restart_count(Some(status.restart_count))
7583            .with_max_restarts(Some(status.max_restarts))
7584            .with_lifetime_restarts(Some(status.lifetime_restarts))
7585            .with_spawn_generation(Some(status.spawn_generation))
7586            .with_restart_window_secs(Some(status.restart_window.as_secs()))
7587            .with_drain_timeout_ms(Some(status.drain_timeout.as_millis() as u64))
7588            .with_restart_backoff_ms(Some(status.restart_backoff.as_millis() as u64))
7589            .with_restart_max_backoff_ms(Some(status.restart_max_backoff.as_millis() as u64))
7590            .with_resources(resources);
7591            entry.pending = pending;
7592            modules.push(entry);
7593        }
7594        for module in &mut modules {
7595            if let Some((tree, hour)) = readings.modules.get(&module.module_id) {
7596                module.tree = tree.clone();
7597                module.cpu_last_hour = hour.clone();
7598            }
7599            module.tree_unavailable = readings
7600                .reasons
7601                .get(&module.module_id)
7602                .map(|reason| (*reason).to_owned());
7603            if module.tree.is_none() {
7604                module.tree_unavailable = Some(
7605                    if not_running.contains(&module.module_id) {
7606                        "not_running"
7607                    } else if let Some(reason) = readings.reasons.get(&module.module_id) {
7608                        reason
7609                    } else {
7610                        "not_yet_measured"
7611                    }
7612                    .to_owned(),
7613                );
7614            }
7615        }
7616        let response = ClientControlResponse::SupervisorList {
7617            generation,
7618            modules,
7619            daemon: readings.daemon,
7620            agent_commands: readings.agent_commands,
7621        };
7622        Ok(vec![control_response_body_frame(
7623            &frame,
7624            &response,
7625            "ClientControlResponse::SupervisorList",
7626        )?])
7627    }
7628
7629    fn handle_supervisor_stderr_tail(
7630        &self,
7631        frame: Frame,
7632        module_id: String,
7633        max_lines: Option<u32>,
7634        max_bytes: Option<u32>,
7635    ) -> Result<Vec<Frame>, RouterError> {
7636        let Some(module) = self.supervisor.get(&module_id) else {
7637            return Ok(vec![control_error_frame(
7638                &frame,
7639                "unknown_module",
7640                format!("module_id '{module_id}' is not supervised"),
7641            )?]);
7642        };
7643
7644        let snapshot = module.stderr_tail(
7645            max_lines.map(|value| value as usize),
7646            max_bytes.map(|value| value as usize),
7647        );
7648
7649        let response = ClientControlResponse::SupervisorStderrTail {
7650            module_id,
7651            tail: StderrTail {
7652                capture: match snapshot.capture {
7653                    CaptureState::Captured => StderrCaptureState::Captured,
7654                    CaptureState::Incomplete { reason } => {
7655                        StderrCaptureState::Incomplete { reason }
7656                    }
7657                    CaptureState::NotCaptured { reason } => {
7658                        StderrCaptureState::NotCaptured { reason }
7659                    }
7660                },
7661                entries: snapshot
7662                    .entries
7663                    .into_iter()
7664                    .map(|entry| match entry {
7665                        TailEntry::Line {
7666                            text,
7667                            truncated,
7668                            at_ms,
7669                        } => StderrTailEntry::Line {
7670                            text,
7671                            truncated,
7672                            at_ms,
7673                        },
7674                        TailEntry::ProcessStart => StderrTailEntry::ProcessStart,
7675                    })
7676                    .collect(),
7677                dropped_lines: snapshot.dropped_lines,
7678            },
7679        };
7680        Ok(vec![control_response_body_frame(
7681            &frame,
7682            &response,
7683            "ClientControlResponse::SupervisorStderrTail",
7684        )?])
7685    }
7686
7687    async fn observe_control_wait<F: std::future::Future>(
7688        &self,
7689        ctx: &RouteCtx,
7690        target: Option<&str>,
7691        kind: &'static str,
7692        future: F,
7693    ) -> F::Output {
7694        self.counters
7695            .observe_reader_wait(
7696                || {
7697                    let module = self
7698                        .forwarding
7699                        .module_id_for_connection(ctx.connection_id)
7700                        .ok()
7701                        .flatten();
7702                    let principal = if module.is_some() { "module" } else { "direct" };
7703                    (
7704                        self.resolve_reader_wait_target(kind, target)
7705                            .or(module)
7706                            .unwrap_or_else(|| crate::observability::CONTROL_WAIT_BUCKET.into()),
7707                        principal.into(),
7708                    )
7709                },
7710                kind,
7711                future,
7712            )
7713            .await
7714    }
7715
7716    /// Resolve the reader-wait module ID only from supervisor or registry
7717    /// records; never attribute a wait from the request selector alone.
7718    pub(crate) fn resolve_reader_wait_target(
7719        &self,
7720        op: &str,
7721        selector: Option<&str>,
7722    ) -> Option<String> {
7723        let selector = selector?;
7724        match op {
7725            ops::SUPERVISOR_TERMINALS | ops::SUPERVISOR_PROVENANCE => self
7726                .supervisor
7727                .get(selector)
7728                .map(|module| module.module_id().to_owned()),
7729            ops::SUPERVISOR_HEALTH_PROBE => self
7730                .registry
7731                .get_module(selector)
7732                .ok()
7733                .flatten()
7734                .map(|registration| registration.manifest.module_id),
7735            _ => None,
7736        }
7737    }
7738
7739    async fn handle_supervisor_terminals(
7740        &self,
7741        ctx: &RouteCtx,
7742        frame: Frame,
7743        module_id: String,
7744    ) -> Result<Vec<Frame>, RouterError> {
7745        let Some(module) = self.supervisor.get(&module_id) else {
7746            return Ok(vec![control_error_frame(
7747                &frame,
7748                "unknown_module",
7749                format!("module_id '{module_id}' is not supervised"),
7750            )?]);
7751        };
7752
7753        // The journal read runs on a blocking thread: it can be megabytes of
7754        // file I/O and must not occupy a runtime worker.
7755        let terminals = self
7756            .observe_control_wait(
7757                ctx,
7758                Some(module.module_id()),
7759                ops::SUPERVISOR_TERMINALS,
7760                module.read_durable_terminal_history(),
7761            )
7762            .await
7763            .map_err(|error| {
7764                RouterError::backend(
7765                    0,
7766                    frame.header.corr,
7767                    format!("failed to read terminal history: {error}"),
7768                )
7769            })?;
7770        let response = ClientControlResponse::SupervisorTerminals {
7771            module_id,
7772            terminals,
7773        };
7774        Ok(vec![control_response_body_frame(
7775            &frame,
7776            &response,
7777            "ClientControlResponse::SupervisorTerminals",
7778        )?])
7779    }
7780
7781    fn handle_supervisor_routes(
7782        &self,
7783        frame: Frame,
7784        module_id: Option<String>,
7785    ) -> Result<Vec<Frame>, RouterError> {
7786        let modules = self
7787            .forwarding
7788            .route_census(module_id.as_deref())
7789            .map_err(RouterError::Forwarding)?
7790            .into_iter()
7791            .map(|(module_id, routes)| SupervisorRouteModule {
7792                module_id,
7793                routes: routes
7794                    .into_iter()
7795                    .map(|route| SupervisorRoute {
7796                        consumer: match route.principal {
7797                            Principal::Reserved { module_id } => {
7798                                SupervisorRouteConsumer::Reserved { module_id }
7799                            }
7800                            Principal::Direct | Principal::Unverified => {
7801                                SupervisorRouteConsumer::Direct {
7802                                    connection_id: route.goodbye_target.connection_id.get(),
7803                                }
7804                            }
7805                        },
7806                        age_ms: Instant::now()
7807                            .saturating_duration_since(route.bound_at)
7808                            .as_millis()
7809                            .try_into()
7810                            .unwrap_or(u64::MAX),
7811                        draining: route.draining,
7812                        drain_reason: route.drain_reason,
7813                    })
7814                    .collect(),
7815            })
7816            .collect();
7817        let response = ClientControlResponse::SupervisorRoutes { modules };
7818        Ok(vec![control_response_body_frame(
7819            &frame,
7820            &response,
7821            "ClientControlResponse::SupervisorRoutes",
7822        )?])
7823    }
7824
7825    fn running_registration_method(
7826        &self,
7827        module: &str,
7828    ) -> Option<subc_control::RegistrationMethod> {
7829        let registration = self.registry.get_module(module).ok()??;
7830        let connection = registration.connection_id;
7831        let channel = self.supervisor.registration_spawn(connection).is_some();
7832        let nonce = if channel {
7833            None
7834        } else {
7835            self.hello_launch_nonces
7836                .lock()
7837                .ok()?
7838                .nonce(connection)
7839                .map(str::to_owned)
7840        };
7841        if !channel && nonce.is_none() {
7842            return None;
7843        }
7844        self.supervisor
7845            .registration_snapshot_is_current_live(
7846                &self.registry,
7847                module,
7848                connection,
7849                nonce.as_deref(),
7850            )
7851            .then_some(if channel {
7852                subc_control::RegistrationMethod::Channel
7853            } else {
7854                subc_control::RegistrationMethod::Nonce
7855            })
7856    }
7857
7858    async fn handle_supervisor_provenance(
7859        &self,
7860        ctx: &RouteCtx,
7861        frame: Frame,
7862        module_id: Option<String>,
7863    ) -> Result<Vec<Frame>, RouterError> {
7864        let targeted = module_id.is_some();
7865        let selected = if let Some(module_id) = module_id {
7866            let Some(module) = self.supervisor.get(&module_id) else {
7867                return Ok(vec![control_error_frame(
7868                    &frame,
7869                    "unknown_module",
7870                    format!("module_id '{module_id}' is not supervised"),
7871                )?]);
7872            };
7873            vec![module]
7874        } else {
7875            self.supervisor.list()
7876        };
7877
7878        let target = targeted.then(|| selected[0].module_id());
7879        let declarations = if let Some(owner) = &self.config_runtime {
7880            owner
7881                .on_blocking(|owner| owner.registration_declarations())
7882                .await
7883                .ok()
7884        } else {
7885            None
7886        };
7887        self.observe_control_wait(ctx, target, ops::SUPERVISOR_PROVENANCE, async {
7888            let mut modules = Vec::with_capacity(selected.len());
7889            let mut extensions = Vec::with_capacity(selected.len());
7890            for module in &selected {
7891                let (status, observed_image) = module
7892                    .status_and_running_image_agreement()
7893                    .await
7894                    .map_err(|err| {
7895                        RouterError::backend(
7896                            0,
7897                            frame.header.corr,
7898                            format!("failed to read supervisor status: {err}"),
7899                        )
7900                    })?;
7901                let module_declared = self
7902                    .registry
7903                    .get_module(&status.module_id)
7904                    .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
7905                    .and_then(|registration| registration.manifest.provenance)
7906                    .map(|build| ModuleDeclaredProvenance::Reported { build })
7907                    .unwrap_or(ModuleDeclaredProvenance::Unverifiable);
7908                #[cfg(test)]
7909                let running_image = match &self.provenance_probe_override {
7910                    Some(result) => result.clone(),
7911                    None => observed_image,
7912                };
7913                #[cfg(not(test))]
7914                let running_image = observed_image;
7915                let registration = self.running_registration_method(&status.module_id);
7916                let mut extension = subc_control::SupervisorModuleProvenanceExt::new()
7917                    .with_registration(registration);
7918                extension.registration_declaration = declarations
7919                    .as_ref()
7920                    .and_then(|entries| entries.get(&status.module_id))
7921                    .cloned();
7922                if status.process_alive && status.registration_declaration.is_some() {
7923                    extension.registration_declaration = status.registration_declaration.clone();
7924                }
7925                extensions.push(extension);
7926                modules.push(SupervisorModuleProvenance {
7927                    module_id: status.module_id,
7928                    module_declared,
7929                    daemon_observed: SupervisorObservedProcess {
7930                        launch_nonce_source: status.launch_nonce_source,
7931                        pid: status.pid,
7932                        spawned_at_ms: status.spawned_at_ms,
7933                        spawned_from: status.spawned_from,
7934                        running_image,
7935                    },
7936                });
7937            }
7938            let daemon = SupervisorDaemonProvenance {
7939                daemon_build: self.daemon_provenance.build.clone(),
7940                daemon_observed: DaemonObservedProcess {
7941                    pid: self.daemon_provenance.pid,
7942                    started_at_ms: self
7943                        .daemon_provenance
7944                        .start_clock
7945                        .map(|clock| clock.started_at_ms())
7946                        .or(self.daemon_provenance.started_at_ms),
7947                    running_image: self
7948                        .daemon_provenance
7949                        .probe
7950                        .observe(
7951                            self.daemon_provenance.pid,
7952                            self.daemon_provenance.executable_path.as_deref(),
7953                            self.daemon_provenance.executable_identity.clone(),
7954                            self.daemon_provenance.process_start_time,
7955                        )
7956                        .await,
7957                },
7958            };
7959            let response = ClientControlResponse::SupervisorProvenance { daemon, modules };
7960            let mut response = serde_json::to_value(response)
7961                .map_err(|error| RouterError::backend(0, frame.header.corr, error.to_string()))?;
7962            for (entry, extension) in response["modules"]
7963                .as_array_mut()
7964                .expect("provenance modules are an array")
7965                .iter_mut()
7966                .zip(extensions)
7967            {
7968                extension.write_to(entry).map_err(|error| {
7969                    RouterError::backend(0, frame.header.corr, error.to_string())
7970                })?;
7971            }
7972            Ok(vec![control_response_body_frame(
7973                &frame,
7974                &response,
7975                "ClientControlResponse::SupervisorProvenance",
7976            )?])
7977        })
7978        .await
7979    }
7980
7981    fn handle_supervisor_health(&self, frame: Frame) -> Result<Vec<Frame>, RouterError> {
7982        self.refresh_capability_requirements();
7983        let publication = self
7984            .config_runtime
7985            .as_ref()
7986            .and_then(|owner| owner.polled_snapshot().ok());
7987        let generation = self
7988            .registry
7989            .generation()
7990            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?;
7991        let modules = self
7992            .supervisor
7993            .list()
7994            .into_iter()
7995            .map(|module| {
7996                let status = module.status_for_control("health").map_err(|err| {
7997                    RouterError::backend(
7998                        0,
7999                        frame.header.corr,
8000                        format!("failed to read supervisor health: {err}"),
8001                    )
8002                })?;
8003                let module_id = status.module_id;
8004                let capability_detail = self
8005                    .capability_evaluator
8006                    .required_problem_detail(&module_id);
8007                let declaration_warning = self.registry.get_module(&module_id).ok().flatten()
8008                    .filter(|registration| registration.manifest.registration_channel == Some(false))
8009                    .filter(|_| publication.as_ref().and_then(|view| view.registration_declaration(&module_id))
8010                        .as_deref().map(|next| if status.process_alive { status.registration_declaration.as_deref().unwrap_or(next) } else { next }) == Some("declared"))
8011                    .map(|_| format!("{module_id}: HELLO registration_channel is false despite the approved channel declaration"));
8012                let capability_detail = append_capability_problem_detail(capability_detail, declaration_warning);
8013                Ok(SupervisorHealthEntry {
8014                    module_id,
8015                    status: status.health.status,
8016                    detail: append_capability_problem_detail(
8017                        status.health.detail,
8018                        capability_detail,
8019                    ),
8020                    metrics: status.health.metrics,
8021                    consecutive_failures: status.health.consecutive_failures,
8022                    late_answer_count: status.health.late_answer_count,
8023                    last_late_answer_latency_ms: status.health.last_late_answer_latency_ms,
8024                    last_action: status.health.last_action,
8025                    last_action_ms: status.health.last_action_ms,
8026                    last_probe_ms: status.health.last_probe_ms,
8027                })
8028            })
8029            .collect::<Result<Vec<_>, RouterError>>()?;
8030        let response = ClientControlResponse::SupervisorHealth {
8031            generation,
8032            modules,
8033        };
8034        Ok(vec![control_response_body_frame(
8035            &frame,
8036            &response,
8037            "ClientControlResponse::SupervisorHealth",
8038        )?])
8039    }
8040
8041    async fn handle_supervisor_restart(
8042        &self,
8043        frame: Frame,
8044        module_id: String,
8045        drain_timeout_ms: Option<u64>,
8046        requester: Principal,
8047    ) -> Result<Vec<Frame>, RouterError> {
8048        let operation_lock = self.supervisor.operation_lock();
8049        let _operation_guard = operation_lock.lock().await;
8050        let Some(module) = self.supervisor.get(&module_id) else {
8051            return Ok(vec![control_error_frame(
8052                &frame,
8053                "unknown_module",
8054                format!("module_id '{module_id}' is not supervised"),
8055            )?]);
8056        };
8057
8058        self.route_outages.mark_operator_action(&module_id);
8059        if let Err(err) = module
8060            .restart_requested(drain_timeout_ms, Some(requester))
8061            .await
8062        {
8063            self.route_outages
8064                .operator_action_ended_unrefused(&module_id);
8065            let (code, message) = match err {
8066                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8067                crate::supervise::SuperviseError::Disabled { .. } => {
8068                    ("module_disabled", err.to_string())
8069                }
8070                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8071                    ("swap_in_progress", err.to_string())
8072                }
8073                _ => (
8074                    "target_unavailable",
8075                    format!("failed to restart module_id '{module_id}': {err}"),
8076                ),
8077            };
8078            return Ok(vec![control_error_frame(&frame, code, message)?]);
8079        }
8080
8081        let response = ClientControlResponse::SupervisorAck {
8082            module_id,
8083            applied: true,
8084        };
8085        Ok(vec![control_response_body_frame(
8086            &frame,
8087            &response,
8088            "ClientControlResponse::SupervisorAck",
8089        )?])
8090    }
8091
8092    /// `supervisor.swap`. Answered when the swap has cut over or failed, not
8093    /// when the old process has finished draining: a caller whose own lane
8094    /// rides the old process must get its reply before that drain waits on it.
8095    async fn handle_supervisor_swap(
8096        &self,
8097        frame: Frame,
8098        module_id: String,
8099        ready_timeout_ms: Option<u64>,
8100        requester: Principal,
8101    ) -> Result<Vec<Frame>, RouterError> {
8102        // The daemon-wide operation lock is held only to resolve the handle,
8103        // not across the swap. The swap can take its whole readiness budget,
8104        // and `supervisor.set_enabled` (ck module stop) takes the same lock:
8105        // holding it here would park an operator's stop behind the swap it is
8106        // meant to abort. A rescan or stop that reaches the module during the
8107        // swap is served by the swap itself (see `supervise_swap`).
8108        let module = {
8109            let operation_lock = self.supervisor.operation_lock();
8110            let _operation_guard = operation_lock.lock().await;
8111            self.supervisor.get(&module_id)
8112        };
8113        let Some(module) = module else {
8114            return Ok(vec![control_error_frame(
8115                &frame,
8116                "unknown_module",
8117                format!("module_id '{module_id}' is not supervised"),
8118            )?]);
8119        };
8120
8121        self.route_outages.mark_operator_action(&module_id);
8122        if let Err(err) = module
8123            .swap_requested(ready_timeout_ms.map(Duration::from_millis), Some(requester))
8124            .await
8125        {
8126            self.route_outages
8127                .operator_action_ended_unrefused(&module_id);
8128            use crate::supervise::SuperviseError;
8129            let message = err.to_string();
8130            let error = match err {
8131                SuperviseError::ConfigHeld { .. } => ErrorBody::new("config_gated", message),
8132                SuperviseError::Disabled { .. } => ErrorBody::new("module_disabled", message),
8133                SuperviseError::SwapRefused { reason, .. } => ErrorBody {
8134                    code: "swap_refused".to_string(),
8135                    message,
8136                    detail: Some(serde_json::json!({ "reason": reason.as_str() })),
8137                },
8138                SuperviseError::SwapFailed {
8139                    arm,
8140                    candidate_exit,
8141                    ..
8142                } => ErrorBody {
8143                    code: "swap_failed".to_string(),
8144                    message,
8145                    detail: Some(serde_json::json!({
8146                        "arm": arm.as_str(),
8147                        "candidate_exit_code": candidate_exit.as_ref().and_then(|exit| exit.code),
8148                        "candidate_exit_signal": candidate_exit.as_ref().and_then(|exit| exit.signal),
8149                    })),
8150                },
8151                _ => ErrorBody::new(
8152                    "target_unavailable",
8153                    format!("failed to swap module_id '{module_id}': {message}"),
8154                ),
8155            };
8156            return Ok(vec![control_error_body_frame(&frame, error)?]);
8157        }
8158        // A completed swap kept the incumbent serving until cutover, so it
8159        // usually opened no outage; a mark left behind would make the next,
8160        // unrelated outage read as requested.
8161        self.route_outages
8162            .operator_action_ended_unrefused(&module_id);
8163
8164        let response = ClientControlResponse::SupervisorAck {
8165            module_id,
8166            applied: true,
8167        };
8168        Ok(vec![control_response_body_frame(
8169            &frame,
8170            &response,
8171            "ClientControlResponse::SupervisorAck",
8172        )?])
8173    }
8174
8175    async fn handle_supervisor_reload(
8176        &self,
8177        frame: Frame,
8178        module_id: String,
8179        requester: Principal,
8180    ) -> Result<Vec<Frame>, RouterError> {
8181        let operation_lock = self.supervisor.operation_lock();
8182        let _operation_guard = operation_lock.lock().await;
8183        let Some(module) = self.supervisor.get(&module_id) else {
8184            return Ok(vec![control_error_frame(
8185                &frame,
8186                "unknown_module",
8187                format!("module_id '{module_id}' is not supervised"),
8188            )?]);
8189        };
8190
8191        self.route_outages.mark_operator_action(&module_id);
8192        if let Err(err) = module.reload_requested(Some(requester)).await {
8193            self.route_outages
8194                .operator_action_ended_unrefused(&module_id);
8195            let (code, message) = match err {
8196                _ if err.is_config_gate_error() => ("config_gated", err.to_string()),
8197                crate::supervise::SuperviseError::Disabled { .. } => {
8198                    ("module_disabled", err.to_string())
8199                }
8200                crate::supervise::SuperviseError::SwapInProgress { .. } => {
8201                    ("swap_in_progress", err.to_string())
8202                }
8203                _ => (
8204                    "reload_failed",
8205                    format!("failed to reload module_id '{module_id}': {err}"),
8206                ),
8207            };
8208            return Ok(vec![control_error_frame(&frame, code, message)?]);
8209        }
8210
8211        let response = ClientControlResponse::SupervisorAck {
8212            module_id,
8213            applied: true,
8214        };
8215        Ok(vec![control_response_body_frame(
8216            &frame,
8217            &response,
8218            "ClientControlResponse::SupervisorAck",
8219        )?])
8220    }
8221
8222    /// `supervisor.rescan` and `supervisor.rescan_checked`. `mode` says where
8223    /// the configuration comes from and whether to apply it; every mode then
8224    /// runs the same comparison, so a preview describes the apply it previews.
8225    async fn handle_supervisor_rescan(
8226        &self,
8227        frame: Frame,
8228        mode: RescanMode,
8229        requester: Principal,
8230    ) -> Result<Vec<Frame>, RouterError> {
8231        let preview = mode.previews();
8232        let Some(context) = self.rescan.clone() else {
8233            return Ok(vec![control_error_frame(
8234                &frame,
8235                "rescan_unavailable",
8236                "the daemon was not started with a reloadable config path".to_string(),
8237            )?]);
8238        };
8239
8240        let _rescan_guard = context.rescan_lock.lock().await;
8241        let rescan_checked::RescanInput {
8242            config: loaded,
8243            approved_preview,
8244            guard: _operation_guard,
8245        } = match self.rescan_input(&mode, &context).await {
8246            Ok(input) => input,
8247            Err(error) => return Ok(vec![error.into_frame(&frame)?]),
8248        };
8249        // `load` reports a missing file as Ok(None), which is correct at boot
8250        // (no config, nothing to supervise) and catastrophic here: rescan treats
8251        // "not in the config" as "remove it", so an absent file would read as an
8252        // empty module list and retire the entire running fleet. An editor
8253        // writing via write-new-then-rename, or a half-finished edit, is enough
8254        // to open that window. Refuse instead: a config that cannot be read
8255        // carries no instruction to remove anything.
8256        let Some((config, activity_config)) = loaded else {
8257            return Ok(vec![control_error_frame(
8258                &frame,
8259                "invalid_daemon_config",
8260                format!(
8261                    "daemon config not found at {}; refusing to rescan (an absent config would \
8262                     retire every supervised module)",
8263                    context.config_path.display()
8264                ),
8265            )?]);
8266        };
8267        let (
8268            configured_port,
8269            storage_config,
8270            admission_facts_carrier_module_id,
8271            admission_facts_targets,
8272            scope_authority_owners,
8273            federated_scope_owner,
8274            privileged_operator_prompt,
8275            modules,
8276            reserved_capabilities,
8277        ) = (
8278            config.port,
8279            config.storage,
8280            config.admission_facts_carrier_module_id,
8281            config.admission_facts_targets,
8282            config.scope_authority_owners,
8283            config.federated_scope_owner,
8284            config.privileged_operator_prompt,
8285            config.modules,
8286            config.reserved_capabilities,
8287        );
8288
8289        // Collect the sections rescan cannot apply, so the REPLY carries them.
8290        //
8291        // The warning below has always been correct and has always gone only to
8292        // the journal -- addressed to whoever reads logs, while the person who
8293        // just edited the config is looking at the CLI. Naming each section
8294        // individually rather than setting a flag: "something outside modules
8295        // changed" sends the operator back to diffing their own file, which is
8296        // the work this is meant to save.
8297        let mut restart_required = Vec::new();
8298        for section in RestartRequiredSection::ALL {
8299            let changed = match section {
8300                RestartRequiredSection::Port => configured_port != context.configured_port,
8301                RestartRequiredSection::Storage => storage_config != context.storage_config,
8302                RestartRequiredSection::AdmissionFactsCarrierModuleId => {
8303                    admission_facts_carrier_module_id != context.admission_facts_carrier_module_id
8304                }
8305                RestartRequiredSection::AdmissionFactsTargets => {
8306                    admission_facts_targets != context.admission_facts_targets
8307                }
8308                RestartRequiredSection::ScopeAuthorityOwners => {
8309                    scope_authority_owners != context.scope_authority_owners
8310                }
8311                RestartRequiredSection::FederatedScopeOwner => {
8312                    federated_scope_owner != context.federated_scope_owner
8313                }
8314                RestartRequiredSection::PrivilegedOperatorPrompt => {
8315                    privileged_operator_prompt != context.privileged_operator_prompt
8316                }
8317            };
8318            if changed {
8319                restart_required.push(section.label().to_string());
8320            }
8321        }
8322        if !restart_required.is_empty() {
8323            warn!(
8324                config_path = %context.config_path.display(),
8325                sections = %restart_required.join(", "),
8326                "daemon config changed outside the modules section; restart the daemon to apply those changes"
8327            );
8328        }
8329
8330        for configured in &modules {
8331            if let Err(err) = validate_spec(&configured.module_spec()) {
8332                return Ok(vec![control_error_frame(
8333                    &frame,
8334                    "invalid_daemon_config",
8335                    format!("supervisor rescan rejected daemon config: {err}"),
8336                )?]);
8337            }
8338        }
8339
8340        let configured_capabilities = modules
8341            .iter()
8342            .map(|module| (module.module_id.clone(), module.enabled))
8343            .collect::<Vec<_>>();
8344        let preview_capability_warnings = if preview {
8345            let (_, registrations) = self.runtime_capability_snapshot()?;
8346            let current_modules = self
8347                .supervisor
8348                .list()
8349                .into_iter()
8350                .map(|module| module.module_id().to_string())
8351                .collect::<BTreeSet<_>>();
8352            let resulting_modules = configured_capabilities.clone();
8353            let removed = current_modules
8354                .into_iter()
8355                .filter(|module_id| {
8356                    !resulting_modules
8357                        .iter()
8358                        .any(|(configured_id, _)| configured_id == module_id)
8359                })
8360                .collect::<Vec<_>>();
8361            // A candidate preview also names providers the candidate disables.
8362            // `supervisor.rescan`'s own preview keeps its removal-only warnings.
8363            let disabled = match &mode {
8364                RescanMode::Candidate(_) => resulting_modules
8365                    .iter()
8366                    .filter(|(_, enabled)| !enabled)
8367                    .map(|(module_id, _)| module_id.clone())
8368                    .collect::<Vec<_>>(),
8369                _ => Vec::new(),
8370            };
8371            self.capability_evaluator.preview_warnings(
8372                resulting_modules,
8373                &removed,
8374                &disabled,
8375                &registrations,
8376            )
8377        } else {
8378            Vec::new()
8379        };
8380        let reconciled = match (&mode, approved_preview.as_ref()) {
8381            (RescanMode::Preview, Some(approved)) => Ok((
8382                config_gate::preview_approved_daemon(approved, &modules),
8383                Vec::new(),
8384            )),
8385            (RescanMode::Candidate(candidate), _) => self
8386                .preview_candidate(&context, modules, candidate)
8387                .map(|result| (result, Vec::new())),
8388            _ => {
8389                self.reconcile_supervised_modules(
8390                    &context.supervisor,
8391                    modules,
8392                    preview,
8393                    requester.clone(),
8394                )
8395                .await
8396            }
8397        };
8398        let (result, changed) = match reconciled {
8399            Ok(result) => result,
8400            Err(message) => {
8401                return Ok(vec![control_error_frame(&frame, "rescan_failed", message)?])
8402            }
8403        };
8404        if !preview {
8405            self.rescan_policy_root(config.agent_policy_root).await;
8406            if let Some(ledger) = &self.activity {
8407                ledger.module_rescanned(&result.added, &result.removed, requester.clone());
8408                ledger.config_changed(&result.added, &result.removed, &changed, requester);
8409            }
8410            if let Err(code) = self.configure_activity(activity_config).await {
8411                warn!(
8412                    code,
8413                    "activity retention could not be applied during rescan"
8414                );
8415            }
8416            self.capability_evaluator
8417                .configure(configured_capabilities, reserved_capabilities);
8418            self.capability_evaluator.wake_deadline_loop();
8419            self.refresh_capability_requirements();
8420        }
8421        let mut result = result;
8422        result.restart_required = restart_required;
8423        result.capability_warnings = preview_capability_warnings;
8424        let response = ClientControlResponse::SupervisorRescan { result };
8425        Ok(vec![control_response_body_frame(
8426            &frame,
8427            &response,
8428            "ClientControlResponse::SupervisorRescan",
8429        )?])
8430    }
8431
8432    async fn handle_supervisor_release_reserved(
8433        &self,
8434        frame: Frame,
8435        module_id: String,
8436    ) -> Result<Vec<Frame>, RouterError> {
8437        let Some(context) = self.rescan.clone() else {
8438            return Ok(vec![control_error_frame(
8439                &frame,
8440                "release_unavailable",
8441                "reserved-id release requires a daemon started with a reloadable config path",
8442            )?]);
8443        };
8444        let operation_lock = self.supervisor.operation_lock();
8445        let _operation_guard = operation_lock.lock().await;
8446        let approved = if let Some(owner) = &self.config_runtime {
8447            // Observe the file as a proposal, but decide membership solely from
8448            // approved bytes. A proposed re-add must not retain a removed id.
8449            match owner
8450                .on_blocking(|owner| {
8451                    owner.observe_file_proposal()?;
8452                    owner.approved_daemon_configuration()
8453                })
8454                .await
8455            {
8456                Ok(config) => config,
8457                Err(error) => return Ok(vec![config_gate::config_error_frame(&frame, error)?]),
8458            }
8459        } else {
8460            None
8461        };
8462        let loaded = if let Some(approved) = approved {
8463            Ok(Some(approved))
8464        } else {
8465            crate::daemon_config::load(&context.config_path)
8466        };
8467        let loaded = match loaded {
8468            Ok(Some(config)) => config,
8469            Ok(None) => {
8470                return Ok(vec![control_error_frame(
8471                    &frame,
8472                    "invalid_daemon_config",
8473                    format!(
8474                        "daemon config not found at {}; refusing to release reserved module_id '{module_id}'",
8475                        context.config_path.display()
8476                    ),
8477                )?])
8478            }
8479            Err(err) => {
8480                return Ok(vec![control_error_frame(
8481                    &frame,
8482                    "invalid_daemon_config",
8483                    format!("unable to verify reserved-id release against daemon config: {err}"),
8484                )?])
8485            }
8486        };
8487        if loaded
8488            .modules
8489            .iter()
8490            .any(|configured| configured.module_id == module_id)
8491        {
8492            return Ok(vec![control_error_frame(
8493                &frame,
8494                "reserved_module_configured",
8495                format!(
8496                    "module_id '{module_id}' remains configured; remove its config entry and rescan before releasing its reserved id"
8497                ),
8498            )?]);
8499        }
8500        if !self.supervisor.release_retained_reserved_gate(&module_id) {
8501            return Ok(vec![control_error_frame(
8502                &frame,
8503                "reserved_gate_not_retained",
8504                format!(
8505                    "module_id '{module_id}' has no retired reserved-id gate to release; rescan its removed reserved configuration first"
8506                ),
8507            )?]);
8508        }
8509
8510        let response = ClientControlResponse::SupervisorAck {
8511            module_id,
8512            applied: true,
8513        };
8514        Ok(vec![control_response_body_frame(
8515            &frame,
8516            &response,
8517            "ClientControlResponse::SupervisorAck",
8518        )?])
8519    }
8520
8521    /// Compare the configured module set with the supervised one, changing
8522    /// nothing. The staged spec each supervised module holds is what the
8523    /// configured entry is compared with.
8524    fn plan_rescan(
8525        &self,
8526        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8527    ) -> Result<RescanPlan, String> {
8528        let mut current = BTreeMap::new();
8529        for module in self.supervisor.list() {
8530            let (spec, health) = module.configuration().map_err(|err| {
8531                format!(
8532                    "failed to read configuration for module_id '{}': {err}",
8533                    module.module_id()
8534                )
8535            })?;
8536            let enabled = module
8537                .status()
8538                .map_err(|err| {
8539                    format!(
8540                        "failed to read status for module_id '{}': {err}",
8541                        module.module_id()
8542                    )
8543                })?
8544                .enabled;
8545            current.insert(
8546                module.module_id().to_string(),
8547                (module, spec, health, enabled),
8548            );
8549        }
8550        let configured = configured_modules
8551            .into_iter()
8552            .map(|module| (module.module_id.clone(), module))
8553            .collect::<BTreeMap<_, _>>();
8554
8555        let added = configured
8556            .keys()
8557            .filter(|module_id| !current.contains_key(*module_id))
8558            .cloned()
8559            .collect::<Vec<_>>();
8560        let removed = current
8561            .keys()
8562            .filter(|module_id| !configured.contains_key(*module_id))
8563            .cloned()
8564            .collect::<Vec<_>>();
8565        let mut changed_pending_reload = Vec::new();
8566        let mut changed_pending = Vec::new();
8567        let mut configuration_changes = BTreeSet::new();
8568        let mut enabled_changes = BTreeSet::new();
8569        let mut unchanged = 0_u32;
8570        let publication = self
8571            .config_runtime
8572            .as_ref()
8573            .and_then(|owner| owner.polled_snapshot().ok());
8574
8575        for (module_id, configured_module) in &configured {
8576            let Some((module, current_spec, current_health, current_enabled)) =
8577                current.get(module_id)
8578            else {
8579                continue;
8580            };
8581            // Compare the whole launch spec so a future launch field cannot
8582            // accidentally become a live-only policy change. Health is stored
8583            // separately and applies live without replacing the process.
8584            let launch_changed = *current_spec != configured_module.module_spec();
8585            let configuration_changed =
8586                launch_changed || *current_health != configured_module.health;
8587            let pending = self.pending_module_fields(
8588                module,
8589                Some(configured_module),
8590                configuration_changed,
8591                Self::registration_channel_in_force(
8592                    publication
8593                        .as_ref()
8594                        .and_then(|view| view.registration_declaration(module_id))
8595                        .as_deref(),
8596                    publication
8597                        .as_ref()
8598                        .and_then(|view| match &view.approved_daemon {
8599                            crate::config_gate::runtime::ApprovedDaemonView::Approved {
8600                                config,
8601                                ..
8602                            } => config
8603                                .modules
8604                                .iter()
8605                                .find(|entry| entry.module_id == *module_id)
8606                                .map(|entry| entry.registration_channel),
8607                            _ => None,
8608                        }),
8609                ),
8610                publication.as_deref(),
8611            )?;
8612            let has_pending = !pending.is_empty();
8613            if has_pending {
8614                changed_pending.push(subc_control::SupervisorPendingModule {
8615                    module_id: module_id.clone(),
8616                    fields: pending
8617                        .into_iter()
8618                        .map(|mut field| {
8619                            field.value = None;
8620                            field
8621                        })
8622                        .collect(),
8623                });
8624            }
8625            // Applying a rescan also replaces the recorded config value, even
8626            // when an operator already put the runtime in the requested state.
8627            let enabled_changed = *current_enabled != configured_module.enabled
8628                || self
8629                    .capability_evaluator
8630                    .configured_enabled(module_id)
8631                    .is_some_and(|enabled| enabled != configured_module.enabled);
8632            if configuration_changed {
8633                configuration_changes.insert(module_id.clone());
8634            }
8635            if launch_changed {
8636                changed_pending_reload.push(module_id.clone());
8637            }
8638            if enabled_changed {
8639                enabled_changes.insert(module_id.clone());
8640            }
8641            if !configuration_changed && !enabled_changed && !has_pending {
8642                unchanged = unchanged.saturating_add(1);
8643            }
8644        }
8645        Ok(RescanPlan {
8646            current,
8647            configured,
8648            added,
8649            removed,
8650            changed_pending_reload,
8651            changed_pending,
8652            configuration_changes,
8653            enabled_changes,
8654            unchanged,
8655        })
8656    }
8657
8658    /// Reconcile the running module set against the configured one.
8659    ///
8660    /// With `preview` set, the diff is computed and returned WITHOUT applying any
8661    /// of it: nothing is retired, reconfigured, enabled or spawned. The preview
8662    /// deliberately shares this function with the executing path rather than
8663    /// computing the same diff somewhere else -- two implementations of one
8664    /// decision agree until they do not, and the whole value of a preview is that
8665    /// it describes the operation that will actually run.
8666    async fn reconcile_supervised_modules(
8667        &self,
8668        supervisor: &Supervisor,
8669        configured_modules: Vec<crate::daemon_config::ConfiguredModule>,
8670        preview: bool,
8671        requester: Principal,
8672    ) -> Result<(SupervisorRescanResult, Vec<String>), String> {
8673        let plan = self.plan_rescan(configured_modules)?;
8674
8675        // Everything above this point is pure computation over two snapshots.
8676        // Everything below MUTATES. The preview returns here so the boundary is a
8677        // single early return rather than a condition repeated at each mutation
8678        // site, where one missed guard would apply part of a change the caller was
8679        // told would not happen.
8680        if preview {
8681            return Ok((plan.preview_result(), Vec::new()));
8682        }
8683        let changed = plan
8684            .configuration_changes
8685            .union(&plan.enabled_changes)
8686            .cloned()
8687            .collect::<Vec<_>>();
8688        let RescanPlan {
8689            current,
8690            configured,
8691            added,
8692            removed,
8693            changed_pending_reload,
8694            changed_pending,
8695            configuration_changes,
8696            enabled_changes,
8697            unchanged,
8698        } = plan;
8699        // The staged generation moves before the first change rather than
8700        // after the last, so a rescan that fails partway still invalidates
8701        // every earlier `supervisor.rescan_checked` preview: part of its diff
8702        // may have run.
8703        if !(added.is_empty()
8704            && removed.is_empty()
8705            && configuration_changes.is_empty()
8706            && changed_pending.is_empty()
8707            && enabled_changes.is_empty())
8708        {
8709            if let Some(context) = &self.rescan {
8710                context
8711                    .generation
8712                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8713            }
8714        }
8715
8716        for module_id in &removed {
8717            let module = &current
8718                .get(module_id)
8719                .expect("removed module came from current supervisor state")
8720                .0;
8721            module
8722                .retire_requested(Some(requester.clone()))
8723                .await
8724                .map_err(|err| {
8725                    format!("failed to retire module_id '{module_id}' during rescan: {err}")
8726                })?;
8727            // TOMBSTONE BEFORE RETIRE, and the order is the whole fix.
8728            //
8729            // `handle_route_open` resolves an absent module in three steps:
8730            // registry, then supervisor status, then tombstone. Retiring first
8731            // opens a window where ALL THREE ARE ABSENT -- the registry entry
8732            // went with the teardown above, the supervisor entry went with
8733            // `retire`, and the tombstone does not exist yet -- so a route.open
8734            // landing in it gets `unknown_module` (RETRYABLE, "never heard of
8735            // it") for a module that was deliberately removed and whose caller
8736            // should get `module_removed` (TERMINAL, carrying a removal age).
8737            //
8738            // Writing the tombstone first closes it: during the window the
8739            // supervisor entry still answers, so the caller gets
8740            // `target_unavailable` -- retryable, and TRUE, because the module
8741            // is mid-teardown. After both statements it is `module_removed`.
8742            // No instant remains where a removed module reads as one that
8743            // never existed.
8744            //
8745            // NOT DETERMINISTICALLY TESTABLE FROM HERE, said plainly because
8746            // the absence of a test beside a fix invites deletion: these are
8747            // two sync statements with no await between them, so reaching the
8748            // window needs a second worker thread to land exactly between them
8749            // and there is no hook to force it. MEASURED: the 25 daemon_config
8750            // tests pass identically with the old order and the new one, so
8751            // the existing suite cannot see this and a green run is not
8752            // evidence either way. What the suite does hold is the
8753            // post-condition -- a removed module answers `module_removed` --
8754            // which this preserves.
8755            //
8756            // Found by an Athena panel reading the shipped tree against a
8757            // design note (2026-09-19), as the one concrete instance of that
8758            // note's class that survived contact with source. Direction is
8759            // benign: retryable where terminal was intended, never the reverse.
8760            self.supervisor.record_rescan_removal(module_id);
8761            self.supervisor.retire(module_id);
8762            self.route_outages.forget(module_id);
8763        }
8764
8765        for module_id in configured.keys() {
8766            let Some((module, _, _, current_enabled)) = current.get(module_id) else {
8767                continue;
8768            };
8769            let configured_module = configured
8770                .get(module_id)
8771                .expect("configured module id came from configured map");
8772            if configuration_changes.contains(module_id) {
8773                module
8774                    .update_configuration(
8775                        configured_module.module_spec(),
8776                        configured_module.health.clone(),
8777                        configured_module.drain_timeout_ms,
8778                    )
8779                    .await
8780                    .map_err(|err| {
8781                        format!(
8782                            "failed to update module_id '{module_id}' configuration during rescan: {err}"
8783                        )
8784                    })?;
8785            }
8786            // Config-only drift is applied by the evaluator's config update;
8787            // do not turn it into a runtime start or stop.
8788            if *current_enabled != configured_module.enabled {
8789                // A rescan that starts or stops a module applies an operator's
8790                // edit to the config, so the resulting outage was asked for.
8791                self.route_outages.mark_operator_action(module_id);
8792                module
8793                    .set_enabled_requested(configured_module.enabled, Some(requester.clone()))
8794                    .await
8795                    .map_err(|err| {
8796                        self.route_outages.operator_action_ended_unrefused(module_id);
8797                        format!(
8798                            "failed to apply module_id '{module_id}' enabled={} during rescan: {err}",
8799                            configured_module.enabled
8800                        )
8801                    })?;
8802            }
8803        }
8804
8805        for module_id in &added {
8806            let configured_module = configured
8807                .get(module_id)
8808                .expect("added module id came from configured map");
8809            supervisor
8810                .supervise_configured_requested_async(
8811                    configured_module.module_spec(),
8812                    configured_module.enabled,
8813                    configured_module.health.clone(),
8814                    configured_module.drain_timeout_ms,
8815                    configured_module.restart,
8816                    configured_module.register_timeout,
8817                    Some(requester.clone()),
8818                )
8819                .await
8820                .map_err(|err| {
8821                    format!("failed to add module_id '{module_id}' during rescan: {err}")
8822                })?;
8823        }
8824
8825        if let Some(context) = &self.rescan {
8826            let mut entries = context
8827                .module_entries
8828                .lock()
8829                .unwrap_or_else(|e| e.into_inner());
8830            entries.record(&configured, &added, &removed);
8831        }
8832
8833        Ok((
8834            SupervisorRescanResult {
8835                added,
8836                removed,
8837                changed_pending_reload,
8838                changed_pending,
8839                enabled_changes: enabled_changes.iter().cloned().collect(),
8840                unchanged,
8841                preview: false,
8842                // Filled by the caller, which is the only layer that can see the
8843                // previous config to diff against.
8844                restart_required: Vec::new(),
8845                capability_warnings: Vec::new(),
8846                module_actions: Vec::new(),
8847                earlier_pending: Vec::new(),
8848                expect: None,
8849            },
8850            changed,
8851        ))
8852    }
8853
8854    async fn handle_supervisor_set_enabled(
8855        &self,
8856        frame: Frame,
8857        module_id: String,
8858        enabled: bool,
8859        requester: Principal,
8860    ) -> Result<Vec<Frame>, RouterError> {
8861        let operation_lock = self.supervisor.operation_lock();
8862        let _operation_guard = operation_lock.lock().await;
8863        let Some(module) = self.supervisor.get(&module_id) else {
8864            return Ok(vec![control_error_frame(
8865                &frame,
8866                "unknown_module",
8867                format!("module_id '{module_id}' is not supervised"),
8868            )?]);
8869        };
8870
8871        // Enabling counts as well as disabling: a module an operator starts
8872        // is refused until it registers, and that wait was asked for.
8873        self.route_outages.mark_operator_action(&module_id);
8874        let applied = match module.set_enabled_requested(enabled, Some(requester)).await {
8875            Ok(applied) => applied,
8876            Err(err) => {
8877                self.route_outages
8878                    .operator_action_ended_unrefused(&module_id);
8879                return Ok(vec![control_error_frame(
8880                    &frame,
8881                    if err.is_config_gate_error() {
8882                        "config_gated"
8883                    } else {
8884                        "target_unavailable"
8885                    },
8886                    format!("failed to set module_id '{module_id}' enabled={enabled}: {err}"),
8887                )?]);
8888            }
8889        };
8890        if !applied {
8891            // Already in the requested state: nothing was made unavailable,
8892            // so the mark must not outlive this request.
8893            self.route_outages
8894                .operator_action_ended_unrefused(&module_id);
8895        }
8896
8897        self.capability_evaluator.wake_deadline_loop();
8898        self.refresh_capability_requirements();
8899        let response = ClientControlResponse::SupervisorAck { module_id, applied };
8900        Ok(vec![control_response_body_frame(
8901            &frame,
8902            &response,
8903            "ClientControlResponse::SupervisorAck",
8904        )?])
8905    }
8906
8907    async fn handle_supervisor_health_probe(
8908        &self,
8909        ctx: &RouteCtx,
8910        frame: Frame,
8911        module_id: String,
8912    ) -> Result<Vec<Frame>, RouterError> {
8913        self.refresh_capability_requirements();
8914        let Some(registration) = self
8915            .registry
8916            .get_module(&module_id)
8917            .map_err(|err| RouterError::backend(0, frame.header.corr, err.to_string()))?
8918        else {
8919            return Ok(vec![control_error_frame(
8920                &frame,
8921                "unknown_module",
8922                format!("module_id '{module_id}' is not registered"),
8923            )?]);
8924        };
8925
8926        // This guard's ACCEPT direction is fenced, but only INCIDENTALLY: no test is
8927        // named for it. Making `module_registration_grants_op` return false
8928        // unconditionally reddens five tests, and every one is named for something
8929        // else -- capability relay, probe/bind demultiplexing, supervision-only
8930        // probing. They exercise a successful advertisement check on the way to their
8931        // own subject.
8932        //
8933        // Real protection, fragile in a specific way: narrowing any of those tests to
8934        // focus on its stated subject would silently remove coverage nobody knows
8935        // they are carrying. Recorded here rather than as a sixth test, because the
8936        // useful fact is WHICH tests hold the guard up -- a new test would add
8937        // coverage without telling the next person what the existing ones quietly do.
8938        if !module_registration_grants_op(&registration.control_ops, MODULE_CONTROL_OP_HEALTH_CHECK)
8939        {
8940            return Ok(vec![control_error_frame(
8941                &frame,
8942                "health_not_advertised",
8943                format!("module_id '{module_id}' did not advertise health.check"),
8944            )?]);
8945        }
8946
8947        self.observe_control_wait(
8948            ctx,
8949            Some(&registration.manifest.module_id),
8950            ops::SUPERVISOR_HEALTH_PROBE,
8951            async {
8952                let deadline = Instant::now() + self.health_probe_timeout;
8953                let pending = match self.forwarding.begin_module_control_rpc_for(
8954                    &module_id,
8955                    MODULE_CONTROL_OP_HEALTH_CHECK,
8956                    deadline,
8957                ) {
8958                    Ok(pending) => pending,
8959                    Err(err) => {
8960                        return Ok(vec![control_error_frame(
8961                            &frame,
8962                            forwarding_error_code(&err),
8963                            err.to_string(),
8964                        )?])
8965                    }
8966                };
8967
8968                let PendingModuleControlRpc {
8969                    endpoint,
8970                    module_sink,
8971                    negotiated_ver,
8972                    corr: probe_corr,
8973                    receiver,
8974                } = pending;
8975                let mut guard =
8976                    ModuleControlRpcGuard::new(Arc::clone(&self.forwarding), endpoint, probe_corr);
8977                let probe_body = serde_json::to_vec(&ModuleControlRequest::HealthCheck {})
8978                    .map_err(|err| {
8979                        RouterError::backend(
8980                            0,
8981                            frame.header.corr,
8982                            format!("failed to encode health.check request: {err}"),
8983                        )
8984                    })?;
8985                let probe_frame = Frame::build_with_version(
8986                    negotiated_ver,
8987                    FrameType::Request,
8988                    control_flags(),
8989                    0,
8990                    0,
8991                    probe_corr,
8992                    probe_body,
8993                )
8994                .map_err(RouterError::FrameBuild)?;
8995
8996                // Queue admission and the reply share one deadline, so a module that
8997                // stops reading cannot park the requesting connection's reader forever.
8998                match timeout_at(deadline, module_sink.send(probe_frame)).await {
8999                    Ok(Ok(())) => {}
9000                    Ok(Err(err)) => {
9001                        return Ok(vec![control_error_frame(
9002                            &frame,
9003                            "target_unavailable",
9004                            err.to_string(),
9005                        )?]);
9006                    }
9007                    Err(_) => {
9008                        return Ok(vec![control_error_frame(
9009                            &frame,
9010                            "module_timeout",
9011                            format!(
9012                                "module_id '{module_id}' did not answer health.check within {:?}",
9013                                self.health_probe_timeout
9014                            ),
9015                        )?]);
9016                    }
9017                }
9018
9019                match timeout_at(deadline, receiver).await {
9020                    Ok(Ok(ModuleControlRpcOutcome::RawResponse(_))) => {
9021                        Ok(vec![control_error_frame(
9022                            &frame,
9023                            "invalid_control_body",
9024                            "health.check returned an unexpected config response",
9025                        )?])
9026                    }
9027                    Ok(Ok(ModuleControlRpcOutcome::Response(response))) => {
9028                        guard.disarm();
9029                        let Some(report) = response.health_report() else {
9030                            return Ok(vec![control_error_frame(
9031                                &frame,
9032                                "invalid_control_body",
9033                                "health.check RPC returned a non-health response",
9034                            )?]);
9035                        };
9036                        // Metrics go out whole here. The supervisor's cached snapshot
9037                        // caps this blob (see truncate_health_metrics), and this path
9038                        // exists precisely to answer without that cap -- so applying it
9039                        // here would leave no way to see what the cached view drops.
9040                        let HealthReport {
9041                            status,
9042                            detail,
9043                            metrics,
9044                        } = report;
9045                        let capability_detail = self
9046                            .capability_evaluator
9047                            .required_problem_detail(&module_id);
9048                        let response = ClientControlResponse::SupervisorHealthProbe {
9049                            module_id,
9050                            status,
9051                            detail: append_capability_problem_detail(detail, capability_detail),
9052                            metrics,
9053                        };
9054                        Ok(vec![control_response_body_frame(
9055                            &frame,
9056                            &response,
9057                            "ClientControlResponse::SupervisorHealthProbe",
9058                        )?])
9059                    }
9060                    Ok(Ok(ModuleControlRpcOutcome::Rejected(body))) => {
9061                        guard.disarm();
9062                        // The module refused the health probe with its own body, so
9063                        // the refusal is relayed without the daemon-origin flag
9064                        // (bit 6): a client must not read it as the daemon's own
9065                        // refusal, which it may treat as never forwarded.
9066                        Ok(vec![control_relayed_error_body_frame(&frame, body)?])
9067                    }
9068                    Ok(Ok(ModuleControlRpcOutcome::ModuleGone(message))) => {
9069                        guard.disarm();
9070                        Ok(vec![control_error_frame(
9071                            &frame,
9072                            "target_unavailable",
9073                            message,
9074                        )?])
9075                    }
9076                    Ok(Ok(ModuleControlRpcOutcome::MalformedResponse(message))) => {
9077                        guard.disarm();
9078                        Ok(vec![control_error_frame(
9079                            &frame,
9080                            "invalid_control_body",
9081                            message,
9082                        )?])
9083                    }
9084                    Ok(Ok(ModuleControlRpcOutcome::UnexpectedOp { expected, actual })) => {
9085                        guard.disarm();
9086                        Ok(vec![control_error_frame(
9087                            &frame,
9088                            "invalid_control_body",
9089                            format!("expected module-control op '{expected}', got '{actual}'"),
9090                        )?])
9091                    }
9092                    Ok(Ok(ModuleControlRpcOutcome::DeadlineElapsed)) => {
9093                        guard.disarm();
9094                        Ok(vec![control_error_frame(
9095                            &frame,
9096                            "module_timeout",
9097                            format!(
9098                                "module_id '{module_id}' answered health.check after {:?}",
9099                                self.health_probe_timeout
9100                            ),
9101                        )?])
9102                    }
9103                    Ok(Err(_)) => Ok(vec![control_error_frame(
9104                        &frame,
9105                        "target_unavailable",
9106                        "health.check waiter was canceled before the module responded",
9107                    )?]),
9108                    Err(_) => Ok(vec![control_error_frame(
9109                        &frame,
9110                        "module_timeout",
9111                        format!(
9112                            "module_id '{module_id}' did not answer health.check within {:?}",
9113                            self.health_probe_timeout
9114                        ),
9115                    )?]),
9116                }
9117            },
9118        )
9119        .await
9120    }
9121
9122    fn supervisor_status(
9123        &self,
9124        module_id: &str,
9125        corr: u64,
9126    ) -> Result<Option<(crate::supervise::ModuleStatus, bool)>, RouterError> {
9127        self.supervisor
9128            .get(module_id)
9129            .map(|module| {
9130                let warming = module.is_warming_for_control("status").map_err(|err| {
9131                    RouterError::backend(
9132                        0,
9133                        corr,
9134                        format!(
9135                            "failed to read supervisor warming state for module_id '{module_id}': {err}"
9136                        ),
9137                    )
9138                })?;
9139                module.status_for_control("status").map_err(|err| {
9140                    RouterError::backend(
9141                        0,
9142                        corr,
9143                        format!(
9144                            "failed to read supervisor status for module_id '{module_id}': {err}"
9145                        ),
9146                    )
9147                }).map(|status| (status, warming))
9148            })
9149            .transpose()
9150    }
9151
9152    fn guard_module_control_op(
9153        &self,
9154        frame: &Frame,
9155        module_id: &str,
9156        op: &str,
9157    ) -> Result<Option<Frame>, RouterError> {
9158        if self.module_grants_op(module_id, op, frame.header.corr)? {
9159            return Ok(None);
9160        }
9161
9162        Ok(Some(control_error_frame(
9163            frame,
9164            "op_not_allowed",
9165            format!("module_id '{module_id}' did not grant control op '{op}'"),
9166        )?))
9167    }
9168
9169    fn module_grants_op(&self, module_id: &str, op: &str, corr: u64) -> Result<bool, RouterError> {
9170        self.registry
9171            .grants_control_op(module_id, op)
9172            .map_err(|err| RouterError::backend(0, corr, err.to_string()))
9173    }
9174
9175    fn handle_status_update(
9176        &self,
9177        endpoint: ModuleEndpointId,
9178        frame: Frame,
9179    ) -> Result<Vec<Frame>, RouterError> {
9180        let update = match serde_json::from_slice::<ModuleControlPush>(&frame.body) {
9181            Ok(update) => update,
9182            Err(err) => {
9183                // Forward-compat: a newer module may push a channel-0 op this subc
9184                // version doesn't know. The control contract says unknown push ops
9185                // are IGNORED, never answered with an error. Only a malformed body
9186                // for an op we DO know is a real error worth surfacing.
9187                if is_known_module_push_op(&frame.body) {
9188                    return Ok(vec![control_error_frame(
9189                        &frame,
9190                        "invalid_control_body",
9191                        format!("malformed module control push body: {err}"),
9192                    )?]);
9193                }
9194                return Ok(Vec::new());
9195            }
9196        };
9197
9198        match update {
9199            ModuleControlPush::RouteStatus {
9200                route_channel,
9201                route_epoch,
9202                status,
9203            } => {
9204                self.forwarding
9205                    .cache_status(endpoint, route_channel, route_epoch, status)
9206                    .map_err(RouterError::Forwarding)?;
9207            }
9208        }
9209        Ok(Vec::new())
9210    }
9211
9212    fn handle_route_poll(
9213        &self,
9214        ctx: &RouteCtx,
9215        frame: Frame,
9216        route_channel: u16,
9217        route_epoch: u32,
9218        kind: PollKind,
9219    ) -> Result<Vec<Frame>, RouterError> {
9220        let snapshot = self
9221            .forwarding
9222            .route_poll_snapshot(ctx.connection_id, route_channel, route_epoch)
9223            .map_err(RouterError::Forwarding)?;
9224        let response = match (kind, snapshot) {
9225            (PollKind::Status, RoutePollSnapshot::Bound { status, .. }) => {
9226                ClientControlResponse::RoutePoll {
9227                    route_channel,
9228                    route_epoch,
9229                    status,
9230                    live: None,
9231                }
9232            }
9233            (PollKind::Status, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9234                route_channel,
9235                route_epoch,
9236                status: None,
9237                live: None,
9238            },
9239            (PollKind::Liveness, RoutePollSnapshot::Bound { module_id, .. }) => {
9240                // ABSENCE HERE MEANS "NOT SUPERVISED", NOT "UNKNOWN", and that
9241                // is what makes reporting `true` correct rather than a
9242                // confident guess. `process_live` returns None only when the
9243                // module id has no supervisor snapshot at all -- an
9244                // externally-started module the daemon did not spawn -- and
9245                // for those the supervisor has no opinion to offer, ever. It
9246                // is never None for a supervised module in an unknown state:
9247                // a supervised module always has a snapshot, and the answer
9248                // comes from `state == Running && process_alive`.
9249                //
9250                // The route is Bound, so the module completed a HELLO on a
9251                // live connection; "the process this route points at is
9252                // running" is therefore attested by the binding rather than
9253                // assumed. Reporting `false` for an unsupervised module would
9254                // be the actual lie -- it would tell a client its healthy
9255                // route is dead because the daemon does not manage the
9256                // process.
9257                //
9258                // IF `process_live` EVER GAINS A THIRD CASE -- a supervised
9259                // module whose liveness is genuinely unknown, e.g. a snapshot
9260                // that has not been populated yet -- THIS DEFAULT BECOMES
9261                // WRONG and must split: unsupervised stays true, unknown
9262                // becomes null so the client can tell the two apart. The
9263                // response field is already `Option<bool>`, so the wire can
9264                // carry that distinction today.
9265                let live = self
9266                    .process_liveness
9267                    .as_ref()
9268                    .and_then(|source| source.process_live(&module_id))
9269                    .unwrap_or(true);
9270                ClientControlResponse::RoutePoll {
9271                    route_channel,
9272                    route_epoch,
9273                    status: None,
9274                    live: Some(live),
9275                }
9276            }
9277            (PollKind::Liveness, RoutePollSnapshot::Absent) => ClientControlResponse::RoutePoll {
9278                route_channel,
9279                route_epoch,
9280                status: None,
9281                live: Some(false),
9282            },
9283        };
9284
9285        Ok(vec![control_response_body_frame(
9286            &frame,
9287            &response,
9288            "ClientControlResponse::RoutePoll",
9289        )?])
9290    }
9291
9292    pub(crate) fn observe_module_control_completion(
9293        &self,
9294        completion: ModuleControlRpcCompletion,
9295    ) -> bool {
9296        match completion {
9297            ModuleControlRpcCompletion::Unknown => false,
9298            ModuleControlRpcCompletion::Settled => true,
9299            ModuleControlRpcCompletion::LateHealthAnswer { module_id, latency } => {
9300                let latency_ms = latency.as_millis().min(u128::from(u64::MAX)) as u64;
9301                info!(
9302                    module_id = %module_id,
9303                    latency_ms,
9304                    "late health.check answer proves the module is alive"
9305                );
9306                match self
9307                    .supervisor
9308                    .record_late_health_answer(&module_id, latency_ms)
9309                {
9310                    Ok(true) => {}
9311                    Ok(false) => debug!(
9312                        module_id = %module_id,
9313                        latency_ms,
9314                        "late health.check answer has no active supervisor snapshot"
9315                    ),
9316                    Err(err) => warn!(
9317                        module_id = %module_id,
9318                        latency_ms,
9319                        error = %err,
9320                        "failed to record late health.check answer"
9321                    ),
9322                }
9323                true
9324            }
9325        }
9326    }
9327
9328    /// Decide whether a failure while settling a relayed `route.bind` belongs to
9329    /// the module connection whose frame is being handled, or to the client that
9330    /// relay was opened for.
9331    ///
9332    /// This runs on the MODULE connection's frame handler, where returning `Err`
9333    /// ends that connection -- and a module connection carries every client's
9334    /// routes to that module, so ending it costs the whole fleet its tools.
9335    /// `ConnectionClosing` carries the id of the connection that is closing, and
9336    /// when that id is a CLIENT's, the condition is entirely about that one
9337    /// client's route.open. A client-scoped condition has no authority over a
9338    /// shared module connection, so it is logged and the single relay is dropped:
9339    /// the client is going away, and `complete_pending_relay` already removed the
9340    /// relay before failing, so there is nothing left to settle. Anything that
9341    /// relay still reserved is released by that client's own connection teardown,
9342    /// which is already under way -- that is what "closing" means.
9343    ///
9344    /// Every other failure is a statement about THIS connection and stays fatal:
9345    /// a poisoned forwarding lock, a stale module endpoint, and the module's own
9346    /// id in `ConnectionClosing` all mean this connection cannot keep serving
9347    /// frames correctly.
9348    fn refuse_to_end_module_connection_for_a_client(
9349        &self,
9350        module_connection_id: ConnectionId,
9351        corr: u64,
9352        err: ForwardingError,
9353    ) -> Result<(), RouterError> {
9354        if let ForwardingError::ConnectionClosing { connection_id } = err {
9355            if connection_id != module_connection_id {
9356                warn!(
9357                    module_connection_id = module_connection_id.get(),
9358                    client_connection_id = connection_id.get(),
9359                    corr,
9360                    "dropping a route.bind response for a closing client; the module connection keeps serving"
9361                );
9362                return Ok(());
9363            }
9364        }
9365        Err(RouterError::Forwarding(err))
9366    }
9367
9368    fn handle_module_relay_response(
9369        &self,
9370        connection_id: ConnectionId,
9371        frame: Frame,
9372    ) -> Result<Vec<Frame>, RouterError> {
9373        let mut secondary_error = None;
9374        let outcome = match frame.header.ty {
9375            FrameType::Response => match module_control_response_probe(&frame.body) {
9376                Ok(probe) if probe.op == "route.bind" => {
9377                    match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9378                        Ok(ModuleControlResponse::RouteBindAck {}) => {
9379                            RouteBindRelayOutcome::Accepted
9380                        }
9381                        Ok(other) => {
9382                            let message =
9383                                format!("route.bind response carried unexpected body: {other:?}");
9384                            secondary_error = Some(control_error_frame(
9385                                &frame,
9386                                "invalid_control_body",
9387                                message.clone(),
9388                            )?);
9389                            RouteBindRelayOutcome::ModuleGone(message)
9390                        }
9391                        Err(err) => {
9392                            let message = format!("malformed route.bind response body: {err}");
9393                            secondary_error = Some(control_error_frame(
9394                                &frame,
9395                                "invalid_control_body",
9396                                message.clone(),
9397                            )?);
9398                            RouteBindRelayOutcome::ModuleGone(message)
9399                        }
9400                    }
9401                }
9402                Ok(probe) => {
9403                    let outcome = if matches!(
9404                        probe.op.as_str(),
9405                        "config.review" | "consent/v1" | "projects.enumerate"
9406                    ) {
9407                        ModuleControlRpcOutcome::RawResponse(frame.body.clone())
9408                    } else {
9409                        match serde_json::from_slice::<ModuleControlResponse>(&frame.body) {
9410                            Ok(response) => ModuleControlRpcOutcome::Response(response),
9411                            Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9412                                "malformed {} response body: {err}",
9413                                probe.op
9414                            )),
9415                        }
9416                    };
9417                    let completion = self
9418                        .forwarding
9419                        .complete_module_control_rpc(
9420                            connection_id,
9421                            frame.header.corr,
9422                            Some(&probe.op),
9423                            outcome,
9424                        )
9425                        .map_err(RouterError::Forwarding)?;
9426                    if !self.observe_module_control_completion(completion) {
9427                        debug!(
9428                            connection_id = connection_id.get(),
9429                            corr = frame.header.corr,
9430                            op = %probe.op,
9431                            "dropping late or unknown module-control RPC response"
9432                        );
9433                    }
9434                    return Ok(Vec::new());
9435                }
9436                Err(err) => {
9437                    if let Some(expected_op) = self
9438                        .forwarding
9439                        .pending_module_control_op(connection_id, frame.header.corr)
9440                        .map_err(RouterError::Forwarding)?
9441                    {
9442                        let completion = self
9443                            .forwarding
9444                            .complete_module_control_rpc(
9445                                connection_id,
9446                                frame.header.corr,
9447                                None,
9448                                ModuleControlRpcOutcome::MalformedResponse(format!(
9449                                    "malformed {expected_op} response body: {err}"
9450                                )),
9451                            )
9452                            .map_err(RouterError::Forwarding)?;
9453                        if !self.observe_module_control_completion(completion) {
9454                            debug!(
9455                                connection_id = connection_id.get(),
9456                                corr = frame.header.corr,
9457                                "dropping late malformed module-control RPC response"
9458                            );
9459                        }
9460                        return Ok(Vec::new());
9461                    }
9462                    let message = format!("malformed route.bind response body: {err}");
9463                    secondary_error = Some(control_error_frame(
9464                        &frame,
9465                        "invalid_control_body",
9466                        message.clone(),
9467                    )?);
9468                    RouteBindRelayOutcome::ModuleGone(message)
9469                }
9470            },
9471            FrameType::Error => {
9472                if self
9473                    .forwarding
9474                    .pending_module_control_op(connection_id, frame.header.corr)
9475                    .map_err(RouterError::Forwarding)?
9476                    .is_some()
9477                {
9478                    let outcome = match serde_json::from_slice::<ErrorBody>(&frame.body) {
9479                        Ok(body) => ModuleControlRpcOutcome::Rejected(body),
9480                        Err(err) => ModuleControlRpcOutcome::MalformedResponse(format!(
9481                            "malformed module-control ERROR body: {err}"
9482                        )),
9483                    };
9484                    let completion = self
9485                        .forwarding
9486                        .complete_module_control_rpc(
9487                            connection_id,
9488                            frame.header.corr,
9489                            None,
9490                            outcome,
9491                        )
9492                        .map_err(RouterError::Forwarding)?;
9493                    if !self.observe_module_control_completion(completion) {
9494                        debug!(
9495                            connection_id = connection_id.get(),
9496                            corr = frame.header.corr,
9497                            "dropping late or unknown module-control RPC error"
9498                        );
9499                    }
9500                    return Ok(Vec::new());
9501                }
9502                match serde_json::from_slice::<ErrorBody>(&frame.body) {
9503                    Ok(body) => RouteBindRelayOutcome::Rejected(body),
9504                    Err(err) => {
9505                        let message = format!("malformed route.bind ERROR body: {err}");
9506                        secondary_error = Some(control_error_frame(
9507                            &frame,
9508                            "invalid_control_body",
9509                            message.clone(),
9510                        )?);
9511                        RouteBindRelayOutcome::ModuleGone(message)
9512                    }
9513                }
9514            }
9515            ty => {
9516                return Ok(vec![control_error_frame(
9517                    &frame,
9518                    "unsupported_control_frame",
9519                    format!("unsupported module channel-0 frame {ty:?}"),
9520                )?])
9521            }
9522        };
9523
9524        let settled = self.settle_route_bind_relay(connection_id, frame.header.corr, outcome);
9525        let completion = match settled {
9526            Ok(completion) => completion,
9527            Err(err) => {
9528                self.refuse_to_end_module_connection_for_a_client(
9529                    connection_id,
9530                    frame.header.corr,
9531                    err,
9532                )?;
9533                return Ok(secondary_error.into_iter().collect());
9534            }
9535        };
9536        if let Some(target) = completion.abandoned.as_ref() {
9537            send_goodbye_target_best_effort(&self.counters, target, "late accepted route.bind");
9538        }
9539        if !completion.settled {
9540            debug!(
9541                connection_id = connection_id.get(),
9542                corr = frame.header.corr,
9543                frame_type = ?frame.header.ty,
9544                "dropping late or unknown route.bind relay response"
9545            );
9546        }
9547        Ok(secondary_error.into_iter().collect())
9548    }
9549
9550    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
9551        debug!(connection_id = connection_id.get(), "handling GOODBYE");
9552        // GOODBYE ends the connection's logical session even when its socket
9553        // stays open. Use disconnect teardown so verdicts, client notices and
9554        // scope authority are released at the same lifecycle boundary.
9555        self.cleanup_connection_with_end_reason(
9556            connection_id,
9557            RegistrationEndReason::ExplicitGoodbye,
9558        )
9559        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
9560        Ok(Vec::new())
9561    }
9562}
9563
9564impl Default for ControlHandler {
9565    fn default() -> Self {
9566        Self::new(Arc::new(Registry::default()))
9567    }
9568}
9569
9570impl crate::supervise::SwapPromotionObserver for ControlHandler {
9571    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
9572        self.apply_registration_capabilities(registration);
9573    }
9574}
9575
9576fn append_capability_problem_detail(
9577    detail: Option<String>,
9578    capability_detail: Option<String>,
9579) -> Option<String> {
9580    match (detail, capability_detail) {
9581        (Some(detail), Some(capability_detail)) => Some(format!("{detail}; {capability_detail}")),
9582        (Some(detail), None) => Some(detail),
9583        (None, Some(capability_detail)) => Some(capability_detail),
9584        (None, None) => None,
9585    }
9586}
9587
9588fn subc_ops() -> Vec<String> {
9589    SUBC_CONTROL_OPS
9590        .iter()
9591        .map(|op| (*op).to_string())
9592        .collect()
9593}
9594
9595fn module_subc_ops() -> Vec<String> {
9596    SUBC_CONTROL_OPS
9597        .iter()
9598        .chain(MODULE_TO_SUBC_CONTROL_OPS.iter())
9599        .map(|op| (*op).to_string())
9600        .collect()
9601}
9602
9603#[cfg(test)]
9604fn module_baseline_control_ops() -> Vec<String> {
9605    MODULE_BASELINE_CONTROL_OPS
9606        .iter()
9607        .map(|op| (*op).to_string())
9608        .collect()
9609}
9610
9611fn effective_module_control_ops(declared: Option<Vec<String>>) -> Vec<String> {
9612    let mut seen = HashSet::new();
9613    let mut effective = Vec::new();
9614    for op in MODULE_BASELINE_CONTROL_OPS {
9615        if seen.insert((*op).to_string()) {
9616            effective.push((*op).to_string());
9617        }
9618    }
9619    for op in declared.unwrap_or_default() {
9620        if seen.insert(op.clone()) {
9621            effective.push(op);
9622        }
9623    }
9624    effective
9625}
9626
9627fn module_registration_grants_op(control_ops: &[String], op: &str) -> bool {
9628    MODULE_BASELINE_CONTROL_OPS.contains(&op) || control_ops.iter().any(|granted| granted == op)
9629}
9630
9631fn target_module_id(target: &RouteTarget) -> &str {
9632    match target {
9633        RouteTarget::ToolProvider { module_id }
9634        | RouteTarget::ManagementSurface { module_id }
9635        | RouteTarget::InternalService { module_id, .. } => module_id,
9636    }
9637}
9638
9639fn target_has_required_role(
9640    target: &RouteTarget,
9641    roles: &[crate::registry::AdmissionRole],
9642) -> bool {
9643    use crate::registry::AdmissionRole;
9644    roles.iter().any(|role| match (target, role) {
9645        (RouteTarget::ToolProvider { .. }, AdmissionRole::ToolProvider) => true,
9646        (RouteTarget::ManagementSurface { .. }, AdmissionRole::ManagementSurface) => true,
9647        (
9648            RouteTarget::InternalService { service_id, .. },
9649            AdmissionRole::InternalService(provided),
9650        ) => service_id == provided,
9651        _ => false,
9652    })
9653}
9654
9655fn is_routable_role(role: &ProviderRole) -> bool {
9656    matches!(
9657        role,
9658        ProviderRole::ToolProvider { .. }
9659            | ProviderRole::ManagementSurface { .. }
9660            | ProviderRole::InternalService { .. }
9661    )
9662}
9663
9664#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9665enum ControlRequestBodyError {
9666    UnknownOp,
9667    InvalidBody,
9668}
9669
9670#[derive(Debug, Deserialize)]
9671struct ControlOpProbe {
9672    op: String,
9673}
9674
9675fn module_control_response_probe(body: &[u8]) -> Result<ControlOpProbe, serde_json::Error> {
9676    serde_json::from_slice(body).or_else(|original| {
9677        #[derive(Deserialize)]
9678        struct ConsentProbe {
9679            protocol: String,
9680        }
9681        match serde_json::from_slice::<ConsentProbe>(body) {
9682            Ok(probe) if probe.protocol == subc_protocol::consent::CONSENT_V1 => {
9683                Ok(ControlOpProbe { op: probe.protocol })
9684            }
9685            _ => Err(original),
9686        }
9687    })
9688}
9689
9690/// Channel-0 push ops this subc version understands. A push whose `op` is not in
9691/// this set is treated as a forward-compat unknown and ignored rather than errored.
9692const MODULE_PUSH_OPS: &[&str] = &["route.status"];
9693
9694fn is_known_module_push_op(body: &[u8]) -> bool {
9695    serde_json::from_slice::<ControlOpProbe>(body)
9696        .map(|probe| MODULE_PUSH_OPS.contains(&probe.op.as_str()))
9697        .unwrap_or(false)
9698}
9699
9700fn is_known_module_request_op(body: &[u8]) -> bool {
9701    serde_json::from_slice::<ControlOpProbe>(body)
9702        .map(|probe| is_module_to_subc_op(&probe.op))
9703        .unwrap_or(false)
9704}
9705
9706fn is_module_to_subc_op(op: &str) -> bool {
9707    MODULE_TO_SUBC_CONTROL_OPS.contains(&op) || MODULE_TO_SUBC_UNADVERTISED_OPS.contains(&op)
9708}
9709
9710fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
9711    debug!(
9712        op = %op,
9713        connection_id = connection_id.get(),
9714        corr,
9715        "control dispatch"
9716    );
9717}
9718
9719fn log_slow_control_dispatch(
9720    dispatch_started_at: Option<StdInstant>,
9721    op: &'static str,
9722    connection_id: ConnectionId,
9723    corr: u64,
9724    route_open_timings: Option<&RouteOpenTimings>,
9725) {
9726    let Some(dispatch_started_at) = dispatch_started_at else {
9727        return;
9728    };
9729    // Use the same monotonic clock as the phase timers and relay deadline.
9730    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
9731    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
9732        if let Some(timings) = route_open_timings {
9733            warn!(
9734                op = %op,
9735                connection_id = connection_id.get(),
9736                corr,
9737                elapsed_ms = elapsed.as_millis() as u64,
9738                module_id = ?timings.module_id,
9739                principal = %timings.principal,
9740                admission_ms = timings.admission.as_millis() as u64,
9741                project_root_ms = timings.project_root.as_millis() as u64,
9742                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
9743                bind_send_ms = timings.bind_send.as_millis() as u64,
9744                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
9745                "slow control dispatch"
9746            );
9747            return;
9748        }
9749        warn!(
9750            op = %op,
9751            connection_id = connection_id.get(),
9752            corr,
9753            elapsed_ms = elapsed.as_millis() as u64,
9754            "slow control dispatch"
9755        );
9756    }
9757}
9758
9759/// A test stand-in for the OS caller lookup, given the recorded endpoints.
9760#[cfg(test)]
9761type TestCallerLookup =
9762    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
9763
9764/// Every new client operation needs an explicit privilege decision here.
9765fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
9766    request.privileged_operation()
9767}
9768
9769trait PrivilegedRequest {
9770    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
9771}
9772
9773impl PrivilegedRequest for ClientControlRequest {
9774    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
9775        let request = self;
9776        match request {
9777        ClientControlRequest::SupervisorRestart { module_id, .. } => {
9778            Some(PrivilegedOperation::Restart { module_id })
9779        }
9780        ClientControlRequest::SupervisorSwap { module_id, .. } => {
9781            Some(PrivilegedOperation::Swap { module_id })
9782        }
9783        ClientControlRequest::SupervisorReload { module_id } => {
9784            Some(PrivilegedOperation::Reload { module_id })
9785        }
9786        ClientControlRequest::SupervisorRescan { preview } => {
9787            if *preview {
9788                None
9789            } else {
9790                Some(PrivilegedOperation::Rescan)
9791            }
9792        }
9793        // Only the well-formed apply asks for approval. A preview changes
9794        // nothing, and any other combination is refused before it touches
9795        // anything, so prompting the operator for it would ask about a request
9796        // that cannot run.
9797        ClientControlRequest::SupervisorRescanChecked {
9798            preview,
9799            candidate,
9800            expect,
9801        } => (!*preview && candidate.is_none() && expect.is_some())
9802            .then_some(PrivilegedOperation::Rescan),
9803        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
9804            Some(PrivilegedOperation::SetEnabled {
9805                module_id,
9806                enabled: *enabled,
9807            })
9808        }
9809        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
9810            Some(PrivilegedOperation::ReleaseReserved { module_id })
9811        }
9812        ClientControlRequest::ServerDescribe {}
9813        | ClientControlRequest::PolicyRoot(_)
9814        | ClientControlRequest::PolicyRootSet(_)
9815        | ClientControlRequest::PolicyRootRecover(_)
9816        // The announcement uses the same client admission as supervisor.restart,
9817        // but cannot stop anything itself and needs no operator confirmation.
9818        | ClientControlRequest::DaemonShutdownIntent { .. }
9819        | ClientControlRequest::CatalogList { .. }
9820        | ClientControlRequest::RouteOpen { .. }
9821        | ClientControlRequest::RoutePoll { .. }
9822        | ClientControlRequest::SupervisorList {}
9823        | ClientControlRequest::SupervisorHealth {}
9824        | ClientControlRequest::SupervisorHealthProbe { .. }
9825        | ClientControlRequest::SupervisorRoutes { .. }
9826        | ClientControlRequest::SupervisorProvenance { .. }
9827        | ClientControlRequest::SupervisorStderrTail { .. }
9828        | ClientControlRequest::SupervisorTerminals { .. }
9829        | ClientControlRequest::SupervisorSpawnSnapshot {}
9830        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
9831    }
9832    }
9833}
9834
9835fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
9836    match request {
9837        ClientControlRequest::PolicyRoot(_) => subc_protocol::policy_root::GET_OP,
9838        ClientControlRequest::PolicyRootSet(_) => subc_control::policy_root::SET_OP,
9839        ClientControlRequest::PolicyRootRecover(_) => subc_control::policy_root::RECOVER_OP,
9840        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
9841        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
9842        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
9843        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
9844        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
9845        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
9846        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
9847        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
9848        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
9849        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
9850        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
9851        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
9852        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
9853        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
9854        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
9855        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
9856        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
9857        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
9858        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
9859        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
9860        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
9861    }
9862}
9863
9864/// The caller of one `route.open`, as its `route.open refused` line names it.
9865///
9866/// A connection id alone cannot name a caller after the fact: ids restart at
9867/// every daemon restart, so the same number belongs to different modules
9868/// before and after one. These three fields are what the refused line needs
9869/// to be attributable on its own, and they are rendered with the same helpers
9870/// as the `route.open accepted` line so both directions grep alike.
9871struct RouteOpenCaller {
9872    /// The attested principal (`direct`, `reserved:<module>`), or `unattested`
9873    /// when the request presented a consumer identity whose launch nonce did
9874    /// not verify. The claimed module id is never printed as a principal.
9875    principal: String,
9876    /// `none` for an unscoped open; the admitted stamp's label once scope
9877    /// admission issued one; before that, the requested selector's label.
9878    scope: String,
9879    /// The bind identity's harness, Debug-quoted and bounded like a scope ref,
9880    /// because it is a string the caller chose.
9881    harness: String,
9882}
9883
9884impl RouteOpenCaller {
9885    fn new(
9886        principal: Option<&Principal>,
9887        scope: Option<&ScopeSelector>,
9888        identity: &BindIdentity,
9889    ) -> Self {
9890        Self {
9891            principal: principal.map_or_else(|| "unattested".to_string(), principal_label),
9892            scope: scope.map_or_else(|| "none".to_string(), route_open_requested_scope_label),
9893            harness: bounded_log_text(&identity.harness),
9894        }
9895    }
9896
9897    /// For a refusal that has no parsed request at hand: names whatever the
9898    /// frame still says, and `unknown` where it says nothing parseable.
9899    fn unknown() -> Self {
9900        Self {
9901            principal: "unknown".to_string(),
9902            scope: "unknown".to_string(),
9903            harness: "unknown".to_string(),
9904        }
9905    }
9906}
9907
9908/// Longest client-chosen text (a scope ref, a harness) a route.open log line
9909/// prints before cutting it.
9910const MAX_LOGGED_TEXT_CHARS: usize = 64;
9911
9912/// `value` Debug-quoted, so control characters land escaped and cannot forge
9913/// a log line, and cut to [`MAX_LOGGED_TEXT_CHARS`] characters with a trailing
9914/// `…` inside the quotes so one request cannot flood the line.
9915fn bounded_log_text(value: &str) -> String {
9916    let mut bounded: String = value.chars().take(MAX_LOGGED_TEXT_CHARS).collect();
9917    if value.chars().nth(MAX_LOGGED_TEXT_CHARS).is_some() {
9918        bounded.push('…');
9919    }
9920    format!("{bounded:?}")
9921}
9922
9923/// The `scope=` field of the `route.open accepted` line, from the stamp that
9924/// admission issued: `<kind>/<owner>/<ref>@<epoch>`. The ref is Debug-quoted
9925/// so a ref holding control characters cannot forge a log line, and cut to 64
9926/// characters with a trailing `…` to bound the line. The bind proof and the
9927/// scope's attributes never appear.
9928fn route_open_scope_label(stamp: &subc_protocol::scope::ScopeStamp) -> String {
9929    use subc_protocol::scope::ScopeKind;
9930    let kind = match stamp.kind {
9931        ScopeKind::Head => "head",
9932        ScopeKind::Worker => "worker",
9933        ScopeKind::Ephemeral => "ephemeral",
9934        ScopeKind::Federated => "federated",
9935        _ => "unknown",
9936    };
9937    format!(
9938        "{kind}/{}/{}@{}",
9939        principal_label(&stamp.owner),
9940        bounded_log_text(&stamp.scope_ref),
9941        stamp.scope_epoch
9942    )
9943}
9944
9945/// The `scope=` field of a `route.open refused` line for an open refused
9946/// before scope admission issued a stamp: `requested/<owner>/<ref>@<epoch>`.
9947/// The kind is not known yet, so the literal `requested` stands in its place.
9948/// The owner is Debug-quoted as well as the ref, because unlike a stamp's
9949/// owner it has not been checked against the configured modules: a quoted
9950/// owner means the value was never validated. The bind proof never appears.
9951fn route_open_requested_scope_label(selector: &ScopeSelector) -> String {
9952    let epoch = selector
9953        .scope_epoch
9954        .map_or_else(|| "none".to_string(), |epoch| epoch.to_string());
9955    format!(
9956        "requested/{}/{}@{epoch}",
9957        bounded_log_text(&principal_label(&selector.owner)),
9958        bounded_log_text(&selector.scope_ref),
9959    )
9960}
9961
9962fn principal_label(principal: &Principal) -> String {
9963    match principal {
9964        Principal::Reserved { module_id } => format!("reserved:{module_id}"),
9965        Principal::Direct => "direct".to_string(),
9966        other => format!("{other:?}"),
9967    }
9968}
9969
9970fn module_control_request_op(request: &ModuleControlRequestFromModule) -> &'static str {
9971    match request {
9972        ModuleControlRequestFromModule::PolicyRoot(_) => subc_protocol::policy_root::GET_OP,
9973        ModuleControlRequestFromModule::PolicyRootRotate(_) => {
9974            subc_protocol::policy_root::ROTATE_OP
9975        }
9976        ModuleControlRequestFromModule::CatalogUpdate { .. } => MODULE_TO_SUBC_OP_CATALOG_UPDATE,
9977        ModuleControlRequestFromModule::CatalogUpdateRoleDeclarations { .. } => {
9978            MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS
9979        }
9980        ModuleControlRequestFromModule::LiveRoots {} => "supervisor.live_roots",
9981        ModuleControlRequestFromModule::ScopeSync { .. } => SCOPE_SYNC_OP,
9982        ModuleControlRequestFromModule::ScopeApply { .. } => SCOPE_APPLY_OP,
9983        ModuleControlRequestFromModule::ScopeDescribe { .. } => SCOPE_DESCRIBE_OP,
9984        ModuleControlRequestFromModule::RouteAuthorize { .. } => {
9985            subc_protocol::scope::ROUTE_AUTHORIZE_OP
9986        }
9987        ModuleControlRequestFromModule::AgentCommands { .. } => "supervisor.agent_commands",
9988        _ => "unsupported",
9989    }
9990}
9991
9992fn parse_client_control_request(
9993    body: &[u8],
9994) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
9995    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
9996        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
9997            Ok(probe)
9998                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
9999                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
10000            {
10001                ControlRequestBodyError::InvalidBody
10002            }
10003            Ok(_) => ControlRequestBodyError::UnknownOp,
10004            Err(_) => ControlRequestBodyError::InvalidBody,
10005        };
10006        (err, classification)
10007    })
10008}
10009
10010fn parse_module_control_request_from_module(
10011    body: &[u8],
10012) -> Result<ModuleControlRequestFromModule, (serde_json::Error, ControlRequestBodyError)> {
10013    serde_json::from_slice::<ModuleControlRequestFromModule>(body).map_err(|err| {
10014        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
10015            Ok(probe) if is_module_to_subc_op(&probe.op) => ControlRequestBodyError::InvalidBody,
10016            Ok(_) => ControlRequestBodyError::UnknownOp,
10017            Err(_) => ControlRequestBodyError::InvalidBody,
10018        };
10019        (err, classification)
10020    })
10021}
10022
10023#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10024enum ProviderRoleKind {
10025    ToolProvider,
10026    PipelineStage,
10027    ManagementSurface,
10028    InternalService,
10029}
10030
10031fn provider_role_kind(role: &ProviderRole) -> ProviderRoleKind {
10032    match role {
10033        ProviderRole::ToolProvider { .. } => ProviderRoleKind::ToolProvider,
10034        ProviderRole::PipelineStage { .. } => ProviderRoleKind::PipelineStage,
10035        ProviderRole::ManagementSurface { .. } => ProviderRoleKind::ManagementSurface,
10036        ProviderRole::InternalService { .. } => ProviderRoleKind::InternalService,
10037    }
10038}
10039
10040fn provider_role_kind_set(roles: &[ProviderRole]) -> BTreeSet<ProviderRoleKind> {
10041    roles.iter().map(provider_role_kind).collect()
10042}
10043
10044/// Most refused scope records named individually in the log per sync; the
10045/// `refused` count on the accepted line is always complete.
10046const MAX_LOGGED_REFUSED_SCOPE_RECORDS: usize = 8;
10047
10048/// Per-outcome counts of one accepted `scope.sync`, for its log line.
10049#[derive(Debug, Default, PartialEq, Eq)]
10050struct ScopeOutcomeCounts {
10051    created: usize,
10052    replaced: usize,
10053    updated: usize,
10054    unchanged: usize,
10055    refused: usize,
10056}
10057
10058impl ScopeOutcomeCounts {
10059    fn of(results: &[ScopeRecordResult]) -> Self {
10060        let mut counts = Self::default();
10061        for result in results {
10062            let slot = match result.outcome {
10063                ScopeRecordOutcome::Created => &mut counts.created,
10064                ScopeRecordOutcome::Replaced => &mut counts.replaced,
10065                ScopeRecordOutcome::Updated => &mut counts.updated,
10066                ScopeRecordOutcome::Unchanged => &mut counts.unchanged,
10067                ScopeRecordOutcome::Refused => &mut counts.refused,
10068            };
10069            *slot += 1;
10070        }
10071        counts
10072    }
10073}
10074
10075#[cfg(test)]
10076mod scope_outcome_count_tests {
10077    use super::*;
10078
10079    fn result(outcome: ScopeRecordOutcome) -> ScopeRecordResult {
10080        ScopeRecordResult {
10081            scope_ref: "r".to_string(),
10082            scope_epoch: 1,
10083            outcome,
10084            code: None,
10085            message: None,
10086            version: None,
10087            parent_state: None,
10088        }
10089    }
10090
10091    /// Each outcome lands in its own count, so a refused record can never be
10092    /// hidden inside the total the log already printed.
10093    #[test]
10094    fn every_outcome_is_counted_in_its_own_field() {
10095        let results = [
10096            result(ScopeRecordOutcome::Created),
10097            result(ScopeRecordOutcome::Created),
10098            result(ScopeRecordOutcome::Replaced),
10099            result(ScopeRecordOutcome::Updated),
10100            result(ScopeRecordOutcome::Unchanged),
10101            result(ScopeRecordOutcome::Refused),
10102            result(ScopeRecordOutcome::Refused),
10103            result(ScopeRecordOutcome::Refused),
10104        ];
10105        assert_eq!(
10106            ScopeOutcomeCounts::of(&results),
10107            ScopeOutcomeCounts {
10108                created: 2,
10109                replaced: 1,
10110                updated: 1,
10111                unchanged: 1,
10112                refused: 3,
10113            }
10114        );
10115    }
10116}
10117
10118/// Return whether a catalog change can create a newly violating live route.
10119/// Removing an attested claim is intentionally excluded: it makes fewer routes
10120/// forbidden and therefore must leave the existing route census untouched.
10121fn capability_census_trigger(
10122    old: Option<&CapabilityDeclarations>,
10123    new: Option<&CapabilityDeclarations>,
10124) -> bool {
10125    let old_provides = old
10126        .map(|capabilities| capabilities.provides.iter().collect::<HashSet<_>>())
10127        .unwrap_or_default();
10128    let old_denies = old
10129        .map(|capabilities| capabilities.must_never_reach.iter().collect::<HashSet<_>>())
10130        .unwrap_or_default();
10131    let new = new.cloned().unwrap_or(CapabilityDeclarations {
10132        provides: Vec::new(),
10133        requires: Vec::new(),
10134        must_never_reach: Vec::new(),
10135    });
10136
10137    new.provides
10138        .iter()
10139        .any(|capability| !old_provides.contains(capability))
10140        || new
10141            .must_never_reach
10142            .iter()
10143            .any(|capability| !old_denies.contains(capability))
10144}
10145
10146fn catalog_update_frozen_field_message(
10147    registered: &ModuleManifest,
10148    provides: &[ProviderRole],
10149) -> Option<String> {
10150    let old_has_provides = !registered.provides.is_empty();
10151    let new_has_provides = !provides.is_empty();
10152    if old_has_provides != new_has_provides {
10153        return Some(format!(
10154            "catalog.update cannot change module '{}' between supervision-only and routable; routability is fixed at HELLO",
10155            registered.module_id
10156        ));
10157    }
10158
10159    if provider_role_kind_set(&registered.provides) != provider_role_kind_set(provides) {
10160        return Some(format!(
10161            "catalog.update cannot change provider role kinds for module '{}'; role kinds are fixed at HELLO",
10162            registered.module_id
10163        ));
10164    }
10165
10166    let registered_concurrency = manifest_concurrency(registered);
10167    let mut candidate = registered.clone();
10168    candidate.provides = provides.to_vec();
10169    let candidate_concurrency = manifest_concurrency(&candidate);
10170    if candidate_concurrency != registered_concurrency {
10171        return Some(format!(
10172            "catalog.update cannot change module '{}' concurrency from {:?} to {:?}; concurrency is fixed at HELLO",
10173            registered.module_id, registered_concurrency, candidate_concurrency
10174        ));
10175    }
10176
10177    // control_ops live beside the manifest in the HELLO body, not inside
10178    // ModuleManifest, so a provides-only catalog.update cannot change them.
10179    None
10180}
10181
10182fn manifest_provides_routable_role(manifest: &ModuleManifest) -> bool {
10183    manifest.provides.iter().any(is_routable_role)
10184}
10185
10186/// Returns the routable-provider concurrency subc should enforce for this manifest.
10187///
10188/// ToolProvider and ManagementSurface store their delivery concurrency directly.
10189/// InternalService has no role-specific concurrency field, so it retains the
10190/// existing ModuleManaged default for backward compatibility.
10191fn manifest_concurrency(manifest: &ModuleManifest) -> Concurrency {
10192    manifest
10193        .provides
10194        .iter()
10195        .find_map(|provider| match provider {
10196            ProviderRole::ToolProvider { concurrency, .. }
10197            | ProviderRole::ManagementSurface { concurrency, .. } => Some(concurrency.clone()),
10198            ProviderRole::PipelineStage { .. } | ProviderRole::InternalService { .. } => None,
10199        })
10200        .unwrap_or(Concurrency::ModuleManaged)
10201}
10202
10203/// True when the manifest carries a ManagementSurface role whose concurrency
10204/// was RESOLVED BY SERDE DEFAULT rather than declared. Reads the raw HELLO
10205/// bytes because the typed manifest deliberately erases that distinction: the
10206/// default exists for wire compatibility, and this probe exists so the default
10207/// stays observable. Any parse irregularity returns false -- the caller only
10208/// logs, and a malformed body already failed registration upstream.
10209fn manifest_concurrency_was_defaulted(raw_hello: &[u8], manifest: &ModuleManifest) -> bool {
10210    let has_management_surface = manifest
10211        .provides
10212        .iter()
10213        .any(|provider| matches!(provider, ProviderRole::ManagementSurface { .. }));
10214    if !has_management_surface {
10215        return false;
10216    }
10217    let Ok(raw) = serde_json::from_slice::<serde_json::Value>(raw_hello) else {
10218        return false;
10219    };
10220    let Some(provides) = raw
10221        .get("manifest")
10222        .and_then(|manifest| manifest.get("provides"))
10223        .and_then(serde_json::Value::as_array)
10224    else {
10225        return false;
10226    };
10227    // ProviderRole is internally tagged (`tag = "role"`), so the wire shape is
10228    // flat: {"role": "management_surface", ..., "concurrency": ...} -- verified
10229    // against the management_surface_manifest_without_concurrency golden, not
10230    // recalled (the externally-tagged guess was this function's first bug).
10231    provides.iter().any(|role| {
10232        role.get("role").and_then(serde_json::Value::as_str) == Some("management_surface")
10233            && role.get("concurrency").is_none()
10234    })
10235}
10236
10237fn negotiate_version(peer_version: u8) -> Result<u8, String> {
10238    if peer_version != PROTOCOL_VERSION {
10239        return Err(format!(
10240            "protocol_ver {peer_version} is unsupported; this daemon requires exactly {PROTOCOL_VERSION}"
10241        ));
10242    }
10243    Ok(PROTOCOL_VERSION)
10244}
10245
10246fn pong(frame: &Frame) -> Result<Frame, RouterError> {
10247    Frame::build_with_version(
10248        response_version(frame),
10249        FrameType::Pong,
10250        frame.header.flags,
10251        0,
10252        0,
10253        frame.header.corr,
10254        Vec::new(),
10255    )
10256    .map_err(RouterError::FrameBuild)
10257}
10258
10259pub(crate) fn control_error_frame(
10260    frame: &Frame,
10261    code: &'static str,
10262    message: impl Into<String>,
10263) -> Result<Frame, RouterError> {
10264    control_error_body_frame(
10265        frame,
10266        ErrorBody {
10267            code: code.to_string(),
10268            message: message.into(),
10269            detail: None,
10270        },
10271    )
10272}
10273
10274/// A channel-0 ERROR for a refusal the daemon decided itself: every
10275/// route.open refusal, the drain `module_reloading` and scope-change/end
10276/// bodies, spawn-subscription and supervisor refusals. Carries the
10277/// daemon-origin bit, which is what lets a client treat `module_reloading`
10278/// as proof that its request never reached a module. Response, push,
10279/// goodbye and relay-request frames keep the plain control flags in their
10280/// own builders.
10281pub(crate) fn control_error_body_frame(
10282    frame: &Frame,
10283    error: ErrorBody,
10284) -> Result<Frame, RouterError> {
10285    control_error_frame_with_flags(frame, error, daemon_error_flags())
10286}
10287
10288/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
10289/// refused route.bind answered as a route.open refusal, or a refused
10290/// module-control RPC. Plain control flags — the code and message are
10291/// module-chosen, so the frame must not claim daemon authorship, even when
10292/// the module picks a daemon code like `module_reloading`.
10293fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
10294    control_error_frame_with_flags(frame, error, control_flags())
10295}
10296
10297fn control_error_frame_with_flags(
10298    frame: &Frame,
10299    error: ErrorBody,
10300    flags: Flags,
10301) -> Result<Frame, RouterError> {
10302    let body = serde_json::to_vec(&error).map_err(|err| {
10303        RouterError::backend(
10304            0,
10305            frame.header.corr,
10306            format!("failed to encode control ERROR: {err}"),
10307        )
10308    })?;
10309
10310    Frame::build_with_version(
10311        response_version(frame),
10312        FrameType::Error,
10313        flags,
10314        0,
10315        0,
10316        frame.header.corr,
10317        body,
10318    )
10319    .map_err(RouterError::FrameBuild)
10320}
10321
10322pub(crate) fn control_response_body_frame<T: Serialize>(
10323    frame: &Frame,
10324    reply: &T,
10325    label: &'static str,
10326) -> Result<Frame, RouterError> {
10327    let body = serde_json::to_vec(reply).map_err(|err| {
10328        RouterError::backend(
10329            0,
10330            frame.header.corr,
10331            format!("failed to encode {label}: {err}"),
10332        )
10333    })?;
10334
10335    Frame::build_with_version(
10336        response_version(frame),
10337        FrameType::Response,
10338        control_flags(),
10339        0,
10340        0,
10341        frame.header.corr,
10342        body,
10343    )
10344    .map_err(RouterError::FrameBuild)
10345}
10346
10347/// Map a forwarding failure to the wire code a client sees.
10348///
10349/// The code is not a label: clients BRANCH on it. Both SDKs decide "retry in
10350/// place" with `subc_protocol::error_codes::is_retryable_route_open`, so a code
10351/// chosen here decides whether a caller retries or gives up.
10352///
10353/// That makes attribution the load-bearing property, not merely having a code. A
10354/// permanent fault published as a retryable one produces a fleet-wide retry storm
10355/// against something that can never recover; a transient fault published as
10356/// permanent gives up on work that would have succeeded. Both look correct in a
10357/// log, which is why `retryability_of_forwarding_codes_matches_the_failure` pins
10358/// the mapping per variant rather than merely asserting that some code exists.
10359///
10360/// That fence partitions by RETRYABILITY, which is coarser than identity: swapping
10361/// two codes on the same side of the boundary passes it. Measured rather than
10362/// assumed — `NoModuleConnection` re-pointed at `module_reloading` is caught only
10363/// by `supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up`,
10364/// a test named for something else that happens to assert the string.
10365///
10366/// That accidental coverage is deliberately left alone rather than promoted to a
10367/// named test, because it guards a property this function does not promise.
10368/// Checked at source: every consumer branches on the RETRYABLE SET and none on a
10369/// specific code within a class, so identity is free to change and only the
10370/// partition is a contract. Splitting it out would assert a guarantee nothing
10371/// depends on — and a suite that promises more than the code does is the harder
10372/// thing to correct later, because the next reader cannot tell which assertions
10373/// are load-bearing.
10374///
10375/// Pin identity here the moment a consumer branches on a specific code.
10376/// The spawn a HELLO would register as and the provider declarations it
10377/// requests, carried from the HELLO's checks to the point the registry
10378/// accepts it.
10379struct HelloAuthority {
10380    record: Arc<crate::spawn_authority::SpawnAuthorityRecord>,
10381    requested: ProviderDeclarations,
10382    /// Whether admitting this HELLO froze the spawn's requested declarations,
10383    /// so a refusal after admission undoes that freeze and no other.
10384    froze: std::sync::atomic::AtomicBool,
10385}
10386
10387fn forwarding_error_code(err: &ForwardingError) -> &'static str {
10388    match err {
10389        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
10390        ForwardingError::NoModuleConnection => "target_unavailable",
10391        ForwardingError::ModuleReloading { .. } => "module_reloading",
10392        ForwardingError::ClientRouteChannelExhausted { .. }
10393        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
10394        ForwardingError::StaleModuleEndpoint
10395        | ForwardingError::UnknownReservation { .. }
10396        | ForwardingError::ConnectionClosing { .. }
10397        | ForwardingError::ClientEgressClosed { .. }
10398        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
10399        // Only a swap candidate's registration can produce this, and it means
10400        // exactly what a second active HELLO for a live id means.
10401        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
10402        ForwardingError::TargetRegistrationChanged(_) => "capability_forbidden",
10403        ForwardingError::RelayDeadlineElapsed => "module_timeout",
10404        ForwardingError::RelayCorrelationExhausted
10405        | ForwardingError::RouteOpenBuild(_)
10406        | ForwardingError::Poisoned => "forwarding_error",
10407    }
10408}
10409
10410fn response_version(frame: &Frame) -> u8 {
10411    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
10412        frame.header.ver
10413    } else {
10414        PROTOCOL_VERSION
10415    }
10416}
10417
10418pub(crate) fn control_flags() -> Flags {
10419    Flags::new(false, Priority::Passive, false)
10420}
10421
10422/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
10423/// channel. The target is the module (a client never saw the route), so this
10424/// takes the module path: delivered late rather than dropped when the module's
10425/// queue is momentarily full, and never closing its connection.
10426fn send_goodbye_target_best_effort(
10427    counters: &DaemonCounters,
10428    target: &GoodbyeTarget,
10429    context: &'static str,
10430) {
10431    let Ok(frame) = Frame::build_with_version(
10432        target.negotiated_ver,
10433        FrameType::Goodbye,
10434        control_flags(),
10435        target.channel,
10436        target.epoch,
10437        0,
10438        Vec::new(),
10439    ) else {
10440        return;
10441    };
10442    crate::forwarding::send_module_route_goodbye(
10443        counters,
10444        &target.sink,
10445        frame,
10446        target.module_id.as_deref(),
10447        context,
10448    );
10449}
10450
10451fn route_close_reason_for_opener(
10452    reason: RouteCloseReason,
10453    accepts_close_reasons: Option<&[String]>,
10454) -> RouteCloseReason {
10455    if reason == RouteCloseReason::AuthorityChanged
10456        && !accepts_close_reasons
10457            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
10458    {
10459        // Older readers forbid reopening for unknown reasons. Reload already
10460        // permits reopening and, like an authority change, requires a new bind.
10461        RouteCloseReason::Reload
10462    } else {
10463        reason
10464    }
10465}
10466
10467pub(crate) fn send_route_control_pushes(
10468    forwarding: &ForwardingTable,
10469    routes: Vec<EndpointRoute>,
10470    push: ClientControlPush,
10471) {
10472    let reason = match &push {
10473        ClientControlPush::RouteClosing { reason, .. }
10474        | ClientControlPush::RouteClosed { reason, .. } => *reason,
10475    };
10476    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
10477    for route in routes {
10478        let recipient_reason =
10479            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
10480        let target = route.goodbye_target;
10481        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
10482            existing.connection_id == target.connection_id && *reason == recipient_reason
10483        }) {
10484            debug_assert_eq!(
10485                existing.negotiated_ver, target.negotiated_ver,
10486                "one connection cannot negotiate multiple frame versions"
10487            );
10488            if !channels.contains(&target.channel) {
10489                channels.push(target.channel);
10490            }
10491            continue;
10492        }
10493        let channel = target.channel;
10494        targets.push((target, recipient_reason, vec![channel]));
10495    }
10496    for (target, recipient_reason, mut channels) in targets {
10497        channels.sort_unstable();
10498        let mut push = push.clone();
10499        match &mut push {
10500            ClientControlPush::RouteClosing {
10501                channels: covered,
10502                reason,
10503                ..
10504            }
10505            | ClientControlPush::RouteClosed {
10506                channels: covered,
10507                reason,
10508                ..
10509            } => {
10510                *covered = channels;
10511                *reason = recipient_reason;
10512            }
10513        }
10514        let body = match serde_json::to_vec(&push) {
10515            Ok(body) => body,
10516            Err(err) => {
10517                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
10518                continue;
10519            }
10520        };
10521        let frame = match Frame::build_with_version(
10522            target.negotiated_ver,
10523            FrameType::Push,
10524            control_flags(),
10525            0,
10526            0,
10527            0,
10528            body.clone(),
10529        ) {
10530            Ok(frame) => frame,
10531            Err(err) => {
10532                warn!(
10533                    route_channel = target.channel,
10534                    error = %err,
10535                    "failed to build route lifecycle control PUSH frame"
10536                );
10537                continue;
10538            }
10539        };
10540        if let Err(err) = target.sink.try_send(frame) {
10541            if target.close_on_delivery_failure() {
10542                warn!(
10543                    target_connection_id = target.connection_id.get(),
10544                    route_channel = target.channel,
10545                    error = %err,
10546                    "route lifecycle control PUSH was not delivered to client; closing target connection"
10547                );
10548                let _ = forwarding.escalate_client_delivery_failure(
10549                    target.connection_id,
10550                    target.channel,
10551                    target.epoch,
10552                    CloseReason::new(
10553                        "route_lifecycle_push_delivery_failed",
10554                        format!(
10555                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
10556                            target.channel
10557                        ),
10558                    ),
10559                    crate::forwarding::UndeliveredFrame {
10560                        module_id: target.module_id.as_deref(),
10561                        sink: &target.sink,
10562                    },
10563                );
10564            }
10565        }
10566    }
10567}
10568
10569#[cfg(test)]
10570mod tests {
10571    include!("control/agent_commands_tests.rs");
10572    include!("control/supervisor_health_vectors_tests.rs");
10573    include!("control/resource_revision_tests.rs");
10574    include!("control/route_open_recovery_tests.rs");
10575    mod router_audit {
10576        use super::*;
10577        include!("control/router_audit_tests.rs");
10578    }
10579    #[tokio::test]
10580    async fn route_busy_wait_attribution_resolves_targets_instead_of_trusting_selectors() {
10581        let registry = Arc::new(Registry::default());
10582        let handler = ControlHandler::new(registry);
10583        assert_eq!(
10584            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10585            None
10586        );
10587        let (ctx, mut rx) = route_ctx(ConnectionId::new(901));
10588        hello_via_sink(
10589            &handler,
10590            &ctx,
10591            &mut rx,
10592            hello_frame("daemon", PROTOCOL_VERSION, 1),
10593        )
10594        .await;
10595        assert_eq!(
10596            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("daemon")),
10597            Some("daemon".into())
10598        );
10599        assert_eq!(
10600            handler.resolve_reader_wait_target(ops::SUPERVISOR_HEALTH_PROBE, Some("missing")),
10601            None
10602        );
10603        assert_eq!(
10604            handler.resolve_reader_wait_target(ops::SUPERVISOR_TERMINALS, Some("daemon")),
10605            None,
10606            "a registered module is not necessarily supervised"
10607        );
10608        assert_eq!(
10609            handler.resolve_reader_wait_target(ops::SUPERVISOR_PROVENANCE, None),
10610            None,
10611            "aggregate provenance has no single target"
10612        );
10613        assert_eq!(
10614            handler.resolve_reader_wait_target(ops::APP_OPEN, Some("daemon")),
10615            None
10616        );
10617    }
10618
10619    mod peer_manifest {
10620        include!("peer_manifest_tests.rs");
10621    }
10622    mod catalog_declarations {
10623        include!("control/catalog_tests.rs");
10624    }
10625    mod activity_read {
10626        include!("activity_read_tests.rs");
10627    }
10628
10629    mod lifecycle_activity {
10630        include!("control_lifecycle_tests.rs");
10631    }
10632    #[cfg(unix)]
10633    #[tokio::test]
10634    async fn rescan_health_only_is_live_but_launch_edits_need_reload() {
10635        let dir = cortexkit_test_support::ScratchDir::new("rescan-live-health");
10636        let path = dir.join("subc.jsonc");
10637        std::fs::write(&path, serde_json::json!({"version":1,"modules":{"stock":{
10638            "program":"/bin/sleep","args":["60"],"protocol":"none",
10639            "env":{"XDG_DATA_HOME":dir.path(),"XDG_RUNTIME_DIR":dir.path(),"XDG_CONFIG_HOME":dir.path()}
10640        }}}).to_string()).unwrap();
10641        let mut configured = crate::daemon_config::load(&path)
10642            .unwrap()
10643            .unwrap()
10644            .modules
10645            .pop()
10646            .unwrap();
10647        let registry = std::sync::Arc::new(crate::Registry::default());
10648        let handle = crate::SupervisorHandle::new();
10649        let supervisor = crate::Supervisor::new(registry.clone(), crate::RestartPolicy::default())
10650            .with_handle(handle.clone());
10651        let module = supervisor
10652            .supervise_configured_with_health(
10653                configured.module_spec(),
10654                true,
10655                configured.health.clone(),
10656                None,
10657                configured.restart,
10658            )
10659            .unwrap();
10660        let handler = super::ControlHandler::new(registry).with_supervisor(handle);
10661        let before = module.status().unwrap().pid;
10662        configured.health.http = Some("http://127.0.0.1:1/healthz".into());
10663        configured.health.cadence = std::time::Duration::from_secs(3600);
10664        let health_only = handler
10665            .reconcile_supervised_modules(
10666                &supervisor,
10667                vec![configured.clone()],
10668                false,
10669                Principal::Direct,
10670            )
10671            .await
10672            .unwrap();
10673        assert!(
10674            health_only.0.changed_pending_reload.is_empty(),
10675            "health policy is already applied live"
10676        );
10677        assert_eq!(module.status().unwrap().pid, before);
10678        assert_eq!(
10679            module.configuration().unwrap().1.http,
10680            configured.health.http
10681        );
10682        configured.args = vec!["61".into()];
10683        let launch = handler
10684            .reconcile_supervised_modules(&supervisor, vec![configured], false, Principal::Direct)
10685            .await
10686            .unwrap();
10687        assert_eq!(launch.0.changed_pending_reload, ["stock"]);
10688        assert_eq!(
10689            module.status().unwrap().pid,
10690            before,
10691            "a launch edit is stored until reload"
10692        );
10693        module.drain().await.unwrap();
10694    }
10695    use cortexkit_test_support::ScratchDir;
10696    use std::{
10697        collections::BTreeMap,
10698        fmt,
10699        path::PathBuf,
10700        sync::{Arc, Mutex},
10701        time::Duration,
10702    };
10703
10704    use serde_json::{json, Value};
10705    use subc_protocol::{
10706        manifest::{
10707            Concurrency, ExecutionMode, IdentityScope, ManagementOperation,
10708            ManagementOperationKind, ObservabilityKind, ObservabilitySurface, ProviderRole, Tool,
10709        },
10710        session::HealthStatus,
10711        FrameType,
10712    };
10713
10714    use super::*;
10715    use crate::{
10716        forwarding::{DataRoute, DataRouteState},
10717        registry::ChannelState,
10718        router::FrameSink,
10719        stderr_tail::DEFAULT_MAX_LINE_BYTES,
10720        supervise::{ModuleSpec, ModuleState, RestartPolicy, Supervisor, SupervisorHandle},
10721        RouteCtx, Router,
10722    };
10723    use tokio::{
10724        sync::mpsc,
10725        time::{sleep, Instant},
10726    };
10727    use tracing::{
10728        field::{Field, Visit},
10729        Event, Subscriber,
10730    };
10731    use tracing_subscriber::{layer::Context, prelude::*, Layer};
10732
10733    /// Locates the `fake-aft-stub` binary from a `src/lib.rs` unit test.
10734    ///
10735    /// `CARGO_BIN_EXE_*` (compile-time `env!` and runtime `std::env::var` alike)
10736    /// is only populated for `tests/*.rs` integration test binaries -- this file
10737    /// compiles as part of the library target, which gets neither. The binary
10738    /// lives in the profile folder this test was built into,
10739    /// `<target-dir>/<profile>/fake-aft-stub`, which `cargo_profile_bin` finds
10740    /// from the test's own path.
10741    ///
10742    /// THE BINARY IS NOT ALWAYS THERE, and the existence check below is why.
10743    /// `cargo test -p subc-core` builds every target including `[[bin]]`, so the
10744    /// stub is on disk; `cargo test -p subc-core --lib` builds ONLY the library
10745    /// test and leaves the stub unbuilt. A bare spawn then fails with a raw
10746    /// `NotFound`, which reads as a broken test rather than an unbuilt
10747    /// dependency -- so state the cause and the remedy instead. Deliberately a
10748    /// panic and not a silent skip: a test that quietly passes when it could not
10749    /// run is worse than one that fails, because it reports health it never
10750    /// verified.
10751    fn fake_aft_stub_path() -> PathBuf {
10752        let path = cortexkit_test_support::cargo_profile_bin("fake-aft-stub");
10753        assert!(
10754            path.exists(),
10755            "fake-aft-stub not built at {}: run `cargo test -p subc-core` (which builds \
10756             [[bin]] targets) rather than `cargo test -p subc-core --lib` (which does not)",
10757            path.display()
10758        );
10759        path
10760    }
10761
10762    /// Whether clients retry `code` in place: the predicate itself, never a copy
10763    /// of its set. A copied list breaks silently when a code is added to or
10764    /// removed from the real one, and a stale copy here would let exactly the
10765    /// failure this test exists to catch pass.
10766    fn client_retries(code: &str) -> bool {
10767        subc_protocol::error_codes::is_retryable_route_open(code)
10768    }
10769
10770    /// A code is not a label — clients branch on it, so publishing the wrong KIND
10771    /// of failure is worse than publishing none. A permanent fault dressed as
10772    /// retryable makes every client in the fleet retry forever against something
10773    /// that cannot recover; a transient fault dressed as permanent abandons work
10774    /// that would have succeeded.
10775    ///
10776    /// Asserting "a code exists" cannot catch either, because the string is free
10777    /// to say anything. This enumerates every variant and pins which side of the
10778    /// retry boundary it lands on, so a new variant must be classified here
10779    /// deliberately rather than inheriting whichever arm it was appended to.
10780    #[test]
10781    fn retryability_of_forwarding_codes_matches_the_failure() {
10782        // Transient by nature: the target is booting, reloading, or its endpoint
10783        // was swapped mid-flight. Retrying is how these resolve.
10784        let transient = [
10785            ForwardingError::NoModuleConnection,
10786            ForwardingError::ModuleReloading {
10787                module_id: "m".into(),
10788            },
10789            ForwardingError::StaleModuleEndpoint,
10790            ForwardingError::UnknownReservation {
10791                client_channel: 1,
10792                module_channel: 1,
10793            },
10794            ForwardingError::ConnectionClosing {
10795                connection_id: ConnectionId::new(1),
10796            },
10797            ForwardingError::ClientEgressClosed {
10798                connection_id: ConnectionId::new(1),
10799            },
10800            ForwardingError::ModuleEgressUnavailable {
10801                connection_id: ConnectionId::new(1),
10802            },
10803        ];
10804        for err in transient {
10805            let code = forwarding_error_code(&err);
10806            assert!(
10807                client_retries(code),
10808                "{err:?} is transient but publishes {code:?}, which clients treat as permanent"
10809            );
10810        }
10811
10812        // Not fixed by retrying. Channel and correlation exhaustion need the
10813        // caller to close routes, and a poisoned lock is a daemon that cannot
10814        // recover at all — the worst thing to advertise as retryable, since every
10815        // client would storm a daemon that will never answer.
10816        let permanent = [
10817            ForwardingError::ConnectionRoleConflict {
10818                connection_id: ConnectionId::new(1),
10819            },
10820            ForwardingError::ClientRouteChannelExhausted {
10821                connection_id: ConnectionId::new(1),
10822            },
10823            ForwardingError::ModuleRouteChannelExhausted {
10824                endpoint: ModuleEndpointId {
10825                    connection_id: ConnectionId::new(1),
10826                    generation: 1,
10827                },
10828            },
10829            ForwardingError::RelayCorrelationExhausted,
10830            ForwardingError::RouteOpenBuild("x".into()),
10831            ForwardingError::Poisoned,
10832        ];
10833        for err in permanent {
10834            let code = forwarding_error_code(&err);
10835            assert!(
10836                !client_retries(code),
10837                "{err:?} cannot be fixed by retrying but publishes {code:?}, which clients retry"
10838            );
10839        }
10840    }
10841
10842    /// The principal is the daemon's answer to "who is calling", and modules
10843    /// branch on it: aft gates bash on it, cerebellum gates browser control,
10844    /// plexus gates connector invocation. So a stamp is an authorization input in
10845    /// another process, not a label — and both possible answers SUCCEED, which is
10846    /// what makes a wrong one quiet. An unattested caller stamped `Reserved` hands
10847    /// first-party capability to something that never proved it; a supervised one
10848    /// stamped `Direct` silently strips a module of capability it is entitled to.
10849    ///
10850    /// Neither shows up in a test that only checks the bind succeeded. Before this
10851    /// test the only coverage was accidental —
10852    /// `route_open_round_trip_via_tagged_shape_forwards_through_stub` asserts the
10853    /// stamped principal on its way past, so narrowing that wire-shape test to its
10854    /// stated subject would have deleted the last assertion on this value. It
10855    /// still asserts the stamp, which is now redundancy rather than the only
10856    /// guard: both fail under the same mutation, and this one names the reason.
10857    /// SCOPE: this handler's supervisor has spawned nothing, so
10858    /// `spawned_consumer_authorized` can only ever return false and the GRANT arm
10859    /// is unreachable here. Both assertions below are refusals, and a mutant that
10860    /// refuses everything would satisfy them.
10861    ///
10862    /// The grant side is covered where a real nonce exists: `tests/forwarding.rs`
10863    /// spawns a supervised consumer, reads its live nonce, and asserts the module
10864    /// observed `principal.kind == "reserved"` carrying that module_id — verified
10865    /// at source rather than assumed, since a citation is a claim about another
10866    /// file and ages like one. Recorded because a harness that structurally
10867    /// cannot reach an arm reports "none" for that arm identically to one that
10868    /// covers it and found nothing.
10869    #[tokio::test]
10870    async fn an_unattested_caller_is_never_stamped_as_a_supervised_module() {
10871        let handler = ControlHandler::default();
10872        let frame =
10873            Frame::build(FrameType::Request, control_flags(), 0, 0, 900, Vec::new()).unwrap();
10874
10875        // Absent consumer_identity is the ordinary case: a human at a terminal, or
10876        // any process holding the connection file. Nothing was proved, so nothing
10877        // may be granted beyond the unattested floor.
10878        let stamped = handler
10879            .route_open_principal(ConnectionId::new(1), &frame, None)
10880            .unwrap()
10881            .unwrap();
10882        assert_eq!(
10883            stamped,
10884            Principal::Direct,
10885            "a caller that proved nothing must not be stamped as a supervised module"
10886        );
10887
10888        // A claimed module_id with a nonce no supervised child was given is a
10889        // forgery attempt, not a weaker caller: it must be REFUSED rather than
10890        // quietly demoted to Direct, or an impersonation attempt looks identical
10891        // to an ordinary unattested connection.
10892        let forged = handler
10893            .route_open_principal(
10894                ConnectionId::new(1),
10895                &frame,
10896                Some(ConsumerIdentity {
10897                    module_id: "aft".to_string(),
10898                    launch_nonce: "not-a-real-nonce".to_string(),
10899                }),
10900            )
10901            .unwrap();
10902        let refusal = forged.expect_err("an unmatched launch nonce must not yield a principal");
10903        assert_eq!(parse_error(&refusal)["code"], "bad_consumer_identity");
10904    }
10905
10906    /// The test above hands `route_open_principal` an identity it built itself,
10907    /// which proves the stamping rule and nothing about where the identity comes
10908    /// from. The real producer is a wire body, and the two are joined by a serde
10909    /// field name that nothing else asserts.
10910    ///
10911    /// That join fails quietly in one specific way: an unrecognised key is simply
10912    /// absent after parsing, so a renamed or misspelled `consumer_identity`
10913    /// yields `None` and every supervised module silently drops to `Direct`.
10914    /// Capability-wise that is the safe direction, but it surfaces far from its
10915    /// cause — as a module mysteriously refused bash — and it would pass every
10916    /// test that builds its own input.
10917    ///
10918    /// Deliberately NOT closed with `deny_unknown_fields`: refusing unknown keys
10919    /// would break every client the moment the daemon gains a field, trading a
10920    /// quiet demotion for a hard refusal on additive change. Asserting the join
10921    /// instead means a rename breaks a test here rather than the fleet.
10922    #[test]
10923    fn a_wire_body_actually_yields_the_consumer_identity_the_daemon_stamps_from() {
10924        let body = br#"{"op":"route.open","target":{"kind":"tool_provider","module_id":"m"},"identity":{"session":"s","project_root":"/p","harness":"h"},"consumer_identity":{"module_id":"aft","launch_nonce":"n"}}"#;
10925        let parsed: ClientControlRequest = serde_json::from_slice(body).unwrap();
10926        let ClientControlRequest::RouteOpen {
10927            consumer_identity, ..
10928        } = parsed
10929        else {
10930            panic!("route.open body must parse as RouteOpen");
10931        };
10932        assert_eq!(
10933            consumer_identity,
10934            Some(ConsumerIdentity {
10935                module_id: "aft".to_string(),
10936                launch_nonce: "n".to_string(),
10937            }),
10938            "the wire field name must reach the value route_open_principal reads"
10939        );
10940    }
10941
10942    fn manifest(module_id: &str, protocol_ver: u8) -> ModuleManifest {
10943        ModuleManifest::builder(module_id, "0.1.0")
10944            .protocol_ver(protocol_ver)
10945            .provides(vec![ProviderRole::ToolProvider {
10946                tools: vec![Tool {
10947                    name: "read".to_string(),
10948                    description: None,
10949                    execution_mode: ExecutionMode::Pure,
10950                    schema: json!({"type": "object"}),
10951                }],
10952                identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
10953                concurrency: Concurrency::ModuleManaged,
10954                emits_push: true,
10955                sub_supervises: true,
10956            }])
10957            .build()
10958    }
10959
10960    fn hello_frame(module_id: &str, protocol_ver: u8, corr: u64) -> Frame {
10961        hello_frame_with_control_ops(module_id, protocol_ver, corr, None)
10962    }
10963
10964    fn hello_frame_with_control_ops(
10965        module_id: &str,
10966        protocol_ver: u8,
10967        corr: u64,
10968        control_ops: Option<Vec<String>>,
10969    ) -> Frame {
10970        hello_frame_full(module_id, protocol_ver, corr, control_ops, None)
10971    }
10972
10973    fn hello_frame_with_nonce(
10974        module_id: &str,
10975        protocol_ver: u8,
10976        corr: u64,
10977        launch_nonce: Option<&str>,
10978    ) -> Frame {
10979        hello_frame_full(
10980            module_id,
10981            protocol_ver,
10982            corr,
10983            None,
10984            launch_nonce.map(ToOwned::to_owned),
10985        )
10986    }
10987
10988    fn hello_frame_full(
10989        module_id: &str,
10990        protocol_ver: u8,
10991        corr: u64,
10992        control_ops: Option<Vec<String>>,
10993        launch_nonce: Option<String>,
10994    ) -> Frame {
10995        let body = serde_json::to_vec(&ModuleHelloBody {
10996            manifest: manifest(module_id, protocol_ver),
10997            protocol_ver,
10998            control_ops,
10999            launch_nonce,
11000        })
11001        .unwrap();
11002        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11003    }
11004
11005    fn hello_frame_with_rich_ui(
11006        module_id: &str,
11007        protocol_ver: u8,
11008        corr: u64,
11009        launch_nonce: Option<&str>,
11010        rich_ui: Value,
11011    ) -> Frame {
11012        let mut body = serde_json::to_value(ModuleHelloBody {
11013            manifest: manifest(module_id, protocol_ver),
11014            protocol_ver,
11015            control_ops: None,
11016            launch_nonce: launch_nonce.map(str::to_string),
11017        })
11018        .unwrap();
11019        body["manifest"]["rich_ui"] = rich_ui;
11020        Frame::build(
11021            FrameType::Hello,
11022            control_flags(),
11023            0,
11024            0,
11025            corr,
11026            serde_json::to_vec(&body).unwrap(),
11027        )
11028        .unwrap()
11029    }
11030
11031    fn non_routable_hello_frame_with_control_ops(
11032        module_id: &str,
11033        corr: u64,
11034        control_ops: Option<Vec<String>>,
11035    ) -> Frame {
11036        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
11037        manifest.provides.clear();
11038        let body = serde_json::to_vec(&ModuleHelloBody {
11039            manifest,
11040            protocol_ver: PROTOCOL_VERSION,
11041            control_ops,
11042            launch_nonce: None,
11043        })
11044        .unwrap();
11045        Frame::build(FrameType::Hello, control_flags(), 0, 0, corr, body).unwrap()
11046    }
11047
11048    fn capability_grammar_hello_frame(
11049        capabilities: Value,
11050        runtime_computed: Option<Value>,
11051        corr: u64,
11052    ) -> Frame {
11053        let mut body = serde_json::to_value(ModuleHelloBody {
11054            manifest: manifest("capability-grammar-test", PROTOCOL_VERSION),
11055            protocol_ver: PROTOCOL_VERSION,
11056            control_ops: None,
11057            launch_nonce: None,
11058        })
11059        .expect("HELLO body serializes");
11060        body["manifest"]["capabilities"] = capabilities;
11061        if let Some(runtime_computed) = runtime_computed {
11062            body["runtime_computed"] = runtime_computed;
11063        }
11064        Frame::build(
11065            FrameType::Hello,
11066            control_flags(),
11067            0,
11068            0,
11069            corr,
11070            serde_json::to_vec(&body).expect("HELLO body reserializes"),
11071        )
11072        .expect("HELLO frame builds")
11073    }
11074
11075    fn channel_request(channel: u16, corr: u64) -> Frame {
11076        Frame::build(
11077            FrameType::Request,
11078            Flags::new(true, Priority::Interactive, false),
11079            channel,
11080            0,
11081            corr,
11082            b"opaque".to_vec(),
11083        )
11084        .unwrap()
11085    }
11086
11087    fn route_ctx(
11088        connection_id: ConnectionId,
11089    ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
11090        let (tx, rx) = mpsc::channel(8);
11091        (
11092            RouteCtx {
11093                connection_id,
11094                egress: FrameSink::new(tx),
11095            },
11096            rx,
11097        )
11098    }
11099
11100    fn parse_ack(frame: &Frame) -> ModuleHelloAckBody {
11101        serde_json::from_slice(&frame.body).unwrap()
11102    }
11103
11104    /// Register a module over a connection that has a sink and return the
11105    /// HELLO_ACK the module reads. A successful HELLO queues its ack on the
11106    /// module's own sink rather than returning it as a reply, so the ack is
11107    /// taken off `rx` here and whatever the test reads next is what followed it.
11108    async fn hello_via_sink(
11109        handler: &ControlHandler,
11110        ctx: &RouteCtx,
11111        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
11112        hello: Frame,
11113    ) -> Frame {
11114        let replies = handler.handle_control_frame(ctx, hello).await.unwrap();
11115        assert!(
11116            replies.is_empty(),
11117            "a registered HELLO replies with nothing; its ack is already queued: {replies:?}"
11118        );
11119        let ack = rx
11120            .try_recv()
11121            .expect("HELLO_ACK is queued on the module sink")
11122            .frame;
11123        assert_eq!(ack.header.ty, FrameType::HelloAck);
11124        ack
11125    }
11126
11127    fn parse_error(frame: &Frame) -> Value {
11128        serde_json::from_slice(&frame.body).unwrap()
11129    }
11130
11131    fn parse_route_poll(frame: &Frame) -> ClientControlResponse {
11132        serde_json::from_slice(&frame.body).unwrap()
11133    }
11134
11135    fn route_poll_frame(corr: u64, kind: PollKind, route_channel: u16) -> Frame {
11136        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
11137            route_channel,
11138            route_epoch: 0,
11139            kind,
11140        })
11141        .unwrap();
11142        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11143    }
11144
11145    fn supervisor_health_probe_frame(corr: u64, module_id: &str) -> Frame {
11146        let body = serde_json::to_vec(&ClientControlRequest::SupervisorHealthProbe {
11147            module_id: module_id.to_string(),
11148        })
11149        .unwrap();
11150        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11151    }
11152
11153    fn route_open_frame(corr: u64, module_id: &str, project_root: ScratchDir) -> Frame {
11154        route_open_frame_with_consumer_capabilities(corr, module_id, project_root, None)
11155    }
11156
11157    // Exercise retired opener fields without putting them back in BindIdentity.
11158    fn legacy_route_open_frame(corr: u64, module_id: &str, root: ScratchDir) -> Frame {
11159        let path = ProjectRootId::from_path_allowing_missing(root.path()).unwrap();
11160        let mut frame = route_open_frame(corr, module_id, root);
11161        let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
11162        body["identity"]["project_root"] = serde_json::json!(path.as_path());
11163        frame.body = serde_json::to_vec(&body).unwrap();
11164        frame
11165    }
11166
11167    fn route_open_frame_with_consumer_capabilities(
11168        corr: u64,
11169        module_id: &str,
11170        _project_root: ScratchDir,
11171        consumer_capabilities: Option<Vec<String>>,
11172    ) -> Frame {
11173        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11174            busy_refusals: None,
11175            target: RouteTarget::ToolProvider {
11176                module_id: module_id.to_string(),
11177            },
11178            identity: BindIdentity::new("unit".to_string(), "session".to_string()),
11179            consumer_identity: None,
11180            consumer_capabilities,
11181            role_versions: None,
11182            admission_facts: None,
11183            scope: None,
11184        })
11185        .unwrap();
11186        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11187    }
11188
11189    fn route_open_frame_with_role_versions(
11190        corr: u64,
11191        module_id: &str,
11192        _project_root: ScratchDir,
11193        role_versions: Option<BTreeMap<String, String>>,
11194    ) -> Frame {
11195        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11196            busy_refusals: None,
11197            target: RouteTarget::ToolProvider {
11198                module_id: module_id.to_string(),
11199            },
11200            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11201            consumer_identity: None,
11202            consumer_capabilities: None,
11203            role_versions,
11204            admission_facts: None,
11205            scope: None,
11206        })
11207        .unwrap();
11208        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11209    }
11210
11211    fn role_versions(entries: &[(&str, &str)]) -> BTreeMap<String, String> {
11212        entries
11213            .iter()
11214            .map(|(role, version)| (role.to_string(), version.to_string()))
11215            .collect()
11216    }
11217
11218    fn route_open_frame_with_admission_facts(
11219        corr: u64,
11220        module_id: &str,
11221        _project_root: ScratchDir,
11222        consumer_identity: Option<subc_control::ConsumerIdentity>,
11223        facts: Option<Value>,
11224    ) -> Frame {
11225        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
11226            busy_refusals: None,
11227            target: RouteTarget::ToolProvider {
11228                module_id: module_id.to_string(),
11229            },
11230            identity: BindIdentity::new("unit".to_string(), format!("session-{corr}")),
11231            consumer_identity,
11232            consumer_capabilities: None,
11233            role_versions: None,
11234            admission_facts: facts,
11235            scope: None,
11236        })
11237        .unwrap();
11238        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
11239    }
11240
11241    #[derive(Clone, Default)]
11242    struct EventCapture {
11243        events: Arc<Mutex<Vec<CapturedEvent>>>,
11244    }
11245
11246    #[derive(Clone, Debug)]
11247    struct CapturedEvent {
11248        target: String,
11249        level: tracing::Level,
11250        fields: BTreeMap<String, String>,
11251    }
11252
11253    impl EventCapture {
11254        fn events(&self) -> Vec<CapturedEvent> {
11255            self.events.lock().unwrap().clone()
11256        }
11257    }
11258
11259    impl<S> Layer<S> for EventCapture
11260    where
11261        S: Subscriber,
11262    {
11263        fn on_event(&self, event: &Event<'_>, _context: Context<'_, S>) {
11264            let mut visitor = EventFieldVisitor::default();
11265            event.record(&mut visitor);
11266            self.events.lock().unwrap().push(CapturedEvent {
11267                target: event.metadata().target().to_string(),
11268                level: *event.metadata().level(),
11269                fields: visitor.fields,
11270            });
11271        }
11272    }
11273
11274    #[derive(Default)]
11275    struct EventFieldVisitor {
11276        fields: BTreeMap<String, String>,
11277    }
11278
11279    impl Visit for EventFieldVisitor {
11280        fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
11281            self.fields
11282                .insert(field.name().to_string(), format!("{value:?}"));
11283        }
11284    }
11285
11286    fn health_response(corr: u64, status: HealthStatus) -> Frame {
11287        let body = serde_json::to_vec(&ModuleControlResponse::HealthCheck {
11288            status,
11289            detail: Some("warming".to_string()),
11290            metrics: Some(json!({"queue_depth": 3})),
11291        })
11292        .unwrap();
11293        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11294    }
11295
11296    fn route_bind_ack(corr: u64) -> Frame {
11297        let body = serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap();
11298        Frame::build(FrameType::Response, control_flags(), 0, 0, corr, body).unwrap()
11299    }
11300
11301    fn unique_project_root(label: &str) -> ScratchDir {
11302        ScratchDir::new(label)
11303    }
11304
11305    fn assert_route_poll_liveness(frame: &Frame, expected_live: bool) {
11306        match parse_route_poll(frame) {
11307            ClientControlResponse::RoutePoll {
11308                status: None,
11309                live: Some(live),
11310                ..
11311            } => assert_eq!(live, expected_live),
11312            other => panic!("unexpected route.poll response: {other:?}"),
11313        }
11314    }
11315
11316    fn bind_liveness_route(
11317        registry: &Registry,
11318        forwarding: &ForwardingTable,
11319        module_id: &str,
11320    ) -> (RouteCtx, u16, u32) {
11321        let module_connection = ConnectionId::new(101);
11322        let client_connection = ConnectionId::new(202);
11323        let registration = registry
11324            .register_with_control_ops(
11325                manifest(module_id, PROTOCOL_VERSION),
11326                PROTOCOL_VERSION,
11327                module_connection,
11328                module_baseline_control_ops(),
11329            )
11330            .unwrap();
11331        let (module_tx, _module_rx) = mpsc::channel(8);
11332        let endpoint = forwarding
11333            .register_module_connection(
11334                module_connection,
11335                module_id.to_string(),
11336                PROTOCOL_VERSION,
11337                manifest_concurrency(&registration.manifest),
11338                FrameSink::new(module_tx),
11339            )
11340            .unwrap();
11341        let (client_ctx, _client_rx) = route_ctx(client_connection);
11342        let pending = forwarding
11343            .begin_route_bind_relay_for_test(
11344                client_connection,
11345                client_ctx.egress.clone(),
11346                1,
11347                module_id,
11348            )
11349            .unwrap();
11350        assert_eq!(pending.endpoint, endpoint);
11351        let route_channel = pending.client_channel;
11352        let route_epoch = pending.client_epoch;
11353        forwarding
11354            .complete_pending_relay(
11355                module_connection,
11356                pending.corr,
11357                RouteBindRelayOutcome::Accepted,
11358            )
11359            .unwrap();
11360        (client_ctx, route_channel, route_epoch)
11361    }
11362
11363    struct FakeProcessLiveness {
11364        live: Option<bool>,
11365    }
11366
11367    impl ModuleProcessLiveness for FakeProcessLiveness {
11368        fn process_live(&self, _module_id: &str) -> Option<bool> {
11369            self.live
11370        }
11371    }
11372
11373    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11374    async fn supervisor_stderr_tail_converts_a_real_truncated_ring_entry_to_prefix_only_wire_data()
11375    {
11376        let registry = Arc::new(Registry::default());
11377        let supervisor_handle = SupervisorHandle::new();
11378        let supervisor = Supervisor::new_for_test(
11379            Arc::clone(&registry),
11380            RestartPolicy::new(1, Duration::from_millis(10)),
11381        )
11382        .with_handle(supervisor_handle.clone());
11383        let source_line = format!("config error: {}", "x".repeat(DEFAULT_MAX_LINE_BYTES));
11384        let module = supervisor
11385            .spawn(ModuleSpec {
11386                script: None,
11387                carry_containment: false,
11388                module_id: "stderr-tail-wire".to_string(),
11389                program: fake_aft_stub_path(),
11390                args: Vec::new(),
11391                env: vec![
11392                    ("FAKE_AFT_STDERR_LINE".to_string(), source_line.clone()),
11393                    ("FAKE_AFT_EXIT_CODE".to_string(), "1".to_string()),
11394                ],
11395                reserved: false,
11396                reserved_prefixes: Vec::new(),
11397                protocol: ModuleProtocol::Subc,
11398                overlap: Default::default(),
11399            })
11400            .unwrap();
11401
11402        let deadline = Instant::now() + Duration::from_secs(5);
11403        loop {
11404            let tail = module.stderr_tail(None, None);
11405            if tail
11406                .entries
11407                .iter()
11408                .any(|entry| matches!(entry, TailEntry::ProcessStart))
11409                && tail.entries.iter().any(|entry| {
11410                    matches!(
11411                        entry,
11412                        TailEntry::Line {
11413                            truncated: true,
11414                            ..
11415                        }
11416                    )
11417                })
11418            {
11419                break;
11420            }
11421            assert!(
11422                Instant::now() < deadline,
11423                "module did not produce a truncated line and restart boundary: {tail:?}"
11424            );
11425            sleep(Duration::from_millis(10)).await;
11426        }
11427
11428        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11429        let request = ClientControlRequest::SupervisorStderrTail {
11430            module_id: "stderr-tail-wire".to_string(),
11431            max_lines: None,
11432            max_bytes: None,
11433        };
11434        let frame = Frame::build(
11435            FrameType::Request,
11436            control_flags(),
11437            0,
11438            0,
11439            1,
11440            serde_json::to_vec(&request).unwrap(),
11441        )
11442        .unwrap();
11443        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11444        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11445        let ClientControlResponse::SupervisorStderrTail { tail, .. } =
11446            serde_json::from_slice(&responses[0].body).unwrap()
11447        else {
11448            panic!("expected supervisor.stderr_tail response");
11449        };
11450
11451        assert!(
11452            tail.entries
11453                .iter()
11454                .any(|entry| matches!(entry, StderrTailEntry::ProcessStart)),
11455            "the control response lost the restart boundary"
11456        );
11457        let Some(StderrTailEntry::Line {
11458            text,
11459            truncated,
11460            at_ms,
11461        }) = tail.entries.iter().find(|entry| {
11462            matches!(
11463                entry,
11464                StderrTailEntry::Line {
11465                    truncated: true,
11466                    ..
11467                }
11468            )
11469        })
11470        else {
11471            panic!("the control response lost the truncated line");
11472        };
11473        assert_eq!(text, &source_line[..DEFAULT_MAX_LINE_BYTES]);
11474        assert!(*truncated);
11475        assert!(
11476            at_ms.is_some(),
11477            "the control response lost the line's capture time"
11478        );
11479    }
11480
11481    /// `supervisor.terminals` reads journal files. On a single-worker runtime a
11482    /// read done on the worker thread would stall every other task until it
11483    /// finished; the read must run off the worker so this test's own task keeps
11484    /// running while the read is paused.
11485    #[tokio::test(flavor = "current_thread")]
11486    async fn supervisor_terminals_reads_the_journal_off_the_runtime_worker() {
11487        let dir = ScratchDir::new("terminals-off-worker");
11488        let journal_path = dir.join("terminals.jsonl");
11489        let registry = Arc::new(Registry::default());
11490        let supervisor_handle = SupervisorHandle::new();
11491        let supervisor =
11492            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11493                .with_handle(supervisor_handle.clone())
11494                .with_terminal_journal(journal_path.clone(), "off-worker-daemon".to_string());
11495        let module = supervisor
11496            .spawn(ModuleSpec {
11497                script: None,
11498                carry_containment: false,
11499                module_id: "terminal-off-worker".to_string(),
11500                program: fake_aft_stub_path(),
11501                args: Vec::new(),
11502                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11503                reserved: false,
11504                reserved_prefixes: Vec::new(),
11505                protocol: ModuleProtocol::Subc,
11506                overlap: Default::default(),
11507            })
11508            .unwrap();
11509        let deadline = Instant::now() + Duration::from_secs(5);
11510        while module.terminal_history().entries.len() != 2 {
11511            assert!(Instant::now() < deadline, "module did not record two exits");
11512            sleep(Duration::from_millis(10)).await;
11513        }
11514
11515        let (started, release) = crate::terminal_journal::read_pause::install(&journal_path);
11516        let handler =
11517            Arc::new(ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle));
11518        let frame = Frame::build(
11519            FrameType::Request,
11520            control_flags(),
11521            0,
11522            0,
11523            1,
11524            serde_json::to_vec(&ClientControlRequest::SupervisorTerminals {
11525                module_id: "terminal-off-worker".to_string(),
11526            })
11527            .unwrap(),
11528        )
11529        .unwrap();
11530        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11531        let spawned_at = std::time::Instant::now();
11532        let read = tokio::spawn({
11533            let handler = Arc::clone(&handler);
11534            async move { handler.handle_control_frame(&ctx, frame).await }
11535        });
11536        // Waiting for the pause from a blocking thread keeps this task pending,
11537        // so the runtime's single worker is free to run the read task.
11538        tokio::task::spawn_blocking(move || started.recv_timeout(Duration::from_secs(5)))
11539            .await
11540            .unwrap()
11541            .expect("the history read reached its pause");
11542        let elapsed = spawned_at.elapsed();
11543        assert!(
11544            elapsed < Duration::from_secs(2) && !read.is_finished(),
11545            "this task could not run while the history read was paused \
11546             (resumed after {elapsed:?}, read finished: {})",
11547            read.is_finished()
11548        );
11549
11550        drop(release);
11551        let responses = read.await.unwrap().unwrap();
11552        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11553        let ClientControlResponse::SupervisorTerminals { terminals, .. } = response else {
11554            panic!("expected supervisor.terminals response");
11555        };
11556        assert_eq!(terminals.entries.len(), 2);
11557        assert_eq!(terminals.journal_skipped_lines, 0);
11558        assert_eq!(terminals.journal_read_errors, 0);
11559    }
11560
11561    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
11562    async fn supervisor_terminals_golden_is_generated_through_the_real_handler() {
11563        let registry = Arc::new(Registry::default());
11564        let supervisor_handle = SupervisorHandle::new();
11565        let supervisor =
11566            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(1, Duration::ZERO))
11567                .with_handle(supervisor_handle.clone());
11568        let module = supervisor
11569            .spawn(ModuleSpec {
11570                script: None,
11571                carry_containment: false,
11572                module_id: "terminal-golden".to_string(),
11573                program: fake_aft_stub_path(),
11574                args: Vec::new(),
11575                env: vec![("FAKE_AFT_EXIT_CODE".to_string(), "23".to_string())],
11576                reserved: false,
11577                reserved_prefixes: Vec::new(),
11578                protocol: ModuleProtocol::Subc,
11579                overlap: Default::default(),
11580            })
11581            .unwrap();
11582
11583        let deadline = Instant::now() + Duration::from_secs(5);
11584        while module.terminal_history().entries.len() != 2 {
11585            assert!(
11586                Instant::now() < deadline,
11587                "module did not retain two terminal exits: {:?}",
11588                module.terminal_history()
11589            );
11590            sleep(Duration::from_millis(10)).await;
11591        }
11592
11593        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
11594        let request = ClientControlRequest::SupervisorTerminals {
11595            module_id: "terminal-golden".to_string(),
11596        };
11597        let frame = Frame::build(
11598            FrameType::Request,
11599            control_flags(),
11600            0,
11601            0,
11602            1,
11603            serde_json::to_vec(&request).unwrap(),
11604        )
11605        .unwrap();
11606        let (ctx, _egress) = route_ctx(ConnectionId::new(1));
11607        let responses = handler.handle_control_frame(&ctx, frame).await.unwrap();
11608        let response: ClientControlResponse = serde_json::from_slice(&responses[0].body).unwrap();
11609        let ClientControlResponse::SupervisorTerminals { terminals, .. } = &response else {
11610            panic!("expected supervisor.terminals response");
11611        };
11612        assert_eq!(terminals.entries.len(), 2);
11613        assert_eq!(terminals.dropped, 0);
11614
11615        let mut rendered = serde_json::to_value(response).unwrap();
11616        // Wall-clock fields are the observation contract, but not stable fixture
11617        // bytes; normalize only them after the real handler has shaped the response.
11618        rendered["daemon_started_at_ms"] = json!(1_700_000_000_000u64);
11619        for (index, entry) in rendered["entries"]
11620            .as_array_mut()
11621            .expect("terminal response entries array")
11622            .iter_mut()
11623            .enumerate()
11624        {
11625            entry["at_ms"] = json!(1_700_000_000_001u64 + index as u64);
11626        }
11627
11628        let golden_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
11629            .join("../subc-control/tests/golden/client_control_response_supervisor_terminals.json");
11630        let serialized = serde_json::to_string_pretty(&rendered).unwrap() + "\n";
11631        if std::env::var_os("UPDATE_GOLDEN").is_some() {
11632            std::fs::write(&golden_path, &serialized).unwrap();
11633        }
11634        let expected: Value =
11635            serde_json::from_str(&std::fs::read_to_string(&golden_path).unwrap()).unwrap();
11636        assert_eq!(rendered, expected);
11637    }
11638
11639    #[test]
11640    fn hello_registers_manifest_and_returns_ack() {
11641        let registry = Arc::new(Registry::default());
11642        let handler = ControlHandler::new(Arc::clone(&registry));
11643        let conn = ConnectionId::new(1);
11644
11645        let responses = handler
11646            .handle_control(conn, hello_frame("aft", PROTOCOL_VERSION, 7))
11647            .unwrap();
11648
11649        assert_eq!(responses.len(), 1);
11650        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
11651        assert_eq!(responses[0].header.channel, 0);
11652        assert_eq!(responses[0].header.corr, 7);
11653        let ack = parse_ack(&responses[0]);
11654        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
11655        assert!(ack
11656            .subc_capabilities
11657            .contains(&CAP_MANIFEST_REGISTRATION.to_string()));
11658        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_LIST.to_string()));
11659        assert!(ack.subc_ops.contains(&ops::SUPERVISOR_RESTART.to_string()));
11660        assert!(ack
11661            .subc_ops
11662            .contains(&ops::SUPERVISOR_SET_ENABLED.to_string()));
11663        assert!(ack
11664            .subc_ops
11665            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE.to_string()));
11666        assert!(ack
11667            .subc_ops
11668            .contains(&MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS.to_string()));
11669
11670        let registration = registry.get_module("aft").unwrap().unwrap();
11671        assert_eq!(registration.negotiated_ver, PROTOCOL_VERSION);
11672        assert_eq!(registration.state, ChannelState::Active);
11673        assert_eq!(registration.connection_id, conn);
11674        assert_eq!(registration.control_ops, module_baseline_control_ops());
11675        assert!(registration.manifest.display_name.is_none());
11676    }
11677
11678    #[test]
11679    fn hello_display_name_refuses_invalid_manifest_by_field() {
11680        let registry = Arc::new(Registry::default());
11681        let handler = ControlHandler::new(Arc::clone(&registry));
11682        for (index, invalid) in [
11683            json!(""),
11684            json!("a".repeat(41)),
11685            json!(" Routing"),
11686            json!("a\nb"),
11687            json!("a\u{202e}b"),
11688            json!(7),
11689        ]
11690        .into_iter()
11691        .enumerate()
11692        {
11693            let module_id = format!("bad-display-name-{index}");
11694            let mut body = serde_json::to_value(ModuleHelloBody {
11695                manifest: manifest(&module_id, PROTOCOL_VERSION),
11696                protocol_ver: PROTOCOL_VERSION,
11697                control_ops: None,
11698                launch_nonce: None,
11699            })
11700            .unwrap();
11701            body["manifest"]["display_name"] = invalid;
11702            let hello = Frame::build(
11703                FrameType::Hello,
11704                control_flags(),
11705                0,
11706                0,
11707                7,
11708                serde_json::to_vec(&body).unwrap(),
11709            )
11710            .unwrap();
11711            let response = handler
11712                .handle_control(ConnectionId::new(100 + index as u64), hello)
11713                .unwrap();
11714            assert_eq!(response[0].header.ty, FrameType::Error);
11715            let error = parse_error(&response[0]);
11716            assert_eq!(error["code"], "invalid_manifest");
11717            assert!(error["message"].as_str().unwrap().contains("display_name"));
11718            assert!(registry.get_module(&module_id).unwrap().is_none());
11719        }
11720    }
11721
11722    #[test]
11723    fn capability_grammar_refusals_name_the_field_and_leave_no_catalog_entry() {
11724        let invalid_identifiers = [
11725            ("case_change", "credentials-Provider/v1"),
11726            ("leading_zero", "credentials-provider/v01"),
11727            ("trailing_hyphen", "credentials-provider-/v1"),
11728            ("consecutive_hyphens", "credentials--provider/v1"),
11729            ("uppercase", "Credentials-provider/v1"),
11730            ("missing_v", "credentials-provider/1"),
11731            ("whitespace", "credentials provider/v1"),
11732            ("zero_version", "credentials-provider/v0"),
11733            ("out_of_range_version", "credentials-provider/v4294967296"),
11734            (
11735                "overlength_name",
11736                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/v1",
11737            ),
11738        ];
11739        let mut cases = invalid_identifiers
11740            .into_iter()
11741            .map(|(name, identifier)| {
11742                (
11743                    format!("identifier_{name}"),
11744                    "capabilities.provides[0]".to_string(),
11745                    identifier.to_string(),
11746                    json!({ "provides": [identifier] }),
11747                    None,
11748                )
11749            })
11750            .collect::<Vec<_>>();
11751        cases.extend([
11752            (
11753                "unknown_need".to_string(),
11754                "capabilities.requires[0].need".to_string(),
11755                "deferred".to_string(),
11756                json!({ "requires": [{ "capability": "credentials-provider/v1", "need": "deferred" }] }),
11757                None,
11758            ),
11759            (
11760                "duplicate_provides".to_string(),
11761                "capabilities.provides[1]".to_string(),
11762                "credentials-provider/v1".to_string(),
11763                json!({ "provides": ["credentials-provider/v1", "credentials-provider/v1"] }),
11764                None,
11765            ),
11766            (
11767                "duplicate_must_never_reach".to_string(),
11768                "capabilities.must_never_reach[1]".to_string(),
11769                "credentials-provider/v1".to_string(),
11770                json!({ "must_never_reach": ["credentials-provider/v1", "credentials-provider/v1"] }),
11771                None,
11772            ),
11773            (
11774                "duplicate_requires_same_need".to_string(),
11775                "capabilities.requires[1]".to_string(),
11776                "credentials-provider/v1".to_string(),
11777                json!({ "requires": [
11778                    { "capability": "credentials-provider/v1", "need": "required" },
11779                    { "capability": "credentials-provider/v1", "need": "required" }
11780                ] }),
11781                None,
11782            ),
11783            (
11784                "duplicate_requires_conflicting_need".to_string(),
11785                "capabilities.requires[1]".to_string(),
11786                "credentials-provider/v1".to_string(),
11787                json!({ "requires": [
11788                    { "capability": "credentials-provider/v1", "need": "required" },
11789                    { "capability": "credentials-provider/v1", "need": "optional" }
11790                ] }),
11791                None,
11792            ),
11793            (
11794                "capabilities_root_pointer".to_string(),
11795                "runtime_computed[0]".to_string(),
11796                "/capabilities".to_string(),
11797                json!({}),
11798                Some(json!(["/capabilities"])),
11799            ),
11800            (
11801                "capabilities_descendant_pointer".to_string(),
11802                "runtime_computed[0]".to_string(),
11803                "/capabilities/provides".to_string(),
11804                json!({}),
11805                Some(json!(["/capabilities/provides"])),
11806            ),
11807            (
11808                "malformed_pointer_without_leading_slash".to_string(),
11809                "runtime_computed[0]".to_string(),
11810                "capabilities".to_string(),
11811                json!({}),
11812                Some(json!(["capabilities"])),
11813            ),
11814            (
11815                "malformed_pointer_escape".to_string(),
11816                "runtime_computed[0]".to_string(),
11817                "/roles/~2/tools".to_string(),
11818                json!({}),
11819                Some(json!(["/roles/~2/tools"])),
11820            ),
11821            (
11822                "unknown_capabilities_field".to_string(),
11823                "capabilities.future".to_string(),
11824                "<array>".to_string(),
11825                json!({ "future": [] }),
11826                None,
11827            ),
11828        ]);
11829
11830        for (index, (name, field, value, capabilities, runtime_computed)) in
11831            cases.into_iter().enumerate()
11832        {
11833            let registry = Arc::new(Registry::default());
11834            let handler = ControlHandler::new(Arc::clone(&registry));
11835            let response = handler
11836                .handle_control(
11837                    ConnectionId::new((index + 1) as u64),
11838                    capability_grammar_hello_frame(
11839                        capabilities,
11840                        runtime_computed,
11841                        index as u64 + 1,
11842                    ),
11843                )
11844                .expect("invalid HELLO returns a refusal");
11845
11846            assert_eq!(response.len(), 1, "{name} must emit one refusal");
11847            let error = parse_error(&response[0]);
11848            assert_eq!(error["code"], "invalid_capability_grammar", "{name}");
11849            let message = error["message"]
11850                .as_str()
11851                .expect("error message is a string");
11852            assert!(
11853                message.contains(&field),
11854                "{name}: field missing from {message}"
11855            );
11856            assert!(
11857                message.contains(&value),
11858                "{name}: value missing from {message}"
11859            );
11860            assert_eq!(
11861                registry
11862                    .active_registration_count()
11863                    .expect("registry reads"),
11864                0,
11865                "{name}: refused HELLO must not create a catalog entry"
11866            );
11867        }
11868    }
11869
11870    #[test]
11871    fn legal_runtime_pointer_and_capabilities_are_mirrored_in_catalog_list() {
11872        let registry = Arc::new(Registry::default());
11873        let handler = ControlHandler::new(Arc::clone(&registry));
11874        let capabilities = json!({
11875            "provides": ["credentials-provider/v1"],
11876            "requires": [{ "capability": "context-transform/v1", "need": "optional" }],
11877            "must_never_reach": ["federation-transport/v1"]
11878        });
11879        let response = handler
11880            .handle_control(
11881                ConnectionId::new(99),
11882                capability_grammar_hello_frame(
11883                    capabilities.clone(),
11884                    Some(json!(["/roles/0/tools"])),
11885                    99,
11886                ),
11887            )
11888            .expect("valid HELLO registers");
11889        assert_eq!(response[0].header.ty, FrameType::HelloAck);
11890
11891        let request = Frame::build(
11892            FrameType::Request,
11893            control_flags(),
11894            0,
11895            0,
11896            100,
11897            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
11898                .expect("catalog request serializes"),
11899        )
11900        .expect("catalog request frame builds");
11901        let response = handler
11902            .handle_catalog_list(request, None)
11903            .expect("catalog list succeeds");
11904        let ClientControlResponse::CatalogList { modules, .. } =
11905            serde_json::from_slice(&response[0].body).expect("catalog response decodes")
11906        else {
11907            panic!("catalog request must return catalog.list");
11908        };
11909        assert_eq!(modules.len(), 1);
11910        assert_eq!(
11911            serde_json::to_value(&modules[0].capabilities).expect("catalog capabilities serialize"),
11912            capabilities
11913        );
11914    }
11915
11916    #[test]
11917    fn catalog_list_mirrors_management_operation_description() {
11918        let registry = Arc::new(Registry::default());
11919        let handler = ControlHandler::new(Arc::clone(&registry));
11920        let description = "List managed records and return their identifiers and metadata.";
11921        let mut manifest = manifest("described-management", PROTOCOL_VERSION);
11922        manifest.provides = vec![ProviderRole::ManagementSurface {
11923            operations: vec![ManagementOperation {
11924                name: "records.list".to_string(),
11925                kind: ManagementOperationKind::Query,
11926                description: Some(description.to_string()),
11927            }],
11928            config_schema: json!({"type": "object"}),
11929            observability: vec![ObservabilitySurface {
11930                name: "records.stats".to_string(),
11931                kind: ObservabilityKind::Snapshot,
11932            }],
11933            identity_scope: vec![IdentityScope::Project],
11934            concurrency: Concurrency::ModuleManaged,
11935        }];
11936        registry
11937            .register_with_control_ops(
11938                manifest,
11939                PROTOCOL_VERSION,
11940                ConnectionId::new(99),
11941                Vec::new(),
11942            )
11943            .expect("described management manifest registers");
11944
11945        let request = Frame::build(
11946            FrameType::Request,
11947            control_flags(),
11948            0,
11949            0,
11950            100,
11951            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
11952                .expect("catalog request serializes"),
11953        )
11954        .expect("catalog request frame builds");
11955        let response = handler
11956            .handle_catalog_list(request, None)
11957            .expect("catalog list succeeds");
11958        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
11959        assert_eq!(
11960            body["modules"][0]["roles"][0]["operations"][0]["description"], description,
11961            "catalog.list must preserve the declared operation description verbatim"
11962        );
11963    }
11964
11965    #[test]
11966    fn catalog_list_mirrors_registered_operation_delivery() {
11967        let registry = Arc::new(Registry::default());
11968        let handler = ControlHandler::new(Arc::clone(&registry));
11969        let delivery =
11970            json!({"status": "watch", "future": "stream-v2", "reset": "watch", "missing": "watch"});
11971        let mut body = serde_json::to_value(ModuleHelloBody {
11972            manifest: manifest("watch-management", PROTOCOL_VERSION),
11973            protocol_ver: PROTOCOL_VERSION,
11974            control_ops: None,
11975            launch_nonce: None,
11976        })
11977        .unwrap();
11978        body["manifest"]["provides"] = json!([{
11979            "role": "management_surface",
11980            "operations": [
11981                {"name": "status", "kind": "query"},
11982                {"name": "future", "kind": "query"},
11983                {"name": "reset", "kind": "mutate"}
11984            ],
11985            "config_schema": {}, "observability": [], "identity_scope": []
11986        }]);
11987        body["manifest"]["operation_delivery"] = delivery.clone();
11988        let hello = Frame::build(
11989            FrameType::Hello,
11990            control_flags(),
11991            0,
11992            0,
11993            99,
11994            serde_json::to_vec(&body).unwrap(),
11995        )
11996        .unwrap();
11997        let response = handler
11998            .handle_control(ConnectionId::new(99), hello)
11999            .unwrap();
12000        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12001
12002        let (_, registrations) = registry.list_modules().unwrap();
12003        let registered = &registrations[0].manifest;
12004        assert!(registered.is_watch_operation("status"));
12005        assert!(!registered.is_watch_operation("future"));
12006        assert!(!registered.is_watch_operation("reset"));
12007        assert!(!registered.is_watch_operation("missing"));
12008
12009        let request = Frame::build(
12010            FrameType::Request,
12011            control_flags(),
12012            0,
12013            0,
12014            100,
12015            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12016        )
12017        .unwrap();
12018        let response = handler.handle_catalog_list(request, None).unwrap();
12019        let body: Value = serde_json::from_slice(&response[0].body).unwrap();
12020        assert_eq!(body["modules"][0]["operation_delivery"], delivery);
12021        let ClientControlResponse::CatalogList { modules, .. } =
12022            serde_json::from_slice(&response[0].body).unwrap()
12023        else {
12024            panic!("expected catalog.list");
12025        };
12026        assert_eq!(modules[0].operation_delivery, registered.operation_delivery);
12027    }
12028
12029    #[test]
12030    fn catalog_list_mirrors_rich_ui_through_hello_and_catalog_update() {
12031        let registry = Arc::new(Registry::default());
12032        let supervisor = SupervisorHandle::new();
12033        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
12034        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12035        let descriptor = json!({
12036            "schema": "ckios.richui.manifest/1",
12037            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12038            "bytes": 4096,
12039            "chunks": 4
12040        });
12041        let connection = ConnectionId::new(201);
12042        let hello = handler
12043            .handle_control(
12044                connection,
12045                hello_frame_with_rich_ui(
12046                    "vault",
12047                    PROTOCOL_VERSION,
12048                    201,
12049                    Some("the-real-nonce"),
12050                    descriptor.clone(),
12051                ),
12052            )
12053            .unwrap();
12054        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12055
12056        let request =
12057            Frame::build(FrameType::Request, control_flags(), 0, 0, 202, Vec::new()).unwrap();
12058        let provides = registry
12059            .get_module_by_connection(connection)
12060            .unwrap()
12061            .unwrap()
12062            .manifest
12063            .provides;
12064        handler
12065            .handle_catalog_update(connection, request, provides, None, Some(false))
12066            .unwrap();
12067
12068        let request = Frame::build(
12069            FrameType::Request,
12070            control_flags(),
12071            0,
12072            0,
12073            203,
12074            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12075        )
12076        .unwrap();
12077        let response = handler.handle_catalog_list(request, None).unwrap();
12078        let ClientControlResponse::CatalogList { modules, .. } =
12079            serde_json::from_slice(&response[0].body).unwrap()
12080        else {
12081            panic!("expected catalog.list");
12082        };
12083        assert_eq!(
12084            serde_json::to_value(&modules[0]).unwrap()["rich_ui"],
12085            descriptor
12086        );
12087        assert!(modules[0].nonce_verified);
12088    }
12089
12090    fn hello_with_role_declarations(declarations: Value) -> Frame {
12091        let mut body = serde_json::to_value(ModuleHelloBody {
12092            manifest: manifest("role-test", PROTOCOL_VERSION),
12093            protocol_ver: PROTOCOL_VERSION,
12094            control_ops: None,
12095            launch_nonce: None,
12096        })
12097        .unwrap();
12098        body["manifest"]["role_declarations"] = declarations;
12099        Frame::build(
12100            FrameType::Hello,
12101            control_flags(),
12102            0,
12103            0,
12104            301,
12105            serde_json::to_vec(&body).unwrap(),
12106        )
12107        .unwrap()
12108    }
12109
12110    fn update_role_declarations_frame(declarations: Value) -> Frame {
12111        Frame::build(
12112            FrameType::Request,
12113            control_flags(),
12114            0,
12115            0,
12116            303,
12117            serde_json::to_vec(&json!({
12118                "op": "catalog.update_role_declarations",
12119                "role_declarations": declarations,
12120            }))
12121            .unwrap(),
12122        )
12123        .unwrap()
12124    }
12125
12126    #[tokio::test]
12127    async fn role_declarations_update_replaces_then_clears_catalog() {
12128        let registry = Arc::new(Registry::default());
12129        let handler = ControlHandler::new(Arc::clone(&registry));
12130        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12131        let initial = json!({"media-provider/v1": {"engines": ["old"]}, "old/v1": {}});
12132        hello_via_sink(
12133            &handler,
12134            &ctx,
12135            &mut rx,
12136            hello_with_role_declarations(initial.clone()),
12137        )
12138        .await;
12139        assert_eq!(
12140            role_declarations_catalog(&handler).0["role_declarations"],
12141            initial
12142        );
12143        let before = registry.get_module("role-test").unwrap().unwrap();
12144        for declarations in [
12145            json!({"media-provider/v1": {"engines": ["new"]}}),
12146            json!({}),
12147        ] {
12148            let response = handler
12149                .handle_control_frame(&ctx, update_role_declarations_frame(declarations.clone()))
12150                .await
12151                .unwrap();
12152            assert_eq!(response[0].header.ty, FrameType::Response);
12153            assert_eq!(
12154                serde_json::from_slice::<Value>(&response[0].body).unwrap(),
12155                json!({"op": "catalog.update_role_declarations"})
12156            );
12157            let (raw, entry) = role_declarations_catalog(&handler);
12158            assert_eq!(
12159                serde_json::to_value(entry.role_declarations).unwrap(),
12160                declarations
12161            );
12162            if declarations.as_object().unwrap().is_empty() {
12163                assert!(raw.get("role_declarations").is_none());
12164            } else {
12165                assert_eq!(raw["role_declarations"], declarations);
12166            }
12167            let after = registry.get_module("role-test").unwrap().unwrap();
12168            let mut expected = before.manifest.clone();
12169            expected.role_declarations = serde_json::from_value(declarations).unwrap();
12170            assert_eq!(after.manifest, expected);
12171            assert_eq!(after.ready, before.ready);
12172        }
12173    }
12174
12175    #[tokio::test]
12176    async fn role_declarations_update_refuses_invalid_maps_without_changing_catalog() {
12177        let registry = Arc::new(Registry::default());
12178        let handler = ControlHandler::new(registry);
12179        let (ctx, mut rx) = route_ctx(ConnectionId::new(301));
12180        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12181        hello_via_sink(
12182            &handler,
12183            &ctx,
12184            &mut rx,
12185            hello_with_role_declarations(initial.clone()),
12186        )
12187        .await;
12188        for (invalid, reason) in [
12189            (json!(null), "role_declarations must be an object"),
12190            (json!([]), "role_declarations must be an object"),
12191            (
12192                json!({"bad key": {}}),
12193                "role_declarations key must use capability-name grammar",
12194            ),
12195            (
12196                json!({"media-provider/v1": []}),
12197                "role_declarations values must be objects",
12198            ),
12199            (
12200                json!({"media-provider/v1": {"padding": "x".repeat(16384)}}),
12201                "role_declarations exceeds 16384 compact JSON bytes",
12202            ),
12203        ] {
12204            let response = handler
12205                .handle_control_frame(&ctx, update_role_declarations_frame(invalid))
12206                .await
12207                .unwrap();
12208            let error = parse_error(&response[0]);
12209            assert_eq!(error["code"], "invalid_role_declarations");
12210            assert_eq!(error["message"], reason);
12211            assert_eq!(
12212                role_declarations_catalog(&handler).0["role_declarations"],
12213                initial
12214            );
12215        }
12216    }
12217
12218    #[tokio::test]
12219    async fn role_declarations_update_is_owned_by_the_registered_connection() {
12220        let registry = Arc::new(Registry::default());
12221        let handler = ControlHandler::new(Arc::clone(&registry));
12222        let (owner, mut owner_rx) = route_ctx(ConnectionId::new(301));
12223        let initial = json!({"media-provider/v1": {"engines": ["old"]}});
12224        hello_via_sink(
12225            &handler,
12226            &owner,
12227            &mut owner_rx,
12228            hello_with_role_declarations(initial.clone()),
12229        )
12230        .await;
12231        let (other, mut other_rx) = route_ctx(ConnectionId::new(302));
12232        let replacement = json!({"media-provider/v1": {"engines": ["other"]}});
12233        let response = handler
12234            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12235            .await
12236            .unwrap();
12237        assert_eq!(parse_error(&response[0])["code"], "not_registered");
12238        hello_via_sink(
12239            &handler,
12240            &other,
12241            &mut other_rx,
12242            hello_frame("other", PROTOCOL_VERSION, 304),
12243        )
12244        .await;
12245        let response = handler
12246            .handle_control_frame(&other, update_role_declarations_frame(replacement.clone()))
12247            .await
12248            .unwrap();
12249        assert_eq!(response[0].header.ty, FrameType::Response);
12250        assert_eq!(
12251            serde_json::to_value(
12252                registry
12253                    .get_module("role-test")
12254                    .unwrap()
12255                    .unwrap()
12256                    .manifest
12257                    .role_declarations
12258            )
12259            .unwrap(),
12260            initial
12261        );
12262        assert_eq!(
12263            serde_json::to_value(
12264                registry
12265                    .get_module("other")
12266                    .unwrap()
12267                    .unwrap()
12268                    .manifest
12269                    .role_declarations
12270            )
12271            .unwrap(),
12272            replacement
12273        );
12274    }
12275
12276    fn role_declarations_catalog(handler: &ControlHandler) -> (Value, CatalogEntry) {
12277        let request = Frame::build(
12278            FrameType::Request,
12279            control_flags(),
12280            0,
12281            0,
12282            302,
12283            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12284        )
12285        .unwrap();
12286        let response = handler.handle_catalog_list(request, None).unwrap();
12287        let raw: Value = serde_json::from_slice(&response[0].body).unwrap();
12288        let ClientControlResponse::CatalogList { mut modules, .. } =
12289            serde_json::from_slice(&response[0].body).unwrap()
12290        else {
12291            panic!("expected catalog.list");
12292        };
12293        (raw["modules"][0].clone(), modules.remove(0))
12294    }
12295
12296    #[test]
12297    fn catalog_list_mirrors_role_declarations_through_hello_and_catalog_update() {
12298        let registry = Arc::new(Registry::default());
12299        let handler = ControlHandler::new(Arc::clone(&registry));
12300        let declarations = json!({
12301            "routing/v1": {"consumers": [{"name": "chat", "default_demand": 2}]},
12302            "future/v2": {"unknown": [null, true, {"nested": "λ"}]}
12303        });
12304        let connection = ConnectionId::new(301);
12305        let response = handler
12306            .handle_control(
12307                connection,
12308                hello_with_role_declarations(declarations.clone()),
12309            )
12310            .unwrap();
12311        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12312        let registered = registry
12313            .get_module_by_connection(connection)
12314            .unwrap()
12315            .unwrap()
12316            .manifest;
12317        // Compared as JSON values, not bytes: object key order is not part of
12318        // the relay's promise, and workspace builds unify serde_json's
12319        // preserve_order feature, which changes the order a literal keeps.
12320        assert_eq!(
12321            serde_json::to_value(&registered.role_declarations).unwrap(),
12322            declarations
12323        );
12324        let (raw, entry) = role_declarations_catalog(&handler);
12325        assert_eq!(raw["role_declarations"], declarations);
12326        assert_eq!(entry.role_declarations, registered.role_declarations);
12327
12328        let request =
12329            Frame::build(FrameType::Request, control_flags(), 0, 0, 303, Vec::new()).unwrap();
12330        handler
12331            .handle_catalog_update(connection, request, registered.provides, None, Some(false))
12332            .unwrap();
12333        let (raw, entry) = role_declarations_catalog(&handler);
12334        assert_eq!(raw["role_declarations"], declarations);
12335        assert_eq!(entry.role_declarations, registered.role_declarations);
12336    }
12337
12338    fn assert_hello_drops_role_declarations_with_warning(declarations: Value, reason: &str) {
12339        let registry = Arc::new(Registry::default());
12340        let handler = ControlHandler::new(Arc::clone(&registry));
12341        let capture = EventCapture::default();
12342        let _subscriber =
12343            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12344        let response = handler
12345            .handle_control(
12346                ConnectionId::new(301),
12347                hello_with_role_declarations(declarations),
12348            )
12349            .unwrap();
12350        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12351        assert!(registry
12352            .get_module_by_connection(ConnectionId::new(301))
12353            .unwrap()
12354            .unwrap()
12355            .manifest
12356            .role_declarations
12357            .is_empty());
12358        let (raw, entry) = role_declarations_catalog(&handler);
12359        assert!(raw.get("role_declarations").is_none());
12360        assert!(entry.role_declarations.is_empty());
12361        let warnings: Vec<_> = capture
12362            .events()
12363            .into_iter()
12364            .filter(|event| {
12365                event.fields.get("message").map(String::as_str)
12366                    == Some("dropping whole role_declarations map from HELLO")
12367            })
12368            .collect();
12369        assert_eq!(warnings.len(), 1);
12370        assert_eq!(warnings[0].level, tracing::Level::WARN);
12371        assert_eq!(warnings[0].fields["module_id"], "\"role-test\"");
12372        assert_eq!(warnings[0].fields["reason"], reason);
12373    }
12374
12375    #[test]
12376    fn hello_non_object_role_declarations_drop_whole_map_and_warn() {
12377        for value in [
12378            json!(null),
12379            json!(false),
12380            json!(0),
12381            json!("opaque"),
12382            json!([]),
12383        ] {
12384            assert_hello_drops_role_declarations_with_warning(
12385                json!({"routing/v1": {}, "broken/v1": value}),
12386                "role_declarations values must be objects",
12387            );
12388        }
12389        assert_hello_drops_role_declarations_with_warning(
12390            json!([]),
12391            "role_declarations must be an object",
12392        );
12393    }
12394
12395    #[test]
12396    fn hello_bad_role_declaration_key_drops_whole_map_and_warns() {
12397        assert_hello_drops_role_declarations_with_warning(
12398            json!({"routing/v1": {}, "bad key": {}}),
12399            "role_declarations key must use capability-name grammar",
12400        );
12401    }
12402
12403    #[test]
12404    fn hello_oversized_role_declarations_drop_whole_map_and_warn() {
12405        assert_hello_drops_role_declarations_with_warning(
12406            json!({"routing/v1": {}, "overflow/v1": {"padding": "x".repeat(16_384)}}),
12407            "role_declarations exceeds 16384 compact JSON bytes",
12408        );
12409    }
12410
12411    fn hello_with_flow_operations(capabilities: Value, flow_operations: Option<Value>) -> Frame {
12412        let mut body = serde_json::to_value(ModuleHelloBody {
12413            manifest: manifest("flow-ops", PROTOCOL_VERSION),
12414            protocol_ver: PROTOCOL_VERSION,
12415            control_ops: None,
12416            launch_nonce: None,
12417        })
12418        .unwrap();
12419        body["manifest"]["provides"] = json!([{
12420            "role": "management_surface",
12421            "operations": [
12422                {"name": "diagnostics.findings", "kind": "query"},
12423                {"name": "reset", "kind": "mutate"}
12424            ],
12425            "config_schema": {}, "observability": [], "identity_scope": []
12426        }]);
12427        body["manifest"]["capabilities"] = json!({ "provides": capabilities });
12428        if let Some(flow_operations) = flow_operations {
12429            body["manifest"]["flow_operations"] = flow_operations;
12430        }
12431        Frame::build(
12432            FrameType::Hello,
12433            control_flags(),
12434            0,
12435            0,
12436            401,
12437            serde_json::to_vec(&body).unwrap(),
12438        )
12439        .unwrap()
12440    }
12441
12442    #[test]
12443    fn catalog_list_mirrors_flow_operations_unchanged() {
12444        // Order is kept as declared (not sorted) and an empty list stays an
12445        // affirmative "none", distinct from an absent declaration.
12446        for (capability, flow_operations) in [
12447            ("flow-scopes/v1", json!(["reset", "diagnostics.findings"])),
12448            ("call-modes/v1", json!(["diagnostics.findings"])),
12449            ("flow-scopes/v1", json!([])),
12450        ] {
12451            let registry = Arc::new(Registry::default());
12452            let handler = ControlHandler::new(Arc::clone(&registry));
12453            let connection = ConnectionId::new(401);
12454            let response = handler
12455                .handle_control(
12456                    connection,
12457                    hello_with_flow_operations(json!([capability]), Some(flow_operations.clone())),
12458                )
12459                .unwrap();
12460            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12461            let registered = registry
12462                .get_module_by_connection(connection)
12463                .unwrap()
12464                .unwrap()
12465                .manifest;
12466            assert_eq!(
12467                serde_json::to_value(&registered.flow_operations).unwrap(),
12468                flow_operations
12469            );
12470            let (raw, entry) = role_declarations_catalog(&handler);
12471            assert_eq!(raw["flow_operations"], flow_operations);
12472            assert_eq!(entry.flow_operations, registered.flow_operations);
12473        }
12474
12475        let registry = Arc::new(Registry::default());
12476        let handler = ControlHandler::new(Arc::clone(&registry));
12477        let response = handler
12478            .handle_control(
12479                ConnectionId::new(401),
12480                hello_with_flow_operations(json!(["flow-scopes/v1"]), None),
12481            )
12482            .unwrap();
12483        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12484        let (raw, entry) = role_declarations_catalog(&handler);
12485        assert!(raw.get("flow_operations").is_none());
12486        assert_eq!(entry.flow_operations, None);
12487    }
12488
12489    #[test]
12490    fn operation_deferral_hello_accepts_valid_and_invalid_maps_and_catalog_relays_only_valid() {
12491        let oversized: serde_json::Map<String, Value> = (0..257)
12492            .map(|n| (format!("tool:t{n}"), json!(true)))
12493            .collect();
12494        for (capabilities, map, valid) in [
12495            (
12496                json!(["scope-federated/v1"]),
12497                json!({"tool:read":true,"management:reset":true}),
12498                true,
12499            ),
12500            (json!(["scope-federated/v1"]), json!({}), true),
12501            (json!([]), json!({"tool:read":true}), false),
12502            (
12503                json!(["scope-federated/v1"]),
12504                json!({"tool:valid":true,"tool:bad":false}),
12505                false,
12506            ),
12507            (
12508                json!(["scope-federated/v1"]),
12509                json!({"tool:valid":true,"management:missing":true}),
12510                false,
12511            ),
12512            (
12513                json!(["scope-federated/v1"]),
12514                Value::Object(oversized),
12515                false,
12516            ),
12517        ] {
12518            let capture = EventCapture::default();
12519            let _subscriber = tracing::subscriber::set_default(
12520                tracing_subscriber::registry().with(capture.clone()),
12521            );
12522            let registry = Arc::new(Registry::default());
12523            let handler = ControlHandler::new(Arc::clone(&registry));
12524            let hello = hello_with_flow_operations(capabilities, None);
12525            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
12526            body["manifest"]["operation_deferral"] = map.clone();
12527            let hello = Frame::build(
12528                FrameType::Hello,
12529                control_flags(),
12530                0,
12531                0,
12532                401,
12533                serde_json::to_vec(&body).unwrap(),
12534            )
12535            .unwrap();
12536            let response = handler
12537                .handle_control(ConnectionId::new(401), hello)
12538                .unwrap();
12539            assert_eq!(response[0].header.ty, FrameType::HelloAck);
12540            let (raw, entry) = role_declarations_catalog(&handler);
12541            if valid {
12542                assert_eq!(raw["operation_deferral"], map);
12543                assert_eq!(
12544                    serde_json::to_value(entry.operation_deferral.unwrap()).unwrap(),
12545                    map
12546                );
12547            } else {
12548                assert!(entry.operation_deferral.is_none());
12549                assert!(raw.get("operation_deferral").is_none());
12550                assert_eq!(
12551                    capture
12552                        .events()
12553                        .iter()
12554                        .filter(|event| event.fields.get("message").map(String::as_str)
12555                            == Some("dropping operation_deferral from HELLO"))
12556                        .count(),
12557                    1
12558                );
12559            }
12560        }
12561    }
12562
12563    fn assert_hello_drops_flow_operations_with_warning(
12564        capabilities: Value,
12565        flow_operations: Value,
12566        reason: &str,
12567    ) {
12568        let registry = Arc::new(Registry::default());
12569        let handler = ControlHandler::new(Arc::clone(&registry));
12570        let capture = EventCapture::default();
12571        let _subscriber =
12572            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
12573        let response = handler
12574            .handle_control(
12575                ConnectionId::new(401),
12576                hello_with_flow_operations(capabilities, Some(flow_operations)),
12577            )
12578            .unwrap();
12579        assert_eq!(response[0].header.ty, FrameType::HelloAck);
12580        let registered = registry
12581            .get_module_by_connection(ConnectionId::new(401))
12582            .unwrap()
12583            .expect("the module still registers")
12584            .manifest;
12585        assert_eq!(registered.module_id, "flow-ops");
12586        assert_eq!(registered.flow_operations, None);
12587        let (raw, entry) = role_declarations_catalog(&handler);
12588        assert_eq!(raw["module_id"], "flow-ops");
12589        assert!(raw.get("flow_operations").is_none());
12590        assert_eq!(entry.flow_operations, None);
12591        let warnings: Vec<_> = capture
12592            .events()
12593            .into_iter()
12594            .filter(|event| {
12595                event.fields.get("message").map(String::as_str)
12596                    == Some("dropping flow_operations from HELLO")
12597            })
12598            .collect();
12599        assert_eq!(warnings.len(), 1);
12600        assert_eq!(warnings[0].level, tracing::Level::WARN);
12601        assert_eq!(warnings[0].fields["module_id"], "\"flow-ops\"");
12602        assert_eq!(warnings[0].fields["reason"], reason);
12603    }
12604
12605    #[test]
12606    fn hello_flow_operations_naming_unknown_operation_is_dropped_with_warning() {
12607        assert_hello_drops_flow_operations_with_warning(
12608            json!(["flow-scopes/v1"]),
12609            json!(["diagnostics.findings", "missing"]),
12610            "flow_operations names 'missing', which is not a declared management operation",
12611        );
12612    }
12613
12614    #[test]
12615    fn hello_flow_operations_without_flow_capability_is_dropped_with_warning() {
12616        assert_hello_drops_flow_operations_with_warning(
12617            json!([]),
12618            json!(["diagnostics.findings"]),
12619            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12620        );
12621        // A run-only capability does not admit flows either.
12622        assert_hello_drops_flow_operations_with_warning(
12623            json!(["agent-run-scopes/v1"]),
12624            json!([]),
12625            "flow_operations requires 'flow-scopes/v1' or 'call-modes/v1' in capabilities.provides",
12626        );
12627    }
12628
12629    #[test]
12630    fn hello_malformed_flow_operations_is_dropped_with_warning() {
12631        assert_hello_drops_flow_operations_with_warning(
12632            json!(["flow-scopes/v1"]),
12633            json!(["reset", "reset"]),
12634            "flow_operations names 'reset' more than once",
12635        );
12636        assert_hello_drops_flow_operations_with_warning(
12637            json!(["flow-scopes/v1"]),
12638            json!(vec!["reset"; 257]),
12639            "flow_operations lists 257 names, more than 256",
12640        );
12641        assert_hello_drops_flow_operations_with_warning(
12642            json!(["flow-scopes/v1"]),
12643            json!("reset"),
12644            "flow_operations must be an array of operation names",
12645        );
12646    }
12647
12648    #[test]
12649    fn rich_ui_descriptor_malformed_fields_are_refused_by_name() {
12650        let registry = Arc::new(Registry::default());
12651        let handler = ControlHandler::new(registry.clone());
12652        let descriptor = json!({
12653            "schema": "ckios.richui.manifest/1",
12654            "manifest_digest": format!("sha256:{}", "a".repeat(64)),
12655            "bytes": 128,
12656            "chunks": 2
12657        });
12658        let malformed = [
12659            ("schema", json!("")),
12660            ("schema", json!("a".repeat(65))),
12661            ("schema", json!("Bad schema")),
12662            (
12663                "manifest_digest",
12664                json!(format!("sha256:{}", "A".repeat(64))),
12665            ),
12666            ("manifest_digest", json!("sha256:abc")),
12667            ("bytes", json!(0)),
12668            ("bytes", json!(16_777_217)),
12669            ("bytes", json!("128")),
12670            ("chunks", json!(0)),
12671            ("chunks", json!(1025)),
12672            ("chunks", json!("2")),
12673        ];
12674        for (index, (field, invalid_value)) in malformed.into_iter().enumerate() {
12675            let mut invalid = descriptor.clone();
12676            invalid[field] = invalid_value;
12677            let response = handler
12678                .handle_control(
12679                    ConnectionId::new(210 + index as u64),
12680                    hello_frame_with_rich_ui(
12681                        &format!("bad-rich-ui-{index}"),
12682                        PROTOCOL_VERSION,
12683                        210 + index as u64,
12684                        None,
12685                        invalid,
12686                    ),
12687                )
12688                .unwrap();
12689            assert_eq!(response[0].header.ty, FrameType::Error);
12690            let error = parse_error(&response[0]);
12691            assert_eq!(error["code"], "invalid_manifest");
12692            assert!(error["message"]
12693                .as_str()
12694                .unwrap()
12695                .contains(&format!("rich_ui.{field}")));
12696            assert!(registry
12697                .get_module(&format!("bad-rich-ui-{index}"))
12698                .unwrap()
12699                .is_none());
12700        }
12701    }
12702
12703    #[test]
12704    fn catalog_update_refuses_malformed_rich_ui_by_field_name() {
12705        let registry = Arc::new(Registry::default());
12706        let handler = ControlHandler::new(Arc::clone(&registry));
12707        let connection = ConnectionId::new(219);
12708        registry
12709            .register_with_control_ops(
12710                ModuleManifest::builder("invalid-rich-ui", "0.1.0")
12711                    .rich_ui(Some(subc_protocol::manifest::RichUiDescriptor::new(
12712                        "bad schema",
12713                        format!("sha256:{}", "a".repeat(64)),
12714                        128,
12715                        2,
12716                    )))
12717                    .build(),
12718                PROTOCOL_VERSION,
12719                connection,
12720                Vec::new(),
12721            )
12722            .unwrap();
12723        let request =
12724            Frame::build(FrameType::Request, control_flags(), 0, 0, 219, Vec::new()).unwrap();
12725        let response = handler
12726            .handle_catalog_update(connection, request, Vec::new(), None, None)
12727            .unwrap();
12728        assert_eq!(response[0].header.ty, FrameType::Error);
12729        let error = parse_error(&response[0]);
12730        assert_eq!(error["code"], "invalid_manifest");
12731        assert!(error["message"]
12732            .as_str()
12733            .unwrap()
12734            .contains("rich_ui.schema"));
12735    }
12736
12737    #[test]
12738    fn swap_candidate_hello_is_nonce_verified_after_promotion() {
12739        let registry = Arc::new(Registry::default());
12740        let supervisor = SupervisorHandle::new();
12741        supervisor.open_swap("provider", "candidate-nonce".to_string());
12742        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
12743        let connection = ConnectionId::new(218);
12744        let hello = handler
12745            .handle_control(
12746                connection,
12747                hello_frame_with_nonce("provider", PROTOCOL_VERSION, 218, Some("candidate-nonce")),
12748            )
12749            .unwrap();
12750        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
12751        assert!(registry.list_modules().unwrap().1.is_empty());
12752
12753        registry.promote_candidate("provider").unwrap().unwrap();
12754        let request = Frame::build(
12755            FrameType::Request,
12756            control_flags(),
12757            0,
12758            0,
12759            219,
12760            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12761        )
12762        .unwrap();
12763        let response = handler.handle_catalog_list(request, None).unwrap();
12764        let ClientControlResponse::CatalogList { modules, .. } =
12765            serde_json::from_slice(&response[0].body).unwrap()
12766        else {
12767            panic!("expected catalog.list");
12768        };
12769        assert_eq!(modules.len(), 1);
12770        assert!(modules[0].nonce_verified);
12771    }
12772
12773    #[test]
12774    fn catalog_list_with_provenance_mirrors_declared_build_bytes() {
12775        for provenance_json in [
12776            r#"{"build_git_sha":"0123456789abcdef0123456789abcdef01234567","build_lock_digest":"abababababababababababababababababababababababababababababababab","wire_crate_version":"0.34.0","store_schema_version":"7","launch_nonce_source":"fd"}"#,
12777            r#"{"build_git_sha_absence_reason":"no_git_dir","build_lock_digest":"abababababababababababababababababababababababababababababababab"}"#,
12778        ] {
12779            let registry = Arc::new(Registry::default());
12780            let handler = ControlHandler::new(registry);
12781            let hello = Frame::build(
12782                FrameType::Hello,
12783                control_flags(),
12784                0,
12785                0,
12786                220,
12787                serde_json::to_vec(&ModuleHelloBody {
12788                    manifest: ModuleManifest::builder("built", "0.1.0")
12789                        .provenance(Some(serde_json::from_str(provenance_json).unwrap()))
12790                        .build(),
12791                    protocol_ver: PROTOCOL_VERSION,
12792                    control_ops: None,
12793                    launch_nonce: None,
12794                })
12795                .unwrap(),
12796            )
12797            .unwrap();
12798            assert_eq!(
12799                handler
12800                    .handle_control(ConnectionId::new(220), hello)
12801                    .unwrap()[0]
12802                    .header
12803                    .ty,
12804                FrameType::HelloAck
12805            );
12806            let request = Frame::build(
12807                FrameType::Request,
12808                control_flags(),
12809                0,
12810                0,
12811                221,
12812                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12813            )
12814            .unwrap();
12815            let response = handler.handle_catalog_list(request, None).unwrap();
12816            let ClientControlResponse::CatalogList { modules, .. } =
12817                serde_json::from_slice(&response[0].body).unwrap()
12818            else {
12819                panic!("expected catalog.list");
12820            };
12821            assert_eq!(modules.len(), 1);
12822            assert_eq!(
12823                serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
12824                format!(
12825                    r#"{{"module_id":"built","ready":true,"module_version":"0.1.0","provenance":{provenance_json},"roles":[],"control_ops":["route.bind","route.status"]}}"#
12826                )
12827                .as_bytes()
12828            );
12829        }
12830    }
12831
12832    #[test]
12833    fn catalog_list_without_rich_ui_or_nonce_keeps_legacy_entry_bytes() {
12834        let registry = Arc::new(Registry::default());
12835        let handler = ControlHandler::new(Arc::clone(&registry));
12836        let hello = Frame::build(
12837            FrameType::Hello,
12838            control_flags(),
12839            0,
12840            0,
12841            220,
12842            serde_json::to_vec(&ModuleHelloBody {
12843                manifest: ModuleManifest::builder("plain", "0.1.0").build(),
12844                protocol_ver: PROTOCOL_VERSION,
12845                control_ops: None,
12846                launch_nonce: Some("unverified".to_string()),
12847            })
12848            .unwrap(),
12849        )
12850        .unwrap();
12851        assert_eq!(
12852            handler
12853                .handle_control(ConnectionId::new(220), hello)
12854                .unwrap()[0]
12855                .header
12856                .ty,
12857            FrameType::HelloAck
12858        );
12859        let request = Frame::build(
12860            FrameType::Request,
12861            control_flags(),
12862            0,
12863            0,
12864            221,
12865            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
12866        )
12867        .unwrap();
12868        let response = handler.handle_catalog_list(request, None).unwrap();
12869        let wire: serde_json::Value = serde_json::from_slice(&response[0].body).unwrap();
12870        assert!(wire["modules"][0].get("provenance").is_none());
12871        let ClientControlResponse::CatalogList { modules, .. } =
12872            serde_json::from_slice(&response[0].body).unwrap()
12873        else {
12874            panic!("expected catalog.list");
12875        };
12876        assert_eq!(
12877            serde_json::to_vec(&catalog_legacy_projection(modules[0].clone())).unwrap(),
12878            br#"{"module_id":"plain","ready":true,"module_version":"0.1.0","roles":[],"control_ops":["route.bind","route.status"]}"#
12879        );
12880        assert!(!modules[0].nonce_verified);
12881        assert!(modules[0].provenance.is_none());
12882    }
12883
12884    // Preserve the legacy-field byte pins while discovery adds optional facts.
12885    fn catalog_legacy_projection(mut entry: CatalogEntry) -> CatalogEntry {
12886        assert_eq!(entry.first_party, Some(false));
12887        entry.incarnation = None;
12888        entry.spawn = None;
12889        entry.first_party = None;
12890        entry.origin = None;
12891        entry.requested_declarations_digest = None;
12892        entry.approved_declarations_digest = None;
12893        entry
12894    }
12895
12896    #[test]
12897    fn reserved_capability_refusal_mutation_proof_leaves_no_catalog_entry() {
12898        let registry = Arc::new(Registry::default());
12899        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
12900            [("vault".to_string(), true), ("squatter".to_string(), true)],
12901            BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
12902        );
12903        let mut squatter = manifest("squatter", PROTOCOL_VERSION);
12904        squatter.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
12905            provides: vec!["credentials-provider/v1".to_string()],
12906            requires: Vec::new(),
12907            must_never_reach: Vec::new(),
12908        });
12909        let frame = Frame::build(
12910            FrameType::Hello,
12911            control_flags(),
12912            0,
12913            0,
12914            77,
12915            serde_json::to_vec(&ModuleHelloBody {
12916                manifest: squatter,
12917                protocol_ver: PROTOCOL_VERSION,
12918                control_ops: None,
12919                launch_nonce: None,
12920            })
12921            .expect("HELLO serializes"),
12922        )
12923        .expect("HELLO frame builds");
12924        let response = handler
12925            .handle_control(ConnectionId::new(77), frame)
12926            .expect("reserved claim receives a typed refusal");
12927        assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
12928        assert_eq!(
12929            registry
12930                .active_registration_count()
12931                .expect("registry reads"),
12932            0,
12933            "a reserved capability refusal must not leave a catalog entry"
12934        );
12935    }
12936
12937    #[test]
12938    fn stale_relay_settlement_cannot_release_the_half_open_probe() {
12939        for settlement in ["timeout", "inconclusive", "drop"] {
12940            let breakers = RouteBindBreakers::default();
12941            let RouteBindAdmission::Admitted {
12942                guard: mut old,
12943                probe: false,
12944            } = breakers.admit("prov")
12945            else {
12946                panic!("ordinary relay admitted")
12947            };
12948            let RouteBindAdmission::Admitted {
12949                guard: mut opener, ..
12950            } = breakers.admit("prov")
12951            else {
12952                panic!("second relay admitted")
12953            };
12954            assert!(
12955                !opener
12956                    .record_timeout(1, Duration::ZERO)
12957                    .unwrap()
12958                    .reopened_after_probe
12959            );
12960            let RouteBindAdmission::Admitted {
12961                guard: mut probe,
12962                probe: true,
12963            } = breakers.admit("prov")
12964            else {
12965                panic!("one cooldown probe admitted")
12966            };
12967            match settlement {
12968                "timeout" => assert!(
12969                    !old.record_timeout(1, Duration::ZERO)
12970                        .unwrap()
12971                        .reopened_after_probe
12972                ),
12973                "inconclusive" => old.record_inconclusive(),
12974                "drop" => drop(old),
12975                _ => unreachable!(),
12976            }
12977            assert!(
12978                matches!(
12979                    breakers.admit("prov"),
12980                    RouteBindAdmission::Refused {
12981                        probe_in_flight: true,
12982                        ..
12983                    }
12984                ),
12985                "{settlement} of a pre-open relay cannot release the real probe"
12986            );
12987            assert!(
12988                probe
12989                    .record_timeout(1, Duration::ZERO)
12990                    .unwrap()
12991                    .reopened_after_probe
12992            );
12993            assert!(matches!(
12994                breakers.admit("prov"),
12995                RouteBindAdmission::Admitted { probe: true, .. }
12996            ));
12997        }
12998        let breakers = RouteBindBreakers::default();
12999        let admit = || match breakers.admit("prov") {
13000            RouteBindAdmission::Admitted { guard, .. } => guard,
13001            _ => panic!("relay admitted"),
13002        };
13003        admit().record_timeout(1, Duration::ZERO);
13004        let mut old_probe = admit();
13005        breakers.reset_for_new_module_connection("prov");
13006        admit().record_timeout(1, Duration::ZERO);
13007        let _new_probe = admit();
13008        old_probe.record_inconclusive();
13009        assert!(matches!(
13010            breakers.admit("prov"),
13011            RouteBindAdmission::Refused {
13012                probe_in_flight: true,
13013                ..
13014            }
13015        ));
13016    }
13017
13018    #[tokio::test]
13019    async fn catalog_update_refuses_reserved_capabilities_for_active_and_candidate() {
13020        for candidate in [false, true] {
13021            let registry = Arc::new(Registry::default());
13022            let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13023                [("vault".to_string(), true), ("squatter".to_string(), true)],
13024                BTreeMap::from([("credentials-provider/v1".to_string(), "vault".to_string())]),
13025            );
13026            let conn = ConnectionId::new(77);
13027            let (ctx, mut rx) = route_ctx(conn);
13028            let initial = capability_manifest("squatter", &[], &[]);
13029            if candidate {
13030                registry
13031                    .register_candidate_with_control_ops(
13032                        initial.clone(),
13033                        PROTOCOL_VERSION,
13034                        conn,
13035                        module_baseline_control_ops(),
13036                    )
13037                    .unwrap();
13038                handler
13039                    .forwarding
13040                    .register_candidate_module_connection(
13041                        conn,
13042                        "squatter".to_string(),
13043                        PROTOCOL_VERSION,
13044                        manifest_concurrency(&initial),
13045                        ctx.egress.clone(),
13046                    )
13047                    .unwrap();
13048            } else {
13049                hello_via_sink(
13050                    &handler,
13051                    &ctx,
13052                    &mut rx,
13053                    hello_frame_with_manifest(initial.clone(), 1),
13054                )
13055                .await;
13056            }
13057            let response = handler
13058                .handle_control_frame(
13059                    &ctx,
13060                    catalog_update_with_capabilities_frame(
13061                        2,
13062                        capability_manifest("squatter", &["credentials-provider/v1"], &[])
13063                            .capabilities
13064                            .unwrap(),
13065                    ),
13066                )
13067                .await
13068                .unwrap();
13069            assert_eq!(parse_error(&response[0])["code"], "reserved_capability");
13070            assert_eq!(
13071                registry
13072                    .get_module_by_connection(conn)
13073                    .unwrap()
13074                    .unwrap()
13075                    .manifest,
13076                initial
13077            );
13078        }
13079    }
13080
13081    #[test]
13082    #[cfg(not(feature = "dev-desktop-approval"))]
13083    fn server_describe_default_build_advertises_no_config_capability() {
13084        let assert_default = |handler: &ControlHandler| {
13085            let request = Frame::build(
13086                FrameType::Request,
13087                control_flags(),
13088                0,
13089                0,
13090                79,
13091                serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13092            )
13093            .unwrap();
13094            let responses = handler.handle_server_describe(request).unwrap();
13095            assert_eq!(responses.len(), 1);
13096            let response: Value = serde_json::from_slice(&responses[0].body).unwrap();
13097            assert_eq!(response["op"], "server.describe");
13098            let capabilities = response["capabilities"]
13099                .as_array()
13100                .expect("capability array");
13101            assert!(
13102                !capabilities.is_empty(),
13103                "exercise an actual describe response, not an empty fixture"
13104            );
13105            assert!(
13106                capabilities
13107                    .iter()
13108                    .all(|capability| !capability.as_str().unwrap().starts_with("config.")),
13109                "a default build must not announce configuration authority: {capabilities:?}"
13110            );
13111        };
13112        assert_default(&ControlHandler::new(Arc::new(Registry::default())));
13113        #[cfg(unix)]
13114        {
13115            // A local store does not prove that project-membership validation,
13116            // active-scope usage tracking and approved-program launch selection
13117            // are connected. Defaults must not advertise that authority.
13118            let (_rig, _owner, _supervisor, handler, _spec) =
13119                crate::config_gate::runtime::RuntimeOwner::unactivated_supervisor_fixture_for_test(
13120                );
13121            assert_default(&handler);
13122        }
13123    }
13124
13125    #[test]
13126    fn server_describe_surfaces_required_capability_verdict_fields() {
13127        let registry = Arc::new(Registry::default());
13128        let handler = ControlHandler::new(Arc::clone(&registry)).with_capability_config(
13129            [
13130                ("consumer".to_string(), true),
13131                ("provider".to_string(), false),
13132            ],
13133            BTreeMap::new(),
13134        );
13135        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13136        consumer.capabilities = Some(subc_protocol::manifest::CapabilityDeclarations {
13137            provides: Vec::new(),
13138            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13139                capability: "credentials-provider/v1".to_string(),
13140                need: subc_protocol::manifest::CapabilityNeed::Required,
13141            }],
13142            must_never_reach: Vec::new(),
13143        });
13144        let hello = Frame::build(
13145            FrameType::Hello,
13146            control_flags(),
13147            0,
13148            0,
13149            78,
13150            serde_json::to_vec(&ModuleHelloBody {
13151                manifest: consumer,
13152                protocol_ver: PROTOCOL_VERSION,
13153                control_ops: None,
13154                launch_nonce: None,
13155            })
13156            .expect("HELLO serializes"),
13157        )
13158        .expect("HELLO frame builds");
13159        handler
13160            .handle_control(ConnectionId::new(78), hello)
13161            .expect("consumer registers");
13162        let describe = Frame::build(
13163            FrameType::Request,
13164            control_flags(),
13165            0,
13166            0,
13167            79,
13168            serde_json::to_vec(&ClientControlRequest::ServerDescribe {})
13169                .expect("request serializes"),
13170        )
13171        .expect("describe frame builds");
13172        let response = handler
13173            .handle_server_describe(describe)
13174            .expect("server.describe succeeds");
13175        let rendered: Value = serde_json::from_slice(&response[0].body).expect("response JSON");
13176        let requirement = &rendered["capability_requirements"][0];
13177        assert_eq!(requirement["consumer"], "consumer");
13178        assert_eq!(requirement["verdict"], "never_provided");
13179        assert_eq!(requirement["episode_seq"], 1);
13180        assert_eq!(requirement["config_satisfiable"], false);
13181        assert_eq!(requirement["runtime_available"], false);
13182        assert!(requirement["detail"]
13183            .as_str()
13184            .expect("detail string")
13185            .contains("credentials-provider/v1"));
13186    }
13187
13188    /// Register a consumer that requires `project-identity/v1` and the provider
13189    /// of it, optionally mark daemon shutdown as begun, then deregister the
13190    /// provider as its connection closes. Returns the `capability.requirement`
13191    /// events that deregistration logged and the verdict the evaluator then
13192    /// holds for the requirement (the one `route.open` refusals read).
13193    fn deregister_required_provider(
13194        daemon_shutdown_begun: bool,
13195    ) -> (Vec<CapturedEvent>, Option<CapabilityVerdict>) {
13196        const CAPABILITY: &str = "project-identity/v1";
13197        let registry = Arc::new(Registry::default());
13198        let daemon_shutdown = DaemonShutdownFlag::default();
13199        let handler = ControlHandler::new(Arc::clone(&registry))
13200            .with_capability_config(
13201                [
13202                    ("consumer".to_string(), true),
13203                    ("provider".to_string(), true),
13204                ],
13205                BTreeMap::new(),
13206            )
13207            .with_daemon_shutdown_flag(daemon_shutdown.clone());
13208        let mut consumer = manifest("consumer", PROTOCOL_VERSION);
13209        consumer.capabilities = Some(CapabilityDeclarations {
13210            provides: Vec::new(),
13211            requires: vec![subc_protocol::manifest::CapabilityRequirement {
13212                capability: CAPABILITY.to_string(),
13213                need: subc_protocol::manifest::CapabilityNeed::Required,
13214            }],
13215            must_never_reach: Vec::new(),
13216        });
13217        let provider = capability_manifest("provider", &[CAPABILITY], &[]);
13218        let provider_conn = ConnectionId::new(182);
13219        for (conn, manifest, corr) in [
13220            (ConnectionId::new(181), consumer, 181),
13221            (provider_conn, provider, 182),
13222        ] {
13223            let hello = handler
13224                .handle_control(conn, hello_frame_with_manifest(manifest, corr))
13225                .expect("module registers");
13226            assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13227        }
13228        assert_eq!(
13229            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13230            Some(CapabilityVerdict::Provided),
13231            "the registered provider must satisfy the requirement first"
13232        );
13233        if daemon_shutdown_begun {
13234            daemon_shutdown.set_for_test();
13235        }
13236
13237        let capture = EventCapture::default();
13238        let _subscriber =
13239            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
13240        handler
13241            .cleanup_connection(provider_conn)
13242            .expect("provider deregisters");
13243        let events = capture
13244            .events()
13245            .into_iter()
13246            .filter(|event| {
13247                event.fields.get("message").map(String::as_str) == Some("capability.requirement")
13248            })
13249            .collect();
13250        (
13251            events,
13252            handler.capability_evaluator.verdict("consumer", CAPABILITY),
13253        )
13254    }
13255
13256    #[test]
13257    fn required_provider_leaving_during_daemon_shutdown_logs_info_with_shutdown_cause() {
13258        let (events, verdict) = deregister_required_provider(true);
13259        assert_eq!(
13260            verdict,
13261            Some(CapabilityVerdict::NeverProvided),
13262            "shutdown must not change the verdict route.open refusals read"
13263        );
13264        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13265        let event = &events[0];
13266        assert_eq!(event.level, tracing::Level::INFO, "{event:?}");
13267        assert_eq!(
13268            event.fields.get("cause").map(String::as_str),
13269            Some("\"daemon_shutdown\""),
13270            "{event:?}"
13271        );
13272        assert_eq!(
13273            event.fields.get("verdict").map(String::as_str),
13274            Some("\"never_provided\""),
13275            "{event:?}"
13276        );
13277    }
13278
13279    #[test]
13280    fn required_provider_leaving_while_daemon_runs_still_logs_error() {
13281        let (events, verdict) = deregister_required_provider(false);
13282        assert_eq!(verdict, Some(CapabilityVerdict::NeverProvided));
13283        assert_eq!(events.len(), 1, "one requirement transition: {events:?}");
13284        let event = &events[0];
13285        assert_eq!(event.level, tracing::Level::ERROR, "{event:?}");
13286        assert_eq!(event.fields.get("cause"), None, "{event:?}");
13287        assert_eq!(
13288            event.fields.get("verdict").map(String::as_str),
13289            Some("\"never_provided\""),
13290            "{event:?}"
13291        );
13292    }
13293
13294    #[test]
13295    fn catalog_list_omits_capabilities_for_legacy_manifest() {
13296        let registry = Arc::new(Registry::default());
13297        let handler = ControlHandler::new(Arc::clone(&registry));
13298        let hello = handler
13299            .handle_control(
13300                ConnectionId::new(101),
13301                hello_frame("legacy-capability-manifest", PROTOCOL_VERSION, 101),
13302            )
13303            .expect("legacy HELLO registers");
13304        assert_eq!(hello[0].header.ty, FrameType::HelloAck);
13305
13306        let request = Frame::build(
13307            FrameType::Request,
13308            control_flags(),
13309            0,
13310            0,
13311            102,
13312            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None })
13313                .expect("catalog request serializes"),
13314        )
13315        .expect("catalog request frame builds");
13316        let response = handler
13317            .handle_catalog_list(request, None)
13318            .expect("catalog list succeeds");
13319        let body: Value = serde_json::from_slice(&response[0].body).expect("catalog response JSON");
13320        assert!(
13321            body["modules"][0].get("capabilities").is_none(),
13322            "legacy manifest must retain an absent capabilities field on catalog.list"
13323        );
13324    }
13325
13326    #[test]
13327    fn hello_ack_omits_storage_when_no_storage_config() {
13328        let registry = Arc::new(Registry::default());
13329        let handler = ControlHandler::new(Arc::clone(&registry));
13330        let responses = handler
13331            .handle_control(
13332                ConnectionId::new(1),
13333                hello_frame("aft", PROTOCOL_VERSION, 7),
13334            )
13335            .unwrap();
13336        let ack = parse_ack(&responses[0]);
13337        assert_eq!(ack.storage, None, "no storage config -> no descriptor");
13338        assert_eq!(ack.machine_id, None, "no machine id configured -> no field");
13339    }
13340
13341    #[tokio::test]
13342    async fn hello_ack_and_server_describe_carry_the_configured_machine_id() {
13343        let id = crate::machine_id::MachineId::parse("0123456789abcdef0123456789abcdef").unwrap();
13344        let registry = Arc::new(Registry::default());
13345        let handler = ControlHandler::new(Arc::clone(&registry)).with_machine_id(Some(id.clone()));
13346        let responses = handler
13347            .handle_control(
13348                ConnectionId::new(1),
13349                hello_frame("aft", PROTOCOL_VERSION, 7),
13350            )
13351            .unwrap();
13352        let ack = parse_ack(&responses[0]);
13353        assert_eq!(ack.machine_id.as_deref(), Some(id.as_str()));
13354
13355        let described = handler
13356            .handle_control_frame(
13357                &route_ctx(ConnectionId::new(2)).0,
13358                Frame::build(
13359                    FrameType::Request,
13360                    control_flags(),
13361                    0,
13362                    0,
13363                    9,
13364                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
13365                )
13366                .unwrap(),
13367            )
13368            .await
13369            .unwrap();
13370        let ClientControlResponse::ServerDescribe { machine_id, .. } =
13371            serde_json::from_slice(&described[0].body).unwrap()
13372        else {
13373            panic!("server.describe answered with another shape");
13374        };
13375        assert_eq!(machine_id.as_deref(), Some(id.as_str()));
13376    }
13377
13378    #[test]
13379    fn hello_ack_delivers_resolved_storage_descriptor_per_module() {
13380        // With a central sqlite storage policy, each registering module gets its
13381        // own resolved descriptor in HELLO_ACK, keyed by its module id.
13382        let registry = Arc::new(Registry::default());
13383        let handler = ControlHandler::new(Arc::clone(&registry)).with_storage_config(Some(
13384            crate::daemon_config::StorageConfig::Sqlite {
13385                data_home: std::path::PathBuf::from("/data"),
13386            },
13387        ));
13388
13389        let responses = handler
13390            .handle_control(
13391                ConnectionId::new(1),
13392                hello_frame("alfonso-routing", PROTOCOL_VERSION, 7),
13393            )
13394            .unwrap();
13395        let ack = parse_ack(&responses[0]);
13396        assert_eq!(
13397            ack.storage,
13398            Some(serde_json::json!({
13399                "module_id": "alfonso-routing",
13400                "storage_namespace": "default",
13401                "isolation": { "kind": "module" },
13402                "backend": {
13403                    "backend": "sqlite",
13404                    "path": "/data/cortexkit/alfonso-routing/store.db"
13405                }
13406            })),
13407            "the delivered descriptor is the module's own sqlite store path"
13408        );
13409    }
13410
13411    #[test]
13412    fn hello_control_ops_none_is_baseline_and_guard_rejects_synthetic_gated_op() {
13413        let registry = Arc::new(Registry::default());
13414        let handler = ControlHandler::new(Arc::clone(&registry));
13415        let conn = ConnectionId::new(1);
13416        let responses = handler
13417            .handle_control(
13418                conn,
13419                hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13420            )
13421            .unwrap();
13422        assert_eq!(responses[0].header.ty, FrameType::HelloAck);
13423        let registration = registry.get_module("aft").unwrap().unwrap();
13424        assert_eq!(registration.control_ops, module_baseline_control_ops());
13425
13426        let frame =
13427            Frame::build(FrameType::Request, control_flags(), 0, 0, 77, Vec::new()).unwrap();
13428        assert!(handler
13429            .guard_module_control_op(&frame, "aft", "route.bind")
13430            .unwrap()
13431            .is_none());
13432        let error = handler
13433            .guard_module_control_op(&frame, "aft", "test.synthetic")
13434            .unwrap()
13435            .expect("synthetic ungranted op should be rejected");
13436        assert_eq!(error.header.ty, FrameType::Error);
13437        assert_eq!(parse_error(&error)["code"], "op_not_allowed");
13438    }
13439
13440    #[test]
13441    fn hello_control_ops_some_adds_optional_grants() {
13442        let registry = Arc::new(Registry::default());
13443        let handler = ControlHandler::new(Arc::clone(&registry));
13444        handler
13445            .handle_control(
13446                ConnectionId::new(1),
13447                hello_frame_with_control_ops(
13448                    "aft",
13449                    PROTOCOL_VERSION,
13450                    7,
13451                    Some(vec![
13452                        "future.synthetic".to_string(),
13453                        "route.bind".to_string(),
13454                    ]),
13455                ),
13456            )
13457            .unwrap();
13458        let registration = registry.get_module("aft").unwrap().unwrap();
13459        assert_eq!(
13460            registration.control_ops,
13461            vec![
13462                "route.bind".to_string(),
13463                "route.status".to_string(),
13464                "future.synthetic".to_string(),
13465            ]
13466        );
13467        let frame =
13468            Frame::build(FrameType::Request, control_flags(), 0, 0, 78, Vec::new()).unwrap();
13469        assert!(handler
13470            .guard_module_control_op(&frame, "aft", "future.synthetic")
13471            .unwrap()
13472            .is_none());
13473    }
13474
13475    #[tokio::test]
13476    async fn health_probe_refuses_unadvertised_module_without_sending_frame() {
13477        let registry = Arc::new(Registry::default());
13478        let forwarding = Arc::new(ForwardingTable::default());
13479        let handler =
13480            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13481        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(10));
13482        hello_via_sink(
13483            &handler,
13484            &module_ctx,
13485            &mut module_rx,
13486            hello_frame_with_control_ops("aft", PROTOCOL_VERSION, 7, None),
13487        )
13488        .await;
13489
13490        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(20));
13491        let responses = handler
13492            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(77, "aft"))
13493            .await
13494            .unwrap();
13495        assert_eq!(responses.len(), 1);
13496        assert_eq!(responses[0].header.ty, FrameType::Error);
13497        assert_eq!(parse_error(&responses[0])["code"], "health_not_advertised");
13498        assert!(module_rx.try_recv().is_err());
13499    }
13500
13501    #[tokio::test]
13502    async fn health_probe_demuxes_while_route_bind_relay_is_in_flight() {
13503        let registry = Arc::new(Registry::default());
13504        let forwarding = Arc::new(ForwardingTable::default());
13505        let handler =
13506            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13507        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(30));
13508        hello_via_sink(
13509            &handler,
13510            &module_ctx,
13511            &mut module_rx,
13512            hello_frame_with_control_ops(
13513                "aft",
13514                PROTOCOL_VERSION,
13515                7,
13516                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
13517            ),
13518        )
13519        .await;
13520
13521        let project_root = unique_project_root("demux");
13522        let (route_client_ctx, mut route_client_rx) = route_ctx(ConnectionId::new(31));
13523        let route_handler = handler.clone();
13524        let route_task = tokio::spawn(async move {
13525            route_handler
13526                .handle_control_frame(
13527                    &route_client_ctx,
13528                    route_open_frame(100, "aft", project_root),
13529                )
13530                .await
13531                .unwrap()
13532        });
13533        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13534            .await
13535            .unwrap()
13536            .unwrap();
13537        assert!(matches!(
13538            serde_json::from_slice::<ModuleControlRequest>(&bind_frame.body).unwrap(),
13539            ModuleControlRequest::RouteBind { .. }
13540        ));
13541
13542        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(32));
13543        let health_handler = handler.clone();
13544        let health_task = tokio::spawn(async move {
13545            health_handler
13546                .handle_control_frame(
13547                    &health_client_ctx,
13548                    supervisor_health_probe_frame(101, "aft"),
13549                )
13550                .await
13551                .unwrap()
13552        });
13553        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13554            .await
13555            .unwrap()
13556            .unwrap();
13557        assert_eq!(
13558            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
13559            ModuleControlRequest::HealthCheck {}
13560        );
13561
13562        handler
13563            .handle_control_frame(
13564                &module_ctx,
13565                health_response(health_frame.header.corr, HealthStatus::Degraded),
13566            )
13567            .await
13568            .unwrap();
13569        let health_response = health_task.await.unwrap();
13570        assert_eq!(health_response.len(), 1);
13571        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
13572            ClientControlResponse::SupervisorHealthProbe {
13573                module_id,
13574                status,
13575                detail,
13576                metrics,
13577            } => {
13578                assert_eq!(module_id, "aft");
13579                assert_eq!(status, HealthStatus::Degraded);
13580                assert_eq!(detail.as_deref(), Some("warming"));
13581                assert_eq!(metrics, Some(json!({"queue_depth": 3})));
13582            }
13583            other => panic!("unexpected health response: {other:?}"),
13584        }
13585
13586        handler
13587            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
13588            .await
13589            .unwrap();
13590        let route_response = route_task.await.unwrap();
13591        assert!(route_response.is_empty());
13592        let published = route_client_rx.recv().await.unwrap();
13593        assert!(matches!(
13594            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
13595            ClientControlResponse::RouteOpen { .. }
13596        ));
13597    }
13598
13599    /// Start one `route.open` on `client_connection` and return its still-running
13600    /// handler task together with the `route.bind` the module received for it.
13601    /// The handler blocks until the module answers, so it has to run as a task
13602    /// while the test drives the module side.
13603    async fn relay_route_open(
13604        handler: &ControlHandler,
13605        client_connection: ConnectionId,
13606        client_egress: &FrameSink,
13607        module_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
13608        corr: u64,
13609        module_id: &str,
13610        project_root_label: &str,
13611    ) -> (tokio::task::JoinHandle<Vec<Frame>>, Frame) {
13612        let ctx = RouteCtx {
13613            connection_id: client_connection,
13614            egress: client_egress.clone(),
13615        };
13616        let handler = handler.clone();
13617        let project_root = unique_project_root(project_root_label);
13618        let module_id = module_id.to_string();
13619        let dispatch = tracing::dispatcher::get_default(|dispatch| dispatch.clone());
13620        let task = tokio::spawn(async move {
13621            let _guard = tracing::dispatcher::set_default(&dispatch);
13622            handler
13623                .handle_control_frame(&ctx, route_open_frame(corr, &module_id, project_root))
13624                .await
13625                .unwrap()
13626        });
13627        let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
13628            .await
13629            .expect("module receives the relayed route.bind")
13630            .expect("module egress is open");
13631        (task, bind.frame)
13632    }
13633
13634    fn route_bind_channel(frame: &Frame) -> (u16, u32) {
13635        match serde_json::from_slice::<ModuleControlRequest>(&frame.body).unwrap() {
13636            ModuleControlRequest::RouteBind {
13637                route_channel,
13638                epoch,
13639                ..
13640            } => (route_channel, epoch),
13641            other => panic!("expected a route.bind request, got {other:?}"),
13642        }
13643    }
13644
13645    fn published_route(frame: &Frame) -> (u16, u32) {
13646        match serde_json::from_slice::<ClientControlResponse>(&frame.body).unwrap() {
13647            ClientControlResponse::RouteOpen {
13648                route_channel,
13649                route_epoch,
13650                ..
13651            } => (route_channel, route_epoch),
13652            other => panic!("expected a route.open response, got {other:?}"),
13653        }
13654    }
13655
13656    /// Reproduction of a production outage. A client had `route.open`s in
13657    /// flight to a module and was already marked closing -- its egress had refused a
13658    /// module frame, so the daemon asked its connection to end -- while its sink
13659    /// was still open. When the module acked those binds, the daemon refused to
13660    /// commit a route for a closing client, and that refusal was returned from
13661    /// the MODULE connection's frame handler, where a router error that has no
13662    /// ERROR-frame translation ends the connection. The module saw EOF, exited 0,
13663    /// the supervisor correctly did not respawn a clean exit, and every seat lost
13664    /// its tools for hours -- one client's teardown took down a connection
13665    /// carrying ~170 other routes.
13666    ///
13667    /// The window is opened here by calling the production path that opens it
13668    /// (`escalate_client_delivery_failure`) rather than by closing a socket. The
13669    /// state that matters is "in `closing_connections`, sink still open, relay
13670    /// still pending", and it lasts only from the close request until the
13671    /// connection loop reacts to it; a socket-level test can flood a client into
13672    /// that escalation but cannot pin the module's ack inside the window. Closing
13673    /// the socket instead takes the other path entirely -- connection teardown
13674    /// removes the pending relay under the same lock, so the ack finds nothing.
13675    #[tokio::test]
13676    async fn late_bind_ack_for_a_closing_client_keeps_the_module_connection_serving() {
13677        let registry = Arc::new(Registry::default());
13678        let forwarding = Arc::new(ForwardingTable::default());
13679        let handler =
13680            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
13681
13682        let module_connection = ConnectionId::new(30);
13683        let (module_ctx, mut module_rx) = route_ctx(module_connection);
13684        hello_via_sink(
13685            &handler,
13686            &module_ctx,
13687            &mut module_rx,
13688            hello_frame("aft", PROTOCOL_VERSION, 7),
13689        )
13690        .await;
13691
13692        let dying_client = ConnectionId::new(31);
13693        let (dying_ctx, mut dying_rx) = route_ctx(dying_client);
13694
13695        // A published route on the dying client. The escalation below only marks
13696        // a connection closing for a route it has already published.
13697        let (first_task, first_bind) = relay_route_open(
13698            &handler,
13699            dying_client,
13700            &dying_ctx.egress,
13701            &mut module_rx,
13702            100,
13703            "aft",
13704            "closing-first",
13705        )
13706        .await;
13707        handler
13708            .handle_control_frame(&module_ctx, route_bind_ack(first_bind.header.corr))
13709            .await
13710            .unwrap();
13711        assert!(first_task.await.unwrap().is_empty());
13712        let (first_channel, first_epoch) = published_route(&dying_rx.recv().await.unwrap());
13713
13714        // A second route.open from the same client, relayed and awaiting its ack.
13715        let (second_task, second_bind) = relay_route_open(
13716            &handler,
13717            dying_client,
13718            &dying_ctx.egress,
13719            &mut module_rx,
13720            101,
13721            "aft",
13722            "closing-second",
13723        )
13724        .await;
13725        let (abandoned_channel, abandoned_epoch) = route_bind_channel(&second_bind);
13726
13727        // The window: the client is closing, its sink is still open, and its
13728        // second bind is still pending.
13729        assert!(forwarding
13730            .escalate_client_delivery_failure(
13731                dying_client,
13732                first_channel,
13733                first_epoch,
13734                CloseReason::new(
13735                    "module_to_client_delivery_failed",
13736                    "client egress refused a module frame",
13737                ),
13738                crate::forwarding::UndeliveredFrame {
13739                    module_id: None,
13740                    sink: &dying_ctx.egress,
13741                },
13742            )
13743            .unwrap());
13744        assert!(!dying_ctx.egress.is_closed());
13745
13746        // The frame that used to end the module connection.
13747        let ack = handler
13748            .handle_control_frame(&module_ctx, route_bind_ack(second_bind.header.corr))
13749            .await;
13750        let module_loop_error = ack.as_ref().err().map(ToString::to_string);
13751        if module_loop_error.is_some() {
13752            // What the server's connection loop does with a router error that has
13753            // no ERROR-frame translation: end the connection, which releases the
13754            // module's registration and every route on it.
13755            handler.cleanup_connection(module_connection).unwrap();
13756        }
13757        // Read the module's next frame before opening the co-tenant's route, so
13758        // the GOODBYE assertion below is about THIS ack and not about later
13759        // traffic. `None` means the module was told nothing.
13760        let post_ack_module_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
13761            .await
13762            .ok()
13763            .flatten();
13764
13765        // 1. The module connection is still registered.
13766        assert!(
13767            registry
13768                .get_module_by_connection(module_connection)
13769                .unwrap()
13770                .is_some(),
13771            "one client's closing connection ended the shared module connection: \
13772             {module_loop_error:?}"
13773        );
13774        // ...and still serving: another client can open and use a route on it.
13775        let cotenant = ConnectionId::new(32);
13776        let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
13777        let (cotenant_task, cotenant_bind) = relay_route_open(
13778            &handler,
13779            cotenant,
13780            &cotenant_ctx.egress,
13781            &mut module_rx,
13782            102,
13783            "aft",
13784            "closing-cotenant",
13785        )
13786        .await;
13787        handler
13788            .handle_control_frame(&module_ctx, route_bind_ack(cotenant_bind.header.corr))
13789            .await
13790            .unwrap();
13791        assert!(cotenant_task.await.unwrap().is_empty());
13792        let (cotenant_channel, cotenant_epoch) =
13793            published_route(&cotenant_rx.recv().await.unwrap());
13794        assert!(matches!(
13795            forwarding
13796                .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
13797                .unwrap(),
13798            DataRoute::Client(DataRouteState::Bound(_))
13799        ));
13800
13801        // 2. The module was told to drop the binding it created for the route
13802        //    that will never be published.
13803        let goodbye = post_ack_module_frame
13804            .expect("module receives a GOODBYE for the abandoned route channel");
13805        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
13806        assert_eq!(goodbye.header.channel, abandoned_channel);
13807        assert_eq!(goodbye.header.epoch, abandoned_epoch);
13808
13809        // 3. The dying client received nothing: no route was ever published to
13810        //    it. Its route.open is answered as unavailable, which the connection
13811        //    loop would write to a socket that is already going away.
13812        assert!(dying_rx.try_recv().is_err());
13813        let second_response = second_task.await.unwrap();
13814        assert_eq!(second_response.len(), 1);
13815        assert_eq!(
13816            parse_error(&second_response[0])["code"],
13817            "target_unavailable"
13818        );
13819    }
13820
13821    /// One `catalog.list` as a client sees it: the generation and the listed
13822    /// module ids with their readiness.
13823    async fn catalog_snapshot(
13824        handler: &ControlHandler,
13825        client_ctx: &RouteCtx,
13826        corr: u64,
13827    ) -> (u64, Vec<(String, bool)>) {
13828        let body =
13829            serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap();
13830        let request = Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap();
13831        let reply = handler
13832            .handle_control_frame(client_ctx, request)
13833            .await
13834            .unwrap()
13835            .pop()
13836            .unwrap();
13837        let ClientControlResponse::CatalogList {
13838            generation,
13839            modules,
13840            ..
13841        } = serde_json::from_slice(&reply.body).unwrap()
13842        else {
13843            panic!("not a catalog.list reply");
13844        };
13845        (
13846            generation,
13847            modules
13848                .into_iter()
13849                .map(|entry| (entry.module_id, entry.ready))
13850                .collect(),
13851        )
13852    }
13853
13854    /// A handler whose HELLO for module "aft" on connection 40 is parked
13855    /// between reserving its registry entry and installing its forwarding
13856    /// endpoint. Returns the handler, the two-party barrier (wait once to know
13857    /// the HELLO is parked, once more to release it), the HELLO's thread, and
13858    /// the module's context and receiver.
13859    fn hello_held_before_forwarding() -> (
13860        ControlHandler,
13861        Arc<std::sync::Barrier>,
13862        std::thread::JoinHandle<Vec<Frame>>,
13863        RouteCtx,
13864        mpsc::Receiver<crate::router::OutboundFrame>,
13865    ) {
13866        let hold = Arc::new(std::sync::Barrier::new(2));
13867        let handler = ControlHandler::with_forwarding(
13868            Arc::new(Registry::default()),
13869            Arc::new(ForwardingTable::default()),
13870        )
13871        .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
13872        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
13873        let hello = {
13874            let handler = handler.clone();
13875            let module_ctx = module_ctx.clone();
13876            std::thread::spawn(move || {
13877                handler
13878                    .handle_hello(
13879                        module_ctx.connection_id,
13880                        Some(module_ctx.egress.clone()),
13881                        hello_frame("aft", PROTOCOL_VERSION, 7),
13882                    )
13883                    .unwrap()
13884            })
13885        };
13886        (handler, hold, hello, module_ctx, module_rx)
13887    }
13888
13889    /// If a lookup can acquire the registry while publication is parked, let
13890    /// the lookup finish before releasing HELLO. Otherwise release HELLO only
13891    /// after the lookup has tried the lock. Both schedules avoid timing guesses
13892    /// and return the actual lookup result, including an unpublished snapshot
13893    /// when the publication lock is missing.
13894    fn lookup_during_hello_publication<T: Send + 'static>(
13895        registry: &Registry,
13896        hold: &std::sync::Barrier,
13897        lookup: impl FnOnce() -> T + Send + 'static,
13898    ) -> T {
13899        let attempted = registry.observe_next_lock_attempt();
13900        let reader = std::thread::spawn(lookup);
13901        if attempted.recv().unwrap() {
13902            let result = reader.join().unwrap();
13903            hold.wait();
13904            result
13905        } else {
13906            hold.wait();
13907            reader.join().unwrap()
13908        }
13909    }
13910
13911    #[test]
13912    fn catalog_read_after_hello_ack_waits_for_publication() {
13913        let registry = Arc::new(Registry::default());
13914        let hold = Arc::new(std::sync::Barrier::new(2));
13915        let mut handler = ControlHandler::with_forwarding(
13916            Arc::clone(&registry),
13917            Arc::new(ForwardingTable::default()),
13918        );
13919        handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
13920        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
13921        let hello = {
13922            let handler = handler.clone();
13923            std::thread::spawn(move || {
13924                handler
13925                    .handle_hello(
13926                        module_ctx.connection_id,
13927                        Some(module_ctx.egress),
13928                        hello_frame("aft", PROTOCOL_VERSION, 7),
13929                    )
13930                    .unwrap()
13931            })
13932        };
13933        hold.wait();
13934        assert_eq!(
13935            module_rx.try_recv().unwrap().frame.header.ty,
13936            FrameType::HelloAck
13937        );
13938        let replies = lookup_during_hello_publication(&registry, &hold, move || {
13939            // A different connection can issue catalog.list as soon as the
13940            // module has read its ACK, even while HELLO has not returned.
13941            let request = Frame::build(
13942                FrameType::Request,
13943                control_flags(),
13944                0,
13945                0,
13946                300,
13947                serde_json::to_vec(&ClientControlRequest::CatalogList { module_id: None }).unwrap(),
13948            )
13949            .unwrap();
13950            handler.handle_catalog_list(request, None).unwrap()
13951        });
13952        assert!(hello.join().unwrap().is_empty());
13953        let ClientControlResponse::CatalogList {
13954            generation,
13955            modules,
13956            ..
13957        } = serde_json::from_slice(&replies[0].body).unwrap()
13958        else {
13959            panic!("not a catalog.list reply");
13960        };
13961        assert_eq!(
13962            modules
13963                .iter()
13964                .map(|entry| entry.module_id.as_str())
13965                .collect::<Vec<_>>(),
13966            vec!["aft"]
13967        );
13968        assert_eq!(generation, 1);
13969    }
13970
13971    /// While a HELLO has reserved its registry entry but its forwarding
13972    /// endpoint is not installed yet, `route.open` to the module can only be
13973    /// refused. `catalog.list` must not list the module in that window: a
13974    /// client that opens a route as soon as it sees a module listed and ready
13975    /// would be refused for a module the daemon had just advertised. The
13976    /// refusal in the window stays the retryable `target_unavailable`, never
13977    /// `unknown_module`, and the id stays claimed against a duplicate HELLO.
13978    /// Once the HELLO completes, the module is listed and a route to it opens.
13979    #[tokio::test]
13980    async fn module_is_listed_only_once_route_open_to_it_can_succeed() {
13981        let (handler, hold, hello, module_ctx, mut module_rx) = hello_held_before_forwarding();
13982        let client = ConnectionId::new(41);
13983        let (client_ctx, mut client_rx) = route_ctx(client);
13984
13985        hold.wait();
13986        // Parked: the registry holds "aft", forwarding has no endpoint for it.
13987        assert!(handler.registry.get_module("aft").unwrap().is_some());
13988        assert!(!handler
13989            .forwarding
13990            .has_live_module_connection("aft")
13991            .unwrap());
13992        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 300).await;
13993        assert!(
13994            listed.is_empty(),
13995            "catalog.list listed a module route.open cannot reach yet: {listed:?}"
13996        );
13997        let refused = handler
13998            .handle_control_frame(
13999                &client_ctx,
14000                route_open_frame(301, "aft", unique_project_root("listed-window")),
14001            )
14002            .await
14003            .unwrap();
14004        assert_eq!(parse_error(&refused[0])["code"], "target_unavailable");
14005        let (duplicate_ctx, _duplicate_rx) = route_ctx(ConnectionId::new(42));
14006        let duplicate = handler
14007            .handle_control_frame(&duplicate_ctx, hello_frame("aft", PROTOCOL_VERSION, 8))
14008            .await
14009            .unwrap();
14010        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
14011
14012        hold.wait();
14013        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14014        let ack = module_rx.try_recv().unwrap().frame;
14015        assert_eq!(ack.header.ty, FrameType::HelloAck);
14016        let (_, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14017        assert_eq!(listed, vec![("aft".to_string(), true)]);
14018
14019        let (open_task, bind) = relay_route_open(
14020            &handler,
14021            client,
14022            &client_ctx.egress,
14023            &mut module_rx,
14024            303,
14025            "aft",
14026            "listed-after",
14027        )
14028        .await;
14029        assert!(handler
14030            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14031            .await
14032            .unwrap()
14033            .is_empty());
14034        assert!(open_task.await.unwrap().is_empty(), "route.open accepted");
14035        published_route(&client_rx.try_recv().unwrap().frame);
14036    }
14037
14038    /// A catalog watcher keys on the generation: when it changes, it re-reads
14039    /// the listing. So the generation must advance exactly when the module
14040    /// appears. If it advanced while the module was still hidden, a watcher
14041    /// would read the new generation without the module, and the module would
14042    /// later appear under that same generation with nothing telling the
14043    /// watcher to look again.
14044    #[tokio::test]
14045    async fn catalog_generation_advances_when_the_module_appears_and_not_before() {
14046        let (handler, hold, hello, _module_ctx, _module_rx) = hello_held_before_forwarding();
14047        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14048        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14049
14050        hold.wait();
14051        let (during, listed) = catalog_snapshot(&handler, &client_ctx, 301).await;
14052        assert!(listed.is_empty());
14053        assert_eq!(
14054            during, before,
14055            "the generation moved while the module was not listed"
14056        );
14057
14058        hold.wait();
14059        assert!(hello.join().unwrap().is_empty(), "HELLO succeeds");
14060        let (after, listed) = catalog_snapshot(&handler, &client_ctx, 302).await;
14061        assert_eq!(listed, vec![("aft".to_string(), true)]);
14062        assert_eq!(
14063            after,
14064            before + 1,
14065            "the module appeared without exactly one generation bump"
14066        );
14067    }
14068
14069    /// A HELLO whose forwarding endpoint cannot be installed (here the
14070    /// module's sink is already closed, so its HELLO_ACK cannot be queued) is
14071    /// refused and leaves nothing behind: no registry entry, no catalog entry,
14072    /// and the catalog generation where it was.
14073    #[tokio::test]
14074    async fn failed_forwarding_registration_leaves_no_registry_or_catalog_trace() {
14075        let registry = Arc::new(Registry::default());
14076        let handler = ControlHandler::with_forwarding(
14077            Arc::clone(&registry),
14078            Arc::new(ForwardingTable::default()),
14079        );
14080        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
14081        let (before, _) = catalog_snapshot(&handler, &client_ctx, 300).await;
14082        let (module_ctx, module_rx) = route_ctx(ConnectionId::new(40));
14083        drop(module_rx);
14084
14085        let replies = handler
14086            .handle_control_frame(&module_ctx, hello_frame("aft", PROTOCOL_VERSION, 7))
14087            .await
14088            .unwrap();
14089        assert_eq!(replies[0].header.ty, FrameType::Error, "{replies:?}");
14090        assert!(registry.get_module("aft").unwrap().is_none());
14091        assert!(registry
14092            .get_module_by_connection(module_ctx.connection_id)
14093            .unwrap()
14094            .is_none());
14095        assert_eq!(
14096            catalog_snapshot(&handler, &client_ctx, 301).await,
14097            (before, Vec::new())
14098        );
14099    }
14100
14101    /// A handler whose `route.open` parks after queueing the route.bind and
14102    /// before marking it enqueued, with module "aft" registered on connection
14103    /// 40. Returns the two-party barrier that parks and releases it.
14104    async fn route_open_held_after_bind_send() -> (
14105        ControlHandler,
14106        Arc<tokio::sync::Barrier>,
14107        RouteCtx,
14108        mpsc::Receiver<crate::router::OutboundFrame>,
14109    ) {
14110        let hold = Arc::new(tokio::sync::Barrier::new(2));
14111        let handler = ControlHandler::with_forwarding(
14112            Arc::new(Registry::default()),
14113            Arc::new(ForwardingTable::default()),
14114        )
14115        .with_route_bind_relay_sent_hold(Arc::clone(&hold));
14116        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
14117        hello_via_sink(
14118            &handler,
14119            &module_ctx,
14120            &mut module_rx,
14121            hello_frame("aft", PROTOCOL_VERSION, 7),
14122        )
14123        .await;
14124        (handler, hold, module_ctx, module_rx)
14125    }
14126
14127    /// A fast module acks the route.bind, and the reader commits the route,
14128    /// before `route.open` has marked the relay enqueued. The daemon used to
14129    /// read the missing relay as an abandoned bind and send the module a
14130    /// GOODBYE for the route it had just committed: the client was told its
14131    /// route was open, the module unbound the channel, and the client's first
14132    /// request was dropped on the module side as unbound.
14133    #[tokio::test]
14134    async fn bind_acked_before_the_enqueue_mark_commits_without_a_module_goodbye() {
14135        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14136        let client = ConnectionId::new(41);
14137        let (client_ctx, mut client_rx) = route_ctx(client);
14138
14139        let (open_task, bind) = relay_route_open(
14140            &handler,
14141            client,
14142            &client_ctx.egress,
14143            &mut module_rx,
14144            200,
14145            "aft",
14146            "acked-before-mark",
14147        )
14148        .await;
14149        let (module_channel, module_epoch) = route_bind_channel(&bind);
14150        // route.open is now parked between queueing the bind and marking it.
14151        hold.wait().await;
14152
14153        // The module answers inside that window, and the route commits.
14154        assert!(handler
14155            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14156            .await
14157            .unwrap()
14158            .is_empty());
14159        let (client_channel, client_epoch) = published_route(&client_rx.try_recv().unwrap().frame);
14160
14161        hold.wait().await;
14162        assert!(
14163            open_task.await.unwrap().is_empty(),
14164            "route.open answers accepted"
14165        );
14166
14167        // Every frame route.open could have sent is already queued, because it
14168        // has returned; the module must have been sent nothing.
14169        match module_rx.try_recv() {
14170            Err(mpsc::error::TryRecvError::Empty) => {}
14171            Ok(outbound) => panic!(
14172                "module was sent {:?} on channel {} epoch {} for a route the daemon committed",
14173                outbound.frame.header.ty,
14174                outbound.frame.header.channel,
14175                outbound.frame.header.epoch
14176            ),
14177            Err(err) => panic!("module egress closed: {err}"),
14178        }
14179
14180        // The client's first request on the route is the next thing the module
14181        // reads, on the binding it just created.
14182        let router = Router::with_control_handler(Arc::new(handler.clone()));
14183        let request = Frame::build(
14184            FrameType::Request,
14185            Flags::new(true, Priority::Interactive, false),
14186            client_channel,
14187            client_epoch,
14188            201,
14189            b"first request".to_vec(),
14190        )
14191        .unwrap();
14192        router
14193            .route_for_connection(&client_ctx, request)
14194            .await
14195            .unwrap();
14196        let delivered = module_rx.try_recv().unwrap().frame;
14197        assert_eq!(delivered.header.ty, FrameType::Request);
14198        assert_eq!(
14199            (delivered.header.channel, delivered.header.epoch),
14200            (module_channel, module_epoch)
14201        );
14202        assert_eq!(delivered.body, b"first request");
14203    }
14204
14205    /// The client goes away while `route.open` is still queueing the bind, so
14206    /// the relay is dropped with no module reply. The teardown cannot send the
14207    /// GOODBYE itself (it could reach the module ahead of the bind), so
14208    /// `route.open` must send it once the bind is queued; otherwise the module
14209    /// keeps a binding the daemon will never commit.
14210    #[tokio::test]
14211    async fn bind_released_before_the_enqueue_mark_still_sends_the_module_a_goodbye() {
14212        let (handler, hold, _module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14213        let client = ConnectionId::new(42);
14214        let (client_ctx, _client_rx) = route_ctx(client);
14215
14216        let (open_task, bind) = relay_route_open(
14217            &handler,
14218            client,
14219            &client_ctx.egress,
14220            &mut module_rx,
14221            300,
14222            "aft",
14223            "released-before-mark",
14224        )
14225        .await;
14226        let (module_channel, module_epoch) = route_bind_channel(&bind);
14227        hold.wait().await;
14228
14229        handler.cleanup_connection(client).unwrap();
14230        assert!(
14231            module_rx.try_recv().is_err(),
14232            "client teardown must not GOODBYE a bind route.open is still queueing"
14233        );
14234
14235        hold.wait().await;
14236        let response = open_task.await.unwrap();
14237        assert_eq!(response.len(), 1);
14238        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14239
14240        let goodbye = module_rx
14241            .try_recv()
14242            .expect("module is told to drop the binding the daemon abandoned")
14243            .frame;
14244        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14245        assert_eq!(
14246            (goodbye.header.channel, goodbye.header.epoch),
14247            (module_channel, module_epoch)
14248        );
14249        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14250    }
14251
14252    /// The module acks inside the same window, but the client's egress closed
14253    /// first, so the reader refuses to commit. The ack proves the module holds
14254    /// the binding, so the reader sends the GOODBYE, and `route.open` must not
14255    /// send a second one.
14256    #[tokio::test]
14257    async fn bind_acked_for_a_gone_client_before_the_enqueue_mark_sends_exactly_one_goodbye() {
14258        let (handler, hold, module_ctx, mut module_rx) = route_open_held_after_bind_send().await;
14259        let client = ConnectionId::new(43);
14260        let (client_ctx, client_rx) = route_ctx(client);
14261
14262        let (open_task, bind) = relay_route_open(
14263            &handler,
14264            client,
14265            &client_ctx.egress,
14266            &mut module_rx,
14267            400,
14268            "aft",
14269            "gone-client-before-mark",
14270        )
14271        .await;
14272        let (module_channel, module_epoch) = route_bind_channel(&bind);
14273        hold.wait().await;
14274
14275        drop(client_rx);
14276        assert!(client_ctx.egress.is_closed());
14277        handler
14278            .handle_control_frame(&module_ctx, route_bind_ack(bind.header.corr))
14279            .await
14280            .unwrap();
14281
14282        hold.wait().await;
14283        let response = open_task.await.unwrap();
14284        assert_eq!(response.len(), 1);
14285        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
14286
14287        let goodbye = module_rx
14288            .try_recv()
14289            .expect("module is told to drop the binding it acked")
14290            .frame;
14291        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
14292        assert_eq!(
14293            (goodbye.header.channel, goodbye.header.epoch),
14294            (module_channel, module_epoch)
14295        );
14296        assert!(module_rx.try_recv().is_err(), "exactly one GOODBYE");
14297        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
14298    }
14299
14300    /// The fence at the module-loop boundary, stated as its own contract: which
14301    /// forwarding failures are allowed to end the module connection that is being
14302    /// served. A `ConnectionClosing` naming some client is about that client, and
14303    /// a module connection is shared; the same error naming the module's own
14304    /// connection is about this connection and must stay fatal, as must failures
14305    /// that are about the forwarding table itself.
14306    #[test]
14307    fn only_the_modules_own_closing_connection_ends_the_module_loop() {
14308        let handler = ControlHandler::default();
14309        let module_connection = ConnectionId::new(30);
14310        let client_connection = ConnectionId::new(31);
14311
14312        handler
14313            .refuse_to_end_module_connection_for_a_client(
14314                module_connection,
14315                77,
14316                ForwardingError::ConnectionClosing {
14317                    connection_id: client_connection,
14318                },
14319            )
14320            .expect("a closing client must never end the module connection");
14321
14322        assert!(matches!(
14323            handler.refuse_to_end_module_connection_for_a_client(
14324                module_connection,
14325                78,
14326                ForwardingError::ConnectionClosing {
14327                    connection_id: module_connection,
14328                },
14329            ),
14330            Err(RouterError::Forwarding(ForwardingError::ConnectionClosing {
14331                connection_id
14332            })) if connection_id == module_connection
14333        ));
14334        assert!(matches!(
14335            handler.refuse_to_end_module_connection_for_a_client(
14336                module_connection,
14337                79,
14338                ForwardingError::Poisoned,
14339            ),
14340            Err(RouterError::Forwarding(ForwardingError::Poisoned))
14341        ));
14342        assert!(matches!(
14343            handler.refuse_to_end_module_connection_for_a_client(
14344                module_connection,
14345                80,
14346                ForwardingError::StaleModuleEndpoint,
14347            ),
14348            Err(RouterError::Forwarding(
14349                ForwardingError::StaleModuleEndpoint
14350            ))
14351        ));
14352    }
14353
14354    /// The spawn-attestation guard is what stops a connected module from claiming
14355    /// another module's identity and being stamped `Reserved` for it. Every other
14356    /// test that supplies a consumer_identity supplies a CORRECT one, because a
14357    /// correct one is what the rest of the flow needs -- so the guard's rejection
14358    /// branch was never the subject of an assertion, only its acceptance branch.
14359    ///
14360    /// Deleting the guard's EFFECT (granting Reserved unconditionally) leaves the
14361    /// whole subc-core library suite green; only the forwarding integration tests
14362    /// notice, and they notice for unrelated reasons. This test exists so the
14363    /// refusal itself is asserted where the guard lives: it fails if the identity
14364    /// check stops refusing, which is the direction that matters, since a guard
14365    /// that wrongly ACCEPTS is silent while one that wrongly REJECTS is loud.
14366    #[tokio::test]
14367    async fn route_open_refuses_consumer_identity_that_fails_spawn_attestation() {
14368        let registry = Arc::new(Registry::default());
14369        let forwarding = Arc::new(ForwardingTable::default());
14370        let supervisor = SupervisorHandle::new();
14371        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14372        let handler =
14373            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14374                .with_supervisor(supervisor);
14375
14376        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
14377        hello_via_sink(
14378            &handler,
14379            &target_ctx,
14380            &mut target_rx,
14381            hello_frame("target", PROTOCOL_VERSION, 1),
14382        )
14383        .await;
14384
14385        // A real supervised module id presenting the wrong nonce. This is the
14386        // impersonation case: the attacker knows a privileged module_id, which is
14387        // public, and guesses at the nonce, which is not.
14388        let wrong_nonce = handler
14389            .handle_control_frame(
14390                &route_ctx(ConnectionId::new(91)).0,
14391                route_open_frame_with_admission_facts(
14392                    20,
14393                    "target",
14394                    unique_project_root("admission-facts"),
14395                    Some(subc_control::ConsumerIdentity {
14396                        module_id: "fed".to_string(),
14397                        launch_nonce: "not-the-real-nonce".to_string(),
14398                    }),
14399                    None,
14400                ),
14401            )
14402            .await
14403            .unwrap();
14404        assert_eq!(
14405            parse_error(&wrong_nonce[0])["code"],
14406            "bad_consumer_identity",
14407            "a mismatched launch nonce must be refused, not stamped Reserved"
14408        );
14409
14410        // A module id the supervisor never spawned at all, so no nonce exists to
14411        // compare against. An implementation that treats "no record" as "nothing
14412        // to check" fails open here while passing the case above.
14413        let never_spawned = handler
14414            .handle_control_frame(
14415                &route_ctx(ConnectionId::new(92)).0,
14416                route_open_frame_with_admission_facts(
14417                    21,
14418                    "target",
14419                    unique_project_root("admission-facts"),
14420                    Some(subc_control::ConsumerIdentity {
14421                        module_id: "never-spawned".to_string(),
14422                        launch_nonce: "any-nonce".to_string(),
14423                    }),
14424                    None,
14425                ),
14426            )
14427            .await
14428            .unwrap();
14429        assert_eq!(
14430            parse_error(&never_spawned[0])["code"],
14431            "bad_consumer_identity",
14432            "an unspawned module_id must be refused rather than accepted for lack of a record"
14433        );
14434    }
14435
14436    /// The refusal test above proves the guard says NO. Nothing proved it can say
14437    /// YES, and the difference is not academic: replacing the whole authorization
14438    /// with `false` -- admitting no consumer identity at all, revoking Reserved
14439    /// standing for every supervised module in the fleet -- leaves 110 of the 111
14440    /// library tests GREEN. The one that notices does so by HANGING, because it
14441    /// waits for a bind that can no longer happen.
14442    ///
14443    /// A hang is the weakest signal a suite can produce. In CI it reads as a slow
14444    /// or flaky test, invites a RETRY rather than an investigation, and the retry
14445    /// hangs too and gets blamed on the runner. So a total revocation of the
14446    /// daemon's trust grant would have shipped behind a symptom nobody attributes
14447    /// to code.
14448    ///
14449    /// The bias is structural rather than accidental. A REFUSAL looks like a
14450    /// failure someone writes a test for; a GRANT looks like the happy path. Every
14451    /// binary-outcome guard whose STRICTNESS is the point acquires a refusal-heavy
14452    /// suite for that reason, and this one is the purest case in the daemon.
14453    ///
14454    /// This test asserts the EFFECT rather than the absence of an error: the module
14455    /// receives a RouteBind and it carries `Reserved` naming the attested module.
14456    /// A guard that admitted nobody would produce no bind at all; one that admitted
14457    /// everybody would stamp the wrong principal, which the refusal test catches.
14458    #[tokio::test]
14459    async fn route_open_stamps_reserved_for_a_correctly_attested_consumer() {
14460        let registry = Arc::new(Registry::default());
14461        let forwarding = Arc::new(ForwardingTable::default());
14462        let supervisor = SupervisorHandle::new();
14463        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14464        let handler =
14465            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14466                .with_supervisor(supervisor);
14467
14468        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(95));
14469        hello_via_sink(
14470            &handler,
14471            &target_ctx,
14472            &mut target_rx,
14473            hello_frame("target", PROTOCOL_VERSION, 1),
14474        )
14475        .await;
14476
14477        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(96));
14478        let route_handler = handler.clone();
14479        let route_task = tokio::spawn(async move {
14480            route_handler
14481                .handle_control_frame(
14482                    &client_ctx,
14483                    route_open_frame_with_admission_facts(
14484                        30,
14485                        "target",
14486                        unique_project_root("admission-facts"),
14487                        Some(subc_control::ConsumerIdentity {
14488                            module_id: "fed".to_string(),
14489                            launch_nonce: "fed-nonce".to_string(),
14490                        }),
14491                        None,
14492                    ),
14493                )
14494                .await
14495                .unwrap()
14496        });
14497
14498        // BOUND THE WAIT. The first version of this test recv'd unbounded, and under
14499        // the very mutation it exists to catch -- a guard that admits nobody -- no
14500        // bind is ever sent, so it HUNG rather than failing. That reproduces the
14501        // exact defect being fixed: a total revocation detected only as a stalled
14502        // suite, which reads as flakiness and invites a retry. An acceptance test
14503        // that waits for an effect must bound the wait, or a red becomes a hang.
14504        let bind_frame = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14505            .await
14506            .expect("no route.bind within 5s: the consumer-identity guard refused a correctly attested consumer")
14507            .expect("module control channel closed before route.bind");
14508        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
14509        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
14510            panic!("expected route.bind")
14511        };
14512        assert_eq!(
14513            principal,
14514            Some(Principal::Reserved {
14515                module_id: "fed".to_string()
14516            }),
14517            "a correctly attested consumer must be stamped Reserved for its own id"
14518        );
14519
14520        handler
14521            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
14522            .await
14523            .unwrap();
14524        assert!(route_task.await.unwrap().is_empty());
14525        assert!(
14526            matches!(
14527                serde_json::from_slice::<ClientControlResponse>(
14528                    &client_rx.recv().await.unwrap().body
14529                )
14530                .unwrap(),
14531                ClientControlResponse::RouteOpen { .. }
14532            ),
14533            "the route must actually open, not merely avoid an error"
14534        );
14535    }
14536
14537    #[tokio::test(start_paused = true)]
14538    async fn supervisor_routes_serializes_live_draining_bindings_from_the_real_handler() {
14539        let registry = Arc::new(Registry::default());
14540        let forwarding = Arc::new(ForwardingTable::default());
14541        let supervisor = SupervisorHandle::new();
14542        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
14543        let handler =
14544            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
14545                .with_supervisor(supervisor);
14546
14547        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(101));
14548        hello_via_sink(
14549            &handler,
14550            &target_ctx,
14551            &mut target_rx,
14552            hello_frame("target", PROTOCOL_VERSION, 1),
14553        )
14554        .await;
14555
14556        let (direct_ctx, mut direct_rx) = route_ctx(ConnectionId::new(102));
14557        let direct_handler = handler.clone();
14558        let direct_open = tokio::spawn(async move {
14559            direct_handler
14560                .handle_control_frame(
14561                    &direct_ctx,
14562                    route_open_frame(2, "target", unique_project_root("route-census-direct")),
14563                )
14564                .await
14565                .unwrap()
14566        });
14567        let direct_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14568            .await
14569            .expect("no direct route.bind within 5s")
14570            .expect("target control channel closed before direct route.bind");
14571        handler
14572            .handle_control_frame(&target_ctx, route_bind_ack(direct_bind.header.corr))
14573            .await
14574            .unwrap();
14575        assert!(direct_open.await.unwrap().is_empty());
14576        let _ = direct_rx.recv().await.unwrap();
14577
14578        let (reserved_ctx, mut reserved_rx) = route_ctx(ConnectionId::new(103));
14579        let reserved_handler = handler.clone();
14580        let reserved_open = tokio::spawn(async move {
14581            reserved_handler
14582                .handle_control_frame(
14583                    &reserved_ctx,
14584                    route_open_frame_with_admission_facts(
14585                        3,
14586                        "target",
14587                        unique_project_root("admission-facts"),
14588                        Some(ConsumerIdentity {
14589                            module_id: "fed".to_string(),
14590                            launch_nonce: "fed-nonce".to_string(),
14591                        }),
14592                        None,
14593                    ),
14594                )
14595                .await
14596                .unwrap()
14597        });
14598        let reserved_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14599            .await
14600            .expect("no reserved route.bind within 5s")
14601            .expect("target control channel closed before reserved route.bind");
14602        handler
14603            .handle_control_frame(&target_ctx, route_bind_ack(reserved_bind.header.corr))
14604            .await
14605            .unwrap();
14606        assert!(reserved_open.await.unwrap().is_empty());
14607        let _ = reserved_rx.recv().await.unwrap();
14608
14609        forwarding
14610            .begin_module_drain("target", subc_control::RouteCloseReason::Reload)
14611            .unwrap();
14612        let (census_ctx, _census_rx) = route_ctx(ConnectionId::new(104));
14613        let census_body = serde_json::to_vec(&ClientControlRequest::SupervisorRoutes {
14614            module_id: Some("target".to_string()),
14615        })
14616        .unwrap();
14617        let census_frame =
14618            Frame::build(FrameType::Request, control_flags(), 0, 0, 4, census_body).unwrap();
14619        let response = handler
14620            .handle_control_frame(&census_ctx, census_frame)
14621            .await
14622            .unwrap()
14623            .pop()
14624            .unwrap();
14625        let actual: Value = serde_json::from_slice(&response.body).unwrap();
14626        let decoded: ClientControlResponse = serde_json::from_value(actual.clone()).unwrap();
14627        assert!(matches!(
14628            decoded,
14629            ClientControlResponse::SupervisorRoutes { .. }
14630        ));
14631        let routes = actual["modules"][0]["routes"].as_array().unwrap();
14632        assert_eq!(routes.len(), 2);
14633        assert!(routes.iter().all(|route| route["draining"] == true));
14634        // The census carries WHY: the reason the drain was begun with, in the
14635        // route.closing vocabulary, on every draining route this drain marked.
14636        assert!(
14637            routes.iter().all(|route| route["drain_reason"] == "reload"),
14638            "draining routes must name the drain's reason: {routes:?}"
14639        );
14640        assert!(routes.iter().any(|route| {
14641            route["consumer"] == serde_json::json!({"kind": "direct", "connection_id": 102})
14642        }));
14643        assert!(routes.iter().any(|route| {
14644            route["consumer"] == serde_json::json!({"kind": "reserved", "module_id": "fed"})
14645        }));
14646
14647        let golden_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14648            .join("../subc-control/tests/golden/client_control_response_supervisor_routes.json");
14649        if std::env::var_os("UPDATE_GOLDEN").is_some() {
14650            std::fs::write(
14651                &golden_path,
14652                format!("{}\n", serde_json::to_string_pretty(&actual).unwrap()),
14653            )
14654            .unwrap();
14655        }
14656        let expected: Value =
14657            serde_json::from_str(&std::fs::read_to_string(golden_path).unwrap()).unwrap();
14658        assert_eq!(actual, expected);
14659    }
14660
14661    async fn query_live_roots(
14662        handler: &ControlHandler,
14663        module_ctx: &RouteCtx,
14664    ) -> ModuleControlResponseToModule {
14665        let body = serde_json::to_vec(&ModuleControlRequestFromModule::LiveRoots {}).unwrap();
14666        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 900, body).unwrap();
14667        let response = handler
14668            .handle_control_frame(module_ctx, frame)
14669            .await
14670            .unwrap()
14671            .pop()
14672            .unwrap();
14673        serde_json::from_slice(&response.body).unwrap()
14674    }
14675
14676    #[tokio::test(start_paused = true)]
14677    async fn supervisor_live_roots_root_known_arm_counts_bound_and_pending_from_real_handler() {
14678        let registry = Arc::new(Registry::default());
14679        let forwarding = Arc::new(ForwardingTable::default());
14680        let handler = ControlHandler::with_forwarding(registry, forwarding);
14681        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(301));
14682        hello_via_sink(
14683            &handler,
14684            &target_ctx,
14685            &mut target_rx,
14686            hello_frame("target", PROTOCOL_VERSION, 1),
14687        )
14688        .await;
14689        let root = unique_project_root("live-roots-known");
14690        let path = ProjectRootId::from_path_allowing_missing(root.path())
14691            .unwrap()
14692            .as_path()
14693            .to_path_buf();
14694        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(302));
14695        let open_handler = handler.clone();
14696        let opened = tokio::spawn(async move {
14697            open_handler
14698                .handle_control_frame(&client_ctx, legacy_route_open_frame(2, "target", root))
14699                .await
14700                .unwrap()
14701        });
14702        let bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14703            .await
14704            .unwrap()
14705            .unwrap();
14706        handler
14707            .handle_control_frame(&target_ctx, route_bind_ack(bind.header.corr))
14708            .await
14709            .unwrap();
14710        assert!(opened.await.unwrap().is_empty());
14711        let _ = client_rx.recv().await.unwrap();
14712
14713        let root = unique_project_root("live-roots-pending");
14714        let pending_path = ProjectRootId::from_path_allowing_missing(root.path())
14715            .unwrap()
14716            .as_path()
14717            .to_path_buf();
14718        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(303));
14719        let open_handler = handler.clone();
14720        let pending = tokio::spawn(async move {
14721            open_handler
14722                .handle_control_frame(&client_ctx, legacy_route_open_frame(3, "target", root))
14723                .await
14724                .unwrap()
14725        });
14726        let pending_bind = tokio::time::timeout(Duration::from_secs(5), target_rx.recv())
14727            .await
14728            .unwrap()
14729            .unwrap();
14730        let actual = query_live_roots(&handler, &target_ctx).await;
14731        let ModuleControlResponseToModule::LiveRoots {
14732            roots,
14733            unknown_root_bindings,
14734            total_bindings,
14735        } = actual
14736        else {
14737            panic!("expected live roots")
14738        };
14739        assert_eq!(total_bindings, 2, "root-known arm must count live routes");
14740        assert_eq!(unknown_root_bindings, 0);
14741        assert_eq!(
14742            roots.len(),
14743            2,
14744            "root-known arm must retain each canonical root"
14745        );
14746        assert_eq!(
14747            total_bindings,
14748            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14749        );
14750        let counts = roots
14751            .iter()
14752            .map(|root| (root.project_root.clone(), root.bound, root.pending))
14753            .collect::<Vec<_>>();
14754        let mut expected = vec![(path, 1, 0), (pending_path, 0, 1)];
14755        expected.sort_by(|a, b| a.0.cmp(&b.0));
14756        assert_eq!(
14757            counts, expected,
14758            "roots must sort by path and count pending separately"
14759        );
14760        handler
14761            .handle_control_frame(&target_ctx, route_bind_ack(pending_bind.header.corr))
14762            .await
14763            .unwrap();
14764        assert!(pending.await.unwrap().is_empty());
14765    }
14766
14767    #[tokio::test(start_paused = true)]
14768    async fn supervisor_live_roots_unknown_root_arm_is_not_no_bindings() {
14769        let forwarding = Arc::new(ForwardingTable::default());
14770        let handler =
14771            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14772        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(311));
14773        hello_via_sink(
14774            &handler,
14775            &target_ctx,
14776            &mut target_rx,
14777            hello_frame("target", PROTOCOL_VERSION, 1),
14778        )
14779        .await;
14780        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(312));
14781        let pending = forwarding
14782            .begin_route_bind_relay_for_test(
14783                client_ctx.connection_id,
14784                client_ctx.egress.clone(),
14785                2,
14786                "target",
14787            )
14788            .unwrap();
14789        forwarding
14790            .complete_pending_relay(
14791                target_ctx.connection_id,
14792                pending.corr,
14793                RouteBindRelayOutcome::Accepted,
14794            )
14795            .unwrap();
14796        let actual = query_live_roots(&handler, &target_ctx).await;
14797        let ModuleControlResponseToModule::LiveRoots {
14798            roots,
14799            unknown_root_bindings,
14800            total_bindings,
14801        } = actual
14802        else {
14803            panic!("expected live roots")
14804        };
14805        assert!(roots.is_empty(), "unknown-root arm must not invent a root");
14806        assert_eq!(
14807            unknown_root_bindings, 1,
14808            "unknown-root arm must not read as no bindings"
14809        );
14810        assert_eq!(total_bindings, 1, "unknown-root arm has a live binding");
14811        assert_eq!(
14812            total_bindings,
14813            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14814        );
14815    }
14816
14817    /// A module reads HELLO_ACK as its first frame and exits on anything else,
14818    /// so the ack has to be on its outbound queue before the module is
14819    /// routable. The connection loop writes a handler's replies only after the
14820    /// handler returns; this test stops in exactly that gap, runs a real
14821    /// route.open from another connection, and only then writes whatever the
14822    /// HELLO handler returned, the way the loop would. If the ack were still a
14823    /// reply, the route.bind request would reach the module first.
14824    #[tokio::test(start_paused = true)]
14825    async fn hello_ack_reaches_the_module_before_a_route_bind_raced_into_the_reply_gap() {
14826        let forwarding = Arc::new(ForwardingTable::default());
14827        let handler =
14828            ControlHandler::with_forwarding(Arc::new(Registry::default()), Arc::clone(&forwarding));
14829        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(341));
14830        let replies = handler
14831            .handle_control_frame(&module_ctx, hello_frame("raced", PROTOCOL_VERSION, 7))
14832            .await
14833            .unwrap();
14834        let queued_by_hello = module_rx.len();
14835
14836        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(342));
14837        let open_handler = handler.clone();
14838        let open = tokio::spawn(async move {
14839            open_handler
14840                .handle_control_frame(
14841                    &client_ctx,
14842                    route_open_frame(2, "raced", unique_project_root("hello-ack-race")),
14843                )
14844                .await
14845                .unwrap()
14846        });
14847        // Let the route.open run until its route.bind is on the module's queue.
14848        let mut spins = 0;
14849        while module_rx.len() == queued_by_hello {
14850            spins += 1;
14851            assert!(spins < 10_000, "route.open never queued a route.bind");
14852            tokio::task::yield_now().await;
14853        }
14854
14855        // Now the connection loop's half: write the HELLO handler's replies.
14856        for reply in replies {
14857            module_ctx.egress.send(reply).await.unwrap();
14858        }
14859
14860        let first = module_rx.recv().await.unwrap().frame;
14861        assert_eq!(
14862            first.header.ty,
14863            FrameType::HelloAck,
14864            "the first frame a registering module reads must be its HELLO_ACK"
14865        );
14866        assert_eq!(first.header.corr, 7);
14867        let second = module_rx.recv().await.unwrap().frame;
14868        assert_eq!(second.header.ty, FrameType::Request);
14869        assert!(
14870            matches!(
14871                serde_json::from_slice::<ModuleControlRequest>(&second.body).unwrap(),
14872                ModuleControlRequest::RouteBind { .. }
14873            ),
14874            "the route.bind follows the ack"
14875        );
14876        assert!(module_rx.try_recv().is_err(), "nothing else was queued");
14877
14878        handler
14879            .handle_control_frame(&module_ctx, route_bind_ack(second.header.corr))
14880            .await
14881            .unwrap();
14882        assert!(open.await.unwrap().is_empty());
14883        let _ = client_rx.recv().await.unwrap();
14884    }
14885
14886    #[tokio::test(start_paused = true)]
14887    async fn supervisor_live_roots_cross_module_scope_uses_requesting_connection() {
14888        let handler = ControlHandler::with_forwarding(
14889            Arc::new(Registry::default()),
14890            Arc::new(ForwardingTable::default()),
14891        );
14892        let (first_ctx, mut first_rx) = route_ctx(ConnectionId::new(315));
14893        let (second_ctx, mut second_rx) = route_ctx(ConnectionId::new(316));
14894        hello_via_sink(
14895            &handler,
14896            &first_ctx,
14897            &mut first_rx,
14898            hello_frame("first", PROTOCOL_VERSION, 1),
14899        )
14900        .await;
14901        hello_via_sink(
14902            &handler,
14903            &second_ctx,
14904            &mut second_rx,
14905            hello_frame("second", PROTOCOL_VERSION, 2),
14906        )
14907        .await;
14908        let root = unique_project_root("second-only");
14909        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(317));
14910        let cloned = handler.clone();
14911        let open = tokio::spawn(async move {
14912            cloned
14913                .handle_control_frame(&client_ctx, route_open_frame(3, "second", root))
14914                .await
14915                .unwrap()
14916        });
14917        let bind = tokio::time::timeout(Duration::from_secs(5), second_rx.recv())
14918            .await
14919            .unwrap()
14920            .unwrap();
14921        let first = query_live_roots(&handler, &first_ctx).await;
14922        let second = query_live_roots(&handler, &second_ctx).await;
14923        assert!(
14924            matches!(
14925                first,
14926                ModuleControlResponseToModule::LiveRoots {
14927                    total_bindings: 0,
14928                    ..
14929                }
14930            ),
14931            "cross-module scope must not expose another module's roots"
14932        );
14933        assert!(
14934            matches!(
14935                second,
14936                ModuleControlResponseToModule::LiveRoots {
14937                    total_bindings: 1,
14938                    ..
14939                }
14940            ),
14941            "second module must see its pending route"
14942        );
14943        handler
14944            .handle_control_frame(&second_ctx, route_bind_ack(bind.header.corr))
14945            .await
14946            .unwrap();
14947        assert!(open.await.unwrap().is_empty());
14948    }
14949
14950    #[tokio::test(start_paused = true)]
14951    async fn supervisor_live_roots_no_bindings_arm_is_empty() {
14952        let handler = ControlHandler::with_forwarding(
14953            Arc::new(Registry::default()),
14954            Arc::new(ForwardingTable::default()),
14955        );
14956        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(321));
14957        hello_via_sink(
14958            &handler,
14959            &target_ctx,
14960            &mut target_rx,
14961            hello_frame("target", PROTOCOL_VERSION, 1),
14962        )
14963        .await;
14964        let actual = query_live_roots(&handler, &target_ctx).await;
14965        let ModuleControlResponseToModule::LiveRoots {
14966            roots,
14967            unknown_root_bindings,
14968            total_bindings,
14969        } = actual
14970        else {
14971            panic!("expected live roots")
14972        };
14973        assert!(roots.is_empty());
14974        assert_eq!(unknown_root_bindings, 0);
14975        assert_eq!(total_bindings, 0);
14976        assert_eq!(
14977            total_bindings,
14978            roots.iter().map(|r| r.bound + r.pending).sum::<u64>() + unknown_root_bindings
14979        );
14980    }
14981
14982    /// Read the vendored fed corpus rather than hand-building a package.
14983    ///
14984    /// A hand-built object encodes what the test author believed the carrier
14985    /// emits. These vectors are what it actually emits, and one of them exists
14986    /// specifically to pin OUR side of the seam: its note reads "SUBC relay
14987    /// ignores additive unknown fields at the traversal emit terminus."
14988    fn fed_admission_facts_vectors() -> Vec<(String, Value)> {
14989        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14990            .join("tests/fixtures/fed/admission-facts-emit.jsonl");
14991        let text = std::fs::read_to_string(&path)
14992            .unwrap_or_else(|err| panic!("vendored fed corpus unreadable at {path:?}: {err}"));
14993        let vectors: Vec<(String, Value)> = text
14994            .lines()
14995            .filter(|line| !line.trim().is_empty())
14996            .map(|line| {
14997                let entry: Value = serde_json::from_str(line).expect("corpus line must be JSON");
14998                let id = entry["corpus_id"]
14999                    .as_str()
15000                    .expect("every vector carries a corpus_id")
15001                    .to_string();
15002                (id, entry["package"].clone())
15003            })
15004            .collect();
15005        // Pin the count: a corpus that silently shrinks would take its coverage
15006        // with it, and a suite reading N-1 vectors reports the same clean pass
15007        // as one reading N.
15008        assert_eq!(
15009            vectors.len(),
15010            3,
15011            "vendored fed corpus changed size; re-sync from subc-federation"
15012        );
15013
15014        // Pin what makes the corpus DISCRIMINATING, not just present.
15015        //
15016        // The relay test below takes its expected value from the corpus, so the
15017        // corpus supplies the test's power to detect a lossy relay rather than
15018        // its correctness. A relay that dropped unrecognised fields would still
15019        // be caught -- but only by a package carrying fields it does not know.
15020        // Shrink every package to the handful of keys any implementation would
15021        // recognise and the test keeps passing over an input that can no longer
15022        // fail, which is the same clean green as a corpus that shrank away.
15023        //
15024        // So assert the precondition rather than duplicating the packages here:
15025        // at least one vector must carry a field beyond the small common set.
15026        // That is one claim to maintain instead of nine, and it fails loudly if
15027        // a re-sync ever flattens the corpus.
15028        const COMMONLY_MODELLED: [&str; 3] = ["schema", "verified_class", "org"];
15029        let richest = vectors
15030            .iter()
15031            .filter_map(|(_, package)| package.as_object())
15032            .map(|object| {
15033                object
15034                    .keys()
15035                    .filter(|key| !COMMONLY_MODELLED.contains(&key.as_str()))
15036                    .count()
15037            })
15038            .max()
15039            .unwrap_or(0);
15040        assert!(
15041            richest >= 2,
15042            "vendored corpus no longer carries a package with unmodelled fields, \
15043             so the relay test can no longer distinguish a verbatim relay from a lossy one"
15044        );
15045
15046        vectors
15047    }
15048
15049    /// The relay must carry the carrier's package through BYTE-FOR-BYTE.
15050    ///
15051    /// The gate test below proves the ACCESS RULE (who may send facts, to whom).
15052    /// This proves the PAYLOAD RULE, which the gate cannot: it hand-builds a
15053    /// three-key object, so a relay that quietly dropped fields it did not
15054    /// recognise would satisfy it. These vectors carry nine keys including ones
15055    /// this crate has no type for, so a typed relay fails here and only here.
15056    #[tokio::test]
15057    async fn admission_facts_relay_carries_vendored_packages_verbatim() {
15058        for (corpus_id, package) in fed_admission_facts_vectors() {
15059            let registry = Arc::new(Registry::default());
15060            let forwarding = Arc::new(ForwardingTable::default());
15061            let supervisor = SupervisorHandle::new();
15062            supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15063            let handler =
15064                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15065                    .with_supervisor(supervisor)
15066                    .with_admission_facts_config(
15067                        Some("fed".to_string()),
15068                        Some(vec!["target".to_string()]),
15069                    );
15070
15071            let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(90));
15072            hello_via_sink(
15073                &handler,
15074                &target_ctx,
15075                &mut target_rx,
15076                hello_frame("target", PROTOCOL_VERSION, 1),
15077            )
15078            .await;
15079
15080            let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(91));
15081            let route_handler = handler.clone();
15082            let expected = package.clone();
15083            let route_task = tokio::spawn(async move {
15084                route_handler
15085                    .handle_control_frame(
15086                        &client_ctx,
15087                        route_open_frame_with_admission_facts(
15088                            20,
15089                            "target",
15090                            unique_project_root("admission-facts"),
15091                            Some(subc_control::ConsumerIdentity {
15092                                module_id: "fed".to_string(),
15093                                launch_nonce: "fed-nonce".to_string(),
15094                            }),
15095                            Some(package),
15096                        ),
15097                    )
15098                    .await
15099                    .unwrap()
15100            });
15101
15102            let bind_frame = target_rx.recv().await.unwrap();
15103            let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15104            let ModuleControlRequest::RouteBind {
15105                admission_facts, ..
15106            } = bind
15107            else {
15108                panic!("{corpus_id}: expected route.bind")
15109            };
15110            assert_eq!(
15111                admission_facts,
15112                Some(expected),
15113                "{corpus_id}: relay must not add, drop or reshape any field"
15114            );
15115
15116            handler
15117                .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15118                .await
15119                .unwrap();
15120            route_task.await.unwrap();
15121        }
15122    }
15123
15124    #[tokio::test]
15125    async fn route_bind_never_relays_the_openers_build_class() {
15126        let registry = Arc::new(Registry::default());
15127        let forwarding = Arc::new(ForwardingTable::default());
15128        let handler =
15129            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15130        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(80));
15131        hello_via_sink(
15132            &handler,
15133            &target_ctx,
15134            &mut target_rx,
15135            hello_frame("target", PROTOCOL_VERSION, 1),
15136        )
15137        .await;
15138
15139        let mut identity = BindIdentity::new("unit".to_string(), "s".to_string());
15140        identity.build_class = Some(subc_protocol::BUILD_CLASS_PRODUCTION.to_string());
15141        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
15142            busy_refusals: None,
15143            target: RouteTarget::ToolProvider {
15144                module_id: "target".to_string(),
15145            },
15146            identity,
15147            consumer_identity: None,
15148            consumer_capabilities: None,
15149            role_versions: None,
15150            admission_facts: None,
15151            scope: None,
15152        })
15153        .unwrap();
15154        let open = Frame::build(FrameType::Request, control_flags(), 0, 0, 30, body).unwrap();
15155
15156        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(81));
15157        let route_handler = handler.clone();
15158        let route_task = tokio::spawn(async move {
15159            route_handler
15160                .handle_control_frame(&client_ctx, open)
15161                .await
15162                .unwrap()
15163        });
15164        let bind_frame = target_rx.recv().await.unwrap();
15165        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15166        let ModuleControlRequest::RouteBind { identity, .. } = bind else {
15167            panic!("expected route.bind")
15168        };
15169        assert_eq!(
15170            identity.build_class, None,
15171            "route.bind carried the build class"
15172        );
15173        assert!(
15174            !String::from_utf8_lossy(&bind_frame.body).contains("build_class"),
15175            "the route.bind bytes still name build_class"
15176        );
15177        handler
15178            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15179            .await
15180            .unwrap();
15181        route_task.await.unwrap();
15182    }
15183
15184    #[tokio::test]
15185    async fn admission_facts_gate_checks_carrier_target_and_precedence() {
15186        let registry = Arc::new(Registry::default());
15187        let forwarding = Arc::new(ForwardingTable::default());
15188        let supervisor = SupervisorHandle::new();
15189        supervisor.set_spawn_nonce("fed", "fed-nonce".to_string());
15190        supervisor.set_spawn_nonce("other", "other-nonce".to_string());
15191        let handler =
15192            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15193                .with_supervisor(supervisor)
15194                .with_admission_facts_config(
15195                    Some("fed".to_string()),
15196                    Some(vec!["target".to_string()]),
15197                );
15198
15199        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(70));
15200        hello_via_sink(
15201            &handler,
15202            &target_ctx,
15203            &mut target_rx,
15204            hello_frame("target", PROTOCOL_VERSION, 1),
15205        )
15206        .await;
15207        let (other_ctx, mut other_rx) = route_ctx(ConnectionId::new(71));
15208        hello_via_sink(
15209            &handler,
15210            &other_ctx,
15211            &mut other_rx,
15212            hello_frame("other", PROTOCOL_VERSION, 2),
15213        )
15214        .await;
15215
15216        let facts = json!({"schema": 1, "verified_class": "member", "org": "01H"});
15217        let expected_facts = facts.clone();
15218        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(72));
15219        let route_handler = handler.clone();
15220        let route_task = tokio::spawn(async move {
15221            route_handler
15222                .handle_control_frame(
15223                    &client_ctx,
15224                    route_open_frame_with_admission_facts(
15225                        10,
15226                        "target",
15227                        unique_project_root("admission-facts"),
15228                        Some(subc_control::ConsumerIdentity {
15229                            module_id: "fed".to_string(),
15230                            launch_nonce: "fed-nonce".to_string(),
15231                        }),
15232                        Some(facts.clone()),
15233                    ),
15234                )
15235                .await
15236                .unwrap()
15237        });
15238        let bind_frame = target_rx.recv().await.unwrap();
15239        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15240        let ModuleControlRequest::RouteBind {
15241            admission_facts, ..
15242        } = bind
15243        else {
15244            panic!("expected route.bind")
15245        };
15246        assert_eq!(admission_facts, Some(expected_facts));
15247        handler
15248            .handle_control_frame(&target_ctx, route_bind_ack(bind_frame.header.corr))
15249            .await
15250            .unwrap();
15251        assert!(route_task.await.unwrap().is_empty());
15252        assert!(matches!(
15253            serde_json::from_slice::<ClientControlResponse>(&client_rx.recv().await.unwrap().body)
15254                .unwrap(),
15255            ClientControlResponse::RouteOpen { .. }
15256        ));
15257
15258        let direct = handler
15259            .handle_control_frame(
15260                &route_ctx(ConnectionId::new(73)).0,
15261                route_open_frame_with_admission_facts(
15262                    11,
15263                    "target",
15264                    unique_project_root("admission-facts"),
15265                    None,
15266                    Some(json!({"x": 1})),
15267                ),
15268            )
15269            .await
15270            .unwrap();
15271        assert_eq!(
15272            parse_error(&direct[0])["code"],
15273            "admission_facts_not_permitted"
15274        );
15275
15276        let different_reserved = handler
15277            .handle_control_frame(
15278                &route_ctx(ConnectionId::new(77)).0,
15279                route_open_frame_with_admission_facts(
15280                    15,
15281                    "target",
15282                    unique_project_root("admission-facts"),
15283                    Some(subc_control::ConsumerIdentity {
15284                        module_id: "other".to_string(),
15285                        launch_nonce: "other-nonce".to_string(),
15286                    }),
15287                    Some(json!({"x": 1})),
15288                ),
15289            )
15290            .await
15291            .unwrap();
15292        assert_eq!(
15293            parse_error(&different_reserved[0])["code"],
15294            "admission_facts_not_permitted"
15295        );
15296
15297        let other_target = handler
15298            .handle_control_frame(
15299                &route_ctx(ConnectionId::new(74)).0,
15300                route_open_frame_with_admission_facts(
15301                    12,
15302                    "other",
15303                    unique_project_root("admission-facts"),
15304                    Some(subc_control::ConsumerIdentity {
15305                        module_id: "fed".to_string(),
15306                        launch_nonce: "fed-nonce".to_string(),
15307                    }),
15308                    Some(json!({"x": 1})),
15309                ),
15310            )
15311            .await
15312            .unwrap();
15313        assert_eq!(
15314            parse_error(&other_target[0])["code"],
15315            "admission_facts_target_not_allowed"
15316        );
15317
15318        let nonexistent = handler
15319            .handle_control_frame(
15320                &route_ctx(ConnectionId::new(75)).0,
15321                route_open_frame_with_admission_facts(
15322                    13,
15323                    "missing",
15324                    unique_project_root("admission-facts"),
15325                    None,
15326                    Some(json!({"x": 1})),
15327                ),
15328            )
15329            .await
15330            .unwrap();
15331        assert_eq!(parse_error(&nonexistent[0])["code"], "unknown_module");
15332
15333        let described = handler
15334            .handle_control_frame(
15335                &route_ctx(ConnectionId::new(76)).0,
15336                Frame::build(
15337                    FrameType::Request,
15338                    control_flags(),
15339                    0,
15340                    0,
15341                    14,
15342                    serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15343                )
15344                .unwrap(),
15345            )
15346            .await
15347            .unwrap();
15348        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15349            serde_json::from_slice(&described[0].body).unwrap()
15350        else {
15351            panic!("expected server.describe response")
15352        };
15353        assert!(capabilities
15354            .iter()
15355            .any(|cap| cap == "admission_facts_relay_v1"));
15356    }
15357
15358    #[tokio::test]
15359    async fn admission_facts_without_configured_carrier_are_rejected() {
15360        let registry = Arc::new(Registry::default());
15361        let forwarding = Arc::new(ForwardingTable::default());
15362        let handler = ControlHandler::with_forwarding(registry, forwarding);
15363        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(78));
15364        hello_via_sink(
15365            &handler,
15366            &target_ctx,
15367            &mut target_rx,
15368            hello_frame("target", PROTOCOL_VERSION, 1),
15369        )
15370        .await;
15371
15372        let responses = handler
15373            .handle_control_frame(
15374                &route_ctx(ConnectionId::new(79)).0,
15375                route_open_frame_with_admission_facts(
15376                    16,
15377                    "target",
15378                    unique_project_root("admission-facts"),
15379                    None,
15380                    Some(json!({"x": 1})),
15381                ),
15382            )
15383            .await
15384            .unwrap();
15385        assert_eq!(
15386            parse_error(&responses[0])["code"],
15387            "admission_facts_not_permitted"
15388        );
15389    }
15390
15391    #[tokio::test]
15392    async fn route_open_relays_consumer_capabilities_verbatim() {
15393        let registry = Arc::new(Registry::default());
15394        let forwarding = Arc::new(ForwardingTable::default());
15395        let handler =
15396            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15397        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(37));
15398        hello_via_sink(
15399            &handler,
15400            &module_ctx,
15401            &mut module_rx,
15402            hello_frame("aft", PROTOCOL_VERSION, 7),
15403        )
15404        .await;
15405
15406        let expected = vec!["elicitation".to_string(), "roots".to_string()];
15407        let expected_for_request = expected.clone();
15408        let project_root = unique_project_root("consumer-capabilities-present");
15409        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(38));
15410        let route_handler = handler.clone();
15411        let route_task = tokio::spawn(async move {
15412            route_handler
15413                .handle_control_frame(
15414                    &client_ctx,
15415                    route_open_frame_with_consumer_capabilities(
15416                        401,
15417                        "aft",
15418                        project_root,
15419                        Some(expected_for_request),
15420                    ),
15421                )
15422                .await
15423                .unwrap()
15424        });
15425        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15426            .await
15427            .unwrap()
15428            .unwrap();
15429        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15430        let ModuleControlRequest::RouteBind {
15431            consumer_capabilities,
15432            ..
15433        } = bind
15434        else {
15435            panic!("expected route.bind request, got {bind:?}");
15436        };
15437        assert_eq!(consumer_capabilities, Some(expected.clone()));
15438
15439        handler
15440            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15441            .await
15442            .unwrap();
15443        let route_response = route_task.await.unwrap();
15444        assert!(route_response.is_empty());
15445        let published = client_rx.recv().await.unwrap();
15446        assert!(matches!(
15447            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15448            ClientControlResponse::RouteOpen { .. }
15449        ));
15450    }
15451
15452    #[tokio::test]
15453    async fn route_open_without_consumer_capabilities_relays_none() {
15454        let registry = Arc::new(Registry::default());
15455        let forwarding = Arc::new(ForwardingTable::default());
15456        let handler =
15457            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15458        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(39));
15459        hello_via_sink(
15460            &handler,
15461            &module_ctx,
15462            &mut module_rx,
15463            hello_frame("aft", PROTOCOL_VERSION, 7),
15464        )
15465        .await;
15466
15467        let project_root = unique_project_root("consumer-capabilities-absent");
15468        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(40));
15469        let route_handler = handler.clone();
15470        let route_task = tokio::spawn(async move {
15471            route_handler
15472                .handle_control_frame(&client_ctx, route_open_frame(402, "aft", project_root))
15473                .await
15474                .unwrap()
15475        });
15476        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15477            .await
15478            .unwrap()
15479            .unwrap();
15480        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15481        let ModuleControlRequest::RouteBind {
15482            consumer_capabilities,
15483            ..
15484        } = bind
15485        else {
15486            panic!("expected route.bind request, got {bind:?}");
15487        };
15488        assert_eq!(consumer_capabilities, None);
15489
15490        handler
15491            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15492            .await
15493            .unwrap();
15494        let route_response = route_task.await.unwrap();
15495        assert!(route_response.is_empty());
15496        let published = client_rx.recv().await.unwrap();
15497        assert!(matches!(
15498            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15499            ClientControlResponse::RouteOpen { .. }
15500        ));
15501    }
15502
15503    /// Opens a route to a freshly registered `aft` with `sent` as the
15504    /// route.open's role_versions, acks the bind, and returns the role_versions
15505    /// the module's bind carried.
15506    async fn bind_role_versions_for(
15507        sent: Option<BTreeMap<String, String>>,
15508        connection: u64,
15509    ) -> Option<BTreeMap<String, String>> {
15510        let registry = Arc::new(Registry::default());
15511        let forwarding = Arc::new(ForwardingTable::default());
15512        let handler =
15513            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15514        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(connection));
15515        hello_via_sink(
15516            &handler,
15517            &module_ctx,
15518            &mut module_rx,
15519            hello_frame("aft", PROTOCOL_VERSION, 7),
15520        )
15521        .await;
15522        let project_root = unique_project_root("role-versions");
15523        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(connection + 1));
15524        let route_handler = handler.clone();
15525        let route_task = tokio::spawn(async move {
15526            route_handler
15527                .handle_control_frame(
15528                    &client_ctx,
15529                    route_open_frame_with_role_versions(403, "aft", project_root, sent),
15530                )
15531                .await
15532                .unwrap()
15533        });
15534        let bind_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15535            .await
15536            .expect("a well-formed route.open reaches the module as a bind")
15537            .unwrap();
15538        let bind: ModuleControlRequest = serde_json::from_slice(&bind_frame.body).unwrap();
15539        let ModuleControlRequest::RouteBind { role_versions, .. } = bind else {
15540            panic!("expected route.bind request, got {bind:?}");
15541        };
15542        handler
15543            .handle_control_frame(&module_ctx, route_bind_ack(bind_frame.header.corr))
15544            .await
15545            .unwrap();
15546        assert!(route_task.await.unwrap().is_empty());
15547        let published = client_rx.recv().await.unwrap();
15548        assert!(matches!(
15549            serde_json::from_slice::<ClientControlResponse>(&published.body).unwrap(),
15550            ClientControlResponse::RouteOpen { .. }
15551        ));
15552        role_versions
15553    }
15554
15555    #[tokio::test]
15556    async fn route_open_relays_role_versions_verbatim() {
15557        let sent = role_versions(&[("tool-provider", "v1"), ("management-surface", "v12")]);
15558        assert_eq!(
15559            bind_role_versions_for(Some(sent.clone()), 141).await,
15560            Some(sent)
15561        );
15562    }
15563
15564    /// An empty map declares nothing, so the provider sees no field rather
15565    /// than an empty object it would have to treat as a second "none".
15566    #[tokio::test]
15567    async fn route_open_with_empty_or_absent_role_versions_relays_none() {
15568        assert_eq!(bind_role_versions_for(None, 143).await, None);
15569        assert_eq!(
15570            bind_role_versions_for(Some(BTreeMap::new()), 145).await,
15571            None
15572        );
15573    }
15574
15575    #[tokio::test]
15576    async fn route_open_refuses_malformed_role_versions_before_any_bind() {
15577        let registry = Arc::new(Registry::default());
15578        let forwarding = Arc::new(ForwardingTable::default());
15579        let handler =
15580            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
15581        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(147));
15582        hello_via_sink(
15583            &handler,
15584            &module_ctx,
15585            &mut module_rx,
15586            hello_frame("aft", PROTOCOL_VERSION, 7),
15587        )
15588        .await;
15589
15590        let nine: BTreeMap<String, String> = (0..9)
15591            .map(|index| (format!("role-{index}"), "v1".to_string()))
15592            .collect();
15593        for (label, malformed) in [
15594            (
15595                "invalid role name",
15596                role_versions(&[("Tool_Provider", "v1")]),
15597            ),
15598            ("invalid version", role_versions(&[("tool-provider", "v0")])),
15599            ("nine entries", nine),
15600        ] {
15601            // A refused open answers at once; one that reached the module
15602            // would wait for its bind ack and trip this timeout.
15603            let responses = tokio::time::timeout(
15604                Duration::from_secs(1),
15605                handler.handle_control_frame(
15606                    &route_ctx(ConnectionId::new(148)).0,
15607                    route_open_frame_with_role_versions(
15608                        404,
15609                        "aft",
15610                        unique_project_root("role-versions-malformed"),
15611                        Some(malformed),
15612                    ),
15613                ),
15614            )
15615            .await
15616            .unwrap_or_else(|_| panic!("{label}: the open was relayed instead of refused"))
15617            .unwrap();
15618            assert_eq!(responses.len(), 1, "{label}");
15619            assert_eq!(responses[0].header.ty, FrameType::Error, "{label}");
15620            let error = parse_error(&responses[0]);
15621            assert_eq!(error["code"], "invalid_request", "{label}: {error}");
15622            assert_eq!(
15623                error["detail"]["field"], "role_versions",
15624                "{label}: {error}"
15625            );
15626            assert!(
15627                !error_codes::is_retryable_route_open(error["code"].as_str().unwrap()),
15628                "{label}: a malformed declaration is terminal"
15629            );
15630            assert!(
15631                module_rx.try_recv().is_err(),
15632                "{label}: the module must never see a bind"
15633            );
15634        }
15635    }
15636
15637    /// `route-role-versions/v1` is in HELLO_ACK and `server.describe`, so a
15638    /// consumer can tell this daemon forwards the field from one that would
15639    /// drop it.
15640    #[tokio::test]
15641    async fn route_role_versions_capability_is_advertised() {
15642        let handler = ControlHandler::new(Arc::new(Registry::default()));
15643        let (ctx, mut rx) = route_ctx(ConnectionId::new(149));
15644        let ack = hello_via_sink(
15645            &handler,
15646            &ctx,
15647            &mut rx,
15648            hello_frame("m", PROTOCOL_VERSION, 1),
15649        )
15650        .await;
15651        let ack = parse_ack(&ack);
15652        assert!(
15653            ack.subc_capabilities
15654                .iter()
15655                .any(|c| c == "route-role-versions/v1"),
15656            "{:?}",
15657            ack.subc_capabilities
15658        );
15659
15660        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15661        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15662        let reply = handler
15663            .handle_control_frame(&route_ctx(ConnectionId::new(150)).0, frame)
15664            .await
15665            .unwrap()
15666            .pop()
15667            .unwrap();
15668        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15669            serde_json::from_slice(&reply.body).unwrap()
15670        else {
15671            panic!("not a server.describe reply");
15672        };
15673        assert!(
15674            capabilities.iter().any(|c| c == CAP_ROUTE_ROLE_VERSIONS_V1),
15675            "{capabilities:?}"
15676        );
15677    }
15678
15679    /// `catalog-events/v1` is in `server.describe`, so a consumer can tell a
15680    /// catalog entry without `events` (the module declares none) from a daemon
15681    /// that never reports declared events.
15682    #[tokio::test]
15683    async fn catalog_events_capability_is_advertised() {
15684        let handler = ControlHandler::new(Arc::new(Registry::default()));
15685        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15686        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15687        let reply = handler
15688            .handle_control_frame(&route_ctx(ConnectionId::new(151)).0, frame)
15689            .await
15690            .unwrap()
15691            .pop()
15692            .unwrap();
15693        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15694            serde_json::from_slice(&reply.body).unwrap()
15695        else {
15696            panic!("not a server.describe reply");
15697        };
15698        assert!(
15699            capabilities
15700                .iter()
15701                .any(|c| c == subc_protocol::manifest::CAP_CATALOG_EVENTS_V1),
15702            "{capabilities:?}"
15703        );
15704    }
15705
15706    #[tokio::test]
15707    async fn scope_bind_proof_capability_is_advertised_in_hello_ack_and_server_describe() {
15708        let handler = ControlHandler::new(Arc::new(Registry::default()));
15709        let (module, mut module_rx) = route_ctx(ConnectionId::new(152));
15710        let ack = hello_via_sink(
15711            &handler,
15712            &module,
15713            &mut module_rx,
15714            hello_frame("scope-proof-owner", PROTOCOL_VERSION, 1),
15715        )
15716        .await;
15717        let ack = parse_ack(&ack);
15718        assert!(
15719            ack.subc_capabilities
15720                .iter()
15721                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15722            "{:?}",
15723            ack.subc_capabilities
15724        );
15725        assert!(ack
15726            .subc_capabilities
15727            .iter()
15728            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15729
15730        let (client, _client_rx) = route_ctx(ConnectionId::new(153));
15731        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15732        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15733        let reply = handler
15734            .handle_control_frame(&client, frame)
15735            .await
15736            .unwrap()
15737            .pop()
15738            .unwrap();
15739        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15740            serde_json::from_slice(&reply.body).unwrap()
15741        else {
15742            panic!("not a server.describe reply");
15743        };
15744        assert!(
15745            capabilities
15746                .iter()
15747                .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1),
15748            "{capabilities:?}"
15749        );
15750        assert!(capabilities
15751            .iter()
15752            .any(|c| c == subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2));
15753    }
15754
15755    #[tokio::test]
15756    async fn scope_on_behalf_of_capability_is_advertised_in_hello_ack_and_server_describe() {
15757        let handler = ControlHandler::new(Arc::new(Registry::default()));
15758        let (module, mut rx) = route_ctx(ConnectionId::new(156));
15759        let ack = hello_via_sink(
15760            &handler,
15761            &module,
15762            &mut rx,
15763            hello_frame("attribution-owner", PROTOCOL_VERSION, 1),
15764        )
15765        .await;
15766        assert!(parse_ack(&ack)
15767            .subc_capabilities
15768            .iter()
15769            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15770        assert!(parse_ack(&ack)
15771            .subc_capabilities
15772            .iter()
15773            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15774        assert!(parse_ack(&ack)
15775            .subc_capabilities
15776            .iter()
15777            .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY));
15778        let (client, _rx) = route_ctx(ConnectionId::new(157));
15779        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15780        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15781        let reply = handler
15782            .handle_control_frame(&client, frame)
15783            .await
15784            .unwrap()
15785            .pop()
15786            .unwrap();
15787        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15788            serde_json::from_slice(&reply.body).unwrap()
15789        else {
15790            panic!("server.describe reply")
15791        };
15792        assert!(capabilities
15793            .iter()
15794            .any(|cap| cap == subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY));
15795        assert!(capabilities
15796            .iter()
15797            .any(|cap| cap == subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY));
15798        assert!(capabilities
15799            .iter()
15800            .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY));
15801    }
15802
15803    #[tokio::test]
15804    async fn scope_workdir_capability_is_advertised_in_hello_ack_and_server_describe() {
15805        let handler = ControlHandler::new(Arc::new(Registry::default()));
15806        let (module, mut rx) = route_ctx(ConnectionId::new(158));
15807        let ack = hello_via_sink(
15808            &handler,
15809            &module,
15810            &mut rx,
15811            hello_frame("project-scope-owner", PROTOCOL_VERSION, 1),
15812        )
15813        .await;
15814        assert!(parse_ack(&ack)
15815            .subc_capabilities
15816            .iter()
15817            .any(|cap| cap == "scope-workdir/v1"));
15818        let (client, _rx) = route_ctx(ConnectionId::new(159));
15819        let frame = Frame::build(
15820            FrameType::Request,
15821            control_flags(),
15822            0,
15823            0,
15824            5,
15825            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15826        )
15827        .unwrap();
15828        let reply = handler
15829            .handle_control_frame(&client, frame)
15830            .await
15831            .unwrap()
15832            .remove(0);
15833        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15834            serde_json::from_slice(&reply.body).unwrap()
15835        else {
15836            panic!("server.describe reply")
15837        };
15838        assert!(capabilities.iter().any(|cap| cap == "scope-workdir/v1"));
15839    }
15840
15841    #[tokio::test]
15842    async fn worker_runs_capability_is_advertised_in_hello_ack_and_server_describe() {
15843        let handler = ControlHandler::new(Arc::new(Registry::default()));
15844        let (module, mut rx) = route_ctx(ConnectionId::new(160));
15845        let ack = hello_via_sink(
15846            &handler,
15847            &module,
15848            &mut rx,
15849            hello_frame("worker-run-owner", PROTOCOL_VERSION, 1),
15850        )
15851        .await;
15852        assert!(parse_ack(&ack)
15853            .subc_capabilities
15854            .iter()
15855            .any(|cap| cap == "worker-runs/v1"));
15856        let (client, _rx) = route_ctx(ConnectionId::new(161));
15857        let frame = Frame::build(
15858            FrameType::Request,
15859            control_flags(),
15860            0,
15861            0,
15862            5,
15863            serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap(),
15864        )
15865        .unwrap();
15866        let reply = handler
15867            .handle_control_frame(&client, frame)
15868            .await
15869            .unwrap()
15870            .remove(0);
15871        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15872            serde_json::from_slice(&reply.body).unwrap()
15873        else {
15874            panic!("server.describe reply")
15875        };
15876        assert!(capabilities.iter().any(|cap| cap == "worker-runs/v1"));
15877    }
15878
15879    #[tokio::test]
15880    async fn scope_replace_if_idle_capability_is_advertised_in_hello_ack_and_server_describe() {
15881        let handler = ControlHandler::new(Arc::new(Registry::default()));
15882        let (module, mut rx) = route_ctx(ConnectionId::new(154));
15883        let ack = hello_via_sink(
15884            &handler,
15885            &module,
15886            &mut rx,
15887            hello_frame("idle-scope-owner", PROTOCOL_VERSION, 1),
15888        )
15889        .await;
15890        assert!(parse_ack(&ack)
15891            .subc_capabilities
15892            .iter()
15893            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
15894        let (client, _rx) = route_ctx(ConnectionId::new(155));
15895        let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
15896        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
15897        let reply = handler
15898            .handle_control_frame(&client, frame)
15899            .await
15900            .unwrap()
15901            .pop()
15902            .unwrap();
15903        let ClientControlResponse::ServerDescribe { capabilities, .. } =
15904            serde_json::from_slice(&reply.body).unwrap()
15905        else {
15906            panic!("not a server.describe reply")
15907        };
15908        assert!(capabilities
15909            .iter()
15910            .any(|cap| cap == subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1));
15911    }
15912
15913    #[tokio::test]
15914    async fn supervision_only_module_health_probe_does_not_enable_route_open_and_cleans_up() {
15915        let registry = Arc::new(Registry::default());
15916        let forwarding = Arc::new(ForwardingTable::default());
15917        let handler =
15918            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
15919                .with_health_probe_timeout(Duration::from_secs(5));
15920        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(35));
15921        hello_via_sink(
15922            &handler,
15923            &module_ctx,
15924            &mut module_rx,
15925            non_routable_hello_frame_with_control_ops(
15926                "mcp",
15927                300,
15928                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
15929            ),
15930        )
15931        .await;
15932        assert!(registry
15933            .get_module("mcp")
15934            .unwrap()
15935            .unwrap()
15936            .manifest
15937            .provides
15938            .is_empty());
15939
15940        let (route_client_ctx, _route_client_rx) = route_ctx(ConnectionId::new(36));
15941        let route_response = handler
15942            .handle_control_frame(
15943                &route_client_ctx,
15944                route_open_frame(301, "mcp", unique_project_root("non-routable-mcp")),
15945            )
15946            .await
15947            .unwrap();
15948        assert_eq!(route_response[0].header.ty, FrameType::Error);
15949        assert_eq!(
15950            parse_error(&route_response[0])["code"],
15951            "target_unavailable"
15952        );
15953        assert!(parse_error(&route_response[0])["message"]
15954            .as_str()
15955            .unwrap()
15956            .contains("does not provide the requested target"));
15957        assert!(module_rx.try_recv().is_err());
15958
15959        let (health_client_ctx, _health_client_rx) = route_ctx(ConnectionId::new(37));
15960        let health_handler = handler.clone();
15961        let health_task = tokio::spawn(async move {
15962            health_handler
15963                .handle_control_frame(
15964                    &health_client_ctx,
15965                    supervisor_health_probe_frame(302, "mcp"),
15966                )
15967                .await
15968                .unwrap()
15969        });
15970        let health_frame = tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
15971            .await
15972            .unwrap()
15973            .unwrap();
15974        assert_eq!(
15975            serde_json::from_slice::<ModuleControlRequest>(&health_frame.body).unwrap(),
15976            ModuleControlRequest::HealthCheck {}
15977        );
15978        handler
15979            .handle_control_frame(
15980                &module_ctx,
15981                health_response(health_frame.header.corr, HealthStatus::Ok),
15982            )
15983            .await
15984            .unwrap();
15985        let health_response = health_task.await.unwrap();
15986        assert_eq!(health_response[0].header.ty, FrameType::Response);
15987        match serde_json::from_slice::<ClientControlResponse>(&health_response[0].body).unwrap() {
15988            ClientControlResponse::SupervisorHealthProbe {
15989                module_id, status, ..
15990            } => {
15991                assert_eq!(module_id, "mcp");
15992                assert_eq!(status, HealthStatus::Ok);
15993            }
15994            other => panic!("unexpected health response: {other:?}"),
15995        }
15996
15997        // Exercise the forwarding cleanup path directly while leaving the registry
15998        // advertisement in place. If cleanup leaves a stale control sink behind,
15999        // the next probe will enqueue onto it and wait for the long probe timeout
16000        // instead of returning an immediate no-connection error.
16001        forwarding
16002            .cleanup_connection(module_ctx.connection_id)
16003            .unwrap();
16004        let (cleanup_probe_ctx, _cleanup_probe_rx) = route_ctx(ConnectionId::new(38));
16005        let cleanup_response = tokio::time::timeout(
16006            Duration::from_millis(200),
16007            handler.handle_control_frame(
16008                &cleanup_probe_ctx,
16009                supervisor_health_probe_frame(303, "mcp"),
16010            ),
16011        )
16012        .await
16013        .expect("probe should fail immediately when the control lane is gone")
16014        .unwrap();
16015        assert_eq!(cleanup_response[0].header.ty, FrameType::Error);
16016        assert_eq!(
16017            parse_error(&cleanup_response[0])["code"],
16018            "target_unavailable"
16019        );
16020        assert!(parse_error(&cleanup_response[0])["message"]
16021            .as_str()
16022            .unwrap()
16023            .contains("no module connection"));
16024
16025        handler
16026            .cleanup_connection(module_ctx.connection_id)
16027            .unwrap();
16028    }
16029
16030    #[tokio::test]
16031    async fn route_open_classifies_unregistered_running_supervised_module_as_warming() {
16032        let registry = Arc::new(Registry::default());
16033        let supervisor_handle = SupervisorHandle::new();
16034        let supervisor =
16035            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
16036                .with_handle(supervisor_handle.clone())
16037                .with_connection_file_path(
16038                    std::env::temp_dir()
16039                        .join(format!("subc-route-open-warming-{}", std::process::id())),
16040                );
16041        let module = supervisor
16042            .supervise_configured(
16043                ModuleSpec {
16044                    script: None,
16045                    carry_containment: false,
16046                    module_id: "warming".to_string(),
16047                    program: fake_aft_stub_path(),
16048                    args: Vec::new(),
16049                    env: Vec::new(),
16050                    reserved: false,
16051                    reserved_prefixes: Vec::new(),
16052                    protocol: ModuleProtocol::Subc,
16053                    overlap: Default::default(),
16054                },
16055                true,
16056            )
16057            .unwrap();
16058        assert_eq!(module.state().unwrap(), ModuleState::Running);
16059
16060        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
16061        let (ctx, _rx) = route_ctx(ConnectionId::new(39));
16062        let response = handler
16063            .handle_control_frame(
16064                &ctx,
16065                route_open_frame(304, "warming", unique_project_root("warming")),
16066            )
16067            .await
16068            .unwrap();
16069        module.stop().await.unwrap();
16070
16071        assert_eq!(response[0].header.ty, FrameType::Error);
16072        let error = parse_error(&response[0]);
16073        assert_eq!(error["code"], "module_warming");
16074        assert!(error["message"]
16075            .as_str()
16076            .unwrap()
16077            .contains("state=running, enabled=true, live=false"));
16078    }
16079
16080    #[test]
16081    fn route_open_connection_cap_logs_admission_reason_and_capacity() {
16082        let handler = ControlHandler::new(Arc::new(Registry::default()));
16083        let capture = EventCapture::default();
16084        let _subscriber =
16085            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16086        let (ctx, _rx) = route_ctx(ConnectionId::new(96));
16087        let limit = crate::server::MAX_PENDING_ROUTE_OPENS_PER_CONNECTION;
16088        let pending = (0..limit).collect::<Vec<_>>();
16089        let response = handler
16090            .route_open_capacity_refusal(
16091                &ctx,
16092                &route_open_frame(396, "busy", unique_project_root("connection-cap")),
16093                "busy",
16094                pending.len(),
16095                limit,
16096            )
16097            .unwrap();
16098        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16099        let event = capture
16100            .events()
16101            .into_iter()
16102            .find(|event| {
16103                event.target == "control"
16104                    && event.fields.get("reason") == Some(&"\"open_admission_full\"".to_string())
16105            })
16106            .expect("connection admission refusal event");
16107        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16108        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16109        // Refused before `handle_route_open` parses the request, so the caller
16110        // fields are read from the frame itself.
16111        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
16112        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
16113    }
16114
16115    #[test]
16116    fn route_open_target_cap_logs_admission_reason_and_capacity() {
16117        let handler = ControlHandler::new(Arc::new(Registry::default()));
16118        let capture = EventCapture::default();
16119        let _subscriber =
16120            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16121        let (ctx, _rx) = route_ctx(ConnectionId::new(97));
16122        let limit = MAX_PENDING_ROUTE_BINDS_PER_TARGET;
16123        let guards = (0..limit)
16124            .map(|_| {
16125                handler
16126                    .route_bind_concurrency
16127                    .try_admit("busy", limit)
16128                    .unwrap()
16129            })
16130            .collect::<Vec<_>>();
16131        let in_flight = match handler.route_bind_concurrency.try_admit("busy", limit) {
16132            Err(in_flight) => in_flight,
16133            Ok(_) => panic!("target cap must refuse after {limit} admissions"),
16134        };
16135        let response = handler
16136            .route_open_target_capacity_refusal(
16137                &ctx,
16138                &RouteOpenCaller::unknown(),
16139                &route_open_frame(397, "busy", unique_project_root("target-cap")),
16140                "busy",
16141                in_flight,
16142            )
16143            .unwrap();
16144        assert_eq!(parse_error(&response)["code"], "target_unavailable");
16145        let event = capture
16146            .events()
16147            .into_iter()
16148            .find(|event| {
16149                event.target == "control"
16150                    && event.fields.get("reason") == Some(&"\"target_binds_full\"".to_string())
16151            })
16152            .expect("target admission refusal event");
16153        assert_eq!(event.fields.get("in_flight"), Some(&limit.to_string()));
16154        assert_eq!(event.fields.get("limit"), Some(&limit.to_string()));
16155        drop(guards);
16156    }
16157
16158    #[cfg(unix)]
16159    #[tokio::test(start_paused = true)]
16160    async fn supervisor_list_shows_a_failed_modules_next_retry() {
16161        let registry = Arc::new(Registry::default());
16162        let handle = SupervisorHandle::new();
16163        let supervisor =
16164            Supervisor::new_for_test(registry.clone(), RestartPolicy::new(0, Duration::ZERO))
16165                .with_handle(handle.clone());
16166        let module = supervisor
16167            .spawn(crate::ModuleSpec {
16168                script: None,
16169                carry_containment: false,
16170                module_id: "retry-list".into(),
16171                program: PathBuf::from("/bin/sh"),
16172                args: vec!["-c".into(), "exit 17".into()],
16173                env: vec![],
16174                reserved: false,
16175                reserved_prefixes: vec![],
16176                protocol: ModuleProtocol::None,
16177                overlap: Default::default(),
16178            })
16179            .unwrap();
16180        let deadline = std::time::Instant::now() + Duration::from_secs(10);
16181        while module.state().unwrap() != crate::ModuleState::Failed {
16182            assert!(
16183                std::time::Instant::now() < deadline,
16184                "waiting for budget failure"
16185            );
16186            tokio::task::yield_now().await;
16187        }
16188        let handler = ControlHandler::new(registry).with_supervisor(handle);
16189        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16190        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16191        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16192        assert_eq!(body["modules"][0]["state"], "failed");
16193        let retry = body["modules"][0]["next_retry_at_ms"]
16194            .as_u64()
16195            .expect("scheduled retry on the wire");
16196        let now = std::time::SystemTime::now()
16197            .duration_since(std::time::UNIX_EPOCH)
16198            .unwrap()
16199            .as_millis() as u64;
16200        assert!((599_000..=600_000).contains(&retry.saturating_sub(now)));
16201        module.set_enabled(false).await.unwrap();
16202        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16203        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16204        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16205        assert!(body["modules"][0].get("next_retry_at_ms").is_none());
16206    }
16207
16208    #[tokio::test]
16209    async fn slow_step_before_pid_read_does_not_spend_its_budget() {
16210        let dir = cortexkit_test_support::ScratchDir::new("pid-read-budget");
16211        let supervisor =
16212            Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default());
16213        let module = supervisor
16214            .spawn(crate::ModuleSpec {
16215                script: None,
16216                carry_containment: false,
16217                module_id: "pid-read-budget".into(),
16218                program: std::env::current_exe().unwrap(),
16219                args: vec![
16220                    "--exact".into(),
16221                    "control::tests::pid_resource_read_fixture".into(),
16222                ],
16223                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16224                    .into_iter()
16225                    .map(|key| (key.into(), dir.display().to_string()))
16226                    .chain(std::iter::once((
16227                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16228                        "1".into(),
16229                    )))
16230                    .collect(),
16231                reserved: false,
16232                reserved_prefixes: Vec::new(),
16233                protocol: ModuleProtocol::None,
16234                overlap: Default::default(),
16235            })
16236            .unwrap();
16237        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16238        while !matches!(
16239            module.child_resource_usage(),
16240            subc_control::ChildResourceUsage::Measured(_)
16241        ) {
16242            assert!(
16243                tokio::time::Instant::now() < ready_deadline,
16244                "fixture process was not measurable"
16245            );
16246            tokio::time::sleep(Duration::from_millis(10)).await;
16247        }
16248        tokio::time::sleep(crate::subtree_resources::READ_TIMEOUT * 2).await;
16249        let reading = {
16250            let _guard = crate::subtree_resources::fault_read_guard().await;
16251            crate::subtree_resources::read_process(module.clone()).await
16252        };
16253        stop_resource_fixture(&module, &dir).await;
16254        assert!(
16255            matches!(reading, subc_control::ChildResourceUsage::Measured(_)),
16256            "{reading:?}"
16257        );
16258    }
16259
16260    #[test]
16261    fn pid_resource_read_fixture() {
16262        if std::env::var_os("SUBC_SUBTREE_PID_FIXTURE").is_some() {
16263            let dir = std::path::PathBuf::from(std::env::var_os("XDG_DATA_HOME").unwrap());
16264            let deadline = std::time::Instant::now() + Duration::from_secs(60);
16265            while !dir.join("stop-module").exists() && std::time::Instant::now() < deadline {
16266                std::thread::sleep(Duration::from_millis(5));
16267            }
16268            std::fs::write(dir.join("module-stopped"), "").unwrap();
16269        }
16270    }
16271
16272    async fn stop_resource_fixture(
16273        module: &crate::supervise::SupervisedModule,
16274        dir: &std::path::Path,
16275    ) {
16276        let stopping = module.stop();
16277        tokio::pin!(stopping);
16278        tokio::select! {
16279            result = &mut stopping => result.unwrap(),
16280            () = async {
16281                while module.state().unwrap() != crate::supervise::ModuleState::Draining {
16282                    tokio::time::sleep(Duration::from_millis(5)).await;
16283                }
16284                std::fs::write(dir.join("stop-module"), "").unwrap();
16285            } => stopping.await.unwrap(),
16286        }
16287        #[cfg(windows)]
16288        assert!(
16289            dir.join("module-stopped").exists(),
16290            "the resource fixture must exit cooperatively, not wait for the drain kill"
16291        );
16292        assert_eq!(
16293            module.state().unwrap(),
16294            crate::supervise::ModuleState::Stopped
16295        );
16296    }
16297
16298    #[tokio::test]
16299    async fn disabled_module_tree_is_not_running_instead_of_permanently_pending() {
16300        let registry = Arc::new(Registry::default());
16301        let handle = SupervisorHandle::new();
16302        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16303            .with_handle(handle.clone());
16304        supervisor
16305            .supervise_configured(
16306                crate::ModuleSpec {
16307                    script: None,
16308                    module_id: "disabled-resource-reading".into(),
16309                    program: std::env::current_exe().unwrap(),
16310                    args: Vec::new(),
16311                    env: Vec::new(),
16312                    reserved: false,
16313                    reserved_prefixes: Vec::new(),
16314                    protocol: ModuleProtocol::None,
16315                    overlap: Default::default(),
16316                    carry_containment: false,
16317                },
16318                false,
16319            )
16320            .unwrap();
16321        let handler = ControlHandler::new(registry).with_supervisor(handle);
16322        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16323        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16324        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16325        assert!(body["modules"][0].get("tree").is_none());
16326        assert_eq!(body["modules"][0]["tree_unavailable"], "not_running");
16327    }
16328
16329    #[tokio::test]
16330    async fn supervisor_list_reads_process_resources_before_a_stalled_tree() {
16331        let dir = cortexkit_test_support::ScratchDir::new("list-process-priority");
16332        let registry = Arc::new(Registry::default());
16333        let handle = SupervisorHandle::new();
16334        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16335            .with_handle(handle.clone());
16336        let module = supervisor
16337            .spawn(crate::ModuleSpec {
16338                script: None,
16339                carry_containment: false,
16340                module_id: "list-process-priority".into(),
16341                program: std::env::current_exe().unwrap(),
16342                args: vec![
16343                    "--exact".into(),
16344                    "control::tests::pid_resource_read_fixture".into(),
16345                ],
16346                env: ["XDG_DATA_HOME", "XDG_RUNTIME_DIR", "XDG_CONFIG_HOME"]
16347                    .into_iter()
16348                    .map(|key| (key.into(), dir.display().to_string()))
16349                    .chain(std::iter::once((
16350                        "SUBC_SUBTREE_PID_FIXTURE".into(),
16351                        "1".into(),
16352                    )))
16353                    .collect(),
16354                reserved: false,
16355                reserved_prefixes: Vec::new(),
16356                protocol: ModuleProtocol::None,
16357                overlap: Default::default(),
16358            })
16359            .unwrap();
16360        let ready_deadline = tokio::time::Instant::now() + Duration::from_secs(5);
16361        loop {
16362            let image = module.running_image_agreement().await;
16363            if matches!(image, subc_control::RunningImageAgreement::Match { .. }) {
16364                break;
16365            }
16366            assert!(
16367                tokio::time::Instant::now() < ready_deadline,
16368                "the fixture process never became observable: {image:?}"
16369            );
16370            tokio::time::sleep(Duration::from_millis(10)).await;
16371        }
16372        let guard = crate::subtree_resources::fault_read_guard().await;
16373        let (target, release, _) = crate::subtree_resources::held();
16374        module.set_subtree_target_for_test(target);
16375        let handler = ControlHandler::new(registry).with_supervisor(handle);
16376        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16377        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16378        drop(release);
16379        drop(guard);
16380        stop_resource_fixture(&module, &dir).await;
16381        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16382        assert_eq!(
16383            body["modules"][0]["resources"]["status"], "measured",
16384            "the optional tree timeout must not discard the process reading: {body}"
16385        );
16386        assert!(body["modules"][0].get("tree").is_none());
16387        assert_eq!(body["modules"][0]["tree_unavailable"], "not_yet_measured");
16388        assert_eq!(
16389            body["modules"][0]["pending_reload"]["image"]["status"], "match",
16390            "the tree timeout must not hide a completed image observation"
16391        );
16392    }
16393
16394    #[cfg(any(target_os = "linux", target_os = "macos"))]
16395    #[tokio::test]
16396    async fn cold_explicit_provenance_completes_while_list_stays_bounded() {
16397        let mut handler = ControlHandler::new(Arc::new(Registry::default()))
16398            .with_daemon_provenance(
16399                std::process::id(),
16400                0,
16401                Some(std::env::current_exe().unwrap()),
16402                None,
16403                None,
16404            );
16405        let (probe, release, began) = ExecutableIdentityProbe::held();
16406        handler.daemon_provenance.probe = probe;
16407        let observe = |handler: ControlHandler, corr| {
16408            tokio::spawn(async move {
16409                let (ctx, _) = route_ctx(ConnectionId::new(corr));
16410                let frame =
16411                    Frame::build(FrameType::Request, control_flags(), 0, 0, corr, Vec::new())
16412                        .unwrap();
16413                handler
16414                    .handle_supervisor_provenance(&ctx, frame, None)
16415                    .await
16416                    .unwrap()
16417            })
16418        };
16419        let explicit = observe(handler.clone(), 114);
16420        began.await.unwrap();
16421        let concurrent = observe(handler.clone(), 115);
16422        // Keep explicit provenance waiting on its first image observation beyond
16423        // the list deadline; release it only after the concurrent list replies.
16424        tokio::time::sleep(Duration::from_millis(300)).await;
16425        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16426        let list = tokio::time::timeout(
16427            Duration::from_secs(1),
16428            handler.handle_supervisor_list(frame),
16429        )
16430        .await;
16431        let explicit_was_pending = !explicit.is_finished() && !concurrent.is_finished();
16432        drop(release);
16433        let replies = explicit.await.unwrap();
16434        let concurrent_replies = concurrent.await.unwrap();
16435        assert!(
16436            explicit_was_pending,
16437            "explicit provenance must await the full observation"
16438        );
16439        let list = list
16440            .expect("a concurrent explicit probe must not stall list")
16441            .unwrap();
16442        let list_body: Value = serde_json::from_slice(&list[0].body).unwrap();
16443        assert_eq!(list_body["op"], "supervisor.list");
16444        for replies in [replies, concurrent_replies] {
16445            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16446            assert_eq!(
16447                body["daemon"]["daemon_observed"]["running_image"]["status"],
16448                "match"
16449            );
16450        }
16451    }
16452
16453    #[tokio::test]
16454    async fn supervisor_list_slow_subtree_does_not_hold_connection_reader() {
16455        let registry = Arc::new(Registry::default());
16456        let handle = SupervisorHandle::new();
16457        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16458            .with_handle(handle.clone());
16459        let module = supervisor
16460            .supervise_configured(
16461                crate::ModuleSpec {
16462                    script: None,
16463                    carry_containment: false,
16464                    module_id: "memory-read".into(),
16465                    program: PathBuf::from("disabled-module"),
16466                    args: Vec::new(),
16467                    env: Vec::new(),
16468                    reserved: false,
16469                    reserved_prefixes: Vec::new(),
16470                    protocol: ModuleProtocol::Subc,
16471                    overlap: Default::default(),
16472                },
16473                true,
16474            )
16475            .unwrap();
16476        let _guard = crate::subtree_resources::fault_read_guard().await;
16477        let (target, release, began) = crate::subtree_resources::held();
16478        // Optional list work may be skipped when its deadline is already spent.
16479        // Establish the stalled fixture before asking the list to observe it.
16480        let stalled_target = target.clone();
16481        let stalled = tokio::task::spawn_blocking(move || {
16482            stalled_target.tree(&subc_os::ProcessTable::default())
16483        });
16484        began.await.unwrap();
16485        module.set_subtree_target_for_test(target);
16486        let handler = ControlHandler::new(registry).with_supervisor(handle);
16487        let (ctx, mut rx) = route_ctx(ConnectionId::new(112));
16488        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16489        let replies = handler
16490            .handle_client_control_request(
16491                &ctx,
16492                frame,
16493                ClientControlRequest::SupervisorList {},
16494                &mut None,
16495            )
16496            .await
16497            .unwrap();
16498        assert!(
16499            replies.is_empty(),
16500            "list reply must be detached from the connection reader"
16501        );
16502        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16503        let replies = handler
16504            .handle_client_control_request(
16505                &ctx,
16506                frame,
16507                ClientControlRequest::SupervisorSpawnSnapshot {},
16508                &mut None,
16509            )
16510            .await
16511            .unwrap();
16512        assert_eq!(
16513            replies.len(),
16514            1,
16515            "another request must complete while the subtree read stalls"
16516        );
16517        let reply = tokio::time::timeout(Duration::from_secs(5), rx.recv())
16518            .await
16519            .unwrap()
16520            .unwrap();
16521        release.send(()).unwrap();
16522        drop(release);
16523        stalled.await.unwrap();
16524        let body: Value = serde_json::from_slice(&reply.frame.body).unwrap();
16525        assert!(
16526            body["modules"][0].get("tree").is_none(),
16527            "an unknown tree reading must be omitted after the bounded read expires"
16528        );
16529        // Lists export completed work rather than measuring synchronously.
16530        // Complete a refresh after the fixture is released before asserting
16531        // that a later list contains its measured tree.
16532        handler
16533            .resource_tracker
16534            .read(handler.supervisor.list(), false, "released_tree_fixture")
16535            .await;
16536        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16537        let replies = handler.handle_supervisor_list(frame).await.unwrap();
16538        let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16539        assert_eq!(
16540            body["modules"][0]["tree"]["source"], "process_tree",
16541            "the next request must export the completed refresh"
16542        );
16543        assert_eq!(body["modules"][0]["tree"]["process_count"], 1);
16544    }
16545
16546    #[tokio::test]
16547    async fn supervisor_list_expired_budget_keeps_committed_accounting_rows() {
16548        use subc_control::{
16549            AgentCommandResources, ChildMemoryKind, ChildResourceReading,
16550            ChildResourceUnavailableReason, ChildResourceUsage, CpuLastHour, DaemonResources,
16551            TreeReading, TreeSource,
16552        };
16553        let registry = Arc::new(Registry::default());
16554        let handle = SupervisorHandle::new();
16555        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16556            .with_handle(handle.clone());
16557        supervisor
16558            .supervise_configured(
16559                crate::ModuleSpec {
16560                    script: None,
16561                    carry_containment: false,
16562                    module_id: "budget-worker".into(),
16563                    program: PathBuf::from("disabled-module"),
16564                    args: Vec::new(),
16565                    env: Vec::new(),
16566                    reserved: false,
16567                    reserved_prefixes: Vec::new(),
16568                    protocol: ModuleProtocol::Subc,
16569                    overlap: Default::default(),
16570                },
16571                true,
16572            )
16573            .unwrap();
16574        let handler = ControlHandler::new(registry).with_supervisor(handle);
16575        let now = u64::try_from(
16576            std::time::SystemTime::now()
16577                .duration_since(std::time::UNIX_EPOCH)
16578                .unwrap()
16579                .as_millis(),
16580        )
16581        .unwrap();
16582        let measured = now - 1_000;
16583        let hour = CpuLastHour::new(100, 60_000);
16584        let daemon = DaemonResources::new(7, 1, "test")
16585            .with_measured_at_ms(Some(measured))
16586            .with_resources(Some(ChildResourceUsage::Measured(
16587                ChildResourceReading::new(20, ChildMemoryKind::ResidentSet, 10, 0),
16588            )))
16589            .with_cpu_last_hour(Some(hour.clone()));
16590        let agents = AgentCommandResources::new("budget-worker", 50, 30, 1)
16591            .with_measured_at_ms(Some(measured))
16592            .with_cpu_last_hour(Some(hour.clone()));
16593        let tree = TreeReading::new(
16594            150,
16595            50,
16596            ChildMemoryKind::ResidentSet,
16597            1,
16598            TreeSource::ProcessTree,
16599        )
16600        .with_measured_at_ms(Some(measured));
16601        handler.resource_tracker.seed_committed_for_test(
16602            &handler.supervisor.list(),
16603            crate::resource_totals::Readings {
16604                modules: BTreeMap::from([("budget-worker".into(), (Some(tree), Some(hour)))]),
16605                daemon: Some(daemon),
16606                agent_commands: Some(vec![agents]),
16607                ..Default::default()
16608            },
16609            now,
16610        );
16611        list_diagnostics::scope(async {
16612            tokio::time::sleep(Duration::from_millis(110)).await;
16613            assert!(list_diagnostics::deadline().unwrap() <= tokio::time::Instant::now());
16614            let request =
16615                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16616            let replies = handler.handle_supervisor_list_inner(request).await.unwrap();
16617            let ClientControlResponse::SupervisorList {
16618                modules,
16619                daemon,
16620                agent_commands,
16621                ..
16622            } = serde_json::from_slice(&replies[0].body).unwrap()
16623            else {
16624                panic!("expected a list response")
16625            };
16626            assert!(matches!(
16627                modules[0].resources,
16628                Some(ChildResourceUsage::Unavailable {
16629                    reason: ChildResourceUnavailableReason::Unreadable
16630                })
16631            ));
16632            assert_eq!(
16633                (
16634                    modules[0].tree.as_ref().unwrap().cpu_ms,
16635                    modules[0].tree.as_ref().unwrap().measured_at_ms
16636                ),
16637                (150, Some(measured))
16638            );
16639            let daemon = daemon.unwrap();
16640            let agents = agent_commands.unwrap();
16641            assert_eq!(daemon.measured_at_ms, Some(measured));
16642            assert_eq!(
16643                (agents.len(), agents[0].cpu_ms, agents[0].measured_at_ms),
16644                (1, 50, Some(measured))
16645            );
16646            for hour in [
16647                modules[0].cpu_last_hour.as_ref(),
16648                daemon.cpu_last_hour.as_ref(),
16649                agents[0].cpu_last_hour.as_ref(),
16650            ] {
16651                let hour = hour.unwrap();
16652                assert_eq!((hour.cpu_ms, hour.covered_ms), (100, 60_000));
16653            }
16654        })
16655        .await;
16656    }
16657
16658    #[tokio::test]
16659    async fn supervisor_list_reports_loaded_config_and_omits_unconfigured() {
16660        let registry = Arc::new(Registry::default());
16661        let handle = SupervisorHandle::new();
16662        let supervisor = Supervisor::new_for_test(registry.clone(), RestartPolicy::default())
16663            .with_handle(handle.clone());
16664        supervisor
16665            .supervise_configured(
16666                crate::ModuleSpec {
16667                    script: None,
16668                    carry_containment: false,
16669                    module_id: "drift".into(),
16670                    program: PathBuf::from("disabled-module"),
16671                    args: Vec::new(),
16672                    env: Vec::new(),
16673                    reserved: false,
16674                    reserved_prefixes: Vec::new(),
16675                    protocol: ModuleProtocol::Subc,
16676                    overlap: Default::default(),
16677                },
16678                false,
16679            )
16680            .unwrap();
16681        let handler = ControlHandler::new(registry).with_supervisor(handle);
16682        for configured in [None, Some(false), Some(true)] {
16683            handler.capability_evaluator.configure(
16684                configured.map(|enabled| ("drift".to_string(), enabled)),
16685                BTreeMap::new(),
16686            );
16687            let frame =
16688                Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16689            let replies = handler
16690                .handle_supervisor_set_enabled(frame, "drift".into(), false, Principal::Direct)
16691                .await
16692                .unwrap();
16693            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16694            assert!(body.get("configured_enabled").is_none());
16695            assert_eq!(body["op"], "supervisor.ack");
16696            let frame =
16697                Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16698            let replies = handler.handle_supervisor_list(frame).await.unwrap();
16699            let body: Value = serde_json::from_slice(&replies[0].body).unwrap();
16700            assert_eq!(
16701                body["modules"][0].get("configured_enabled"),
16702                configured.map(Value::Bool).as_ref()
16703            );
16704            assert!(body["modules"][0].get("tree").is_none());
16705            assert!(body["modules"][0].get("subtree").is_none());
16706        }
16707    }
16708
16709    #[tokio::test(flavor = "current_thread")]
16710    async fn supervisor_set_enabled_logs_request_received_with_direct_caller() {
16711        let handler = ControlHandler::new(Arc::new(Registry::default()));
16712        let capture = EventCapture::default();
16713        let _subscriber =
16714            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16715        let (ctx, _rx) = route_ctx(ConnectionId::new(101));
16716        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16717
16718        let _ = handler
16719            .handle_client_control_request(
16720                &ctx,
16721                frame,
16722                ClientControlRequest::SupervisorSetEnabled {
16723                    module_id: "broca".to_string(),
16724                    enabled: false,
16725                },
16726                &mut None,
16727            )
16728            .await
16729            .unwrap();
16730
16731        let events = capture
16732            .events()
16733            .into_iter()
16734            .filter(|event| {
16735                event.target == "control"
16736                    && event.fields.get("message").map(String::as_str)
16737                        == Some("supervisor request received")
16738            })
16739            .collect::<Vec<_>>();
16740        assert_eq!(events.len(), 1, "one supervisor request log line");
16741        let event = &events[0];
16742        assert_eq!(event.level, tracing::Level::INFO);
16743        assert_eq!(
16744            event.fields.get("op"),
16745            Some(&format!("{:?}", ops::SUPERVISOR_SET_ENABLED))
16746        );
16747        assert_eq!(
16748            event.fields.get("module_id"),
16749            Some(&"\"broca\"".to_string())
16750        );
16751        assert_eq!(event.fields.get("enabled"), Some(&"false".to_string()));
16752        assert_eq!(event.fields.get("connection_id"), Some(&"101".to_string()));
16753        assert_eq!(event.fields.get("caller"), Some(&"direct".to_string()));
16754    }
16755
16756    #[tokio::test(flavor = "current_thread")]
16757    async fn supervisor_request_from_a_registered_module_logs_its_reserved_principal() {
16758        let registry = Arc::new(Registry::default());
16759        let module_connection = ConnectionId::new(303);
16760        registry
16761            .register_with_control_ops(
16762                manifest("aft", PROTOCOL_VERSION),
16763                PROTOCOL_VERSION,
16764                module_connection,
16765                module_baseline_control_ops(),
16766            )
16767            .unwrap();
16768        let handler = ControlHandler::new(registry);
16769        let capture = EventCapture::default();
16770        let _subscriber =
16771            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16772        let (ctx, _rx) = route_ctx(module_connection);
16773        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 1, Vec::new()).unwrap();
16774
16775        let _ = handler
16776            .handle_client_control_request(
16777                &ctx,
16778                frame,
16779                ClientControlRequest::SupervisorSetEnabled {
16780                    module_id: "broca".to_string(),
16781                    enabled: false,
16782                },
16783                &mut None,
16784            )
16785            .await
16786            .unwrap();
16787
16788        let callers = capture
16789            .events()
16790            .into_iter()
16791            .filter(|event| {
16792                event.fields.get("message").map(String::as_str)
16793                    == Some("supervisor request received")
16794            })
16795            .map(|event| event.fields.get("caller").cloned())
16796            .collect::<Vec<_>>();
16797        assert_eq!(callers, vec![Some("reserved:aft".to_string())]);
16798    }
16799
16800    #[tokio::test(flavor = "current_thread")]
16801    async fn supervisor_list_does_not_log_request_received() {
16802        let handler = ControlHandler::new(Arc::new(Registry::default()));
16803        let capture = EventCapture::default();
16804        let _subscriber =
16805            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16806        let (ctx, _rx) = route_ctx(ConnectionId::new(102));
16807        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 2, Vec::new()).unwrap();
16808
16809        handler
16810            .handle_client_control_request(
16811                &ctx,
16812                frame,
16813                ClientControlRequest::SupervisorList {},
16814                &mut None,
16815            )
16816            .await
16817            .unwrap();
16818
16819        assert!(capture.events().into_iter().all(|event| {
16820            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16821        }));
16822    }
16823
16824    #[tokio::test(flavor = "current_thread")]
16825    async fn supervisor_rescan_preview_does_not_log_request_received() {
16826        let handler = ControlHandler::new(Arc::new(Registry::default()));
16827        let capture = EventCapture::default();
16828        let _subscriber =
16829            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16830        let (ctx, _rx) = route_ctx(ConnectionId::new(103));
16831        let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 3, Vec::new()).unwrap();
16832
16833        handler
16834            .handle_client_control_request(
16835                &ctx,
16836                frame,
16837                ClientControlRequest::SupervisorRescan { preview: true },
16838                &mut None,
16839            )
16840            .await
16841            .unwrap();
16842
16843        assert!(capture.events().into_iter().all(|event| {
16844            event.fields.get("message").map(String::as_str) != Some("supervisor request received")
16845        }));
16846    }
16847
16848    struct ApproveOperator;
16849    impl crate::operator_confirm::OperatorProvider for ApproveOperator {
16850        fn prompt(
16851            &self,
16852            _: &str,
16853            _: Box<dyn FnOnce(Arc<dyn crate::operator_confirm::OperatorWithdraw>) + Send>,
16854        ) -> crate::operator_confirm::ProviderResult {
16855            crate::operator_confirm::ProviderResult::Approved
16856        }
16857    }
16858
16859    #[tokio::test]
16860    async fn privileged_operator_prompt_rescan_reports_changes_without_changing_running_mode() {
16861        assert_eq!(
16862            ControlHandler::default().privileged_operator_prompt,
16863            PrivilegedOperatorPrompt::Log
16864        );
16865        for (initial, changed, running) in [
16866            ("log", "enforce", PrivilegedOperatorPrompt::Log),
16867            ("enforce", "log", PrivilegedOperatorPrompt::Enforce),
16868        ] {
16869            let dir = ScratchDir::new("rescan-privileged-operator-prompt");
16870            let path = dir.join("subc.jsonc");
16871            std::fs::write(
16872                &path,
16873                json!({"version":1,"privileged_operator_prompt":initial}).to_string(),
16874            )
16875            .unwrap();
16876            let config = crate::daemon_config::load(&path).unwrap().unwrap();
16877            let registry = Arc::new(Registry::default());
16878            let handle = SupervisorHandle::new();
16879            let supervisor = Supervisor::new(registry.clone(), RestartPolicy::default())
16880                .with_handle(handle.clone());
16881            let handler = ControlHandler::new(registry)
16882                .with_supervisor(handle)
16883                .with_privileged_operator_prompt(config.privileged_operator_prompt)
16884                .with_supervisor_rescan(supervisor, &path, config.port);
16885            handler.forwarding.operator_confirms().configure(
16886                Arc::new(ApproveOperator),
16887                crate::operator_confirm::OperatorLimits::default(),
16888            );
16889            let (ctx, _rx) = route_ctx(ConnectionId::new(104));
16890
16891            for (disk_mode, needs_restart) in [
16892                (Some(initial), false),
16893                (Some(changed), true),
16894                (Some(changed), true),
16895                (None, running == PrivilegedOperatorPrompt::Enforce),
16896                (Some(initial), false),
16897            ] {
16898                let mut doc = json!({"version":1});
16899                if let Some(mode) = disk_mode {
16900                    doc["privileged_operator_prompt"] = json!(mode);
16901                }
16902                std::fs::write(&path, doc.to_string()).unwrap();
16903                for preview in [true, false] {
16904                    let request = ClientControlRequest::SupervisorRescan { preview };
16905                    let frame = Frame::build(
16906                        FrameType::Request,
16907                        control_flags(),
16908                        0,
16909                        0,
16910                        1,
16911                        serde_json::to_vec(&request).unwrap(),
16912                    )
16913                    .unwrap();
16914                    let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
16915                    assert_eq!(frames.len(), 1);
16916                    let ClientControlResponse::SupervisorRescan { result } =
16917                        serde_json::from_slice(&frames[0].body).unwrap()
16918                    else {
16919                        panic!("expected a rescan response");
16920                    };
16921                    let expected = if needs_restart {
16922                        vec!["privileged_operator_prompt"]
16923                    } else {
16924                        Vec::new()
16925                    };
16926                    assert_eq!(result.restart_required, expected);
16927                    assert_eq!(handler.privileged_operator_prompt, running);
16928                    assert_eq!(
16929                        handler.rescan.as_ref().unwrap().privileged_operator_prompt,
16930                        running
16931                    );
16932                }
16933            }
16934        }
16935    }
16936
16937    #[tokio::test]
16938    async fn privileged_operator_prompt_rescan_refuses_invalid_values() {
16939        let dir = ScratchDir::new("rescan-invalid-privileged-operator-prompt");
16940        let path = dir.join("subc.jsonc");
16941        let registry = Arc::new(Registry::default());
16942        let handle = SupervisorHandle::new();
16943        let supervisor =
16944            Supervisor::new(registry.clone(), RestartPolicy::default()).with_handle(handle.clone());
16945        let handler = ControlHandler::new(registry)
16946            .with_supervisor(handle)
16947            .with_privileged_operator_prompt(PrivilegedOperatorPrompt::Enforce)
16948            .with_supervisor_rescan(supervisor, &path, None);
16949        handler.forwarding.operator_confirms().configure(
16950            Arc::new(ApproveOperator),
16951            crate::operator_confirm::OperatorLimits::default(),
16952        );
16953        let (ctx, _rx) = route_ctx(ConnectionId::new(105));
16954        for preview in [true, false] {
16955            std::fs::write(
16956                &path,
16957                r#"{"version":1,"privileged_operator_prompt":"unknown"}"#,
16958            )
16959            .unwrap();
16960            let request = ClientControlRequest::SupervisorRescan { preview };
16961            let frame = Frame::build(
16962                FrameType::Request,
16963                control_flags(),
16964                0,
16965                0,
16966                1,
16967                serde_json::to_vec(&request).unwrap(),
16968            )
16969            .unwrap();
16970            let frames = handler.handle_control_frame(&ctx, frame).await.unwrap();
16971            assert_eq!(frames.len(), 1);
16972            assert_eq!(parse_error(&frames[0])["code"], "invalid_daemon_config");
16973            assert_eq!(
16974                handler.privileged_operator_prompt,
16975                PrivilegedOperatorPrompt::Enforce
16976            );
16977        }
16978    }
16979
16980    /// One wire code has several senders, so the refusal line names the check
16981    /// that refused. This drives the shared refusal path for ordinary refusals
16982    /// with an unregistered
16983    /// target and requires the branch label on the event.
16984    #[tokio::test]
16985    async fn route_open_refusal_names_the_check_that_refused() {
16986        let handler = ControlHandler::new(Arc::new(Registry::default()));
16987        let capture = EventCapture::default();
16988        let _subscriber =
16989            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
16990        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
16991        let response = handler
16992            .handle_control_frame(
16993                &ctx,
16994                route_open_frame(395, "nobody", unique_project_root("refusal-reason")),
16995            )
16996            .await
16997            .unwrap();
16998
16999        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17000        let event = capture
17001            .events()
17002            .into_iter()
17003            .find(|event| {
17004                event.target == "control"
17005                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17006            })
17007            .expect("route.open refusal event");
17008        assert_eq!(
17009            event.fields.get("reason"),
17010            Some(&"\"not_registered\"".to_string())
17011        );
17012    }
17013
17014    #[tokio::test]
17015    async fn route_open_supervised_absence_emits_refusal_fields_and_counts_code() {
17016        let registry = Arc::new(Registry::default());
17017        let supervisor_handle = SupervisorHandle::new();
17018        let supervisor =
17019            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17020                .with_handle(supervisor_handle.clone())
17021                .with_connection_file_path(std::env::temp_dir().join(format!(
17022                    "subc-route-open-refusal-info-{}",
17023                    std::process::id()
17024                )));
17025        let module = supervisor
17026            .supervise_configured(
17027                ModuleSpec {
17028                    script: None,
17029                    carry_containment: false,
17030                    module_id: "warming".to_string(),
17031                    program: fake_aft_stub_path(),
17032                    args: Vec::new(),
17033                    env: Vec::new(),
17034                    reserved: false,
17035                    reserved_prefixes: Vec::new(),
17036                    protocol: ModuleProtocol::Subc,
17037                    overlap: Default::default(),
17038                },
17039                true,
17040            )
17041            .unwrap();
17042        assert_eq!(module.state().unwrap(), ModuleState::Running);
17043
17044        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17045        assert!(handler
17046            .counters()
17047            .snapshot()
17048            .get("route_open_refused_by_code")
17049            .is_none());
17050        let capture = EventCapture::default();
17051        let _subscriber =
17052            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17053        let (ctx, _rx) = route_ctx(ConnectionId::new(94));
17054        let response = handler
17055            .handle_control_frame(
17056                &ctx,
17057                route_open_frame(394, "warming", unique_project_root("refusal-info")),
17058            )
17059            .await
17060            .unwrap();
17061        module.stop().await.unwrap();
17062
17063        assert_eq!(parse_error(&response[0])["code"], "module_warming");
17064        let event = capture
17065            .events()
17066            .into_iter()
17067            .find(|event| {
17068                event.target == "control"
17069                    && event.fields.get("code") == Some(&"\"module_warming\"".to_string())
17070            })
17071            .expect("route.open refusal event");
17072        assert_eq!(
17073            event.fields.get("module_id"),
17074            Some(&"\"warming\"".to_string())
17075        );
17076        assert_eq!(event.fields.get("connection_id"), Some(&"94".to_string()));
17077        assert_eq!(
17078            event.fields.get("reason"),
17079            Some(&"\"supervised_not_registered\"".to_string())
17080        );
17081        assert_eq!(event.fields.get("state"), Some(&"running".to_string()));
17082        assert_eq!(event.fields.get("enabled"), Some(&"true".to_string()));
17083        assert_eq!(event.fields.get("live"), Some(&"false".to_string()));
17084        assert_eq!(event.fields.get("principal"), Some(&"direct".to_string()));
17085        assert_eq!(event.fields.get("scope"), Some(&"none".to_string()));
17086        assert_eq!(event.fields.get("harness"), Some(&"\"unit\"".to_string()));
17087        assert_eq!(
17088            handler.counters().snapshot()["route_open_refused_by_code"],
17089            json!({ "module_warming": 1 })
17090        );
17091    }
17092
17093    const OUTAGE_START: &str = "route.open refusing module: not serving";
17094    const OUTAGE_RECOVERED: &str = "route.open accepted again after module outage";
17095
17096    fn outage_lines(capture: &EventCapture, message: &str) -> Vec<CapturedEvent> {
17097        capture
17098            .events()
17099            .into_iter()
17100            .filter(|event| event.fields.get("message").map(String::as_str) == Some(message))
17101            .collect()
17102    }
17103
17104    fn supervise_stub(
17105        registry: &Arc<Registry>,
17106        module_id: &str,
17107        enabled: bool,
17108    ) -> (SupervisorHandle, crate::supervise::SupervisedModule) {
17109        let supervisor_handle = SupervisorHandle::new();
17110        let supervisor =
17111            Supervisor::new_for_test(Arc::clone(registry), RestartPolicy::new(0, Duration::ZERO))
17112                .with_handle(supervisor_handle.clone())
17113                .with_connection_file_path(std::env::temp_dir().join(format!(
17114                    "subc-route-outage-{module_id}-{}",
17115                    std::process::id()
17116                )));
17117        let module = supervisor
17118            .supervise_configured(
17119                ModuleSpec {
17120                    script: None,
17121                    carry_containment: false,
17122                    module_id: module_id.to_string(),
17123                    program: fake_aft_stub_path(),
17124                    args: Vec::new(),
17125                    env: Vec::new(),
17126                    reserved: false,
17127                    reserved_prefixes: Vec::new(),
17128                    protocol: ModuleProtocol::Subc,
17129                    overlap: Default::default(),
17130                },
17131                enabled,
17132            )
17133            .unwrap();
17134        (supervisor_handle, module)
17135    }
17136
17137    fn supervisor_restart_frame(corr: u64, module_id: &str) -> Frame {
17138        let body = serde_json::to_vec(&ClientControlRequest::SupervisorRestart {
17139            module_id: module_id.to_string(),
17140            drain_timeout_ms: Some(50),
17141        })
17142        .unwrap();
17143        Frame::build(FrameType::Request, control_flags(), 0, 0, corr, body).unwrap()
17144    }
17145
17146    /// Two handlers built over one forwarding table must share one outage
17147    /// tracker; separate trackers would each log their own opening line for
17148    /// the same outage.
17149    #[test]
17150    fn handlers_over_one_forwarding_table_share_the_outage_tracker() {
17151        let registry = Arc::new(Registry::default());
17152        let forwarding = Arc::new(ForwardingTable::default());
17153        let first = ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17154        let second = ControlHandler::with_forwarding(registry, forwarding);
17155        assert!(Arc::ptr_eq(&first.route_outages, &second.route_outages));
17156    }
17157
17158    /// A client can name any module id it likes. Refusing an unknown one,
17159    /// however often, must not create outage state or outage lines, or the
17160    /// tracker would be a memory sink any client could fill.
17161    #[tokio::test(flavor = "current_thread")]
17162    async fn route_open_unknown_module_refusals_add_no_outage_state() {
17163        let handler = ControlHandler::new(Arc::new(Registry::default()));
17164        let capture = EventCapture::default();
17165        let _subscriber =
17166            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17167        let (ctx, _rx) = route_ctx(ConnectionId::new(90));
17168        for corr in 0..8 {
17169            let response = handler
17170                .handle_control_frame(
17171                    &ctx,
17172                    route_open_frame(
17173                        380 + corr,
17174                        &format!("nobody-{corr}"),
17175                        unique_project_root("outage-unknown"),
17176                    ),
17177                )
17178                .await
17179                .unwrap();
17180            assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17181        }
17182
17183        assert_eq!(handler.route_outages.tracked_module_count(), 0);
17184        assert!(outage_lines(&capture, OUTAGE_START).is_empty());
17185        assert!(outage_lines(&capture, OUTAGE_RECOVERED).is_empty());
17186    }
17187
17188    /// Drives the refusal path end to end: a supervised module that served
17189    /// before and stopped being registered with no instruction to stop is a
17190    /// WARN, and the same module refused after an operator `supervisor.restart`
17191    /// is an INFO.
17192    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17193    async fn route_open_outage_level_separates_operator_restart_from_unexplained() {
17194        let registry = Arc::new(Registry::default());
17195        let (supervisor_handle, module) = supervise_stub(&registry, "outage-restart", true);
17196        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17197        let capture = EventCapture::default();
17198        let _subscriber =
17199            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17200        let (ctx, _rx) = route_ctx(ConnectionId::new(91));
17201        // The stub never registers, so pretend it served once: otherwise every
17202        // refusal would fall in its startup window.
17203        handler.route_outages.record_accepted("outage-restart");
17204
17205        let response = handler
17206            .handle_control_frame(
17207                &ctx,
17208                route_open_frame(391, "outage-restart", unique_project_root("outage-a")),
17209            )
17210            .await
17211            .unwrap();
17212        assert_eq!(response[0].header.ty, FrameType::Error);
17213        let starts = outage_lines(&capture, OUTAGE_START);
17214        assert_eq!(starts.len(), 1, "{starts:?}");
17215        assert_eq!(starts[0].level, tracing::Level::WARN);
17216        assert_eq!(starts[0].fields["initiated_by"], "\"unexplained\"");
17217        assert_eq!(starts[0].fields["reason"], "\"supervised_not_registered\"");
17218        assert_eq!(starts[0].fields["module_id"], "\"outage-restart\"");
17219        handler.route_outages.record_accepted("outage-restart");
17220        assert_eq!(outage_lines(&capture, OUTAGE_RECOVERED).len(), 1);
17221
17222        // The missing connection file makes the stub exit immediately. Restart
17223        // is deliberately deferred while that exit is being recorded; Failed
17224        // means the zero restart budget and terminal record have been published.
17225        tokio::time::timeout(Duration::from_secs(10), async {
17226            while module.state().unwrap() != crate::ModuleState::Failed {
17227                tokio::task::yield_now().await;
17228            }
17229        })
17230        .await
17231        .expect("stub exit must be recorded before the operator restart");
17232
17233        let restart = handler
17234            .handle_control_frame(&ctx, supervisor_restart_frame(392, "outage-restart"))
17235            .await
17236            .unwrap();
17237        assert_eq!(
17238            restart[0].header.ty,
17239            FrameType::Response,
17240            "{:?}",
17241            parse_error(&restart[0])
17242        );
17243        handler
17244            .handle_control_frame(
17245                &ctx,
17246                route_open_frame(393, "outage-restart", unique_project_root("outage-b")),
17247            )
17248            .await
17249            .unwrap();
17250        module.stop().await.unwrap();
17251
17252        let starts = outage_lines(&capture, OUTAGE_START);
17253        assert_eq!(starts.len(), 2, "{starts:?}");
17254        assert_eq!(starts[1].level, tracing::Level::INFO);
17255        assert_eq!(starts[1].fields["initiated_by"], "\"operator\"");
17256    }
17257
17258    /// A restart refused before it touched the module (here: the module is
17259    /// disabled) must clear its operator mark, so the next real outage is
17260    /// still reported as a warning.
17261    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
17262    async fn failed_operator_restart_leaves_no_operator_mark() {
17263        let registry = Arc::new(Registry::default());
17264        let (supervisor_handle, _module) = supervise_stub(&registry, "outage-disabled", false);
17265        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17266        let capture = EventCapture::default();
17267        let _subscriber =
17268            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17269        let (ctx, _rx) = route_ctx(ConnectionId::new(92));
17270        handler.route_outages.record_accepted("outage-disabled");
17271
17272        let restart = handler
17273            .handle_control_frame(&ctx, supervisor_restart_frame(394, "outage-disabled"))
17274            .await
17275            .unwrap();
17276        assert_eq!(parse_error(&restart[0])["code"], "module_disabled");
17277        assert!(!handler.route_outages.has_operator_mark("outage-disabled"));
17278
17279        handler
17280            .handle_control_frame(
17281                &ctx,
17282                route_open_frame(395, "outage-disabled", unique_project_root("outage-c")),
17283            )
17284            .await
17285            .unwrap();
17286        let starts = outage_lines(&capture, OUTAGE_START);
17287        assert_eq!(starts.len(), 1, "{starts:?}");
17288        assert_eq!(starts[0].level, tracing::Level::WARN);
17289    }
17290
17291    #[tokio::test(flavor = "current_thread")]
17292    async fn route_open_unknown_module_escapes_target_module_id() {
17293        let handler = ControlHandler::new(Arc::new(Registry::default()));
17294        let capture = EventCapture::default();
17295        let _subscriber =
17296            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17297        let hostile_module_id = "\u{1b}]52;c;AAAA\u{07}";
17298        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17299        let response = handler
17300            .handle_control_frame(
17301                &ctx,
17302                route_open_frame(
17303                    395,
17304                    hostile_module_id,
17305                    unique_project_root("hostile-target-module-id"),
17306                ),
17307            )
17308            .await
17309            .unwrap();
17310
17311        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17312        let event = capture
17313            .events()
17314            .into_iter()
17315            .find(|event| {
17316                event.target == "control"
17317                    && event.fields.get("code") == Some(&"\"unknown_module\"".to_string())
17318            })
17319            .expect("route.open unknown-module refusal event");
17320        let logged = event.fields.get("module_id").expect("module_id field");
17321        assert!(!logged.bytes().any(|byte| byte < 0x20));
17322        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17323    }
17324
17325    /// A route.open refusal is the daemon's own answer, so its ERROR carries
17326    /// the daemon-origin bit on the frame the client receives.
17327    #[tokio::test(flavor = "current_thread")]
17328    async fn route_open_refusal_carries_daemon_origin() {
17329        let handler = ControlHandler::new(Arc::new(Registry::default()));
17330        let (ctx, _rx) = route_ctx(ConnectionId::new(95));
17331        let response = handler
17332            .handle_control_frame(
17333                &ctx,
17334                route_open_frame(395, "nobody", unique_project_root("refusal-origin")),
17335            )
17336            .await
17337            .unwrap();
17338
17339        assert_eq!(response.len(), 1);
17340        assert_eq!(response[0].header.ty, FrameType::Error);
17341        assert_eq!(parse_error(&response[0])["code"], "unknown_module");
17342        assert!(
17343            response[0].header.flags.is_daemon_origin(),
17344            "route.open refusal must carry daemon origin: {:?}",
17345            response[0].header.flags
17346        );
17347    }
17348
17349    /// The drain `module_reloading` refusal is daemon-synthesized for an
17350    /// endpoint that is reloading, so it carries the daemon-origin bit on the
17351    /// frame the client receives.
17352    #[tokio::test(flavor = "current_thread")]
17353    async fn route_open_to_draining_module_refuses_module_reloading_with_daemon_origin() {
17354        let registry = Arc::new(Registry::default());
17355        let forwarding = Arc::new(ForwardingTable::default());
17356        let handler =
17357            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17358        let module_connection = ConnectionId::new(95);
17359        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17360        hello_via_sink(
17361            &handler,
17362            &module_ctx,
17363            &mut module_rx,
17364            hello_frame("aft", PROTOCOL_VERSION, 395),
17365        )
17366        .await;
17367        forwarding
17368            .begin_module_drain("aft", RouteCloseReason::Restart)
17369            .unwrap()
17370            .expect("the module endpoint drains");
17371
17372        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(96));
17373        let response = handler
17374            .handle_control_frame(
17375                &client_ctx,
17376                route_open_frame(396, "aft", unique_project_root("drain-origin")),
17377            )
17378            .await
17379            .unwrap();
17380
17381        assert_eq!(response.len(), 1);
17382        assert_eq!(response[0].header.ty, FrameType::Error);
17383        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17384        assert!(
17385            response[0].header.flags.is_daemon_origin(),
17386            "drain module_reloading must carry daemon origin: {:?}",
17387            response[0].header.flags
17388        );
17389    }
17390
17391    /// A module that refuses a bind with a daemon code still cannot mint a
17392    /// daemon refusal: the relayed `module_reloading` body reaches the client
17393    /// with the daemon-origin bit clear.
17394    #[tokio::test(flavor = "current_thread")]
17395    async fn route_open_module_rejection_with_daemon_code_carries_no_daemon_origin() {
17396        let registry = Arc::new(Registry::default());
17397        let forwarding = Arc::new(ForwardingTable::default());
17398        let handler =
17399            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17400        let module_connection = ConnectionId::new(95);
17401        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17402        hello_via_sink(
17403            &handler,
17404            &module_ctx,
17405            &mut module_rx,
17406            hello_frame("aft", PROTOCOL_VERSION, 395),
17407        )
17408        .await;
17409
17410        let client_connection = ConnectionId::new(96);
17411        let (client_ctx, _client_rx) = route_ctx(client_connection);
17412        let (route_task, bind) = relay_route_open(
17413            &handler,
17414            client_connection,
17415            &client_ctx.egress,
17416            &mut module_rx,
17417            396,
17418            "aft",
17419            "spoofed-reloading",
17420        )
17421        .await;
17422        // The module sets the origin bit on its own rejection too: neither
17423        // the bit nor the daemon code may survive the relay as daemon-owned.
17424        let rejection = Frame::build(
17425            FrameType::Error,
17426            crate::router::daemon_error_flags(),
17427            0,
17428            0,
17429            bind.header.corr,
17430            serde_json::to_vec(&ErrorBody::new(
17431                "module_reloading",
17432                "module refused route.bind",
17433            ))
17434            .unwrap(),
17435        )
17436        .unwrap();
17437        handler
17438            .handle_control_frame(&module_ctx, rejection)
17439            .await
17440            .unwrap();
17441
17442        let response = route_task.await.unwrap();
17443        assert_eq!(response.len(), 1);
17444        assert_eq!(response[0].header.ty, FrameType::Error);
17445        assert_eq!(parse_error(&response[0])["code"], "module_reloading");
17446        assert!(
17447            !response[0].header.flags.is_daemon_origin(),
17448            "a module's own rejection must not carry daemon origin: {:?}",
17449            response[0].header.flags
17450        );
17451    }
17452
17453    #[tokio::test(flavor = "current_thread")]
17454    async fn route_open_module_rejection_uses_daemon_counter_key() {
17455        let registry = Arc::new(Registry::default());
17456        let forwarding = Arc::new(ForwardingTable::default());
17457        let handler =
17458            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17459        let module_connection = ConnectionId::new(95);
17460        let (module_ctx, mut module_rx) = route_ctx(module_connection);
17461        hello_via_sink(
17462            &handler,
17463            &module_ctx,
17464            &mut module_rx,
17465            hello_frame("aft", PROTOCOL_VERSION, 395),
17466        )
17467        .await;
17468
17469        let client_connection = ConnectionId::new(96);
17470        let (client_ctx, _client_rx) = route_ctx(client_connection);
17471        let capture = EventCapture::default();
17472        // tracing-core decides once per callsite whether its events are enabled,
17473        // and caches the answer. If a parallel test with no subscriber reaches
17474        // this callsite first, the cached answer is "disabled" and this test's
17475        // capture sees nothing. Keeping a second dispatch alive makes tracing-core
17476        // ask every live subscriber instead, while only this test's default
17477        // receives the events.
17478        static INTEREST_ANCHOR: std::sync::OnceLock<tracing::Dispatch> = std::sync::OnceLock::new();
17479        INTEREST_ANCHOR.get_or_init(|| tracing::Dispatch::new(tracing_subscriber::registry()));
17480        let _subscriber =
17481            tracing::subscriber::set_default(tracing_subscriber::registry().with(capture.clone()));
17482        let (route_task, bind) = relay_route_open(
17483            &handler,
17484            client_connection,
17485            &client_ctx.egress,
17486            &mut module_rx,
17487            396,
17488            "aft",
17489            "hostile-module-code",
17490        )
17491        .await;
17492        let hostile_code = "\u{1b}]52;c;AAAA\u{07}";
17493        let rejection = Frame::build(
17494            FrameType::Error,
17495            control_flags(),
17496            0,
17497            0,
17498            bind.header.corr,
17499            serde_json::to_vec(&ErrorBody::new(hostile_code, "module refused route.bind")).unwrap(),
17500        )
17501        .unwrap();
17502        handler
17503            .handle_control_frame(&module_ctx, rejection)
17504            .await
17505            .unwrap();
17506
17507        let response = route_task.await.unwrap();
17508        assert_eq!(parse_error(&response[0])["code"], hostile_code);
17509        let counters = handler.counters().snapshot();
17510        assert_eq!(
17511            counters["route_open_refused_by_code"],
17512            json!({ "module_rejected": 1 })
17513        );
17514        assert!(counters["route_open_refused_by_code"]
17515            .get(hostile_code)
17516            .is_none());
17517
17518        let event = capture
17519            .events()
17520            .into_iter()
17521            .find(|event| {
17522                event.target == "control"
17523                    && event.fields.get("code") == Some(&"\"module_rejected\"".to_string())
17524            })
17525            .expect("route.open module-rejection refusal event");
17526        let logged = event.fields.get("module_code").expect("module_code field");
17527        assert!(!logged.bytes().any(|byte| byte < 0x20));
17528        assert_eq!(logged, r#""\u{1b}]52;c;AAAA\u{7}""#);
17529    }
17530
17531    #[tokio::test]
17532    async fn route_open_keeps_failed_unregistered_supervised_module_unavailable() {
17533        let registry = Arc::new(Registry::default());
17534        let supervisor_handle = SupervisorHandle::new();
17535        let missing_program = std::env::temp_dir().join(format!(
17536            "subc-route-open-missing-program-{}",
17537            std::process::id()
17538        ));
17539        let supervisor =
17540            Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::new(0, Duration::ZERO))
17541                .with_handle(supervisor_handle.clone());
17542        let module = supervisor
17543            .supervise_configured(
17544                ModuleSpec {
17545                    script: None,
17546                    carry_containment: false,
17547                    module_id: "failed".to_string(),
17548                    program: missing_program,
17549                    args: Vec::new(),
17550                    env: Vec::new(),
17551                    reserved: false,
17552                    reserved_prefixes: Vec::new(),
17553                    protocol: ModuleProtocol::Subc,
17554                    overlap: Default::default(),
17555                },
17556                true,
17557            )
17558            .unwrap();
17559        assert_eq!(module.state().unwrap(), ModuleState::Failed);
17560
17561        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
17562        let (ctx, _rx) = route_ctx(ConnectionId::new(40));
17563        let response = handler
17564            .handle_control_frame(
17565                &ctx,
17566                route_open_frame(305, "failed", unique_project_root("failed")),
17567            )
17568            .await
17569            .unwrap();
17570
17571        assert_eq!(response[0].header.ty, FrameType::Error);
17572        let error = parse_error(&response[0]);
17573        assert_eq!(error["code"], "target_unavailable");
17574        assert!(error["message"]
17575            .as_str()
17576            .unwrap()
17577            .contains("state=failed, enabled=true, live=false"));
17578    }
17579
17580    #[tokio::test]
17581    async fn route_open_role_mismatch_remains_target_unavailable() {
17582        let registry = Arc::new(Registry::default());
17583        let handler = ControlHandler::new(Arc::clone(&registry));
17584        handler
17585            .handle_control(
17586                ConnectionId::new(41),
17587                non_routable_hello_frame_with_control_ops("health-only", 306, None),
17588            )
17589            .unwrap();
17590
17591        let (ctx, _rx) = route_ctx(ConnectionId::new(42));
17592        let response = handler
17593            .handle_control_frame(
17594                &ctx,
17595                route_open_frame(307, "health-only", unique_project_root("role-mismatch")),
17596            )
17597            .await
17598            .unwrap();
17599
17600        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17601        assert!(parse_error(&response[0])["message"]
17602            .as_str()
17603            .unwrap()
17604            .contains("does not provide the requested target"));
17605    }
17606
17607    #[tokio::test]
17608    async fn route_open_inactive_registration_remains_target_unavailable() {
17609        let registry = Arc::new(Registry::default());
17610        let handler = ControlHandler::new(Arc::clone(&registry));
17611        handler
17612            .handle_control(
17613                ConnectionId::new(43),
17614                hello_frame("inactive", PROTOCOL_VERSION, 308),
17615            )
17616            .unwrap();
17617        assert!(registry
17618            .set_module_state_for_test("inactive", ChannelState::Closed)
17619            .unwrap());
17620
17621        let (ctx, _rx) = route_ctx(ConnectionId::new(44));
17622        let response = handler
17623            .handle_control_frame(
17624                &ctx,
17625                route_open_frame(309, "inactive", unique_project_root("inactive")),
17626            )
17627            .await
17628            .unwrap();
17629
17630        assert_eq!(parse_error(&response[0])["code"], "target_unavailable");
17631        assert!(parse_error(&response[0])["message"]
17632            .as_str()
17633            .unwrap()
17634            .contains("is not active"));
17635    }
17636
17637    #[tokio::test]
17638    async fn late_health_reply_is_recorded_through_the_module_response_path() {
17639        let registry = Arc::new(Registry::default());
17640        let forwarding = Arc::new(ForwardingTable::default());
17641        let supervisor_handle = SupervisorHandle::new();
17642        let supervisor =
17643            Supervisor::new_for_test(Arc::clone(&registry), crate::RestartPolicy::default())
17644                .with_forwarding(Arc::clone(&forwarding))
17645                .with_handle(supervisor_handle.clone());
17646        let module = supervisor
17647            .supervise_configured(
17648                crate::ModuleSpec {
17649                    script: None,
17650                    carry_containment: false,
17651                    module_id: "late-health-response".to_string(),
17652                    program: PathBuf::from("disabled-module"),
17653                    args: Vec::new(),
17654                    env: Vec::new(),
17655                    reserved: false,
17656                    reserved_prefixes: Vec::new(),
17657                    protocol: ModuleProtocol::Subc,
17658                    overlap: Default::default(),
17659                },
17660                false,
17661            )
17662            .unwrap();
17663        let handler =
17664            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17665                .with_supervisor(supervisor_handle);
17666        let (module_ctx, _module_rx) = route_ctx(ConnectionId::new(39));
17667        handler
17668            .handle_control_frame(
17669                &module_ctx,
17670                hello_frame_with_control_ops(
17671                    "late-health-response",
17672                    PROTOCOL_VERSION,
17673                    7,
17674                    Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17675                ),
17676            )
17677            .await
17678            .unwrap();
17679        let probe_started_at = Instant::now() - Duration::from_millis(80);
17680        let pending = forwarding
17681            .begin_health_probe_rpc_for(
17682                "late-health-response",
17683                MODULE_CONTROL_OP_HEALTH_CHECK,
17684                probe_started_at,
17685                Instant::now() - Duration::from_millis(1),
17686            )
17687            .unwrap();
17688        assert!(forwarding
17689            .tombstone_health_probe_rpc(pending.endpoint, pending.corr)
17690            .unwrap());
17691
17692        let responses = handler
17693            .handle_control_frame(&module_ctx, health_response(pending.corr, HealthStatus::Ok))
17694            .await
17695            .unwrap();
17696
17697        assert!(responses.is_empty());
17698        let health = module.status().unwrap().health;
17699        assert_eq!(health.late_answer_count, 1);
17700        assert!(health.last_late_answer_latency_ms.unwrap() >= 80);
17701    }
17702
17703    #[tokio::test]
17704    async fn health_probe_timeout_and_module_death_are_typed() {
17705        let registry = Arc::new(Registry::default());
17706        let forwarding = Arc::new(ForwardingTable::default());
17707        let handler =
17708            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
17709                .with_health_probe_timeout(Duration::from_millis(50));
17710        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(40));
17711        hello_via_sink(
17712            &handler,
17713            &module_ctx,
17714            &mut module_rx,
17715            hello_frame_with_control_ops(
17716                "aft",
17717                PROTOCOL_VERSION,
17718                7,
17719                Some(vec![MODULE_CONTROL_OP_HEALTH_CHECK.to_string()]),
17720            ),
17721        )
17722        .await;
17723
17724        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(41));
17725        let responses = handler
17726            .handle_control_frame(&client_ctx, supervisor_health_probe_frame(201, "aft"))
17727            .await
17728            .unwrap();
17729        assert_eq!(responses[0].header.ty, FrameType::Error);
17730        assert_eq!(parse_error(&responses[0])["code"], "module_timeout");
17731        let _ = module_rx.try_recv();
17732
17733        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(42));
17734        let health_handler = handler.clone();
17735        let death_task = tokio::spawn(async move {
17736            health_handler
17737                .handle_control_frame(&client_ctx, supervisor_health_probe_frame(202, "aft"))
17738                .await
17739                .unwrap()
17740        });
17741        tokio::time::timeout(Duration::from_secs(1), module_rx.recv())
17742            .await
17743            .unwrap()
17744            .unwrap();
17745        handler
17746            .cleanup_connection(module_ctx.connection_id)
17747            .unwrap();
17748        let responses = death_task.await.unwrap();
17749        assert_eq!(responses[0].header.ty, FrameType::Error);
17750        assert_eq!(parse_error(&responses[0])["code"], "target_unavailable");
17751    }
17752
17753    #[test]
17754    fn hello_requires_exact_protocol_version() {
17755        for (connection, offered) in [(1, PROTOCOL_VERSION - 1), (2, PROTOCOL_VERSION + 1)] {
17756            let registry = Arc::new(Registry::default());
17757            let handler = ControlHandler::new(Arc::clone(&registry));
17758            let responses = handler
17759                .handle_control(
17760                    ConnectionId::new(connection),
17761                    hello_frame("aft", offered, 9),
17762                )
17763                .unwrap();
17764
17765            assert_eq!(responses.len(), 1);
17766            assert_eq!(responses[0].header.ty, FrameType::Error);
17767            let error = parse_error(&responses[0]);
17768            assert_eq!(error["code"], "version_unsupported");
17769            assert!(registry.get_module("aft").unwrap().is_none());
17770            assert_eq!(registry.active_registration_count().unwrap(), 0);
17771        }
17772    }
17773
17774    #[test]
17775    fn unknown_module_push_op_is_ignored_but_malformed_known_op_errors() {
17776        let registry = Arc::new(Registry::default());
17777        let forwarding = Arc::new(ForwardingTable::default());
17778        let handler =
17779            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17780        let module_connection = ConnectionId::new(301);
17781        let registration = registry
17782            .register_with_control_ops(
17783                manifest("aft-push", PROTOCOL_VERSION),
17784                PROTOCOL_VERSION,
17785                module_connection,
17786                module_baseline_control_ops(),
17787            )
17788            .unwrap();
17789        let (module_tx, _module_rx) = mpsc::channel(8);
17790        let endpoint = forwarding
17791            .register_module_connection(
17792                module_connection,
17793                "aft-push".to_string(),
17794                PROTOCOL_VERSION,
17795                manifest_concurrency(&registration.manifest),
17796                FrameSink::new(module_tx),
17797            )
17798            .unwrap();
17799
17800        // A push op this version does not know is ignored (forward-compat), not errored.
17801        let unknown = Frame::build(
17802            FrameType::Push,
17803            control_flags(),
17804            0,
17805            0,
17806            5,
17807            serde_json::to_vec(&json!({"op": "route.future.v2", "extra": 1})).unwrap(),
17808        )
17809        .unwrap();
17810        let out = handler.handle_status_update(endpoint, unknown).unwrap();
17811        assert!(
17812            out.is_empty(),
17813            "unknown push op must be ignored, got {out:?}"
17814        );
17815
17816        // A malformed body for a KNOWN op is a real error worth surfacing.
17817        let malformed = Frame::build(
17818            FrameType::Push,
17819            control_flags(),
17820            0,
17821            0,
17822            6,
17823            serde_json::to_vec(&json!({"op": "route.status"})).unwrap(),
17824        )
17825        .unwrap();
17826        let out = handler.handle_status_update(endpoint, malformed).unwrap();
17827        assert_eq!(out.len(), 1);
17828        assert_eq!(out[0].header.ty, FrameType::Error);
17829        assert_eq!(parse_error(&out[0])["code"], "invalid_control_body");
17830    }
17831
17832    #[test]
17833    fn hello_rejected_when_connection_already_owns_client_routes() {
17834        let registry = Arc::new(Registry::default());
17835        let forwarding = Arc::new(ForwardingTable::default());
17836        let handler =
17837            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
17838        // Commits a client route on connection 202 (bound to a module on conn 101).
17839        let _ = bind_liveness_route(&registry, &forwarding, "aft-module");
17840        let client_connection = ConnectionId::new(202);
17841
17842        // That same connection now tries to register as a module: rejected, so one
17843        // connection never holds both client-route and module-endpoint state.
17844        let responses = handler
17845            .handle_control(
17846                client_connection,
17847                hello_frame("aft-second", PROTOCOL_VERSION, 9),
17848            )
17849            .unwrap();
17850        assert_eq!(responses[0].header.ty, FrameType::Error);
17851        assert_eq!(parse_error(&responses[0])["code"], "invalid_hello");
17852        assert!(registry.get_module("aft-second").unwrap().is_none());
17853    }
17854
17855    #[tokio::test]
17856    async fn second_hello_preserves_registration_routes_and_launch_nonce() {
17857        let registry = Arc::new(Registry::default());
17858        let forwarding = Arc::new(ForwardingTable::default());
17859        let handler = ControlHandler::with_forwarding(registry.clone(), forwarding.clone());
17860        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(101));
17861        hello_via_sink(
17862            &handler,
17863            &module_ctx,
17864            &mut module_rx,
17865            hello_frame_with_nonce("alpha", PROTOCOL_VERSION, 1, Some("alpha-nonce")),
17866        )
17867        .await;
17868        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(202));
17869        let pending = forwarding
17870            .begin_route_bind_relay_for_test(
17871                client_ctx.connection_id,
17872                client_ctx.egress.clone(),
17873                2,
17874                "alpha",
17875            )
17876            .unwrap();
17877        forwarding
17878            .complete_pending_relay(
17879                module_ctx.connection_id,
17880                pending.corr,
17881                RouteBindRelayOutcome::Accepted,
17882            )
17883            .unwrap();
17884        client_rx.try_recv().unwrap();
17885        for module_id in ["beta", "alpha"] {
17886            let replies = handler
17887                .handle_control_frame(
17888                    &module_ctx,
17889                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 3, Some("replacement")),
17890                )
17891                .await
17892                .unwrap();
17893            assert_eq!(replies.len(), 1, "second HELLO must be refused");
17894            assert_eq!(parse_error(&replies[0])["code"], "invalid_hello");
17895        }
17896        assert_eq!(registry.list_modules().unwrap().1.len(), 1);
17897        assert!(registry.get_module("beta").unwrap().is_none());
17898        assert!(matches!(
17899            forwarding
17900                .lookup_data_route(
17901                    client_ctx.connection_id,
17902                    pending.client_channel,
17903                    pending.client_epoch,
17904                )
17905                .unwrap(),
17906            DataRoute::Client(DataRouteState::Bound(_))
17907        ));
17908        assert!(handler
17909            .hello_launch_nonces
17910            .lock()
17911            .unwrap()
17912            .presented(module_ctx.connection_id, Some("alpha-nonce")));
17913        assert!(module_rx.try_recv().is_err());
17914    }
17915
17916    #[test]
17917    fn reserved_module_hello_requires_matching_launch_nonce() {
17918        let registry = Arc::new(Registry::default());
17919        let supervisor = SupervisorHandle::new();
17920        // The supervisor recorded the nonce it injected when it spawned the reserved
17921        // module; the HELLO verifier checks against the same shared handle.
17922        supervisor.set_reserved_nonce("vault", "the-real-nonce".to_string());
17923        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
17924
17925        // A HELLO with NO nonce is rejected.
17926        let no_nonce = handler
17927            .handle_control(
17928                ConnectionId::new(1),
17929                hello_frame("vault", PROTOCOL_VERSION, 1),
17930            )
17931            .unwrap();
17932        assert_eq!(no_nonce[0].header.ty, FrameType::Error);
17933        assert_eq!(parse_error(&no_nonce[0])["code"], "reserved_module");
17934        assert!(registry.get_module("vault").unwrap().is_none());
17935
17936        // A HELLO with the WRONG nonce is rejected.
17937        let wrong = handler
17938            .handle_control(
17939                ConnectionId::new(2),
17940                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some("forged")),
17941            )
17942            .unwrap();
17943        assert_eq!(wrong[0].header.ty, FrameType::Error);
17944        assert_eq!(parse_error(&wrong[0])["code"], "reserved_module");
17945        assert!(registry.get_module("vault").unwrap().is_none());
17946
17947        // A HELLO with the CORRECT nonce registers.
17948        let ok = handler
17949            .handle_control(
17950                ConnectionId::new(3),
17951                hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some("the-real-nonce")),
17952            )
17953            .unwrap();
17954        assert_eq!(ok[0].header.ty, FrameType::HelloAck);
17955        assert!(registry.get_module("vault").unwrap().is_some());
17956    }
17957
17958    #[test]
17959    fn reserved_prefix_hello_uses_delimiter_sensitive_owner_nonce() {
17960        let registry = Arc::new(Registry::default());
17961        let supervisor = SupervisorHandle::new();
17962        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
17963        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
17964        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
17965
17966        let squat = handler
17967            .handle_control(
17968                ConnectionId::new(1),
17969                hello_frame("fed:peerA:tool", PROTOCOL_VERSION, 1),
17970            )
17971            .unwrap();
17972        assert_eq!(squat[0].header.ty, FrameType::Error);
17973        assert_eq!(parse_error(&squat[0])["code"], "reserved_module");
17974        assert!(parse_error(&squat[0])["message"]
17975            .as_str()
17976            .unwrap()
17977            .contains("fed:"));
17978
17979        let accepted_peer = handler
17980            .handle_control(
17981                ConnectionId::new(2),
17982                hello_frame_with_nonce("fed:peerA:tool", PROTOCOL_VERSION, 2, Some("owner-nonce")),
17983            )
17984            .unwrap();
17985        assert_eq!(accepted_peer[0].header.ty, FrameType::HelloAck);
17986
17987        let accepted_short = handler
17988            .handle_control(
17989                ConnectionId::new(3),
17990                hello_frame_with_nonce("fed:x", PROTOCOL_VERSION, 3, Some("owner-nonce")),
17991            )
17992            .unwrap();
17993        assert_eq!(accepted_short[0].header.ty, FrameType::HelloAck);
17994
17995        for (conn, module_id) in [(4, "fedx:tool"), (5, "fed"), (6, "FED:x")] {
17996            let response = handler
17997                .handle_control(
17998                    ConnectionId::new(conn),
17999                    hello_frame(module_id, PROTOCOL_VERSION, conn),
18000                )
18001                .unwrap();
18002            assert_eq!(response[0].header.ty, FrameType::HelloAck, "{module_id}");
18003        }
18004    }
18005
18006    #[test]
18007    fn exact_reserved_module_takes_precedence_over_reserved_prefix() {
18008        let registry = Arc::new(Registry::default());
18009        let supervisor = SupervisorHandle::new();
18010        supervisor.set_spawn_nonce("federation", "owner-nonce".to_string());
18011        supervisor.set_reserved_prefixes("federation", &["fed:".to_string()]);
18012        supervisor.set_reserved_nonce("fed:special", "exact-nonce".to_string());
18013        let handler = ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor);
18014
18015        let owner_nonce = handler
18016            .handle_control(
18017                ConnectionId::new(1),
18018                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 1, Some("owner-nonce")),
18019            )
18020            .unwrap();
18021        assert_eq!(owner_nonce[0].header.ty, FrameType::Error);
18022        assert_eq!(parse_error(&owner_nonce[0])["code"], "reserved_module");
18023        assert!(registry.get_module("fed:special").unwrap().is_none());
18024
18025        let exact_nonce = handler
18026            .handle_control(
18027                ConnectionId::new(2),
18028                hello_frame_with_nonce("fed:special", PROTOCOL_VERSION, 2, Some("exact-nonce")),
18029            )
18030            .unwrap();
18031        assert_eq!(exact_nonce[0].header.ty, FrameType::HelloAck);
18032        assert!(registry.get_module("fed:special").unwrap().is_some());
18033    }
18034
18035    #[test]
18036    fn non_reserved_module_ignores_launch_nonce() {
18037        let registry = Arc::new(Registry::default());
18038        // No reserved nonce recorded for these ids: they are not reserved, so HELLO
18039        // registration succeeds whether a spawned process echoes a nonce or not.
18040        let handler = ControlHandler::new(Arc::clone(&registry));
18041        let no_nonce = handler
18042            .handle_control(
18043                ConnectionId::new(1),
18044                hello_frame("aft-no-nonce", PROTOCOL_VERSION, 1),
18045            )
18046            .unwrap();
18047        assert_eq!(no_nonce[0].header.ty, FrameType::HelloAck);
18048        assert!(registry.get_module("aft-no-nonce").unwrap().is_some());
18049
18050        let echoed_nonce = handler
18051            .handle_control(
18052                ConnectionId::new(2),
18053                hello_frame_with_nonce("aft-with-nonce", PROTOCOL_VERSION, 2, Some("spawn-nonce")),
18054            )
18055            .unwrap();
18056        assert_eq!(echoed_nonce[0].header.ty, FrameType::HelloAck);
18057        assert!(registry.get_module("aft-with-nonce").unwrap().is_some());
18058    }
18059
18060    #[test]
18061    fn malformed_hello_returns_error_and_handler_still_answers_ping() {
18062        let handler = ControlHandler::default();
18063        let conn = ConnectionId::new(1);
18064        let malformed = Frame::build(
18065            FrameType::Hello,
18066            control_flags(),
18067            0,
18068            0,
18069            3,
18070            b"{not json".to_vec(),
18071        )
18072        .unwrap();
18073
18074        let error = handler.handle_control(conn, malformed).unwrap();
18075        assert_eq!(error[0].header.ty, FrameType::Error);
18076        assert_eq!(parse_error(&error[0])["code"], "invalid_hello");
18077
18078        let ping = Frame::build(FrameType::Ping, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18079        let pong = handler.handle_control(conn, ping).unwrap();
18080        assert_eq!(pong[0].header.ty, FrameType::Pong);
18081        assert_eq!(pong[0].header.corr, 4);
18082    }
18083
18084    #[test]
18085    fn duplicate_module_id_is_rejected_without_replacing_active_registration() {
18086        let registry = Arc::new(Registry::default());
18087        let handler = ControlHandler::new(Arc::clone(&registry));
18088
18089        handler
18090            .handle_control(
18091                ConnectionId::new(1),
18092                hello_frame("aft", PROTOCOL_VERSION, 1),
18093            )
18094            .unwrap();
18095        let duplicate = handler
18096            .handle_control(
18097                ConnectionId::new(2),
18098                hello_frame("aft", PROTOCOL_VERSION, 2),
18099            )
18100            .unwrap();
18101
18102        assert_eq!(duplicate[0].header.ty, FrameType::Error);
18103        assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
18104        let registration = registry.get_module("aft").unwrap().unwrap();
18105        assert_eq!(registration.connection_id, ConnectionId::new(1));
18106    }
18107
18108    #[test]
18109    fn liveness_poll_reports_false_when_process_liveness_reports_dead() {
18110        let registry = Arc::new(Registry::default());
18111        let forwarding = Arc::new(ForwardingTable::default());
18112        let process_liveness = Arc::new(FakeProcessLiveness { live: Some(false) });
18113        let handler =
18114            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18115                .with_process_liveness(process_liveness);
18116        let (ctx, route_channel, route_epoch) =
18117            bind_liveness_route(&registry, &forwarding, "aft-dead");
18118        let responses = handler
18119            .handle_route_poll(
18120                &ctx,
18121                route_poll_frame(41, PollKind::Liveness, route_channel),
18122                route_channel,
18123                route_epoch,
18124                PollKind::Liveness,
18125            )
18126            .unwrap();
18127
18128        assert_eq!(responses.len(), 1);
18129        assert_eq!(responses[0].header.ty, FrameType::Response);
18130        assert_route_poll_liveness(&responses[0], false);
18131    }
18132
18133    #[test]
18134    fn liveness_poll_without_process_source_uses_bound_route() {
18135        let registry = Arc::new(Registry::default());
18136        let forwarding = Arc::new(ForwardingTable::default());
18137        let handler =
18138            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
18139        let (ctx, route_channel, route_epoch) =
18140            bind_liveness_route(&registry, &forwarding, "aft-bound-only");
18141        let responses = handler
18142            .handle_route_poll(
18143                &ctx,
18144                route_poll_frame(42, PollKind::Liveness, route_channel),
18145                route_channel,
18146                route_epoch,
18147                PollKind::Liveness,
18148            )
18149            .unwrap();
18150
18151        assert_route_poll_liveness(&responses[0], true);
18152    }
18153
18154    #[test]
18155    fn liveness_poll_untracked_process_source_uses_bound_route() {
18156        let registry = Arc::new(Registry::default());
18157        let forwarding = Arc::new(ForwardingTable::default());
18158        let process_liveness = Arc::new(FakeProcessLiveness { live: None });
18159        let handler =
18160            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18161                .with_process_liveness(process_liveness);
18162        let (ctx, route_channel, route_epoch) =
18163            bind_liveness_route(&registry, &forwarding, "aft-untracked");
18164        let responses = handler
18165            .handle_route_poll(
18166                &ctx,
18167                route_poll_frame(43, PollKind::Liveness, route_channel),
18168                route_channel,
18169                route_epoch,
18170                PollKind::Liveness,
18171            )
18172            .unwrap();
18173
18174        assert_route_poll_liveness(&responses[0], true);
18175    }
18176
18177    #[tokio::test]
18178    async fn unknown_op_returns_unknown_control_op() {
18179        let handler = ControlHandler::default();
18180        let (ctx, _rx) = route_ctx(ConnectionId::new(77));
18181        let request = Frame::build(
18182            FrameType::Request,
18183            control_flags(),
18184            0,
18185            0,
18186            55,
18187            br#"{"op":"route.nope","route_channel":1}"#.to_vec(),
18188        )
18189        .unwrap();
18190
18191        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18192
18193        assert_eq!(response.len(), 1);
18194        assert_eq!(response[0].header.ty, FrameType::Error);
18195        assert_eq!(response[0].header.corr, 55);
18196        assert_eq!(parse_error(&response[0])["code"], "unknown_control_op");
18197    }
18198
18199    #[tokio::test]
18200    async fn supervisor_provenance_rejects_unknown_exact_module() {
18201        let handler = ControlHandler::default();
18202        let (ctx, _rx) = route_ctx(ConnectionId::new(79));
18203        let request = Frame::build(
18204            FrameType::Request,
18205            control_flags(),
18206            0,
18207            0,
18208            57,
18209            br#"{"op":"supervisor.provenance","module_id":"missing"}"#.to_vec(),
18210        )
18211        .unwrap();
18212
18213        let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18214
18215        assert_eq!(response.len(), 1);
18216        assert_eq!(response[0].header.ty, FrameType::Error);
18217        assert_eq!(response[0].header.corr, 57);
18218        let error = parse_error(&response[0]);
18219        assert_eq!(error["code"], "unknown_module");
18220        assert_eq!(error["message"], "module_id 'missing' is not supervised");
18221    }
18222
18223    #[test]
18224    fn provenance_probe_override_keeps_handler_tests_deterministic() {
18225        let expected = subc_control::RunningImageAgreement::Unavailable {
18226            reason: subc_control::RunningImageUnavailableReason::HashFailed,
18227        };
18228        let handler = ControlHandler::default().with_provenance_probe_result(expected.clone());
18229        assert_eq!(handler.provenance_probe_override, Some(expected));
18230    }
18231
18232    #[test]
18233    fn reload_verdict_detects_configured_program_different_from_spawned_path() {
18234        let verdict = reload_verdict(
18235            std::path::Path::new("/bin/new"),
18236            Some(std::path::Path::new("/bin/old")),
18237            subc_control::RunningImageAgreement::Unavailable {
18238                reason: subc_control::RunningImageUnavailableReason::HashFailed,
18239            },
18240        );
18241        assert!(matches!(
18242            verdict.path,
18243            subc_control::ReloadPathAgreement::Mismatch { configured, spawned_from }
18244                if configured == std::path::Path::new("/bin/new")
18245                    && spawned_from == std::path::Path::new("/bin/old")
18246        ));
18247    }
18248
18249    #[test]
18250    fn launch_spec_without_running_digest_is_unavailable_not_match() {
18251        use subc_control::{
18252            LaunchSpecAgreement as Agreement, LaunchSpecUnavailableReason as Reason,
18253        };
18254        let configured = crate::supervise::ModuleSpec {
18255            script: None,
18256            carry_containment: false,
18257            module_id: "legacy".into(),
18258            program: "/module".into(),
18259            args: Vec::new(),
18260            env: Vec::new(),
18261            reserved: false,
18262            reserved_prefixes: Vec::new(),
18263            protocol: subc_control::ModuleProtocol::Subc,
18264            overlap: Default::default(),
18265        };
18266        let digest = crate::supervise::LaunchSpecDigest::from_spec(&configured);
18267        assert_eq!(
18268            launch_spec_agreement(&configured, false, Some(&digest)),
18269            Agreement::Unavailable {
18270                reason: Reason::NotRunning
18271            }
18272        );
18273        assert_eq!(
18274            launch_spec_agreement(&configured, true, None),
18275            Agreement::Unavailable {
18276                reason: Reason::SpawnedSpecUnavailable
18277            }
18278        );
18279        assert_eq!(
18280            launch_spec_agreement(&configured, true, Some(&digest)),
18281            Agreement::Match
18282        );
18283    }
18284
18285    #[cfg(windows)]
18286    #[test]
18287    fn windows_reload_path_matches_configured_and_verbatim_spawn_spellings() {
18288        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-spelling");
18289        let configured = dir.join("module.exe");
18290        std::fs::write(&configured, b"executable path fixture").unwrap();
18291        let spawned = std::fs::canonicalize(&configured).unwrap();
18292        assert_ne!(
18293            configured, spawned,
18294            "fixture must exercise different path spellings"
18295        );
18296        let forward_slashes = configured.to_string_lossy().replace('\\', "/");
18297        let lower_case = configured.to_string_lossy().to_lowercase();
18298        for spelling in [
18299            &configured,
18300            Path::new(&forward_slashes),
18301            Path::new(&lower_case),
18302        ] {
18303            let verdict = reload_verdict(
18304                spelling,
18305                Some(&spawned),
18306                subc_control::RunningImageAgreement::Unavailable {
18307                    reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18308                },
18309            );
18310            assert_eq!(
18311                verdict.path,
18312                ReloadPathAgreement::Match,
18313                "configured {spelling:?}, spawned {spawned:?}"
18314            );
18315        }
18316    }
18317
18318    #[cfg(windows)]
18319    #[test]
18320    fn windows_reload_path_keeps_different_existing_program_pending() {
18321        let dir = cortexkit_test_support::ScratchDir::new("windows-reload-path-change");
18322        let old = dir.join("old.exe");
18323        let new = dir.join("new.exe");
18324        std::fs::write(&old, b"same executable content").unwrap();
18325        std::fs::copy(&old, &new).unwrap();
18326        let spawned = std::fs::canonicalize(&old).unwrap();
18327        let image = subc_control::RunningImageAgreement::Unavailable {
18328            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18329        };
18330        let verdict = reload_verdict(&new, Some(&spawned), image.clone());
18331        assert!(
18332            matches!(verdict.path, ReloadPathAgreement::Mismatch { configured, spawned_from }
18333            if configured == new && spawned_from == spawned)
18334        );
18335        let missing = dir.join("missing.exe");
18336        assert!(matches!(
18337            reload_verdict(&missing, Some(&spawned), image).path,
18338            ReloadPathAgreement::Mismatch { .. }
18339        ));
18340    }
18341
18342    #[test]
18343    fn reload_verdict_detects_replaced_image_at_same_path() {
18344        let image = subc_control::RunningImageAgreement::Mismatch {
18345            running: subc_control::RunningImageEvidence::LinuxProcSha256 {
18346                digest: "old".into(),
18347            },
18348            disk: subc_control::RunningImageEvidence::LinuxProcSha256 {
18349                digest: "new".into(),
18350            },
18351        };
18352        let verdict = reload_verdict(
18353            std::path::Path::new("/bin/same"),
18354            Some(std::path::Path::new("/bin/same")),
18355            image.clone(),
18356        );
18357        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18358        assert_eq!(verdict.image, image);
18359    }
18360
18361    #[test]
18362    fn reload_verdict_preserves_stopped_and_unavailable_reasons() {
18363        let image = subc_control::RunningImageAgreement::Unavailable {
18364            reason: subc_control::RunningImageUnavailableReason::NotRunning,
18365        };
18366        let verdict = reload_verdict(std::path::Path::new("/bin/same"), None, image.clone());
18367        assert_eq!(
18368            verdict.path,
18369            subc_control::ReloadPathAgreement::Unavailable {
18370                reason: subc_control::ReloadPathUnavailableReason::NotRunning,
18371            }
18372        );
18373        assert_eq!(verdict.image, image);
18374
18375        let unconfirmed = subc_control::RunningImageAgreement::Unavailable {
18376            reason: subc_control::RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
18377        };
18378        let verdict = reload_verdict(
18379            std::path::Path::new("/bin/same"),
18380            Some(std::path::Path::new("/bin/same")),
18381            unconfirmed.clone(),
18382        );
18383        assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18384        assert_eq!(verdict.image, unconfirmed);
18385    }
18386
18387    #[test]
18388    fn reload_verdict_preserves_each_image_unavailability_reason() {
18389        use subc_control::RunningImageUnavailableReason as Reason;
18390
18391        for reason in [
18392            Reason::NotRunning,
18393            Reason::UnsupportedPlatform,
18394            Reason::RunningExecutableUnreadable,
18395            Reason::SpawnedPathUnreadable,
18396            Reason::HashFailed,
18397            Reason::ProcessIdentityUnconfirmed,
18398            Reason::Unknown("future_probe_reason".to_string()),
18399        ] {
18400            let image = subc_control::RunningImageAgreement::Unavailable {
18401                reason: reason.clone(),
18402            };
18403            let verdict = reload_verdict(
18404                std::path::Path::new("/bin/same"),
18405                Some(std::path::Path::new("/bin/same")),
18406                image.clone(),
18407            );
18408            assert_eq!(verdict.path, subc_control::ReloadPathAgreement::Match);
18409            assert_eq!(verdict.image, image, "{reason:?}");
18410        }
18411    }
18412
18413    #[tokio::test]
18414    async fn malformed_control_bodies_return_invalid_control_body() {
18415        let handler = ControlHandler::default();
18416        let (ctx, _rx) = route_ctx(ConnectionId::new(78));
18417
18418        for (corr, body) in [
18419            (56, br#"{"route_channel":1}"#.as_slice()),
18420            (57, br#"{"op":17,"route_channel":1}"#.as_slice()),
18421            (
18422                58,
18423                br#"{"op":"route.poll","route_channel":"bad","kind":"status"}"#.as_slice(),
18424            ),
18425        ] {
18426            let request = Frame::build(
18427                FrameType::Request,
18428                control_flags(),
18429                0,
18430                0,
18431                corr,
18432                body.to_vec(),
18433            )
18434            .unwrap();
18435            let response = handler.handle_control_frame(&ctx, request).await.unwrap();
18436
18437            assert_eq!(response.len(), 1);
18438            assert_eq!(response[0].header.ty, FrameType::Error);
18439            assert_eq!(response[0].header.corr, corr);
18440            assert_eq!(parse_error(&response[0])["code"], "invalid_control_body");
18441        }
18442    }
18443
18444    #[tokio::test]
18445    async fn goodbye_tears_down_registration_and_later_channel_is_unknown() {
18446        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18447        let registry = Arc::new(Registry::default());
18448        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18449        let router = Router::with_control_handler(Arc::clone(&control));
18450        let connection = router.begin_connection();
18451        let (ctx, mut rx) = route_ctx(connection.id());
18452
18453        router
18454            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 11))
18455            .await
18456            .unwrap();
18457        let response = rx.recv().await.unwrap();
18458        let ack = parse_ack(&response);
18459        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18460        let channel = 1;
18461
18462        let goodbye =
18463            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 12, Vec::new()).unwrap();
18464        router.route_for_connection(&ctx, goodbye).await.unwrap();
18465        assert!(rx.try_recv().is_err());
18466        assert!(registry.get_module("aft").unwrap().is_none());
18467
18468        router
18469            .route_for_connection(&ctx, channel_request(channel, 13))
18470            .await
18471            .unwrap();
18472        let error_frame = rx.recv().await.unwrap();
18473        assert_eq!(error_frame.header.ty, FrameType::Error);
18474        assert_eq!(error_frame.header.channel, channel);
18475        let captured = crate::router::test_log::captured_logs(&logs);
18476        assert_eq!(
18477            captured
18478                .lines()
18479                .filter(|line| {
18480                    line.contains("module_id=aft")
18481                        && line.contains("reason=explicit_goodbye")
18482                        && line.contains("module registration ended")
18483                })
18484                .count(),
18485            1,
18486            "unexpected GOODBYE registry log: {captured}"
18487        );
18488    }
18489
18490    #[tokio::test]
18491    async fn module_goodbye_refreshes_requirements_and_pushes_route_closed() {
18492        let registry = Arc::new(Registry::default());
18493        let handler = ControlHandler::new(registry).with_capability_config(
18494            [("prov".to_string(), true), ("cons".to_string(), true)],
18495            BTreeMap::new(),
18496        );
18497        let (provider_ctx, mut provider_rx) = route_ctx(ConnectionId::new(701));
18498        register_capability_manifest(
18499            &handler,
18500            &provider_ctx,
18501            &mut provider_rx,
18502            capability_manifest("prov", &["thing/v1"], &[]),
18503            1,
18504        )
18505        .await;
18506        let mut consumer = capability_manifest("cons", &[], &[]);
18507        consumer.capabilities.as_mut().unwrap().requires.push(
18508            subc_protocol::manifest::CapabilityRequirement {
18509                capability: "thing/v1".to_string(),
18510                need: subc_protocol::manifest::CapabilityNeed::Required,
18511            },
18512        );
18513        let (consumer_ctx, mut consumer_rx) = route_ctx(ConnectionId::new(702));
18514        register_capability_manifest(&handler, &consumer_ctx, &mut consumer_rx, consumer, 2).await;
18515        assert_eq!(
18516            handler.capability_evaluator.verdict("cons", "thing/v1"),
18517            Some(CapabilityVerdict::Provided)
18518        );
18519        let (mut client_rx, _) = open_route_for_capability_test(
18520            &handler,
18521            &provider_ctx,
18522            &mut provider_rx,
18523            703,
18524            3,
18525            "prov",
18526            None,
18527        )
18528        .await;
18529        let goodbye =
18530            Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap();
18531        handler
18532            .handle_control_frame(&provider_ctx, goodbye)
18533            .await
18534            .unwrap();
18535        assert_eq!(
18536            handler.capability_evaluator.verdict("cons", "thing/v1"),
18537            Some(CapabilityVerdict::NeverProvided)
18538        );
18539        let closed = client_rx
18540            .try_recv()
18541            .expect("GOODBYE pushes route.closed before route GOODBYE");
18542        assert!(
18543            matches!(serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap(),
18544            ClientControlPush::RouteClosed { module_id, channels, .. } if module_id == "prov" && channels.len() == 1)
18545        );
18546        assert_eq!(client_rx.try_recv().unwrap().header.ty, FrameType::Goodbye);
18547        assert_eq!(handler.forwarding.active_binding_count().unwrap(), 0);
18548    }
18549
18550    struct RouteClosedFixture {
18551        handler: ControlHandler,
18552        #[cfg(unix)]
18553        supervisor: Supervisor,
18554        module_ctx: RouteCtx,
18555        #[cfg(unix)]
18556        module_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18557        client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
18558        route: Arc<crate::forwarding::RouteBinding>,
18559    }
18560
18561    async fn route_closed_fixture() -> RouteClosedFixture {
18562        let registry = Arc::new(Registry::default());
18563        let handler = ControlHandler::new(Arc::clone(&registry));
18564        #[cfg(unix)]
18565        let supervisor = Supervisor::new(registry, RestartPolicy::default())
18566            .with_forwarding(Arc::clone(&handler.forwarding));
18567        let (module_ctx, mut module_rx) = route_ctx(ConnectionId::new(701));
18568        register_capability_manifest(
18569            &handler,
18570            &module_ctx,
18571            &mut module_rx,
18572            capability_manifest("prov", &[], &[]),
18573            1,
18574        )
18575        .await;
18576        let (client_rx, bind) = open_route_for_capability_test(
18577            &handler,
18578            &module_ctx,
18579            &mut module_rx,
18580            702,
18581            2,
18582            "prov",
18583            None,
18584        )
18585        .await;
18586        let ModuleControlRequest::RouteBind {
18587            route_channel: channel,
18588            epoch: route_epoch,
18589            ..
18590        } = bind
18591        else {
18592            panic!("expected route.bind");
18593        };
18594        let crate::forwarding::DataRoute::Module(crate::forwarding::DataRouteState::Bound(route)) =
18595            handler
18596                .forwarding
18597                .lookup_data_route(module_ctx.connection_id, channel, route_epoch)
18598                .unwrap()
18599        else {
18600            panic!("the acknowledged route must be bound");
18601        };
18602        RouteClosedFixture {
18603            handler,
18604            #[cfg(unix)]
18605            supervisor,
18606            module_ctx,
18607            #[cfg(unix)]
18608            module_rx,
18609            client_rx,
18610            route,
18611        }
18612    }
18613
18614    impl RouteClosedFixture {
18615        #[cfg(unix)]
18616        async fn cut(&mut self) {
18617            let notices = async {
18618                let mut draining = self.module_rx.recv().await.unwrap();
18619                assert!(matches!(
18620                    serde_json::from_slice::<subc_protocol::session::ModuleControlCommand>(
18621                        &draining.body
18622                    )
18623                    .unwrap(),
18624                    subc_protocol::session::ModuleControlCommand::Draining {
18625                        reason: RouteCloseReason::Disable,
18626                        ..
18627                    }
18628                ));
18629                draining.flushed.take().unwrap().send(()).unwrap();
18630                let mut closing = self.client_rx.recv().await.unwrap();
18631                assert!(matches!(
18632                    serde_json::from_slice::<ClientControlPush>(&closing.body).unwrap(),
18633                    ClientControlPush::RouteClosing {
18634                        reason: RouteCloseReason::Restart,
18635                        ..
18636                    }
18637                ));
18638                closing.flushed.take().unwrap().send(()).unwrap();
18639            };
18640            let (result, ()) = tokio::join!(self.supervisor.drain_for_daemon_shutdown(), notices);
18641            result.unwrap();
18642        }
18643
18644        fn disconnect(&mut self) -> ClientControlPush {
18645            self.handler
18646                .cleanup_connection(self.module_ctx.connection_id)
18647                .unwrap();
18648            let closed = self.client_rx.try_recv().unwrap();
18649            assert_eq!(closed.header.ty, FrameType::Push);
18650            let push = serde_json::from_slice::<ClientControlPush>(&closed.body).unwrap();
18651            assert!(matches!(
18652                &push,
18653                ClientControlPush::RouteClosed { channels, abandoned: 0, .. }
18654                    if channels == &[self.route.client_channel]
18655            ));
18656            assert_eq!(
18657                self.client_rx.try_recv().unwrap().header.ty,
18658                FrameType::Goodbye
18659            );
18660            assert_eq!(self.handler.forwarding.active_binding_count().unwrap(), 0);
18661            push
18662        }
18663    }
18664
18665    #[cfg(unix)]
18666    #[tokio::test(start_paused = true)]
18667    async fn daemon_cut_quiet_routes_report_restart_and_drained() {
18668        let mut fixture = route_closed_fixture().await;
18669        fixture.cut().await;
18670        assert!(matches!(
18671            fixture.disconnect(),
18672            ClientControlPush::RouteClosed {
18673                reason: RouteCloseReason::Restart,
18674                drained: true,
18675                ..
18676            }
18677        ));
18678    }
18679
18680    #[cfg(unix)]
18681    #[tokio::test(start_paused = true)]
18682    async fn daemon_cut_in_flight_past_budget_reports_restart_and_not_drained() {
18683        let mut fixture = route_closed_fixture().await;
18684        fixture.route.flow.acquire_tagged(99, false).await.unwrap();
18685        let started = tokio::time::Instant::now();
18686        fixture.cut().await;
18687        assert!(started.elapsed() >= Duration::from_secs(2));
18688        assert_eq!(fixture.route.flow.in_flight(), 1);
18689        assert!(matches!(
18690            fixture.disconnect(),
18691            ClientControlPush::RouteClosed {
18692                reason: RouteCloseReason::Restart,
18693                drained: false,
18694                ..
18695            }
18696        ));
18697    }
18698
18699    #[tokio::test]
18700    async fn module_connection_crash_reports_crash_and_not_drained() {
18701        let mut fixture = route_closed_fixture().await;
18702        // The server calls cleanup_connection on module EOF. Without a planned
18703        // daemon shutdown, that disconnect must remain a crash with no prior
18704        // route.closing notice, even when the route has no in-flight calls.
18705        assert!(matches!(
18706            fixture.disconnect(),
18707            ClientControlPush::RouteClosed {
18708                reason: RouteCloseReason::Crash,
18709                drained: false,
18710                ..
18711            }
18712        ));
18713    }
18714
18715    #[tokio::test]
18716    async fn dropping_router_connection_releases_registration() {
18717        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18718        let registry = Arc::new(Registry::default());
18719        let control = Arc::new(ControlHandler::new(Arc::clone(&registry)));
18720        let router = Router::with_control_handler(Arc::clone(&control));
18721        let connection = router.begin_connection();
18722        let connection_id = connection.id();
18723        let (ctx, mut rx) = route_ctx(connection_id);
18724
18725        router
18726            .route_for_connection(&ctx, hello_frame("aft", PROTOCOL_VERSION, 31))
18727            .await
18728            .unwrap();
18729        let response = rx.recv().await.unwrap();
18730        let ack = parse_ack(&response);
18731        assert_eq!(ack.negotiated_ver, PROTOCOL_VERSION);
18732        assert!(registry.get_module("aft").unwrap().is_some());
18733
18734        drop(connection);
18735
18736        assert!(registry.get_module("aft").unwrap().is_none());
18737        assert_eq!(registry.active_registration_count().unwrap(), 0);
18738
18739        control
18740            .cleanup_connection(ConnectionId::new(u64::MAX))
18741            .unwrap();
18742        let captured = crate::router::test_log::captured_logs(&logs);
18743        println!("captured registry lifecycle logs:\n{captured}");
18744        let events: Vec<_> = captured
18745            .lines()
18746            .filter(|line| {
18747                line.contains("module registered module_id=aft ")
18748                    || line.contains("module registration ended")
18749            })
18750            .collect();
18751        assert_eq!(
18752            events.len(),
18753            2,
18754            "unexpected registry lifecycle logs: {captured}"
18755        );
18756        assert!(events[0].contains("module registered module_id=aft "));
18757        assert!(events[0].contains(&format!("connection_id={}", connection_id.get())));
18758        assert!(events[1].contains(&format!(
18759            "module_id=aft connection_id={}",
18760            connection_id.get()
18761        )));
18762        assert!(events[1].contains("reason=connection_closed"));
18763        assert!(events[1].contains("module registration ended"));
18764        assert_eq!(
18765            captured
18766                .lines()
18767                .filter(|line| line.contains("module registered module_id=aft "))
18768                .count(),
18769            1,
18770            "legacy registration admission line must appear once: {captured}"
18771        );
18772    }
18773
18774    #[tokio::test]
18775    async fn hello_registration_keeps_legacy_module_registered_line_once() {
18776        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
18777        let registry = Arc::new(Registry::default());
18778        let control = ControlHandler::new(Arc::clone(&registry));
18779        let (ctx, mut rx) = route_ctx(ConnectionId::new(777));
18780        hello_via_sink(
18781            &control,
18782            &ctx,
18783            &mut rx,
18784            hello_frame("prefrontal-host:test", PROTOCOL_VERSION, 1),
18785        )
18786        .await;
18787
18788        let captured = crate::router::test_log::captured_logs(&logs);
18789        let admissions: Vec<_> = captured
18790            .lines()
18791            .filter(|line| line.contains("module registered module_id=prefrontal-host:test "))
18792            .collect();
18793        assert_eq!(
18794            admissions.len(),
18795            1,
18796            "legacy admission line must remain exactly once: {captured}"
18797        );
18798        assert!(admissions[0].contains("routable_provider=true"));
18799        assert!(admissions[0].contains("connection_id=777"));
18800    }
18801
18802    fn capability_manifest(
18803        module_id: &str,
18804        provides: &[&str],
18805        must_never_reach: &[&str],
18806    ) -> ModuleManifest {
18807        let mut manifest = manifest(module_id, PROTOCOL_VERSION);
18808        manifest.capabilities = Some(CapabilityDeclarations {
18809            provides: provides
18810                .iter()
18811                .map(|capability| (*capability).to_string())
18812                .collect(),
18813            requires: Vec::new(),
18814            must_never_reach: must_never_reach
18815                .iter()
18816                .map(|capability| (*capability).to_string())
18817                .collect(),
18818        });
18819        manifest
18820    }
18821
18822    fn hello_frame_with_manifest(manifest: ModuleManifest, corr: u64) -> Frame {
18823        Frame::build(
18824            FrameType::Hello,
18825            control_flags(),
18826            0,
18827            0,
18828            corr,
18829            serde_json::to_vec(&ModuleHelloBody {
18830                protocol_ver: manifest.protocol_ver,
18831                manifest,
18832                control_ops: None,
18833                launch_nonce: None,
18834            })
18835            .expect("capability test HELLO serializes"),
18836        )
18837        .expect("capability test HELLO frame builds")
18838    }
18839
18840    fn catalog_update_with_capabilities_frame(
18841        corr: u64,
18842        capabilities: CapabilityDeclarations,
18843    ) -> Frame {
18844        Frame::build(
18845            FrameType::Request,
18846            control_flags(),
18847            0,
18848            0,
18849            corr,
18850            serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
18851                provides: manifest("catalog-update-placeholder", PROTOCOL_VERSION).provides,
18852                capabilities: Some(capabilities),
18853                ready: None,
18854            })
18855            .expect("capability catalog.update serializes"),
18856        )
18857        .expect("capability catalog.update frame builds")
18858    }
18859
18860    async fn register_capability_manifest(
18861        handler: &ControlHandler,
18862        ctx: &RouteCtx,
18863        rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
18864        manifest: ModuleManifest,
18865        corr: u64,
18866    ) {
18867        hello_via_sink(handler, ctx, rx, hello_frame_with_manifest(manifest, corr)).await;
18868    }
18869
18870    async fn open_route_for_capability_test(
18871        handler: &ControlHandler,
18872        target_ctx: &RouteCtx,
18873        target_rx: &mut mpsc::Receiver<crate::router::OutboundFrame>,
18874        client_connection_id: u64,
18875        corr: u64,
18876        target_module_id: &str,
18877        consumer_identity: Option<ConsumerIdentity>,
18878    ) -> (
18879        mpsc::Receiver<crate::router::OutboundFrame>,
18880        ModuleControlRequest,
18881    ) {
18882        let (client_ctx, mut client_rx) = route_ctx(ConnectionId::new(client_connection_id));
18883        let route_handler = handler.clone();
18884        let target_module_id = target_module_id.to_string();
18885        let route_task = tokio::spawn(async move {
18886            route_handler
18887                .handle_control_frame(
18888                    &client_ctx,
18889                    route_open_frame_with_admission_facts(
18890                        corr,
18891                        &target_module_id,
18892                        unique_project_root("admission-facts"),
18893                        consumer_identity,
18894                        None,
18895                    ),
18896                )
18897                .await
18898                .expect("capability test route.open succeeds")
18899        });
18900        let bind = tokio::time::timeout(Duration::from_secs(1), target_rx.recv())
18901            .await
18902            .expect("capability test route.open must reach route.bind")
18903            .expect("target control receiver stays open");
18904        let bind_request: ModuleControlRequest =
18905            serde_json::from_slice(&bind.body).expect("route.bind decodes");
18906        handler
18907            .handle_control_frame(target_ctx, route_bind_ack(bind.header.corr))
18908            .await
18909            .expect("capability test route.bind ACK succeeds");
18910        assert!(route_task.await.expect("route.open task joins").is_empty());
18911        let opened = client_rx
18912            .recv()
18913            .await
18914            .expect("successful route.open publishes a response");
18915        assert!(matches!(
18916            serde_json::from_slice::<ClientControlResponse>(&opened.body),
18917            Ok(ClientControlResponse::RouteOpen { .. })
18918        ));
18919        (client_rx, bind_request)
18920    }
18921
18922    fn assert_capability_denied_push(frame: Frame, target_module_id: &str) -> u16 {
18923        assert_eq!(frame.header.ty, FrameType::Push);
18924        assert_eq!(frame.header.channel, 0);
18925        let push = serde_json::from_slice::<ClientControlPush>(&frame.body)
18926            .expect("route.closed control push decodes");
18927        let ClientControlPush::RouteClosed { channels, .. } = &push else {
18928            panic!("expected route.closed");
18929        };
18930        assert_eq!(channels.len(), 1, "exactly one violating route closed");
18931        let closed_channel = channels[0];
18932        let channels = channels.clone();
18933        assert_eq!(
18934            push,
18935            ClientControlPush::RouteClosed {
18936                module_id: target_module_id.to_string(),
18937                channels,
18938                reason: RouteCloseReason::CapabilityDenied,
18939                drained: false,
18940                abandoned: 0,
18941                excluded_subscriptions: 0,
18942                terminal: Some(false),
18943            }
18944        );
18945        closed_channel
18946    }
18947
18948    #[tokio::test]
18949    async fn route_open_capability_forbidden_mutation_proof_creates_no_route() {
18950        let registry = Arc::new(Registry::default());
18951        let forwarding = Arc::new(ForwardingTable::default());
18952        let supervisor = SupervisorHandle::new();
18953        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
18954        let handler =
18955            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
18956                .with_supervisor(supervisor);
18957        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(700));
18958        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(701));
18959        register_capability_manifest(
18960            &handler,
18961            &target_ctx,
18962            &mut target_rx,
18963            capability_manifest("target", &["credentials-provider/v1"], &[]),
18964            1,
18965        )
18966        .await;
18967        register_capability_manifest(
18968            &handler,
18969            &opener_ctx,
18970            &mut opener_rx,
18971            capability_manifest("opener", &[], &["credentials-provider/v1"]),
18972            2,
18973        )
18974        .await;
18975
18976        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(702));
18977        let replies = handler
18978            .handle_control_frame(
18979                &client_ctx,
18980                route_open_frame_with_admission_facts(
18981                    3,
18982                    "target",
18983                    unique_project_root("admission-facts"),
18984                    Some(ConsumerIdentity {
18985                        module_id: "opener".to_string(),
18986                        launch_nonce: "opener-nonce".to_string(),
18987                    }),
18988                    None,
18989                ),
18990            )
18991            .await
18992            .expect("denied route.open returns a typed frame");
18993        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
18994        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
18995        assert!(
18996            target_rx.try_recv().is_err(),
18997            "forbidden route.open must not relay route.bind"
18998        );
18999    }
19000
19001    #[tokio::test]
19002    async fn capability_deny_edge_hello_mutation_proof_force_closes_existing_route() {
19003        let registry = Arc::new(Registry::default());
19004        let forwarding = Arc::new(ForwardingTable::default());
19005        let supervisor = SupervisorHandle::new();
19006        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19007        let handler =
19008            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19009                .with_supervisor(supervisor);
19010        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(710));
19011        let (old_opener_ctx, mut old_opener_rx) = route_ctx(ConnectionId::new(711));
19012        register_capability_manifest(
19013            &handler,
19014            &target_ctx,
19015            &mut target_rx,
19016            capability_manifest("target", &["credentials-provider/v1"], &[]),
19017            1,
19018        )
19019        .await;
19020        register_capability_manifest(
19021            &handler,
19022            &old_opener_ctx,
19023            &mut old_opener_rx,
19024            capability_manifest("opener", &[], &[]),
19025            2,
19026        )
19027        .await;
19028        let (mut client_rx, _) = open_route_for_capability_test(
19029            &handler,
19030            &target_ctx,
19031            &mut target_rx,
19032            712,
19033            3,
19034            "target",
19035            Some(ConsumerIdentity {
19036                module_id: "opener".to_string(),
19037                launch_nonce: "opener-nonce".to_string(),
19038            }),
19039        )
19040        .await;
19041        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19042
19043        handler
19044            .cleanup_connection(old_opener_ctx.connection_id)
19045            .expect("old opener registration cleans up");
19046        let (new_opener_ctx, mut new_opener_rx) = route_ctx(ConnectionId::new(713));
19047        register_capability_manifest(
19048            &handler,
19049            &new_opener_ctx,
19050            &mut new_opener_rx,
19051            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19052            4,
19053        )
19054        .await;
19055
19056        let closed_channel = assert_capability_denied_push(
19057            client_rx
19058                .try_recv()
19059                .expect("HELLO deny addition must emit route.closed")
19060                .frame,
19061            "target",
19062        );
19063        let goodbye = client_rx
19064            .try_recv()
19065            .expect("HELLO deny addition must send the client a route GOODBYE")
19066            .frame;
19067        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19068        assert_eq!(goodbye.header.channel, closed_channel);
19069        assert_ne!(goodbye.header.channel, 0);
19070        assert_ne!(goodbye.header.epoch, 0);
19071        assert!(client_rx.try_recv().is_err());
19072        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19073        assert!(matches!(
19074            target_rx.try_recv(),
19075            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19076        ));
19077    }
19078
19079    #[tokio::test]
19080    async fn capability_claim_catalog_update_mutation_proof_force_closes_existing_route() {
19081        let registry = Arc::new(Registry::default());
19082        let forwarding = Arc::new(ForwardingTable::default());
19083        let supervisor = SupervisorHandle::new();
19084        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19085        let handler =
19086            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19087                .with_supervisor(supervisor);
19088        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(720));
19089        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(721));
19090        register_capability_manifest(
19091            &handler,
19092            &target_ctx,
19093            &mut target_rx,
19094            capability_manifest("target", &[], &[]),
19095            1,
19096        )
19097        .await;
19098        register_capability_manifest(
19099            &handler,
19100            &opener_ctx,
19101            &mut opener_rx,
19102            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19103            2,
19104        )
19105        .await;
19106        let (mut client_rx, _) = open_route_for_capability_test(
19107            &handler,
19108            &target_ctx,
19109            &mut target_rx,
19110            722,
19111            3,
19112            "target",
19113            Some(ConsumerIdentity {
19114                module_id: "opener".to_string(),
19115                launch_nonce: "opener-nonce".to_string(),
19116            }),
19117        )
19118        .await;
19119        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19120
19121        let replies = handler
19122            .handle_control_frame(
19123                &target_ctx,
19124                catalog_update_with_capabilities_frame(
19125                    4,
19126                    CapabilityDeclarations {
19127                        provides: vec!["credentials-provider/v1".to_string()],
19128                        requires: Vec::new(),
19129                        must_never_reach: Vec::new(),
19130                    },
19131                ),
19132            )
19133            .await
19134            .expect("claim catalog.update succeeds");
19135        assert!(matches!(
19136            serde_json::from_slice::<ModuleControlResponseToModule>(&replies[0].body),
19137            Ok(ModuleControlResponseToModule::CatalogUpdate {})
19138        ));
19139        let closed_channel = assert_capability_denied_push(
19140            client_rx
19141                .try_recv()
19142                .expect("claim addition must emit route.closed")
19143                .frame,
19144            "target",
19145        );
19146        let goodbye = client_rx
19147            .try_recv()
19148            .expect("claim addition must send the client a route GOODBYE")
19149            .frame;
19150        assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19151        assert_eq!(goodbye.header.channel, closed_channel);
19152        assert_ne!(goodbye.header.channel, 0);
19153        assert_ne!(goodbye.header.epoch, 0);
19154        assert!(client_rx.try_recv().is_err());
19155        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19156        assert!(matches!(
19157            target_rx.try_recv(),
19158            Ok(outbound) if outbound.header.ty == FrameType::Goodbye
19159        ));
19160    }
19161
19162    #[tokio::test]
19163    async fn capability_claim_removal_mutation_proof_keeps_route_open_without_close_frame() {
19164        let registry = Arc::new(Registry::default());
19165        let forwarding = Arc::new(ForwardingTable::default());
19166        let supervisor = SupervisorHandle::new();
19167        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19168        let handler =
19169            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19170                .with_supervisor(supervisor);
19171        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(730));
19172        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(731));
19173        register_capability_manifest(
19174            &handler,
19175            &target_ctx,
19176            &mut target_rx,
19177            capability_manifest("target", &["credentials-provider/v1"], &[]),
19178            1,
19179        )
19180        .await;
19181        register_capability_manifest(
19182            &handler,
19183            &opener_ctx,
19184            &mut opener_rx,
19185            capability_manifest("opener", &[], &[]),
19186            2,
19187        )
19188        .await;
19189        let (mut client_rx, _) = open_route_for_capability_test(
19190            &handler,
19191            &target_ctx,
19192            &mut target_rx,
19193            732,
19194            3,
19195            "target",
19196            Some(ConsumerIdentity {
19197                module_id: "opener".to_string(),
19198                launch_nonce: "opener-nonce".to_string(),
19199            }),
19200        )
19201        .await;
19202        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19203
19204        handler
19205            .handle_control_frame(
19206                &target_ctx,
19207                catalog_update_with_capabilities_frame(
19208                    4,
19209                    CapabilityDeclarations {
19210                        provides: Vec::new(),
19211                        requires: Vec::new(),
19212                        must_never_reach: Vec::new(),
19213                    },
19214                ),
19215            )
19216            .await
19217            .expect("claim removal catalog.update succeeds");
19218        assert_eq!(
19219            forwarding.active_binding_count().unwrap(),
19220            1,
19221            "removing an attested target claim must leave the route census unchanged"
19222        );
19223        assert!(
19224            client_rx.try_recv().is_err(),
19225            "claim removal must not emit route.closed or a client route GOODBYE"
19226        );
19227        assert!(
19228            target_rx.try_recv().is_err(),
19229            "claim removal must not send the target a route GOODBYE"
19230        );
19231    }
19232
19233    /// A direct client may open a route to a denied capability provider; this
19234    /// policy applies only to attested supervised module origins, not to direct clients.
19235    #[tokio::test]
19236    async fn direct_client_scope_honesty_mutation_proof_opens_denied_capability_provider() {
19237        let registry = Arc::new(Registry::default());
19238        let forwarding = Arc::new(ForwardingTable::default());
19239        let supervisor = SupervisorHandle::new();
19240        supervisor.set_spawn_nonce("opener", "opener-nonce".to_string());
19241        let handler =
19242            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19243                .with_supervisor(supervisor);
19244        let (target_ctx, mut target_rx) = route_ctx(ConnectionId::new(740));
19245        let (opener_ctx, mut opener_rx) = route_ctx(ConnectionId::new(741));
19246        register_capability_manifest(
19247            &handler,
19248            &target_ctx,
19249            &mut target_rx,
19250            capability_manifest("target", &["credentials-provider/v1"], &[]),
19251            1,
19252        )
19253        .await;
19254        register_capability_manifest(
19255            &handler,
19256            &opener_ctx,
19257            &mut opener_rx,
19258            capability_manifest("opener", &[], &["credentials-provider/v1"]),
19259            2,
19260        )
19261        .await;
19262
19263        let (_client_rx, bind) = open_route_for_capability_test(
19264            &handler,
19265            &target_ctx,
19266            &mut target_rx,
19267            742,
19268            3,
19269            "target",
19270            None,
19271        )
19272        .await;
19273        let ModuleControlRequest::RouteBind { principal, .. } = bind else {
19274            panic!("direct scope-honesty route must bind");
19275        };
19276        assert_eq!(principal, Some(Principal::Direct));
19277        assert_eq!(forwarding.active_binding_count().unwrap(), 1);
19278    }
19279
19280    /// A module that denies a capability receives no self-route exemption when it
19281    /// also attestedly provides that capability.
19282    #[tokio::test]
19283    async fn must_never_reach_self_route_is_capability_forbidden() {
19284        let registry = Arc::new(Registry::default());
19285        let forwarding = Arc::new(ForwardingTable::default());
19286        let supervisor = SupervisorHandle::new();
19287        supervisor.set_spawn_nonce("self-provider", "self-nonce".to_string());
19288        let handler =
19289            ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
19290                .with_supervisor(supervisor);
19291        let (self_ctx, mut self_rx) = route_ctx(ConnectionId::new(750));
19292        register_capability_manifest(
19293            &handler,
19294            &self_ctx,
19295            &mut self_rx,
19296            capability_manifest(
19297                "self-provider",
19298                &["credentials-provider/v1"],
19299                &["credentials-provider/v1"],
19300            ),
19301            1,
19302        )
19303        .await;
19304
19305        let (client_ctx, _client_rx) = route_ctx(ConnectionId::new(751));
19306        let replies = handler
19307            .handle_control_frame(
19308                &client_ctx,
19309                route_open_frame_with_admission_facts(
19310                    2,
19311                    "self-provider",
19312                    unique_project_root("admission-facts"),
19313                    Some(ConsumerIdentity {
19314                        module_id: "self-provider".to_string(),
19315                        launch_nonce: "self-nonce".to_string(),
19316                    }),
19317                    None,
19318                ),
19319            )
19320            .await
19321            .expect("self-route refusal returns a typed frame");
19322        assert_eq!(parse_error(&replies[0])["code"], "capability_forbidden");
19323        assert_eq!(forwarding.active_binding_count().unwrap(), 0);
19324        assert!(
19325            self_rx.try_recv().is_err(),
19326            "self denial must not relay route.bind"
19327        );
19328    }
19329
19330    #[test]
19331    fn unsupported_channel_zero_frame_returns_error() {
19332        let handler = ControlHandler::default();
19333        let request = Frame::build(
19334            FrameType::Request,
19335            control_flags(),
19336            0,
19337            0,
19338            21,
19339            b"opaque".to_vec(),
19340        )
19341        .unwrap();
19342
19343        let response = handler
19344            .handle_control(ConnectionId::new(1), request)
19345            .unwrap();
19346
19347        assert_eq!(response[0].header.ty, FrameType::Error);
19348        assert_eq!(
19349            parse_error(&response[0])["code"],
19350            "unsupported_control_frame"
19351        );
19352    }
19353
19354    /// Blue/green swap at the control-plane boundary. The supervisor that opens
19355    /// a swap is not wired yet, so the candidate is registered here directly
19356    /// into the registry and forwarding candidate slots, the way the swap's
19357    /// HELLO admission will.
19358    mod swap {
19359        use super::*;
19360
19361        const INCUMBENT: ConnectionId = ConnectionId::new(30);
19362        const CANDIDATE: ConnectionId = ConnectionId::new(40);
19363
19364        struct Swap {
19365            registry: Arc<Registry>,
19366            forwarding: Arc<ForwardingTable>,
19367            handler: ControlHandler,
19368            incumbent_ctx: RouteCtx,
19369            incumbent_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19370            candidate_ctx: RouteCtx,
19371            candidate_rx: mpsc::Receiver<crate::router::OutboundFrame>,
19372        }
19373
19374        async fn swap_with_incumbent() -> Swap {
19375            let registry = Arc::new(Registry::default());
19376            let forwarding = Arc::new(ForwardingTable::default());
19377            let handler =
19378                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding));
19379            let (incumbent_ctx, mut incumbent_rx) = route_ctx(INCUMBENT);
19380            hello_via_sink(
19381                &handler,
19382                &incumbent_ctx,
19383                &mut incumbent_rx,
19384                hello_frame("aft", PROTOCOL_VERSION, 7),
19385            )
19386            .await;
19387            let (candidate_ctx, candidate_rx) = route_ctx(CANDIDATE);
19388            Swap {
19389                registry,
19390                forwarding,
19391                handler,
19392                incumbent_ctx,
19393                incumbent_rx,
19394                candidate_ctx,
19395                candidate_rx,
19396            }
19397        }
19398
19399        fn register_candidate(swap: &Swap, ready: Option<bool>) {
19400            let mut candidate_manifest = manifest("aft", PROTOCOL_VERSION);
19401            candidate_manifest.ready = ready;
19402            let registration = swap
19403                .registry
19404                .register_candidate_with_control_ops(
19405                    candidate_manifest,
19406                    PROTOCOL_VERSION,
19407                    CANDIDATE,
19408                    module_baseline_control_ops(),
19409                )
19410                .unwrap();
19411            swap.forwarding
19412                .register_candidate_module_connection(
19413                    CANDIDATE,
19414                    "aft".to_string(),
19415                    PROTOCOL_VERSION,
19416                    manifest_concurrency(&registration.manifest),
19417                    swap.candidate_ctx.egress.clone(),
19418                )
19419                .unwrap();
19420        }
19421
19422        fn cutover(swap: &Swap) -> crate::forwarding::ModuleEndpointId {
19423            let cutover = swap.forwarding.cutover_candidate("aft").unwrap().unwrap();
19424            swap.registry.promote_candidate("aft").unwrap().unwrap();
19425            cutover.incumbent.unwrap()
19426        }
19427
19428        /// A swap candidate's HELLO reserves its candidate registry entry
19429        /// before installing its candidate forwarding endpoint. The swap
19430        /// supervisor promotes a ready candidate as soon as it reads it as
19431        /// registered, and promotion cuts forwarding over to the candidate
19432        /// endpoint, so the lookup the supervisor reads
19433        /// (`Registry::published_registration`) must not return the candidate
19434        /// until that endpoint exists. Otherwise the cutover finds no candidate
19435        /// endpoint and the swap fails as if the candidate had disconnected.
19436        #[tokio::test]
19437        async fn swap_candidate_is_published_only_after_its_forwarding_endpoint_exists() {
19438            let mut swap = swap_with_incumbent().await;
19439            let hold = Arc::new(std::sync::Barrier::new(2));
19440            let handler = swap
19441                .handler
19442                .clone()
19443                .with_hello_registry_to_forwarding_hold(Arc::clone(&hold));
19444            handler
19445                .supervisor
19446                .open_swap("aft", "candidate-nonce".to_string());
19447            let hello = {
19448                let handler = handler.clone();
19449                let candidate_ctx = swap.candidate_ctx.clone();
19450                std::thread::spawn(move || {
19451                    handler
19452                        .handle_hello(
19453                            candidate_ctx.connection_id,
19454                            Some(candidate_ctx.egress.clone()),
19455                            hello_frame_with_nonce(
19456                                "aft",
19457                                PROTOCOL_VERSION,
19458                                8,
19459                                Some("candidate-nonce"),
19460                            ),
19461                        )
19462                        .unwrap()
19463                })
19464            };
19465
19466            hold.wait();
19467            // Parked: the candidate slot is claimed but not published, and
19468            // forwarding has no candidate endpoint.
19469            assert!(swap
19470                .registry
19471                .registration(crate::registry::RegistrationSlot::Candidate("aft"))
19472                .unwrap()
19473                .is_some());
19474            assert!(swap
19475                .registry
19476                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19477                .unwrap()
19478                .is_none());
19479            assert!(swap
19480                .forwarding
19481                .module_endpoint_for_connection(CANDIDATE)
19482                .unwrap()
19483                .is_none());
19484
19485            hold.wait();
19486            assert!(hello.join().unwrap().is_empty(), "candidate HELLO succeeds");
19487            assert_eq!(
19488                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19489                FrameType::HelloAck
19490            );
19491            let published = swap
19492                .registry
19493                .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19494                .unwrap()
19495                .expect("candidate is published once its HELLO completes");
19496            assert_eq!(published.connection_id, CANDIDATE);
19497            assert!(swap
19498                .forwarding
19499                .module_endpoint_for_connection(CANDIDATE)
19500                .unwrap()
19501                .is_some());
19502        }
19503
19504        #[tokio::test]
19505        async fn candidate_lookup_after_hello_ack_waits_for_publication() {
19506            let mut swap = swap_with_incumbent().await;
19507            let hold = Arc::new(std::sync::Barrier::new(2));
19508            swap.handler.hello_ack_to_publication_hold = Some(Arc::clone(&hold));
19509            swap.handler
19510                .supervisor
19511                .open_swap("aft", "candidate-nonce".to_string());
19512            let hello = {
19513                let handler = swap.handler.clone();
19514                let candidate_ctx = swap.candidate_ctx.clone();
19515                std::thread::spawn(move || {
19516                    handler
19517                        .handle_hello(
19518                            CANDIDATE,
19519                            Some(candidate_ctx.egress),
19520                            hello_frame_with_nonce(
19521                                "aft",
19522                                PROTOCOL_VERSION,
19523                                8,
19524                                Some("candidate-nonce"),
19525                            ),
19526                        )
19527                        .unwrap()
19528                })
19529            };
19530            hold.wait();
19531            assert_eq!(
19532                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19533                FrameType::HelloAck
19534            );
19535            let reader_registry = Arc::clone(&swap.registry);
19536            let published = lookup_during_hello_publication(&swap.registry, &hold, move || {
19537                reader_registry
19538                    .published_registration(crate::registry::RegistrationSlot::Candidate("aft"))
19539                    .unwrap()
19540            });
19541            assert!(hello.join().unwrap().is_empty());
19542            assert_eq!(
19543                published
19544                    .expect("ACK makes candidate publication visible")
19545                    .connection_id,
19546                CANDIDATE
19547            );
19548            assert_eq!(
19549                swap.registry.generation().unwrap(),
19550                1,
19551                "candidate is not a second catalog entry"
19552            );
19553        }
19554
19555        #[tokio::test]
19556        async fn audit4_ungated_removed_candidate_publication_rolls_back_admission() {
19557            let mut swap = swap_with_incumbent().await;
19558            let hold = Arc::new(std::sync::Barrier::new(2));
19559            let handler = swap
19560                .handler
19561                .clone()
19562                .with_hello_registry_to_forwarding_hold(hold.clone());
19563            handler
19564                .supervisor
19565                .open_swap("aft", "candidate-nonce".into());
19566            let hello = {
19567                let handler = handler.clone();
19568                let ctx = swap.candidate_ctx.clone();
19569                std::thread::spawn(move || {
19570                    handler
19571                        .handle_hello(
19572                            CANDIDATE,
19573                            Some(ctx.egress),
19574                            hello_frame_with_nonce(
19575                                "aft",
19576                                PROTOCOL_VERSION,
19577                                8,
19578                                Some("candidate-nonce"),
19579                            ),
19580                        )
19581                        .unwrap()
19582                })
19583            };
19584            hold.wait();
19585            assert_eq!(
19586                swap.registry
19587                    .deregister_connection(CANDIDATE)
19588                    .unwrap()
19589                    .len(),
19590                1
19591            );
19592            hold.wait();
19593            assert!(hello.join().unwrap().is_empty());
19594            assert_eq!(
19595                swap.candidate_rx.try_recv().unwrap().frame.header.ty,
19596                FrameType::HelloAck
19597            );
19598            assert!(swap.registry.get_candidate("aft").unwrap().is_none());
19599            assert_eq!(
19600                handler
19601                    .supervisor
19602                    .swap_hello_admission("aft", Some("candidate-nonce")),
19603                SwapHelloAdmission::Candidate,
19604                "failed publication must roll back candidate_admitted for an ungated nonce swap"
19605            );
19606            handler.supervisor.close_swap("aft");
19607        }
19608
19609        fn keyed_total(counters: &Value, key: &str) -> u64 {
19610            counters[key]
19611                .as_object()
19612                .map(|counts| counts.values().filter_map(Value::as_u64).sum())
19613                .unwrap_or(0)
19614        }
19615
19616        #[tokio::test]
19617        async fn replacement_logs_old_end_and_new_admission_once() {
19618            let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
19619            let mut swap = swap_with_incumbent().await;
19620            swap.handler
19621                .supervisor
19622                .open_swap("aft", "candidate-nonce".to_string());
19623            hello_via_sink(
19624                &swap.handler,
19625                &swap.candidate_ctx,
19626                &mut swap.candidate_rx,
19627                hello_frame_with_nonce("aft", PROTOCOL_VERSION, 8, Some("candidate-nonce")),
19628            )
19629            .await;
19630            cutover(&swap);
19631            swap.handler.cleanup_connection(INCUMBENT).unwrap();
19632
19633            let captured = crate::router::test_log::captured_logs(&logs);
19634            println!("captured replacement registry logs:\n{captured}");
19635            let new_admissions: Vec<_> = captured
19636                .lines()
19637                .filter(|line| {
19638                    line.contains("connection_id=40")
19639                        && line.contains("swap candidate registered; not routable until cutover")
19640                })
19641                .collect();
19642            assert_eq!(
19643                new_admissions.len(),
19644                1,
19645                "unexpected admission logs: {captured}"
19646            );
19647            assert!(new_admissions[0].contains("module_id=aft"));
19648            assert!(new_admissions[0].contains("connection_id=40"));
19649            assert!(
19650                new_admissions[0].contains("swap candidate registered; not routable until cutover")
19651            );
19652            assert!(new_admissions[0].contains("ready=true"));
19653
19654            let old_admissions: Vec<_> = captured
19655                .lines()
19656                .filter(|line| {
19657                    line.contains("module registered module_id=aft ")
19658                        && line.contains("connection_id=30")
19659                })
19660                .collect();
19661            assert_eq!(
19662                old_admissions.len(),
19663                1,
19664                "unexpected incumbent admission: {captured}"
19665            );
19666
19667            let old_ends: Vec<_> = captured
19668                .lines()
19669                .filter(|line| {
19670                    line.contains("connection_id=30") && line.contains("module registration ended")
19671                })
19672                .collect();
19673            assert_eq!(old_ends.len(), 1, "unexpected end logs: {captured}");
19674            assert!(old_ends[0].contains("module_id=aft"));
19675            assert!(old_ends[0].contains("connection_id=30"));
19676            assert!(old_ends[0].contains("reason=replaced"));
19677            assert!(old_ends[0].contains("replaced_by_connection_id=40"));
19678            assert_eq!(
19679                captured
19680                    .lines()
19681                    .filter(|line| line.contains("module registration promoted"))
19682                    .count(),
19683                1,
19684                "unexpected promotion logs: {captured}"
19685            );
19686        }
19687
19688        /// An ack from the incumbent for a bind it was sent before cutover,
19689        /// arriving before the incumbent is drained. The incumbent is the live
19690        /// connection carrying every other client's routes, so the ack must
19691        /// not end it: the waiting client is told to retry, the reservation is
19692        /// given back, and the incumbent is told to drop just that binding.
19693        #[tokio::test]
19694        async fn incumbent_ack_between_promotion_and_drain_keeps_the_incumbent_serving() {
19695            let mut swap = swap_with_incumbent().await;
19696            let handler = swap.handler.clone();
19697
19698            // A co-tenant route, bound on the incumbent before the swap.
19699            let cotenant = ConnectionId::new(31);
19700            let (cotenant_ctx, mut cotenant_rx) = route_ctx(cotenant);
19701            let (cotenant_task, cotenant_bind) = relay_route_open(
19702                &handler,
19703                cotenant,
19704                &cotenant_ctx.egress,
19705                &mut swap.incumbent_rx,
19706                100,
19707                "aft",
19708                "swap-cotenant",
19709            )
19710            .await;
19711            handler
19712                .handle_control_frame(
19713                    &swap.incumbent_ctx,
19714                    route_bind_ack(cotenant_bind.header.corr),
19715                )
19716                .await
19717                .unwrap();
19718            assert!(cotenant_task.await.unwrap().is_empty());
19719            let (cotenant_channel, cotenant_epoch) =
19720                published_route(&cotenant_rx.recv().await.unwrap());
19721
19722            // A second route.open, relayed to the incumbent and not yet acked.
19723            let caller = ConnectionId::new(32);
19724            let (caller_ctx, mut caller_rx) = route_ctx(caller);
19725            let (caller_task, caller_bind) = relay_route_open(
19726                &handler,
19727                caller,
19728                &caller_ctx.egress,
19729                &mut swap.incumbent_rx,
19730                101,
19731                "aft",
19732                "swap-caller",
19733            )
19734            .await;
19735            let (abandoned_channel, abandoned_epoch) = route_bind_channel(&caller_bind);
19736
19737            register_candidate(&swap, None);
19738            cutover(&swap);
19739
19740            // The incumbent acks after promotion and before any drain.
19741            let ack = handler
19742                .handle_control_frame(&swap.incumbent_ctx, route_bind_ack(caller_bind.header.corr))
19743                .await;
19744            let module_loop_error = ack.as_ref().err().map(ToString::to_string);
19745            if module_loop_error.is_some() {
19746                // What the connection loop does with an untranslated router
19747                // error: end the connection, releasing every route on it.
19748                handler.cleanup_connection(INCUMBENT).unwrap();
19749            }
19750
19751            // 1. The incumbent's other routes survive.
19752            assert!(
19753                cotenant_rx.try_recv().is_err(),
19754                "the co-tenant route on the incumbent was torn down by one late ack: \
19755                 {module_loop_error:?}"
19756            );
19757            assert!(matches!(
19758                swap.forwarding
19759                    .lookup_data_route(cotenant, cotenant_channel, cotenant_epoch)
19760                    .unwrap(),
19761                DataRoute::Client(DataRouteState::Bound(_))
19762            ));
19763            assert_eq!(module_loop_error, None);
19764            assert!(swap
19765                .registry
19766                .get_module_by_connection(INCUMBENT)
19767                .unwrap()
19768                .is_some());
19769
19770            // 2. Exactly one channel-scoped GOODBYE to the incumbent.
19771            let goodbye = tokio::time::timeout(Duration::from_secs(1), swap.incumbent_rx.recv())
19772                .await
19773                .expect("the incumbent is told to drop the abandoned binding")
19774                .unwrap()
19775                .frame;
19776            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
19777            assert_eq!(goodbye.header.channel, abandoned_channel);
19778            assert_eq!(goodbye.header.epoch, abandoned_epoch);
19779            assert!(swap.incumbent_rx.try_recv().is_err());
19780
19781            // 3. The waiting client gets a retryable refusal and no route.
19782            let response = caller_task.await.unwrap();
19783            assert_eq!(response.len(), 1);
19784            assert_eq!(parse_error(&response[0])["code"], "module_reloading");
19785            assert!(caller_rx.try_recv().is_err());
19786
19787            // 4. The reservation pair is given back, and the pending bind
19788            //    settled exactly once: one accepted open (the co-tenant) and one
19789            //    refused open (the caller), nothing counted twice.
19790            assert_eq!(swap.forwarding.reserved_route_count().unwrap(), (0, 0));
19791            let counters = handler.counters().snapshot();
19792            assert_eq!(
19793                keyed_total(&counters, "route_open_accepted_by_principal"),
19794                1
19795            );
19796            assert_eq!(keyed_total(&counters, "route_open_refused_by_code"), 1);
19797            assert_eq!(counters["route_open_refused_by_code"]["module_rejected"], 1);
19798        }
19799
19800        /// After cutover the incumbent is drained BY ENDPOINT. Draining by module
19801        /// id would resolve to the promoted candidate and every new route.open
19802        /// would be refused as reloading, leaving neither process routable.
19803        #[tokio::test]
19804        async fn route_open_after_cutover_and_incumbent_drain_is_relayed_to_the_candidate() {
19805            let mut swap = swap_with_incumbent().await;
19806            register_candidate(&swap, None);
19807            let incumbent = cutover(&swap);
19808            swap.forwarding
19809                .begin_endpoint_drain(incumbent, RouteCloseReason::Restart)
19810                .unwrap()
19811                .expect("the incumbent is still registered");
19812
19813            let client = ConnectionId::new(33);
19814            let (client_ctx, mut client_rx) = route_ctx(client);
19815            let route_handler = swap.handler.clone();
19816            let open_ctx = RouteCtx {
19817                connection_id: client,
19818                egress: client_ctx.egress.clone(),
19819            };
19820            let mut route_task = tokio::spawn(async move {
19821                route_handler
19822                    .handle_control_frame(
19823                        &open_ctx,
19824                        route_open_frame(90, "aft", unique_project_root("swap-after-drain")),
19825                    )
19826                    .await
19827                    .unwrap()
19828            });
19829            let bind = tokio::select! {
19830                bind = swap.candidate_rx.recv() => bind.expect("candidate egress is open").frame,
19831                response = &mut route_task => {
19832                    let response = response.unwrap();
19833                    panic!(
19834                        "post-cutover route.open was refused instead of relayed to the candidate: {}",
19835                        parse_error(&response[0])["code"]
19836                    );
19837                }
19838            };
19839            swap.handler
19840                .handle_control_frame(&swap.candidate_ctx, route_bind_ack(bind.header.corr))
19841                .await
19842                .unwrap();
19843            assert!(route_task.await.unwrap().is_empty());
19844            let (channel, epoch) = published_route(&client_rx.recv().await.unwrap());
19845            match swap
19846                .forwarding
19847                .lookup_data_route(client, channel, epoch)
19848                .unwrap()
19849            {
19850                DataRoute::Client(DataRouteState::Bound(route)) => {
19851                    assert_eq!(route.module_endpoint.connection_id, CANDIDATE)
19852                }
19853                other => panic!("expected a bound route on the candidate, got {other:?}"),
19854            }
19855            assert!(swap.incumbent_rx.try_recv().is_err());
19856        }
19857
19858        /// A candidate declares itself ready with `catalog.update` on its own
19859        /// connection. If the connection-keyed registry lookups searched only the
19860        /// active slot, this would answer `not_registered` and the candidate
19861        /// would never become ready.
19862        #[tokio::test]
19863        async fn candidate_catalog_update_ready_reaches_the_candidate_registration() {
19864            let swap = swap_with_incumbent().await;
19865            register_candidate(&swap, Some(false));
19866            let update = Frame::build(
19867                FrameType::Request,
19868                control_flags(),
19869                0,
19870                0,
19871                55,
19872                serde_json::to_vec(&ModuleControlRequestFromModule::CatalogUpdate {
19873                    provides: manifest("aft", PROTOCOL_VERSION).provides,
19874                    capabilities: None,
19875                    ready: Some(true),
19876                })
19877                .unwrap(),
19878            )
19879            .unwrap();
19880
19881            let replies = swap
19882                .handler
19883                .handle_control_frame(&swap.candidate_ctx, update)
19884                .await
19885                .unwrap();
19886
19887            assert_eq!(replies.len(), 1);
19888            assert_eq!(
19889                replies[0].header.ty,
19890                FrameType::Response,
19891                "candidate catalog.update was refused: {:?}",
19892                serde_json::from_slice::<Value>(&replies[0].body).ok()
19893            );
19894            assert!(swap.registry.get_candidate("aft").unwrap().unwrap().ready);
19895            assert_eq!(
19896                swap.registry
19897                    .get_module("aft")
19898                    .unwrap()
19899                    .unwrap()
19900                    .connection_id,
19901                INCUMBENT
19902            );
19903        }
19904    }
19905
19906    /// The HELLO gate while the supervisor has a swap open: only the nonce it
19907    /// minted for the candidate admits a second process, into the candidate
19908    /// slot, and that check runs ahead of the reserved-module gate.
19909    mod swap_admission {
19910        use super::*;
19911
19912        const INCUMBENT_NONCE: &str = "incumbent-nonce";
19913        const CANDIDATE_NONCE: &str = "candidate-nonce";
19914
19915        fn handler_with_incumbent(
19916            module_id: &str,
19917            reserved: bool,
19918        ) -> (Arc<Registry>, SupervisorHandle, ControlHandler) {
19919            let registry = Arc::new(Registry::default());
19920            let supervisor = SupervisorHandle::new();
19921            supervisor.set_spawn_nonce(module_id, INCUMBENT_NONCE.to_string());
19922            if reserved {
19923                supervisor.set_reserved_nonce(module_id, INCUMBENT_NONCE.to_string());
19924            }
19925            let handler =
19926                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor.clone());
19927            let incumbent = handler
19928                .handle_control(
19929                    ConnectionId::new(1),
19930                    hello_frame_with_nonce(module_id, PROTOCOL_VERSION, 1, Some(INCUMBENT_NONCE)),
19931                )
19932                .unwrap();
19933            assert_eq!(incumbent[0].header.ty, FrameType::HelloAck);
19934            supervisor.open_swap(module_id, CANDIDATE_NONCE.to_string());
19935            (registry, supervisor, handler)
19936        }
19937
19938        /// Design mutation arm (ii). On an UNRESERVED id the reserved gate
19939        /// admits every nonce, so while a swap is open the swap gate is the only
19940        /// thing between a key-holder and the candidate slot. A nonce the
19941        /// supervisor did not mint, or none at all, is refused, and neither the
19942        /// incumbent's registration nor the candidate slot moves.
19943        #[test]
19944        fn unminted_nonce_on_an_unreserved_id_with_an_open_swap_is_refused() {
19945            let (registry, _supervisor, handler) = handler_with_incumbent("aft", false);
19946
19947            for (connection, nonce) in [(2, Some("forged")), (3, None)] {
19948                let replies = handler
19949                    .handle_control(
19950                        ConnectionId::new(connection),
19951                        hello_frame_with_nonce("aft", PROTOCOL_VERSION, connection, nonce),
19952                    )
19953                    .unwrap();
19954                assert_eq!(replies[0].header.ty, FrameType::Error);
19955                assert_eq!(
19956                    parse_error(&replies[0])["code"],
19957                    "swap_token_invalid",
19958                    "nonce {nonce:?}"
19959                );
19960            }
19961            assert!(registry.get_candidate("aft").unwrap().is_none());
19962            assert_eq!(
19963                registry.get_module("aft").unwrap().unwrap().connection_id,
19964                ConnectionId::new(1)
19965            );
19966
19967            // Control: the minted token is admitted, into the candidate slot,
19968            // and only once.
19969            let admitted = handler
19970                .handle_control(
19971                    ConnectionId::new(4),
19972                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 4, Some(CANDIDATE_NONCE)),
19973                )
19974                .unwrap();
19975            assert_eq!(admitted[0].header.ty, FrameType::HelloAck);
19976            assert_eq!(
19977                registry
19978                    .get_candidate("aft")
19979                    .unwrap()
19980                    .unwrap()
19981                    .connection_id,
19982                ConnectionId::new(4)
19983            );
19984            assert_eq!(
19985                registry.get_module("aft").unwrap().unwrap().connection_id,
19986                ConnectionId::new(1),
19987                "the candidate must not take the active slot"
19988            );
19989            let replayed = handler
19990                .handle_control(
19991                    ConnectionId::new(5),
19992                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 5, Some(CANDIDATE_NONCE)),
19993                )
19994                .unwrap();
19995            assert_eq!(parse_error(&replayed[0])["code"], "swap_token_invalid");
19996
19997            // The case only this gate covers: the incumbent has died mid-swap,
19998            // so its duplicate refusal is gone too, and without the gate a
19999            // key-holder would take the id's ACTIVE slot.
20000            handler.cleanup_connection(ConnectionId::new(1)).unwrap();
20001            let squatter = handler
20002                .handle_control(
20003                    ConnectionId::new(6),
20004                    hello_frame_with_nonce("aft", PROTOCOL_VERSION, 6, Some("forged")),
20005                )
20006                .unwrap();
20007            assert_eq!(parse_error(&squatter[0])["code"], "swap_token_invalid");
20008            assert!(
20009                registry.get_module("aft").unwrap().is_none(),
20010                "a squatter took the active slot of an id being swapped"
20011            );
20012        }
20013
20014        /// Design mutation arm (iii). A reserved module's candidate presents a
20015        /// nonce the reserved gate has never seen (that gate holds the
20016        /// incumbent's), so the swap gate must run first or the candidate is
20017        /// refused `reserved_module` and a reserved module can never be swapped.
20018        #[test]
20019        fn reserved_module_candidate_is_admitted_ahead_of_the_reserved_gate() {
20020            let (registry, _supervisor, handler) = handler_with_incumbent("vault", true);
20021
20022            let replies = handler
20023                .handle_control(
20024                    ConnectionId::new(2),
20025                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20026                )
20027                .unwrap();
20028
20029            assert_eq!(
20030                replies[0].header.ty,
20031                FrameType::HelloAck,
20032                "reserved candidate refused: {:?}",
20033                serde_json::from_slice::<Value>(&replies[0].body).ok()
20034            );
20035            assert_eq!(
20036                registry
20037                    .get_candidate("vault")
20038                    .unwrap()
20039                    .unwrap()
20040                    .connection_id,
20041                ConnectionId::new(2)
20042            );
20043        }
20044
20045        /// With no swap open the gate is inert: the incumbent's reserved gate
20046        /// and duplicate refusal behave exactly as before.
20047        #[test]
20048        fn without_an_open_swap_the_ordinary_gates_decide() {
20049            let (registry, supervisor, handler) = handler_with_incumbent("vault", true);
20050            supervisor.close_swap("vault");
20051
20052            let candidate = handler
20053                .handle_control(
20054                    ConnectionId::new(2),
20055                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 2, Some(CANDIDATE_NONCE)),
20056                )
20057                .unwrap();
20058            assert_eq!(parse_error(&candidate[0])["code"], "reserved_module");
20059            let duplicate = handler
20060                .handle_control(
20061                    ConnectionId::new(3),
20062                    hello_frame_with_nonce("vault", PROTOCOL_VERSION, 3, Some(INCUMBENT_NONCE)),
20063                )
20064                .unwrap();
20065            assert_eq!(parse_error(&duplicate[0])["code"], "duplicate_module_id");
20066            assert!(registry.get_candidate("vault").unwrap().is_none());
20067        }
20068    }
20069
20070    /// `scope.sync` and `scope.describe` through the real control handler: who
20071    /// may sync is decided by the registration and launch nonce of the module
20072    /// connection, never by the request body.
20073    mod scopes {
20074        mod close_reasons {
20075            include!("route_close_reason_tests.rs");
20076        }
20077        mod idle_tests {
20078            use super::*;
20079            include!("scope_idle_tests.rs");
20080        }
20081        mod route_open_timings {
20082            use super::*;
20083            include!("route_open_timing_tests.rs");
20084        }
20085        mod route_open_refusal_log {
20086            use super::*;
20087            include!("route_open_refusal_log_tests.rs");
20088        }
20089        mod activity {
20090            include!("activity_scope_tests.rs");
20091        }
20092        mod delta {
20093            include!("scope_handler_delta_tests.rs");
20094        }
20095        mod watch {
20096            include!("scope_watch_tests.rs");
20097        }
20098        mod call_modes {
20099            include!("scope_call_mode_tests.rs");
20100        }
20101        mod router_audit {
20102            use super::*;
20103            include!("control/router_audit_scope_tests.rs");
20104        }
20105        mod federated {
20106            include!("scope_federated_tests.rs");
20107        }
20108        mod authorize {
20109            include!("route_authorize_tests.rs");
20110        }
20111        #[tokio::test]
20112        async fn served_by_dispatch_bypasses_exhaustive_decoder_and_requires_registration() {
20113            let rig = rig().await;
20114            let body = serde_json::to_vec(&subc_control::ScopeServedByRequest::new(
20115                "s".into(),
20116                1,
20117                "tool".into(),
20118            ))
20119            .unwrap();
20120            assert!(serde_json::from_slice::<ModuleControlRequestFromModule>(&body).is_err());
20121            let (direct, _rx) = wide_ctx(999);
20122            for (ctx, expected) in [
20123                (&rig.owner, FrameType::Response),
20124                (&direct, FrameType::Error),
20125            ] {
20126                let frame =
20127                    Frame::build(FrameType::Request, control_flags(), 0, 0, 90, body.clone())
20128                        .unwrap();
20129                let replies = rig.handler.handle_control_frame(ctx, frame).await.unwrap();
20130                assert_eq!(replies[0].header.ty, expected);
20131                if expected == FrameType::Response {
20132                    let reply: subc_control::ScopeServedByReply =
20133                        serde_json::from_slice(&replies[0].body).unwrap();
20134                    assert_eq!(reply.answer, subc_control::ScopeServedByAnswer::Unknown);
20135                } else {
20136                    assert_eq!(parse_error(&replies[0])["code"], "not_registered");
20137                }
20138            }
20139            let reply = call(
20140                &rig.handler,
20141                &rig.owner,
20142                &ModuleControlRequestFromModule::ScopeDescribe {
20143                    owner: Principal::Reserved {
20144                        module_id: OWNER.into(),
20145                    },
20146                    scope_ref: "s".into(),
20147                },
20148            )
20149            .await;
20150            assert!(matches!(
20151                serde_json::from_slice::<ModuleControlResponseToModule>(&reply.body).unwrap(),
20152                ModuleControlResponseToModule::ScopeDescribe { .. }
20153            ));
20154        }
20155
20156        use subc_protocol::scope::{
20157            ParentState, ScopeCarrier, ScopeKind, ScopeParent, ScopeRecordOutcome, ScopeStamp,
20158            ScopeStatus,
20159        };
20160
20161        use super::*;
20162
20163        const OWNER: &str = "prefrontal-core";
20164
20165        fn head(scope_ref: &str, scope_epoch: u64) -> ScopeRecord {
20166            ScopeRecord::new(scope_ref, scope_epoch, ScopeKind::Head)
20167        }
20168
20169        async fn call(
20170            handler: &ControlHandler,
20171            ctx: &RouteCtx,
20172            request: &ModuleControlRequestFromModule,
20173        ) -> Frame {
20174            let body = serde_json::to_vec(request).unwrap();
20175            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 77, body).unwrap();
20176            let mut replies = handler.handle_control_frame(ctx, frame).await.unwrap();
20177            assert_eq!(replies.len(), 1, "{replies:?}");
20178            replies.pop().unwrap()
20179        }
20180
20181        async fn sync(
20182            handler: &ControlHandler,
20183            ctx: &RouteCtx,
20184            generation: u64,
20185            scopes: Vec<ScopeRecord>,
20186        ) -> Result<ModuleControlResponseToModule, String> {
20187            let reply = call(
20188                handler,
20189                ctx,
20190                &ModuleControlRequestFromModule::ScopeSync { generation, scopes },
20191            )
20192            .await;
20193            match reply.header.ty {
20194                FrameType::Response => Ok(serde_json::from_slice(&reply.body).unwrap()),
20195                _ => Err(parse_error(&reply)["code"].as_str().unwrap().to_string()),
20196            }
20197        }
20198
20199        async fn describe(
20200            handler: &ControlHandler,
20201            ctx: &RouteCtx,
20202            owner: &str,
20203            scope_ref: &str,
20204        ) -> ModuleControlResponseToModule {
20205            let reply = call(
20206                handler,
20207                ctx,
20208                &ModuleControlRequestFromModule::ScopeDescribe {
20209                    owner: Principal::Reserved {
20210                        module_id: owner.to_string(),
20211                    },
20212                    scope_ref: scope_ref.to_string(),
20213                },
20214            )
20215            .await;
20216            assert_eq!(
20217                reply.header.ty,
20218                FrameType::Response,
20219                "{:?}",
20220                parse_error(&reply)
20221            );
20222            serde_json::from_slice(&reply.body).unwrap()
20223        }
20224
20225        #[tokio::test]
20226        async fn scope_describe_never_echoes_bind_proof_or_hash() {
20227            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
20228            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
20229            let mut rig = rig().await;
20230            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
20231                .await;
20232            let _bound = rig
20233                .bound(
20234                    Some(AFT),
20235                    PLEXUS,
20236                    Some(
20237                        rig.selector("s", Some(1))
20238                            .with_bind_proof(Some(PROOF.into())),
20239                    ),
20240                )
20241                .await;
20242            let reply = describe(&rig.handler, &rig.owner, OWNER, "s").await;
20243            let output = serde_json::to_string(&reply).unwrap();
20244            assert!(output.contains("\"status\":\"live\""));
20245            assert!(!output.contains(PROOF));
20246            assert!(!output.contains(HASH));
20247        }
20248
20249        /// Register `module_id` on `connection` with `nonce`, returning its ctx.
20250        async fn module(
20251            handler: &ControlHandler,
20252            connection: u64,
20253            module_id: &str,
20254            nonce: Option<&str>,
20255        ) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20256            let (ctx, mut rx) = route_ctx(ConnectionId::new(connection));
20257            hello_via_sink(
20258                handler,
20259                &ctx,
20260                &mut rx,
20261                hello_frame_with_nonce(module_id, PROTOCOL_VERSION, connection, nonce),
20262            )
20263            .await;
20264            (ctx, rx)
20265        }
20266
20267        /// `direct` and every other client connection has no registration, so
20268        /// it can neither sync nor own a scope.
20269        #[tokio::test]
20270        async fn a_client_connection_cannot_sync_or_describe() {
20271            let handler = ControlHandler::new(Arc::new(Registry::default()));
20272            let (ctx, _rx) = route_ctx(ConnectionId::new(9));
20273            for request in [
20274                ModuleControlRequestFromModule::ScopeSync {
20275                    generation: 1,
20276                    scopes: vec![head("s", 1)],
20277                },
20278                ModuleControlRequestFromModule::ScopeDescribe {
20279                    owner: Principal::Direct,
20280                    scope_ref: "s".to_string(),
20281                },
20282            ] {
20283                let reply = call(&handler, &ctx, &request).await;
20284                assert_eq!(parse_error(&reply)["code"], "not_registered", "{request:?}");
20285            }
20286            assert!(
20287                !handler
20288                    .scopes
20289                    .read()
20290                    .unwrap()
20291                    .describe(
20292                        &Principal::Reserved {
20293                            module_id: OWNER.to_string()
20294                        },
20295                        "s"
20296                    )
20297                    .owner_synced
20298            );
20299        }
20300
20301        /// A module the supervisor did not spawn registers without a launch
20302        /// nonce, so it is never an owner's current launch.
20303        #[tokio::test]
20304        async fn a_module_without_a_supervised_launch_cannot_sync() {
20305            let handler = ControlHandler::new(Arc::new(Registry::default()));
20306            let (ctx, _rx) = module(&handler, 1, OWNER, None).await;
20307            assert_eq!(
20308                sync(&handler, &ctx, 1, vec![head("s", 1)]).await,
20309                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20310            );
20311        }
20312
20313        #[tokio::test]
20314        async fn sync_authority_follows_the_supervisors_recorded_spawn_nonce_across_a_swap() {
20315            let supervisor = SupervisorHandle::new();
20316            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20317            let handler = ControlHandler::new(Arc::new(Registry::default()))
20318                .with_supervisor(supervisor.clone());
20319            let (incumbent, _incumbent_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20320            sync(&handler, &incumbent, 1, vec![head("s", 1)])
20321                .await
20322                .expect("the current launch syncs");
20323
20324            // A swap candidate registers with the swap token and is refused
20325            // while the incumbent keeps syncing.
20326            supervisor.open_swap(OWNER, "n2".to_string());
20327            let (candidate, _candidate_rx) = module(&handler, 2, OWNER, Some("n2")).await;
20328            assert_eq!(
20329                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20330                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20331            );
20332            sync(&handler, &incumbent, 2, vec![head("s", 1)])
20333                .await
20334                .expect("the serving owner syncs during the swap");
20335
20336            // The swap fails and is rolled back. The candidate never held sync
20337            // authority, and still cannot sync.
20338            supervisor.close_swap(OWNER);
20339            assert_eq!(
20340                sync(&handler, &candidate, 1, vec![head("x", 1)]).await,
20341                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20342            );
20343            sync(&handler, &incumbent, 3, vec![head("s", 1)])
20344                .await
20345                .expect("the serving owner syncs after the rollback");
20346            handler.cleanup_connection(candidate.connection_id).unwrap();
20347
20348            // A swap that cuts over. Promotion records the candidate's nonce as
20349            // the module's spawn nonce, which is what `set_spawn_nonce` does
20350            // here; the promoted connection then takes authority at any
20351            // generation and the superseded incumbent is refused.
20352            supervisor.open_swap(OWNER, "n3".to_string());
20353            let (promoted, _promoted_rx) = module(&handler, 3, OWNER, Some("n3")).await;
20354            supervisor.set_spawn_nonce(OWNER, "n3".to_string());
20355            let reply = sync(&handler, &promoted, 1, vec![head("s", 1)])
20356                .await
20357                .expect("the promoted launch takes authority");
20358            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
20359                panic!("unexpected reply {reply:?}");
20360            };
20361            assert_eq!(results[0].outcome, ScopeRecordOutcome::Unchanged);
20362            assert_eq!(
20363                sync(&handler, &incumbent, 4, Vec::new()).await,
20364                Err(error_codes::SCOPE_SYNC_NOT_AUTHORITY.to_string())
20365            );
20366        }
20367
20368        /// Authority dies with its connection: the cleanup path releases it,
20369        /// so the owner's next connection takes it at any generation.
20370        #[tokio::test]
20371        async fn closing_the_authority_connection_frees_sync_authority() {
20372            let supervisor = SupervisorHandle::new();
20373            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20374            let handler = ControlHandler::new(Arc::new(Registry::default()))
20375                .with_supervisor(supervisor.clone());
20376            let (first, _first_rx) = module(&handler, 1, OWNER, Some("n1")).await;
20377            sync(&handler, &first, 10, vec![head("s", 1)])
20378                .await
20379                .unwrap();
20380            handler.cleanup_connection(first.connection_id).unwrap();
20381
20382            let (second, _second_rx) = module(&handler, 2, OWNER, Some("n1")).await;
20383            sync(&handler, &second, 1, vec![head("s", 1)])
20384                .await
20385                .expect("the next connection takes the released authority");
20386        }
20387
20388        #[tokio::test]
20389        async fn module_goodbye_releases_scope_sync_authority_without_socket_close() {
20390            let supervisor = SupervisorHandle::new();
20391            supervisor.set_spawn_nonce(OWNER, "n1".to_string());
20392            let handler =
20393                ControlHandler::new(Arc::new(Registry::default())).with_supervisor(supervisor);
20394            let (first, _rx) = module(&handler, 1, OWNER, Some("n1")).await;
20395            sync(&handler, &first, 10, vec![head("s", 1)])
20396                .await
20397                .unwrap();
20398            handler
20399                .handle_control_frame(
20400                    &first,
20401                    Frame::build(FrameType::Goodbye, control_flags(), 0, 0, 4, Vec::new()).unwrap(),
20402                )
20403                .await
20404                .unwrap();
20405            let (second, _rx) = module(&handler, 2, OWNER, Some("n1")).await;
20406            sync(&handler, &second, 1, vec![head("s", 1)])
20407                .await
20408                .expect("GOODBYE releases authority even if the old socket remains open");
20409        }
20410
20411        #[tokio::test]
20412        async fn describe_reports_the_incarnation_and_whether_the_owner_is_configured() {
20413            let registry = Arc::new(Registry::default());
20414            let supervisor_handle = SupervisorHandle::new();
20415            let supervisor =
20416                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20417                    .with_handle(supervisor_handle.clone())
20418                    .with_daemon_incarnation("incarnation-7".to_string());
20419            // Configured with enabled: false, so the supervisor lists the
20420            // module without spawning a process for it.
20421            supervisor
20422                .supervise_configured(
20423                    ModuleSpec {
20424                        script: None,
20425                        carry_containment: false,
20426                        module_id: OWNER.to_string(),
20427                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20428                        args: Vec::new(),
20429                        env: Vec::new(),
20430                        reserved: false,
20431                        reserved_prefixes: Vec::new(),
20432                        protocol: ModuleProtocol::Subc,
20433                        overlap: Default::default(),
20434                    },
20435                    false,
20436                )
20437                .unwrap();
20438            supervisor_handle.set_spawn_nonce(OWNER, "n1".to_string());
20439            let handler =
20440                ControlHandler::new(Arc::clone(&registry)).with_supervisor(supervisor_handle);
20441            let (reader, _reader_rx) = module(&handler, 5, "reader", None).await;
20442
20443            // Configured but not yet synced: a reader waits for the owner.
20444            let ModuleControlResponseToModule::ScopeDescribe {
20445                status,
20446                daemon_incarnation,
20447                owner_synced,
20448                owner_configured,
20449                scope,
20450                ..
20451            } = describe(&handler, &reader, OWNER, "s").await
20452            else {
20453                panic!("not a describe reply");
20454            };
20455            assert_eq!(status, ScopeStatus::NotLive);
20456            assert_eq!(daemon_incarnation, "incarnation-7");
20457            assert!(!owner_synced);
20458            assert!(owner_configured);
20459            assert!(scope.is_none());
20460
20461            // Not a supervised module: the owner will never sync, and a reader
20462            // refuses rather than waits.
20463            let ModuleControlResponseToModule::ScopeDescribe {
20464                status,
20465                owner_configured,
20466                ..
20467            } = describe(&handler, &reader, "ghost", "s").await
20468            else {
20469                panic!("not a describe reply");
20470            };
20471            assert_eq!(status, ScopeStatus::NotLive);
20472            assert!(!owner_configured);
20473
20474            // Live, with the stamp fields and the computed owner_authorized.
20475            let (owner, _owner_rx) = module(&handler, 6, OWNER, Some("n1")).await;
20476            sync(&handler, &owner, 1, vec![head("s", 4)]).await.unwrap();
20477            let ModuleControlResponseToModule::ScopeDescribe {
20478                status,
20479                scope_epoch,
20480                owner_synced,
20481                scope,
20482                ..
20483            } = describe(&handler, &reader, OWNER, "s").await
20484            else {
20485                panic!("not a describe reply");
20486            };
20487            assert_eq!(status, ScopeStatus::Live);
20488            assert_eq!(scope_epoch, Some(4));
20489            assert!(owner_synced);
20490            let stamp = scope.expect("a live scope carries its stamp");
20491            assert!(
20492                stamp.owner_authorized,
20493                "prefrontal-core is the default authority"
20494            );
20495            assert_eq!(stamp.kind, ScopeKind::Head);
20496        }
20497
20498        #[tokio::test]
20499        async fn scope_authority_owners_decides_owner_authorized() {
20500            let supervisor = SupervisorHandle::new();
20501            supervisor.set_spawn_nonce("broca", "b1".to_string());
20502            let handler = ControlHandler::new(Arc::new(Registry::default()))
20503                .with_supervisor(supervisor)
20504                .with_scope_authority_owners(vec!["broca".to_string()]);
20505            let (broca, _rx) = module(&handler, 1, "broca", Some("b1")).await;
20506            let mut gated = head("s", 1);
20507            gated.attributes.agent_id = Some("agent".to_string());
20508            sync(&handler, &broca, 1, vec![gated]).await.unwrap();
20509            let ModuleControlResponseToModule::ScopeDescribe { scope, .. } =
20510                describe(&handler, &broca, "broca", "s").await
20511            else {
20512                panic!("not a describe reply");
20513            };
20514            assert!(scope.unwrap().owner_authorized);
20515        }
20516
20517        /// With route admission, the stamp, the commit re-check and drains in
20518        /// place, the feature is advertised: the module ops in HELLO_ACK, and
20519        /// `scopes/v1` in HELLO_ACK and `server.describe`.
20520        #[tokio::test]
20521        async fn scope_ops_and_the_scopes_capability_are_advertised() {
20522            let handler = ControlHandler::new(Arc::new(Registry::default()));
20523            let (ctx, mut rx) = route_ctx(ConnectionId::new(1));
20524            let ack = hello_via_sink(
20525                &handler,
20526                &ctx,
20527                &mut rx,
20528                hello_frame("m", PROTOCOL_VERSION, 1),
20529            )
20530            .await;
20531            let ack = parse_ack(&ack);
20532            for op in [SCOPE_SYNC_OP, SCOPE_DESCRIBE_OP] {
20533                assert!(ack.subc_ops.iter().any(|o| o == op), "{:?}", ack.subc_ops);
20534            }
20535            assert!(ack.subc_capabilities.iter().any(|c| c == CAP_SCOPES_V1));
20536
20537            let (client, _client_rx) = route_ctx(ConnectionId::new(2));
20538            let body = serde_json::to_vec(&ClientControlRequest::ServerDescribe {}).unwrap();
20539            let frame = Frame::build(FrameType::Request, control_flags(), 0, 0, 5, body).unwrap();
20540            let reply = handler
20541                .handle_control_frame(&client, frame)
20542                .await
20543                .unwrap()
20544                .pop()
20545                .unwrap();
20546            let ClientControlResponse::ServerDescribe { capabilities, .. } =
20547                serde_json::from_slice(&reply.body).unwrap()
20548            else {
20549                panic!("not a server.describe reply");
20550            };
20551            assert!(
20552                capabilities.iter().any(|c| c == CAP_SCOPES_V1),
20553                "{capabilities:?}"
20554            );
20555        }
20556
20557        // ---- route admission, stamps, commit re-check and drains ----------
20558
20559        const PLEXUS: &str = "plexus";
20560        const OTHER: &str = "other";
20561        const AFT: &str = "aft";
20562        const BROCA: &str = "broca";
20563        const MAGIC: &str = "magic-context";
20564
20565        fn nonce(module_id: &str) -> String {
20566            format!("nonce-{module_id}")
20567        }
20568
20569        fn wide_ctx(connection: u64) -> (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>) {
20570            let (tx, rx) = mpsc::channel(64);
20571            (
20572                RouteCtx {
20573                    connection_id: ConnectionId::new(connection),
20574                    egress: FrameSink::new(tx),
20575                },
20576                rx,
20577            )
20578        }
20579
20580        /// A daemon with a configured owner (prefrontal-core) registered on its
20581        /// own module connection, two routable targets (plexus, other), and
20582        /// launch nonces minted for the modules that open routes as carriers.
20583        struct Rig {
20584            handler: ControlHandler,
20585            forwarding: Arc<ForwardingTable>,
20586            owner: RouteCtx,
20587            _owner_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20588            modules: BTreeMap<String, (RouteCtx, mpsc::Receiver<crate::router::OutboundFrame>)>,
20589            generation: u64,
20590            next_connection: u64,
20591            _supervisor: Supervisor,
20592        }
20593
20594        async fn rig() -> Rig {
20595            rig_with_flow_support(true).await
20596        }
20597
20598        async fn rig_with_flow_support(flow_support: bool) -> Rig {
20599            rig_with_scope_capabilities(flow_support, false).await
20600        }
20601
20602        async fn rig_with_scope_capabilities(flow_support: bool, run_support: bool) -> Rig {
20603            let mut provides = Vec::new();
20604            if flow_support {
20605                provides.push("flow-scopes/v1");
20606            }
20607            if run_support {
20608                provides.push("agent-run-scopes/v1");
20609            }
20610            rig_with_target_capabilities(&provides).await
20611        }
20612
20613        fn hello_with_capabilities(module_id: &str, connection: u64, provides: &[&str]) -> Frame {
20614            let hello = hello_frame(module_id, PROTOCOL_VERSION, connection);
20615            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
20616            // Decoder versions alone cannot admit scoped calls: only a capability
20617            // declaration promises the required run or flow behaviour.
20618            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
20619            body["manifest"]["capabilities"] = serde_json::json!({"provides": provides});
20620            Frame::build(
20621                FrameType::Hello,
20622                control_flags(),
20623                0,
20624                0,
20625                connection,
20626                serde_json::to_vec(&body).unwrap(),
20627            )
20628            .unwrap()
20629        }
20630
20631        async fn rig_with_target_capabilities(provides: &[&str]) -> Rig {
20632            let registry = Arc::new(Registry::default());
20633            let forwarding = Arc::new(ForwardingTable::default());
20634            let supervisor_handle = SupervisorHandle::new();
20635            let supervisor =
20636                Supervisor::new_for_test(Arc::clone(&registry), RestartPolicy::default())
20637                    .with_handle(supervisor_handle.clone());
20638            supervisor
20639                .supervise_configured(
20640                    ModuleSpec {
20641                        script: None,
20642                        carry_containment: false,
20643                        module_id: OWNER.to_string(),
20644                        program: PathBuf::from("/nonexistent/prefrontal-core"),
20645                        args: Vec::new(),
20646                        env: Vec::new(),
20647                        reserved: false,
20648                        reserved_prefixes: Vec::new(),
20649                        protocol: ModuleProtocol::Subc,
20650                        overlap: Default::default(),
20651                    },
20652                    false,
20653                )
20654                .unwrap();
20655            for module_id in [OWNER, AFT, BROCA, MAGIC] {
20656                supervisor_handle.set_spawn_nonce(module_id, nonce(module_id));
20657            }
20658            let handler =
20659                ControlHandler::with_forwarding(Arc::clone(&registry), Arc::clone(&forwarding))
20660                    .with_supervisor(supervisor_handle);
20661            let (owner, mut owner_rx) = wide_ctx(1);
20662            hello_via_sink(
20663                &handler,
20664                &owner,
20665                &mut owner_rx,
20666                hello_frame_with_nonce(OWNER, PROTOCOL_VERSION, 1, Some(&nonce(OWNER))),
20667            )
20668            .await;
20669            let mut modules = BTreeMap::new();
20670            for (connection, module_id) in [(2, PLEXUS), (3, OTHER)] {
20671                let (ctx, mut rx) = wide_ctx(connection);
20672                let hello = hello_with_capabilities(module_id, connection, provides);
20673                hello_via_sink(&handler, &ctx, &mut rx, hello).await;
20674                modules.insert(module_id.to_string(), (ctx, rx));
20675            }
20676            Rig {
20677                handler,
20678                forwarding,
20679                owner,
20680                _owner_rx: owner_rx,
20681                modules,
20682                generation: 0,
20683                next_connection: 100,
20684                _supervisor: supervisor,
20685            }
20686        }
20687
20688        fn carrier(module_id: &str, targets: Option<&[&str]>) -> ScopeCarrier {
20689            ScopeCarrier::new(Principal::Reserved {
20690                module_id: module_id.to_string(),
20691            })
20692            .with_targets(targets.map(|targets| targets.iter().map(|t| t.to_string()).collect()))
20693        }
20694
20695        /// The scope most tests open under: aft carries to any module, broca
20696        /// only to plexus and other, and the owner delegates as agent-1.
20697        fn session(scope_epoch: u64) -> ScopeRecord {
20698            let mut record = head("s", scope_epoch);
20699            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS, OTHER]))];
20700            record.attributes.agent_id = Some("agent-1".to_string());
20701            record.attributes.delegates = true;
20702            record
20703        }
20704
20705        impl Rig {
20706            async fn sync(&mut self, scopes: Vec<ScopeRecord>) {
20707                self.generation += 1;
20708                sync(&self.handler, &self.owner, self.generation, scopes)
20709                    .await
20710                    .expect("the owner's sync is accepted");
20711            }
20712
20713            fn selector(&self, scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
20714                ScopeSelector::new(
20715                    Principal::Reserved {
20716                        module_id: OWNER.to_string(),
20717                    },
20718                    scope_ref.to_string(),
20719                    scope_epoch,
20720                )
20721            }
20722
20723            fn open_frame(
20724                &mut self,
20725                opener: Option<&str>,
20726                target: &str,
20727                scope: Option<ScopeSelector>,
20728            ) -> (
20729                RouteCtx,
20730                mpsc::Receiver<crate::router::OutboundFrame>,
20731                Frame,
20732            ) {
20733                self.next_connection += 1;
20734                let (ctx, rx) = wide_ctx(self.next_connection);
20735                let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
20736                    busy_refusals: None,
20737                    target: RouteTarget::ToolProvider {
20738                        module_id: target.to_string(),
20739                    },
20740                    identity: BindIdentity::new("unit".to_string(), "session".to_string()),
20741                    consumer_identity: opener.map(|module_id| ConsumerIdentity {
20742                        module_id: module_id.to_string(),
20743                        launch_nonce: nonce(module_id),
20744                    }),
20745                    consumer_capabilities: None,
20746                    role_versions: None,
20747                    admission_facts: None,
20748                    scope,
20749                })
20750                .unwrap();
20751                let frame = Frame::build(
20752                    FrameType::Request,
20753                    control_flags(),
20754                    0,
20755                    0,
20756                    self.next_connection,
20757                    body,
20758                )
20759                .unwrap();
20760                (ctx, rx, frame)
20761            }
20762
20763            /// Open and expect a refusal before anything is relayed.
20764            async fn refused(
20765                &mut self,
20766                opener: Option<&str>,
20767                target: &str,
20768                scope: Option<ScopeSelector>,
20769            ) -> String {
20770                self.refusal_body(opener, target, scope).await["code"]
20771                    .as_str()
20772                    .unwrap()
20773                    .to_string()
20774            }
20775
20776            async fn refusal_body(
20777                &mut self,
20778                opener: Option<&str>,
20779                target: &str,
20780                scope: Option<ScopeSelector>,
20781            ) -> Value {
20782                let (ctx, _rx, frame) = self.open_frame(opener, target, scope);
20783                let replies = tokio::time::timeout(
20784                    Duration::from_secs(2),
20785                    self.handler.handle_control_frame(&ctx, frame),
20786                )
20787                .await
20788                .expect("the open must be refused before waiting for a bind ack")
20789                .unwrap();
20790                assert_eq!(replies.len(), 1, "{replies:?}");
20791                assert_eq!(replies[0].header.ty, FrameType::Error);
20792                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20793                assert!(
20794                    module_rx.try_recv().is_err(),
20795                    "a refused open relays nothing"
20796                );
20797                assert_eq!(self.forwarding.reserved_route_count().unwrap(), (0, 0));
20798                parse_error(&replies[0])
20799            }
20800
20801            /// Start an open and return its task and the bind the target got.
20802            async fn relayed(
20803                &mut self,
20804                opener: Option<&str>,
20805                target: &str,
20806                scope: Option<ScopeSelector>,
20807            ) -> Relayed {
20808                self.relayed_with_legacy_root(opener, target, scope, None)
20809                    .await
20810            }
20811
20812            async fn relayed_with_legacy_root(
20813                &mut self,
20814                opener: Option<&str>,
20815                target: &str,
20816                scope: Option<ScopeSelector>,
20817                legacy_root: Option<&std::path::Path>,
20818            ) -> Relayed {
20819                let (ctx, rx, mut frame) = self.open_frame(opener, target, scope);
20820                if let Some(root) = legacy_root {
20821                    let mut body: Value = serde_json::from_slice(&frame.body).unwrap();
20822                    body["identity"]["project_root"] = serde_json::json!(root);
20823                    frame.body = serde_json::to_vec(&body).unwrap();
20824                }
20825                let handler = self.handler.clone();
20826                let task_ctx = ctx.clone();
20827                let task = tokio::spawn(async move {
20828                    handler
20829                        .handle_control_frame(&task_ctx, frame)
20830                        .await
20831                        .unwrap()
20832                });
20833                let (_, module_rx) = self.modules.get_mut(target).unwrap();
20834                let bind = tokio::time::timeout(Duration::from_secs(2), module_rx.recv())
20835                    .await
20836                    .expect("the target receives the relayed route.bind")
20837                    .unwrap()
20838                    .frame;
20839                Relayed {
20840                    target: target.to_string(),
20841                    client: ctx,
20842                    client_rx: rx,
20843                    task,
20844                    bind,
20845                }
20846            }
20847
20848            async fn ack(&self, relayed: &Relayed) {
20849                let (module, _) = &self.modules[&relayed.target];
20850                self.handler
20851                    .handle_control_frame(module, route_bind_ack(relayed.bind.header.corr))
20852                    .await
20853                    .unwrap();
20854            }
20855
20856            /// Open, ack and return the bound route.
20857            async fn bound(
20858                &mut self,
20859                opener: Option<&str>,
20860                target: &str,
20861                scope: Option<ScopeSelector>,
20862            ) -> Bound {
20863                let relayed = self.relayed(opener, target, scope).await;
20864                self.commit_relayed(relayed).await
20865            }
20866
20867            async fn bound_with_legacy_root(
20868                &mut self,
20869                opener: Option<&str>,
20870                target: &str,
20871                scope: Option<ScopeSelector>,
20872                root: &std::path::Path,
20873            ) -> Bound {
20874                let relayed = self
20875                    .relayed_with_legacy_root(opener, target, scope, Some(root))
20876                    .await;
20877                self.commit_relayed(relayed).await
20878            }
20879
20880            async fn commit_relayed(&self, relayed: Relayed) -> Bound {
20881                self.ack(&relayed).await;
20882                let Relayed {
20883                    target,
20884                    client,
20885                    mut client_rx,
20886                    task,
20887                    bind,
20888                } = relayed;
20889                assert!(
20890                    task.await.unwrap().is_empty(),
20891                    "the open is answered by commit"
20892                );
20893                let (channel, epoch) = published_route(&client_rx.recv().await.unwrap().frame);
20894                Bound {
20895                    target,
20896                    client,
20897                    client_rx,
20898                    channel,
20899                    epoch,
20900                    bind,
20901                }
20902            }
20903
20904            fn live(&self, route: &Bound) -> bool {
20905                matches!(
20906                    self.forwarding
20907                        .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
20908                        .unwrap(),
20909                    DataRoute::Client(DataRouteState::Bound(_))
20910                )
20911            }
20912        }
20913
20914        struct Relayed {
20915            target: String,
20916            client: RouteCtx,
20917            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20918            task: tokio::task::JoinHandle<Vec<Frame>>,
20919            bind: Frame,
20920        }
20921
20922        struct Bound {
20923            target: String,
20924            client: RouteCtx,
20925            client_rx: mpsc::Receiver<crate::router::OutboundFrame>,
20926            channel: u16,
20927            epoch: u32,
20928            bind: Frame,
20929        }
20930
20931        impl Bound {
20932            /// The reason of the `route.closed` this client was sent, after
20933            /// checking it also got a GOODBYE on exactly this route.
20934            fn closed_reason(&mut self) -> RouteCloseReason {
20935                let mut reason = None;
20936                let mut goodbye = false;
20937                while let Ok(outbound) = self.client_rx.try_recv() {
20938                    let frame = outbound.frame;
20939                    match frame.header.ty {
20940                        FrameType::Goodbye => {
20941                            assert_eq!(
20942                                (frame.header.channel, frame.header.epoch),
20943                                (self.channel, self.epoch)
20944                            );
20945                            goodbye = true;
20946                        }
20947                        FrameType::Push => {
20948                            let ClientControlPush::RouteClosed {
20949                                reason: r,
20950                                module_id,
20951                                ..
20952                            } = serde_json::from_slice(&frame.body).unwrap()
20953                            else {
20954                                panic!("unexpected push");
20955                            };
20956                            assert_eq!(module_id, self.target);
20957                            reason = Some(r);
20958                        }
20959                        other => panic!("unexpected frame {other:?}"),
20960                    }
20961                }
20962                assert!(goodbye, "the client is sent a GOODBYE for the closed route");
20963                reason.expect("the client is told why the route closed")
20964            }
20965
20966            fn untouched(&mut self) -> bool {
20967                self.client_rx.try_recv().is_err()
20968            }
20969
20970            fn stamp(&self) -> Option<ScopeStamp> {
20971                match serde_json::from_slice::<ModuleControlRequest>(&self.bind.body).unwrap() {
20972                    ModuleControlRequest::RouteBind { scope, .. } => scope,
20973                    other => panic!("expected a route.bind, got {other:?}"),
20974                }
20975            }
20976        }
20977
20978        #[tokio::test]
20979        async fn only_the_owner_or_a_listed_carrier_is_admitted_and_a_targeted_carrier_only_to_its_modules(
20980        ) {
20981            let mut rig = rig().await;
20982            let mut record = session(1);
20983            record.carriers = vec![carrier(AFT, None), carrier(BROCA, Some(&[PLEXUS]))];
20984            record.child_owners = vec![Principal::Reserved {
20985                module_id: MAGIC.to_string(),
20986            }];
20987            rig.sync(vec![record]).await;
20988            let scope = || Some(rig_selector("s", Some(1)));
20989
20990            // Admitted: the owner, a bare carrier to any module, a targeted
20991            // carrier to its listed module.
20992            rig.bound(Some(OWNER), PLEXUS, scope()).await;
20993            rig.bound(Some(AFT), OTHER, scope()).await;
20994            rig.bound(Some(BROCA), PLEXUS, scope()).await;
20995
20996            // Refused scope_not_carrier: a targeted carrier to an unlisted
20997            // module, a module that is not listed at all (a child owner is not
20998            // a carrier), and a direct key-holder.
20999            for (opener, target) in [(Some(BROCA), OTHER), (Some(MAGIC), PLEXUS), (None, PLEXUS)] {
21000                assert_eq!(
21001                    rig.refused(opener, target, scope()).await,
21002                    error_codes::SCOPE_NOT_CARRIER,
21003                    "{opener:?} -> {target}"
21004                );
21005            }
21006        }
21007
21008        fn rig_selector(scope_ref: &str, scope_epoch: Option<u64>) -> ScopeSelector {
21009            ScopeSelector::new(
21010                Principal::Reserved {
21011                    module_id: OWNER.to_string(),
21012                },
21013                scope_ref.to_string(),
21014                scope_epoch,
21015            )
21016        }
21017
21018        #[tokio::test]
21019        async fn an_open_without_an_epoch_is_refused_the_owners_included() {
21020            let mut rig = rig().await;
21021            rig.sync(vec![session(1)]).await;
21022            for opener in [OWNER, AFT] {
21023                assert_eq!(
21024                    rig.refused(Some(opener), PLEXUS, Some(rig.selector("s", None)))
21025                        .await,
21026                    error_codes::SCOPE_EPOCH_REQUIRED,
21027                    "{opener}"
21028                );
21029            }
21030        }
21031
21032        #[tokio::test]
21033        async fn admission_separates_not_synced_not_live_and_ended() {
21034            let mut rig = rig().await;
21035            // Before the configured owner's first sync: retryable.
21036            let code = rig
21037                .refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21038                .await;
21039            assert_eq!(code, error_codes::SCOPE_NOT_SYNCED);
21040            assert!(subc_protocol::error_codes::is_retryable_route_open(&code));
21041
21042            // An owner that is not configured will never sync: terminal.
21043            let ghost = ScopeSelector::new(
21044                Principal::Reserved {
21045                    module_id: "ghost".to_string(),
21046                },
21047                "s".to_string(),
21048                Some(1),
21049            );
21050            assert_eq!(
21051                rig.refused(Some(AFT), PLEXUS, Some(ghost)).await,
21052                error_codes::SCOPE_NOT_LIVE
21053            );
21054
21055            rig.sync(vec![session(2)]).await;
21056            assert_eq!(
21057                rig.refused(Some(AFT), PLEXUS, Some(rig_selector("missing", Some(1))))
21058                    .await,
21059                error_codes::SCOPE_NOT_LIVE
21060            );
21061            for epoch in [1, 3] {
21062                assert_eq!(
21063                    rig.refused(Some(AFT), PLEXUS, Some(rig_selector("s", Some(epoch))))
21064                        .await,
21065                    error_codes::SCOPE_ENDED,
21066                    "epoch {epoch}"
21067                );
21068            }
21069            // Control: the live epoch is admitted.
21070            rig.bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(2))))
21071                .await;
21072        }
21073
21074        #[tokio::test]
21075        async fn the_bind_is_stamped_and_owner_authorized_only_for_listed_owners() {
21076            let mut rig = rig().await;
21077            rig.sync(vec![session(1)]).await;
21078            let route = rig
21079                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21080                .await;
21081            let stamp = route.stamp().expect("a scoped bind carries the stamp");
21082            assert_eq!(stamp.scope_ref, "s");
21083            assert_eq!(stamp.scope_epoch, 1);
21084            assert_eq!(stamp.kind, ScopeKind::Head);
21085            assert_eq!(stamp.attributes.agent_id.as_deref(), Some("agent-1"));
21086            assert!(stamp.attributes.delegates);
21087            assert!(stamp.owner_authorized);
21088            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21089            assert_eq!(unscoped.stamp(), None, "an unscoped open is not stamped");
21090
21091            // broca owns a scope of its own on its own module connection; it is
21092            // not in scope_authority_owners, so its stamp is not authorized.
21093            let (broca, mut broca_rx) = wide_ctx(50);
21094            hello_via_sink(
21095                &rig.handler,
21096                &broca,
21097                &mut broca_rx,
21098                hello_frame_with_nonce(BROCA, PROTOCOL_VERSION, 50, Some(&nonce(BROCA))),
21099            )
21100            .await;
21101            sync(&rig.handler, &broca, 1, vec![head("b", 1)])
21102                .await
21103                .unwrap();
21104            let own = ScopeSelector::new(
21105                Principal::Reserved {
21106                    module_id: BROCA.to_string(),
21107                },
21108                "b".to_string(),
21109                Some(1),
21110            );
21111            let route = rig.bound(Some(BROCA), PLEXUS, Some(own)).await;
21112            assert!(!route.stamp().unwrap().owner_authorized);
21113        }
21114
21115        #[tokio::test]
21116        async fn an_authority_owners_flow_id_without_an_agent_is_stamped_verbatim_on_bind() {
21117            let mut rig = rig().await;
21118            let mut record = head("s", 1);
21119            record.carriers = vec![carrier(AFT, None)];
21120            let flow_id = "Flow:run-7/step_2!~";
21121            record.attributes.flow_id = Some(flow_id.to_string());
21122            let reply = sync(&rig.handler, &rig.owner, 1, vec![record])
21123                .await
21124                .unwrap();
21125            let ModuleControlResponseToModule::ScopeSync { results, .. } = reply else {
21126                panic!("not a sync reply");
21127            };
21128            assert_eq!(results[0].outcome, ScopeRecordOutcome::Created);
21129            let route = rig
21130                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21131                .await;
21132            assert!(rig.live(&route), "the stamped bind committed");
21133            let stamp = route.stamp().expect("a flow scope carries a stamp");
21134            assert_eq!(stamp.attributes.flow_id.as_deref(), Some(flow_id));
21135            assert_eq!(stamp.attributes.agent_id, None);
21136            assert!(!stamp.attributes.delegates);
21137            assert!(stamp.owner_authorized);
21138            let unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21139            assert_eq!(unscoped.stamp(), None);
21140        }
21141
21142        #[tokio::test]
21143        async fn flow_scope_refuses_a_0_29_target_without_flow_capability_and_relays_nothing() {
21144            let mut rig = rig_with_flow_support(false).await;
21145            let mut record = session(1);
21146            record.attributes.flow_id = Some("flow:7".to_string());
21147            rig.sync(vec![record]).await;
21148            for opener in [OWNER, AFT] {
21149                let body = rig
21150                    .refusal_body(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21151                    .await;
21152                assert_eq!(body["code"], "target_flow_unsupported");
21153                let message = body["message"].as_str().unwrap();
21154                for required in [PLEXUS, "flow-scopes/v1"] {
21155                    assert!(message.contains(required), "{message}");
21156                }
21157            }
21158        }
21159
21160        #[tokio::test]
21161        async fn flow_scope_admits_a_capable_target_and_preserves_flow_id_on_bind() {
21162            let mut rig = rig_with_flow_support(true).await;
21163            let mut record = session(1);
21164            record.attributes.flow_id = Some("flow:7".to_string());
21165            rig.sync(vec![record]).await;
21166            for opener in [OWNER, AFT] {
21167                let route = rig
21168                    .bound(Some(opener), PLEXUS, Some(rig_selector("s", Some(1))))
21169                    .await;
21170                assert!(rig.live(&route));
21171                assert_eq!(
21172                    route.stamp().unwrap().attributes.flow_id.as_deref(),
21173                    Some("flow:7")
21174                );
21175            }
21176        }
21177
21178        #[tokio::test]
21179        async fn flow_scope_rechecks_the_relay_target_after_a_reconnect() {
21180            use std::future::Future;
21181
21182            let mut rig = rig_with_flow_support(true).await;
21183            let mut record = session(1);
21184            record.attributes.flow_id = Some("flow:7".to_string());
21185            rig.sync(vec![record]).await;
21186            let (client, mut client_rx, frame) =
21187                rig.open_frame(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))));
21188            // Hold the route-open response permit so admission sees the first
21189            // target but relay reservation cannot capture an endpoint yet.
21190            for _ in 0..64 {
21191                client.egress.try_send(route_bind_ack(1)).unwrap();
21192            }
21193            let handler = rig.handler.clone();
21194            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21195            std::future::poll_fn(|cx| {
21196                assert!(open.as_mut().poll(cx).is_pending());
21197                std::task::Poll::Ready(())
21198            })
21199            .await;
21200            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21201
21202            let old_connection = rig.modules[PLEXUS].0.connection_id;
21203            rig.handler.cleanup_connection(old_connection).unwrap();
21204            let (replacement, mut replacement_rx) = wide_ctx(200);
21205            let hello = hello_frame(PLEXUS, PROTOCOL_VERSION, 200);
21206            let mut body: Value = serde_json::from_slice(&hello.body).unwrap();
21207            body["manifest"]["provenance"] = serde_json::json!({"wire_crate_version": "0.29.0"});
21208            let hello = Frame::build(
21209                FrameType::Hello,
21210                control_flags(),
21211                0,
21212                0,
21213                200,
21214                serde_json::to_vec(&body).unwrap(),
21215            )
21216            .unwrap();
21217            hello_via_sink(&rig.handler, &replacement, &mut replacement_rx, hello).await;
21218
21219            client_rx.try_recv().unwrap();
21220            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21221                .await
21222                .expect("the replacement is refused without waiting for a bind ack")
21223                .unwrap();
21224            assert_eq!(replies.len(), 1);
21225            let body = parse_error(&replies[0]);
21226            assert_eq!(body["code"], "target_flow_unsupported");
21227            for required in [PLEXUS, "flow-scopes/v1"] {
21228                assert!(body["message"].as_str().unwrap().contains(required));
21229            }
21230            assert!(replacement_rx.try_recv().is_err(), "no bind is relayed");
21231            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21232            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21233            assert!(rig
21234                .handler
21235                .registry
21236                .get_module_by_connection(replacement.connection_id)
21237                .unwrap()
21238                .is_some());
21239        }
21240
21241        #[tokio::test]
21242        async fn scope_bind_proof_rechecks_current_hash_before_captured_relay() {
21243            use std::future::Future;
21244            const PROOF: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
21245            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21246            const NEXT_HASH: &str =
21247                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21248            let mut rig = rig().await;
21249            let mut record = session(1).with_bind_proof_sha256(Some(HASH.into()));
21250            record.carriers.push(ScopeCarrier::new(Principal::Direct));
21251            rig.sync(vec![record.clone()]).await;
21252            let (client, mut rx, frame) = rig.open_frame(
21253                None,
21254                PLEXUS,
21255                Some(
21256                    rig.selector("s", Some(1))
21257                        .with_bind_proof(Some(PROOF.into())),
21258                ),
21259            );
21260            // Hold egress reservation while the scope owner changes its bind-proof
21261            // hash, so a proof valid at admission must be checked again at relay.
21262            for _ in 0..64 {
21263                client.egress.try_send(route_bind_ack(1)).unwrap();
21264            }
21265            let handler = rig.handler.clone();
21266            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21267            std::future::poll_fn(|cx| {
21268                assert!(open.as_mut().poll(cx).is_pending());
21269                std::task::Poll::Ready(())
21270            })
21271            .await;
21272            record.bind_proof_sha256 = Some(NEXT_HASH.into());
21273            rig.sync(vec![record]).await;
21274            rx.try_recv().unwrap();
21275            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21276                .await
21277                .unwrap()
21278                .unwrap();
21279            assert_eq!(
21280                parse_error(&replies[0])["code"],
21281                error_codes::SCOPE_BIND_PROOF_MISMATCH
21282            );
21283            assert!(!String::from_utf8_lossy(&replies[0].body).contains(PROOF));
21284            assert!(rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_err());
21285            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21286        }
21287
21288        #[tokio::test]
21289        async fn scope_bind_proof_reserved_openers_ignore_proof() {
21290            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21291            let mut rig = rig().await;
21292            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21293                .await;
21294            for opener in [OWNER, AFT] {
21295                for proof in [None, Some("malformed+proof=")] {
21296                    let route = rig
21297                        .bound(
21298                            Some(opener),
21299                            PLEXUS,
21300                            Some(
21301                                rig.selector("s", Some(1))
21302                                    .with_bind_proof(proof.map(str::to_string)),
21303                            ),
21304                        )
21305                        .await;
21306                    assert!(rig.live(&route));
21307                }
21308            }
21309        }
21310
21311        #[tokio::test]
21312        async fn scope_bind_proof_reserved_opener_passes_hash_change_before_captured_relay() {
21313            use std::future::Future;
21314            const HASH: &str = "4bb06f8e4e3a7715d201d573d0aa423762e55dabd61a2c02278fa56cc6d294e0";
21315            const NEXT_HASH: &str =
21316                "2578ccf8645b2d1dc10c465eff843585970f3a7e22296a92cad55d489a272072";
21317            let mut rig = rig().await;
21318            rig.sync(vec![session(1).with_bind_proof_sha256(Some(HASH.into()))])
21319                .await;
21320            let (client, mut rx, frame) =
21321                rig.open_frame(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))));
21322            for _ in 0..64 {
21323                client.egress.try_send(route_bind_ack(1)).unwrap();
21324            }
21325            let handler = rig.handler.clone();
21326            let mut open = Box::pin(handler.handle_control_frame(&client, frame));
21327            std::future::poll_fn(|cx| {
21328                assert!(open.as_mut().poll(cx).is_pending());
21329                std::task::Poll::Ready(())
21330            })
21331            .await;
21332            rig.sync(vec![
21333                session(1).with_bind_proof_sha256(Some(NEXT_HASH.into()))
21334            ])
21335            .await;
21336            rx.try_recv().unwrap();
21337            let (_, module_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21338            let bind = std::future::poll_fn(|cx| {
21339                assert!(open.as_mut().poll(cx).is_pending());
21340                module_rx.poll_recv(cx)
21341            })
21342            .await
21343            .unwrap()
21344            .frame;
21345            handler
21346                .handle_control_frame(&rig.modules[PLEXUS].0, route_bind_ack(bind.header.corr))
21347                .await
21348                .unwrap();
21349            let replies = tokio::time::timeout(Duration::from_secs(2), open)
21350                .await
21351                .unwrap()
21352                .unwrap();
21353            assert_eq!(replies.len(), 1);
21354            // Proof rechecking allowed the relay. Independent tag settlement
21355            // still asks the opener to retry after any same-epoch content change.
21356            assert_eq!(parse_error(&replies[0])["code"], error_codes::SCOPE_CHANGED);
21357            assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21358            while rig.modules.get_mut(PLEXUS).unwrap().1.try_recv().is_ok() {}
21359            let route = rig
21360                .bound(Some(AFT), PLEXUS, Some(rig.selector("s", Some(1))))
21361                .await;
21362            assert!(rig.live(&route));
21363        }
21364
21365        #[tokio::test]
21366        async fn scope_without_flow_id_and_unscoped_routes_admit_a_target_without_flow_capability()
21367        {
21368            let mut rig = rig_with_flow_support(false).await;
21369            rig.sync(vec![session(1)]).await;
21370            let route = rig
21371                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21372                .await;
21373            assert!(rig.live(&route));
21374            assert_eq!(route.stamp().unwrap().attributes.flow_id, None);
21375            let mut record = session(1);
21376            record.attributes.flow_id = Some("flow:7".to_string());
21377            rig.sync(vec![record]).await;
21378            let unscoped = rig.bound(Some(AFT), OTHER, None).await;
21379            assert!(rig.live(&unscoped));
21380            assert_eq!(unscoped.stamp(), None);
21381        }
21382
21383        #[tokio::test]
21384        async fn a_same_epoch_flow_id_change_bumps_version_and_drains_all_scoped_routes() {
21385            let mut rig = rig().await;
21386            let mut record = session(1);
21387            record.attributes.flow_id = Some("flow:7".to_string());
21388            rig.sync(vec![record.clone()]).await;
21389            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21390            let mut owner_route = rig
21391                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21392                .await;
21393            let mut carrier_route = rig
21394                .bound(Some(AFT), OTHER, Some(rig_selector("s", Some(1))))
21395                .await;
21396            let mut unscoped = rig.bound(Some(AFT), PLEXUS, None).await;
21397            rig.sync(vec![record.clone()]).await;
21398            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21399            assert!(rig.live(&owner_route) && owner_route.untouched());
21400            assert!(rig.live(&carrier_route) && carrier_route.untouched());
21401
21402            record.attributes.flow_id = Some("flow:8".to_string());
21403            rig.sync(vec![record]).await;
21404            let after = rig.forwarding.published_scope_tag(OWNER, "s").unwrap();
21405            let before = before.unwrap();
21406            assert_eq!(after.scope_epoch, before.scope_epoch);
21407            assert!(after.version > before.version);
21408            for route in [&mut owner_route, &mut carrier_route] {
21409                assert!(!rig.live(route));
21410                assert_eq!(
21411                    route.closed_reason(),
21412                    RouteCloseReason::ScopeDelegationChanged
21413                );
21414            }
21415            assert!(rig.live(&unscoped) && unscoped.untouched());
21416            // Each provider also receives a GOODBYE for its drained route;
21417            // consume it before expecting the next route.bind on that sink.
21418            for target in [PLEXUS, OTHER] {
21419                let (_, module_rx) = rig.modules.get_mut(target).unwrap();
21420                let goodbye = module_rx
21421                    .try_recv()
21422                    .expect("the provider sees the drain")
21423                    .frame;
21424                assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21425                assert!(module_rx.try_recv().is_err());
21426            }
21427            let rebound = rig
21428                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21429                .await;
21430            assert_eq!(
21431                rebound.stamp().unwrap().attributes.flow_id.as_deref(),
21432                Some("flow:8")
21433            );
21434        }
21435
21436        /// The owner's sync lands between admission and the module's ack. The
21437        /// open is refused by name, the module's other routes stay up, and the
21438        /// reserved pair is released. Changed content is retryable; an ended
21439        /// scope is not.
21440        #[tokio::test]
21441        async fn a_scope_changed_or_ended_between_admission_and_commit_refuses_the_open() {
21442            let mut rig = rig().await;
21443            rig.sync(vec![session(1)]).await;
21444            let mut cotenant = rig
21445                .bound(Some(OWNER), PLEXUS, Some(rig_selector("s", Some(1))))
21446                .await;
21447
21448            let mut changed = session(1);
21449            changed.child_owners.push(Principal::Reserved {
21450                module_id: MAGIC.to_string(),
21451            });
21452            let mut ended = None;
21453            for (code, next) in [
21454                (error_codes::SCOPE_CHANGED, vec![changed]),
21455                (error_codes::SCOPE_ENDED, Vec::new()),
21456            ] {
21457                let relayed = rig
21458                    .relayed(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21459                    .await;
21460                let (bind_channel, bind_epoch) = route_bind_channel(&relayed.bind);
21461                ended = Some(next.is_empty());
21462                rig.sync(next).await;
21463                rig.ack(&relayed).await;
21464                let replies = relayed.task.await.unwrap();
21465                assert_eq!(replies.len(), 1, "{replies:?}");
21466                assert_eq!(parse_error(&replies[0])["code"], code);
21467                assert_eq!(
21468                    subc_protocol::error_codes::is_retryable_route_open(code),
21469                    code == error_codes::SCOPE_CHANGED
21470                );
21471                assert_eq!(rig.forwarding.reserved_route_count().unwrap(), (0, 0));
21472                // The module is told to drop just the binding it created.
21473                let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21474                // Collected, because ending the scope also closes the co-tenant
21475                // route, whose GOODBYE comes first.
21476                let mut goodbyes = Vec::new();
21477                while let Ok(outbound) = plexus_rx.try_recv() {
21478                    assert_eq!(outbound.frame.header.ty, FrameType::Goodbye);
21479                    goodbyes.push((outbound.frame.header.channel, outbound.frame.header.epoch));
21480                }
21481                assert!(
21482                    goodbyes.contains(&(bind_channel, bind_epoch)),
21483                    "{goodbyes:?}"
21484                );
21485                assert!(rig
21486                    .handler
21487                    .registry
21488                    .get_module_by_connection(rig.modules[PLEXUS].0.connection_id)
21489                    .unwrap()
21490                    .is_some());
21491            }
21492            assert_eq!(ended, Some(true));
21493            // The co-tenant stayed up through the change, and closed only when
21494            // the scope ended, by the drain rule rather than by the commit.
21495            assert_eq!(cotenant.closed_reason(), RouteCloseReason::ScopeEnded);
21496        }
21497
21498        /// Each row of the drain table on one set of routes: the owner's, a
21499        /// bare carrier's, and a targeted carrier's to each of its targets.
21500        #[tokio::test]
21501        async fn each_revocation_drains_exactly_the_affected_routes_with_its_own_reason() {
21502            struct Case {
21503                name: &'static str,
21504                change: fn(&mut ScopeRecord),
21505                /// Closed routes by index: owner->plexus, aft->plexus,
21506                /// broca->plexus, broca->other.
21507                closed: [Option<RouteCloseReason>; 4],
21508            }
21509            use RouteCloseReason::*;
21510            let cases = [
21511                Case {
21512                    name: "a carrier entry removed",
21513                    change: |r| {
21514                        r.carriers.retain(|c| {
21515                            c.principal
21516                                != Principal::Reserved {
21517                                    module_id: AFT.to_string(),
21518                                }
21519                        })
21520                    },
21521                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21522                },
21523                Case {
21524                    name: "a target removed from a carrier",
21525                    change: |r| r.carriers[1].targets = Some(vec![PLEXUS.to_string()]),
21526                    closed: [None, None, None, Some(ScopeCarrierRemoved)],
21527                },
21528                Case {
21529                    name: "a bare carrier narrowed to targets",
21530                    change: |r| r.carriers[0].targets = Some(vec![OTHER.to_string()]),
21531                    closed: [None, Some(ScopeCarrierRemoved), None, None],
21532                },
21533                Case {
21534                    name: "delegates turned off",
21535                    change: |r| r.attributes.delegates = false,
21536                    closed: [Some(ScopeDelegationChanged); 4],
21537                },
21538                Case {
21539                    name: "agent_id changed",
21540                    change: |r| r.attributes.agent_id = Some("agent-2".to_string()),
21541                    closed: [Some(ScopeDelegationChanged); 4],
21542                },
21543                Case {
21544                    name: "a carrier added, child owners changed, the record re-sent",
21545                    change: |r| {
21546                        r.carriers.push(carrier(MAGIC, None));
21547                        r.child_owners.push(Principal::Reserved {
21548                            module_id: MAGIC.to_string(),
21549                        });
21550                    },
21551                    closed: [None; 4],
21552                },
21553                Case {
21554                    name: "a target added",
21555                    change: |r| {
21556                        r.carriers[1]
21557                            .targets
21558                            .as_mut()
21559                            .unwrap()
21560                            .push("third".to_string())
21561                    },
21562                    closed: [None; 4],
21563                },
21564                Case {
21565                    name: "delegates turned on",
21566                    change: |r| r.attributes.delegates = true,
21567                    closed: [None; 4],
21568                },
21569            ];
21570            for case in cases {
21571                let mut rig = rig().await;
21572                rig.sync(vec![session(1)]).await;
21573                let scope = || Some(rig_selector("s", Some(1)));
21574                let mut routes = [
21575                    rig.bound(Some(OWNER), PLEXUS, scope()).await,
21576                    rig.bound(Some(AFT), PLEXUS, scope()).await,
21577                    rig.bound(Some(BROCA), PLEXUS, scope()).await,
21578                    rig.bound(Some(BROCA), OTHER, scope()).await,
21579                ];
21580                let mut record = session(1);
21581                (case.change)(&mut record);
21582                rig.sync(vec![record]).await;
21583                for (index, expected) in case.closed.iter().enumerate() {
21584                    let route = &mut routes[index];
21585                    match expected {
21586                        Some(reason) => {
21587                            assert!(!rig.live(route), "{}: route {index} still live", case.name);
21588                            assert_eq!(
21589                                route.closed_reason(),
21590                                *reason,
21591                                "{}: route {index}",
21592                                case.name
21593                            );
21594                        }
21595                        None => {
21596                            assert!(rig.live(route), "{}: route {index} closed", case.name);
21597                            assert!(
21598                                route.untouched(),
21599                                "{}: route {index} was told something",
21600                                case.name
21601                            );
21602                        }
21603                    }
21604                }
21605            }
21606        }
21607
21608        #[tokio::test]
21609        async fn ending_or_replacing_a_scope_and_a_parent_ending_drain_every_route_under_it() {
21610            // Removed, and replaced by a higher epoch.
21611            for next in [Vec::new(), vec![session(2)]] {
21612                let mut rig = rig().await;
21613                rig.sync(vec![session(1)]).await;
21614                let mut route = rig
21615                    .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21616                    .await;
21617                rig.sync(next).await;
21618                assert!(!rig.live(&route));
21619                assert_eq!(route.closed_reason(), RouteCloseReason::ScopeEnded);
21620            }
21621
21622            // A child whose parent ends: its routes close as parent-ended, the
21623            // child stays live, and routes under the parent close as ended.
21624            let mut rig = rig().await;
21625            let mut child = session(1);
21626            child.scope_ref = "child".to_string();
21627            child.kind = ScopeKind::Worker;
21628            child.parent = Some(ScopeParent::new(
21629                Principal::Reserved {
21630                    module_id: OWNER.to_string(),
21631                },
21632                "s".to_string(),
21633                1,
21634            ));
21635            rig.sync(vec![session(1), child.clone()]).await;
21636            let mut child_route = rig
21637                .bound(Some(AFT), PLEXUS, Some(rig_selector("child", Some(1))))
21638                .await;
21639            assert_eq!(
21640                child_route.stamp().unwrap().parent_state,
21641                Some(ParentState::Linked)
21642            );
21643            rig.sync(vec![child]).await;
21644            assert!(!rig.live(&child_route));
21645            assert_eq!(
21646                child_route.closed_reason(),
21647                RouteCloseReason::ScopeParentEnded
21648            );
21649        }
21650
21651        #[tokio::test]
21652        async fn re_sending_an_unchanged_record_drains_nothing_and_a_new_carrier_leaves_in_flight_calls(
21653        ) {
21654            let mut rig = rig().await;
21655            rig.sync(vec![session(1)]).await;
21656            let mut route = rig
21657                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21658                .await;
21659            let before = rig.forwarding.published_scope_tag(OWNER, "s");
21660            rig.sync(vec![session(1)]).await;
21661            assert_eq!(rig.forwarding.published_scope_tag(OWNER, "s"), before);
21662            assert!(rig.live(&route) && route.untouched());
21663
21664            // A call in flight on the route when another carrier is added. A
21665            // forwarded REQUEST holds one credit on the route's flow until the
21666            // module answers; the router takes it exactly like this.
21667            let DataRoute::Client(DataRouteState::Bound(binding)) = rig
21668                .forwarding
21669                .lookup_data_route(route.client.connection_id, route.channel, route.epoch)
21670                .unwrap()
21671            else {
21672                panic!("the route is bound");
21673            };
21674            binding.flow.acquire_tagged(9, false).await.unwrap();
21675            let mut widened = session(1);
21676            widened.carriers.push(carrier(MAGIC, None));
21677            rig.sync(vec![widened]).await;
21678            assert!(rig.live(&route) && route.untouched());
21679            let (_, plexus_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21680            assert!(plexus_rx.try_recv().is_err(), "the module is told nothing");
21681            // The call's credit is still held on an open flow, so its answer
21682            // will be delivered: closing the route would have closed the flow.
21683            assert_eq!(binding.flow.in_flight(), 1);
21684            binding
21685                .flow
21686                .acquire_tagged(10, false)
21687                .await
21688                .expect("the flow is still open");
21689        }
21690
21691        /// A swap's superseded endpoint keeps its routes until drained; ending
21692        /// the scope closes them there too.
21693        #[tokio::test]
21694        async fn ending_a_scope_drains_its_routes_on_a_superseded_endpoint() {
21695            let mut rig = rig().await;
21696            rig.sync(vec![session(1)]).await;
21697            let mut on_incumbent = rig
21698                .bound(Some(AFT), PLEXUS, Some(rig_selector("s", Some(1))))
21699                .await;
21700
21701            // Swap plexus: register a candidate and cut over, leaving the
21702            // incumbent superseded with the route still on it.
21703            let (candidate, _candidate_rx) = wide_ctx(9);
21704            let registration = rig
21705                .handler
21706                .registry
21707                .register_candidate_with_control_ops(
21708                    manifest(PLEXUS, PROTOCOL_VERSION),
21709                    PROTOCOL_VERSION,
21710                    candidate.connection_id,
21711                    module_baseline_control_ops(),
21712                )
21713                .unwrap();
21714            rig.forwarding
21715                .register_candidate_module_connection(
21716                    candidate.connection_id,
21717                    PLEXUS.to_string(),
21718                    PROTOCOL_VERSION,
21719                    manifest_concurrency(&registration.manifest),
21720                    candidate.egress.clone(),
21721                )
21722                .unwrap();
21723            rig.forwarding.cutover_candidate(PLEXUS).unwrap().unwrap();
21724            rig.handler
21725                .registry
21726                .promote_candidate(PLEXUS)
21727                .unwrap()
21728                .unwrap();
21729            assert!(rig.live(&on_incumbent), "cutover alone does not drain");
21730
21731            rig.sync(Vec::new()).await;
21732            assert!(!rig.live(&on_incumbent));
21733            assert_eq!(on_incumbent.closed_reason(), RouteCloseReason::ScopeEnded);
21734            let (_, incumbent_rx) = rig.modules.get_mut(PLEXUS).unwrap();
21735            let goodbye = incumbent_rx
21736                .try_recv()
21737                .expect("the superseded endpoint is told")
21738                .frame;
21739            assert_eq!(goodbye.header.ty, FrameType::Goodbye);
21740        }
21741    }
21742}
21743
21744#[cfg(test)]
21745mod concurrency_default_exposure_tests {
21746    use super::*;
21747
21748    fn hello_body(role_json: &str) -> Vec<u8> {
21749        format!(
21750            r#"{{"protocol_ver":2,"module_id":"m","manifest":{{"module_id":"m","module_version":"1.0.0","protocol_ver":2,"trust_tier":"first_party","provides":[{role_json}],"consumes":[],"bindings":{{"storage":{{"kind":"sqlite","scope":"project","owns_schema":false}},"vault_grants":[],"identity":{{"requires":[],"optional":[]}}}}}}}}"#
21751        )
21752        .into_bytes()
21753    }
21754
21755    fn manifest_from(body: &[u8]) -> ModuleManifest {
21756        let value: serde_json::Value = serde_json::from_slice(body).expect("hello parses");
21757        serde_json::from_value(value.get("manifest").expect("manifest key").clone())
21758            .expect("manifest parses")
21759    }
21760
21761    const SURFACE_TAIL: &str = r#""operations":[],"config_schema":{"type":"object"},"observability":[],"identity_scope":[]"#;
21762
21763    #[test]
21764    fn absent_concurrency_on_management_surface_is_reported_as_defaulted() {
21765        let body = hello_body(&format!(
21766            r#"{{"role":"management_surface",{SURFACE_TAIL}}}"#
21767        ));
21768        let manifest = manifest_from(&body);
21769        // Precondition: serde really resolved it to the default, so the typed
21770        // manifest alone cannot answer the question this probe exists for.
21771        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21772        assert!(manifest_concurrency_was_defaulted(&body, &manifest));
21773    }
21774
21775    #[test]
21776    fn declared_concurrency_is_not_reported_even_when_it_equals_the_default() {
21777        let body = hello_body(&format!(
21778            r#"{{"role":"management_surface",{SURFACE_TAIL},"concurrency":"module_managed"}}"#
21779        ));
21780        let manifest = manifest_from(&body);
21781        assert_eq!(manifest_concurrency(&manifest), Concurrency::ModuleManaged);
21782        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21783    }
21784
21785    #[test]
21786    fn non_management_roles_are_never_reported() {
21787        let body = hello_body(
21788            r#"{"role":"internal_service","service_id":"s","transport":"bulk","agent_facing":false,"operations":[]}"#,
21789        );
21790        let manifest = manifest_from(&body);
21791        assert!(!manifest_concurrency_was_defaulted(&body, &manifest));
21792    }
21793}